mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-16 19:04:13 -06:00
Compare commits
77
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d30834cca | ||
|
|
97423d80fd | ||
|
|
9e7fa3b571 | ||
|
|
bb2c2254ee | ||
|
|
0d5c0b854b | ||
|
|
349d3d1c24 | ||
|
|
f33d22001c | ||
|
|
d842a0cc2a | ||
|
|
e51ff1a6a8 | ||
|
|
988d721d7d | ||
|
|
6bbb593d82 | ||
|
|
187afbd4e5 | ||
|
|
1af57126a0 | ||
|
|
b0c532d2d1 | ||
|
|
3bad02d1f1 | ||
|
|
1ff3b87f5a | ||
|
|
9f7d1c426f | ||
|
|
a4674dbd1c | ||
|
|
04907481c1 | ||
|
|
3c60448691 | ||
|
|
772219838e | ||
|
|
e86c25af9c | ||
|
|
10fef35fe6 | ||
|
|
b0c77ebd6a | ||
|
|
68a4190f95 | ||
|
|
69379cf689 | ||
|
|
7a24b20c8e | ||
|
|
ef9ac9ac7a | ||
|
|
eebede8ee4 | ||
|
|
a024a0e86c | ||
|
|
9850dc6088 | ||
|
|
3ce1886bea | ||
|
|
0a75620a73 | ||
|
|
74a0468917 | ||
|
|
6166cb0870 | ||
|
|
d2ee3ca9fc | ||
|
|
506db24b07 | ||
|
|
7f9acc1c27 | ||
|
|
3a92bcc93c | ||
|
|
18355eeca2 | ||
|
|
2d1e6ff348 | ||
|
|
6a3cbd18d2 | ||
|
|
5914363930 | ||
|
|
e0b0817288 | ||
|
|
63331b8ab6 | ||
|
|
3975b8cc5e | ||
|
|
db257178f5 | ||
|
|
e8802ccfbd | ||
|
|
730c6cde9c | ||
|
|
b7e5cf05ea | ||
|
|
ce2bd95414 | ||
|
|
41dd2bd3bb | ||
|
|
1469419354 | ||
|
|
70a0d7a2d8 | ||
|
|
ea97b18c70 | ||
|
|
17db75b74a | ||
|
|
cdca5bd09d | ||
|
|
7ebfa82297 | ||
|
|
de5398cfc5 | ||
|
|
2750e65096 | ||
|
|
c564070d9e | ||
|
|
3def50c98a | ||
|
|
a570031909 | ||
|
|
9d9610a893 | ||
|
|
5a2cab9483 | ||
|
|
3e2dc9ca7f | ||
|
|
6b1e2d6aef | ||
|
|
283a148420 | ||
|
|
d680914140 | ||
|
|
1c8b14edad | ||
|
|
09548fe55c | ||
|
|
ea809d93f5 | ||
|
|
26c1ac83dc | ||
|
|
23d0f67d17 | ||
|
|
fb67888e25 | ||
|
|
9e6758e276 | ||
|
|
6c0886a68a |
@@ -35,6 +35,7 @@ artwork. The ribbon and menu icons stay original drawings.
|
||||
| `crates/fonts/tests/fixtures/legacy-semibold.ttf` | DeckCraft contributors | a one-glyph Semibold face named like Segoe UI Semibold (its Windows family differs from the typographic one), built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests |
|
||||
| `crates/fonts/tests/fixtures/legacy-regular.ttf` | DeckCraft contributors | the same family's one-glyph Regular face, built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests |
|
||||
| `crates/render/tests/fixtures/make_colr_font.py` | DeckCraft contributors | this repository | MIT OR Apache-2.0 | Regenerates the COLR test font |
|
||||
| `crates/format/tests/golden/deck.deckcraft` | DeckCraft contributors | a synthetic deck (placeholder bytes, no images or text from elsewhere) written by `crates/format/src/golden_tests.rs` with `DECKCRAFT_BLESS_GOLDEN=1` | CC0-1.0 | Native format golden bytes |
|
||||
| Lucide icon paths in `crates/engine/src/icon_data.rs` (Insert › Icons) | Lucide Contributors; Feather icons by Cole Bemis | https://github.com/lucide-icons/lucide/tree/440a1e1dfb1e712505308da46bead3c28b1f1398/icons (release 1.56.0, 2026-10-13) | ISC; MIT for the Feather-derived icons named in that commit's LICENSE | Stroke icons inserted as shapes |
|
||||
|
||||
## Bundled through dependencies
|
||||
|
||||
Generated
+90
-28
@@ -222,7 +222,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -853,6 +853,28 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32"
|
||||
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
|
||||
|
||||
[[package]]
|
||||
name = "craft-deckcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32"
|
||||
dependencies = [
|
||||
"craft-zip",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
@@ -900,6 +922,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -909,6 +941,15 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-rtf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725"
|
||||
dependencies = [
|
||||
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725)",
|
||||
"encoding_rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -986,6 +1027,25 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-zip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.2"
|
||||
@@ -1059,7 +1119,7 @@ checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"chrono",
|
||||
@@ -1081,7 +1141,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-anim"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"deckcraft-geom",
|
||||
"deckcraft-model",
|
||||
@@ -1090,7 +1150,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-cli"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"deckcraft-engine",
|
||||
"deckcraft-mcp",
|
||||
@@ -1100,16 +1160,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-color"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-engine"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-mime",
|
||||
"deckcraft-anim",
|
||||
"deckcraft-color",
|
||||
"deckcraft-fonts",
|
||||
@@ -1133,7 +1194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-fonts"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"epaint_default_fonts",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1145,18 +1206,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-format"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-deckcraft-format",
|
||||
"craft-rtf",
|
||||
"deckcraft-model",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 3.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-geom"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"serde",
|
||||
@@ -1164,7 +1225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-mcp"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"deckcraft-engine",
|
||||
"deckcraft-render",
|
||||
@@ -1174,7 +1235,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-media"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-audio",
|
||||
"craft-media",
|
||||
@@ -1187,7 +1248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-model"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"deckcraft-color",
|
||||
"deckcraft-geom",
|
||||
@@ -1199,7 +1260,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-pdf"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"deckcraft-fonts",
|
||||
@@ -1217,8 +1278,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-pptx"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"deckcraft-color",
|
||||
"deckcraft-engine",
|
||||
"deckcraft-geom",
|
||||
@@ -1233,7 +1295,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-render"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-metafile",
|
||||
"deckcraft-anim",
|
||||
@@ -1252,7 +1314,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-text"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"deckcraft-color",
|
||||
@@ -1266,7 +1328,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-ui-egui"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -1292,7 +1354,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "deckcraft-web"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
@@ -1687,7 +1749,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3049,7 +3111,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4077,7 +4139,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4134,7 +4196,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4805,10 +4867,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5759,7 +5821,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6277,7 +6339,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+8
-1
@@ -4,13 +4,15 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/deckcraft", "apps/deckcraft-cli"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/deckcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
# XML writer primitives; parser admission and OOXML policy stay app-local.
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" }
|
||||
# internal
|
||||
deckcraft-geom = { path = "crates/geom" }
|
||||
deckcraft-color = { path = "crates/color" }
|
||||
@@ -48,7 +50,12 @@ harfrust = "0.13"
|
||||
vello_cpu = "0.2"
|
||||
vello_common = { version = "0.2", default-features = false }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
|
||||
# Base64 for command payloads (engine); base64_compat keeps the legacy lenient decoder. Same rev as craft-deckcraft-format.
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" }
|
||||
# craft-media, craft-audio and craft-video share types and stay on one rev.
|
||||
# The .deckcraft package layer (identity, manifest, member names, bounded reads); crates/format maps the presentation onto it.
|
||||
craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
|
||||
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false }
|
||||
craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] }
|
||||
# H.264, HEVC, VP9 and AV1 decoders.
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~20 points and ~120–210 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** trivial (the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** trivial (slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
@@ -155,6 +155,7 @@ app's JSON control channel (`deckcraft --control PORT`).
|
||||
| Date | What landed |
|
||||
|---|---|
|
||||
| 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed |
|
||||
| 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Slide lists over 10,000 entries are explicitly refused before a partial load; exactly 10,000 remain supported. Synthetic 13-slide regression; does not establish the cause of #1910's field report. |
|
||||
| 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered |
|
||||
| 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop |
|
||||
| 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) |
|
||||
|
||||
@@ -73,3 +73,7 @@ sync_github_name = true
|
||||
display_name = "Arshiya"
|
||||
real_name = "Arshiya Rahgozar"
|
||||
sync_github_name = false
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "DeckCraft engine: sessions, undo history, selection, the command
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-mime = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
deckcraft-model = { workspace = true }
|
||||
|
||||
+113
-31
@@ -607,51 +607,133 @@ fn param_optional(alt: &str) -> Option<bool> {
|
||||
|
||||
/// Base64 (standard alphabet) for binary payloads in JSON params and results.
|
||||
pub fn base64_encode(data: &[u8]) -> String {
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
|
||||
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
|
||||
for (i, shift) in [18, 12, 6, 0].iter().enumerate() {
|
||||
if i <= chunk.len() {
|
||||
out.push(A.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A') as char);
|
||||
} else {
|
||||
out.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
craft_mime::base64::STANDARD.encode(data)
|
||||
}
|
||||
|
||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let s = s.split_once("base64,").map(|(_, b)| b).unwrap_or(s);
|
||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0;
|
||||
// Preserve the command transport's admission rules before the shared legacy decoder:
|
||||
// padding ends the payload and one trailing symbol cannot encode a byte.
|
||||
let (mut symbols_mod_four, mut padded) = (0u8, false);
|
||||
for c in s.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
b'=' | b'\n' | b'\r' | b' ' => continue,
|
||||
match c {
|
||||
b'=' => padded = true,
|
||||
b'\n' | b'\r' | b' ' => {}
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'/' | b'_' if !padded => {
|
||||
symbols_mod_four = (symbols_mod_four + 1) % 4;
|
||||
}
|
||||
_ => return None,
|
||||
} as u32;
|
||||
acc = (acc << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((acc >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
if symbols_mod_four == 1 {
|
||||
return None;
|
||||
}
|
||||
craft_mime::base64_compat::decode(s).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Frozen pre-cutover implementation (Brandon Thomas, with Mex's padding/tail fixes).
|
||||
fn previous_base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let s = s.split_once("base64,").map(|(_, b)| b).unwrap_or(s);
|
||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0;
|
||||
let mut padded = false;
|
||||
for c in s.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
b'=' => {
|
||||
padded = true;
|
||||
continue;
|
||||
}
|
||||
b'\n' | b'\r' | b' ' => continue,
|
||||
_ => return None,
|
||||
} as u32;
|
||||
// Padding ends the payload; no further data may be decoded.
|
||||
if padded {
|
||||
return None;
|
||||
}
|
||||
acc = (acc << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push(((acc >> bits) & 0xff) as u8);
|
||||
}
|
||||
}
|
||||
// A trailing lone Base64 character cannot encode another byte.
|
||||
(bits != 6).then_some(out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_decoder_preserves_command_transport_admission() {
|
||||
for text in ["", "=", "Zg== \r\n==", "Zg==A", "A", "AAAAA", "AB", "+_8=", "Z=m9v", "Zm9v\t", "Zm9v!", "data:text/plain;base64,Zm9v"] {
|
||||
assert_eq!(base64_decode(text), previous_base64_decode(text), "{text:?}");
|
||||
}
|
||||
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/-_= \r\n!\t";
|
||||
let mut seed = 0x1234_5678u32;
|
||||
for n in 0..50_000 {
|
||||
let mut text = String::new();
|
||||
for _ in 0..n % 65 {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
text.push(char::from(alphabet[(seed as usize) % alphabet.len()]));
|
||||
}
|
||||
assert_eq!(base64_decode(&text), previous_base64_decode(&text), "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_encoder_preserves_rfc4648_and_all_byte_remainders() {
|
||||
for (input, expected) in
|
||||
[("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy")]
|
||||
{
|
||||
assert_eq!(base64_encode(input.as_bytes()), expected);
|
||||
}
|
||||
// The decoder accepts both alphabets, so pin the standard one explicitly.
|
||||
assert_eq!(base64_encode(&[0xfb, 0xff]), "+/8=");
|
||||
let all: Vec<u8> = (0..=255).cycle().take(513).collect();
|
||||
for len in 0..=all.len() {
|
||||
let encoded = base64_encode(&all[..len]);
|
||||
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
|
||||
assert_eq!(encoded.bytes().rev().take_while(|b| *b == b'=').count(), (3 - len % 3) % 3);
|
||||
assert_eq!(base64_decode(&encoded).as_deref(), Some(&all[..len]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_rejects_a_single_character_tail() {
|
||||
for (encoded, decoded) in [
|
||||
("", b"".as_slice()),
|
||||
("Zg==", b"f"),
|
||||
("Zg", b"f"),
|
||||
("Zm8=", b"fo"),
|
||||
("Zm8", b"fo"),
|
||||
(" Zm9v \r\n", b"foo"),
|
||||
("data:text/plain;base64,Zm9v", b"foo"),
|
||||
("+/8=", &[0xfb, 0xff]),
|
||||
("-_8=", &[0xfb, 0xff]),
|
||||
] {
|
||||
assert_eq!(base64_decode(encoded).as_deref(), Some(decoded), "{encoded:?}");
|
||||
}
|
||||
for encoded in ["A", "AAAAA", "Zm9vZ", " Zm9vZ \r\n", "data:text/plain;base64,Z"] {
|
||||
assert!(base64_decode(encoded).is_none(), "{encoded:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_rejects_data_after_padding() {
|
||||
assert_eq!(base64_decode("Zg== \r\n=="), Some(b"f".to_vec()));
|
||||
for encoded in ["Zg==A", "Zg== Zm8=", "Zm8=A", "=Zg", "Zg==\r\nA", "data:text/plain;base64,Zg==A"] {
|
||||
assert!(base64_decode(encoded).is_none(), "{encoded:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_palette_skips_a_command_that_needs_a_value() {
|
||||
assert!(needs_arguments("{path}"));
|
||||
|
||||
@@ -365,6 +365,38 @@ fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
out.push(sh);
|
||||
}
|
||||
*list = out;
|
||||
// A group inside a group: its children take its place in the outer group, mapped into the
|
||||
// outer group's child space, where the inner group's own box is.
|
||||
for id in &ids {
|
||||
let Some(siblings) = deckcraft_model::sibling_list_mut(list, *id) else { continue };
|
||||
let Some(at) = siblings.iter().position(|x| x.id == *id) else { continue };
|
||||
let freed: Vec<Shape> = match siblings.get(at) {
|
||||
Some(Shape { kind: ShapeKind::Group { children, child }, xfrm: Some(gx), .. }) => children
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let mut c = c.clone();
|
||||
if let Some(cx) = c.xfrm {
|
||||
c.xfrm = Some(child_to_parent(gx, child, &cx));
|
||||
}
|
||||
c
|
||||
})
|
||||
.collect(),
|
||||
_ => continue,
|
||||
};
|
||||
let freed_ids: Vec<ShapeId> = freed.iter().map(|c| c.id).collect();
|
||||
siblings.splice(at..=at, freed);
|
||||
// Ungrouped along with an outer group, it was listed among that group's children (once per expanded ancestor).
|
||||
match new_sel.iter().position(|x| x == id) {
|
||||
Some(i) => {
|
||||
new_sel.splice(i..=i, freed_ids);
|
||||
new_sel.retain(|x| x != id);
|
||||
}
|
||||
None => new_sel.extend(freed_ids),
|
||||
}
|
||||
}
|
||||
// A shape freed from a named group and then from a named group around it is listed once.
|
||||
let mut listed = std::collections::HashSet::new();
|
||||
new_sel.retain(|x| listed.insert(*x));
|
||||
sel.shapes = new_sel.clone();
|
||||
Ok(json!({"ids": new_sel}))
|
||||
})
|
||||
|
||||
@@ -120,6 +120,12 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// A shape in a group is copied with the box it is drawn in, so it pastes where it was seen.
|
||||
for sh in &mut shapes {
|
||||
if let Some(x) = sh.xfrm.and_then(|x| box_on_slide(&st.doc, &st.selection, st.shapes(), sh.id, &x)) {
|
||||
sh.xfrm = Some(x);
|
||||
}
|
||||
}
|
||||
// Copying is the last chance to read what a placeholder inherits: a cut removes it, and the
|
||||
// paste can be in another deck. Slide Master view pastes the originals instead.
|
||||
let placeholders: Vec<Shape> = shapes.iter().filter(|x| x.ph.is_some()).cloned().collect();
|
||||
@@ -147,6 +153,39 @@ pub(crate) fn detach_on_slide(doc: &deckcraft_model::Presentation, sel: &crate::
|
||||
}
|
||||
}
|
||||
|
||||
/// Where shape `id` is drawn on the slide when it is inside a group: `x`, its box in its group's
|
||||
/// space, mapped out through each group around it, as Ungroup places a freed shape. `None` for a
|
||||
/// shape on the top level or not found. A turned shape in a group stretched more one way than the
|
||||
/// other is drawn skewed, which a box cannot hold, so it gets the unskewed box Ungroup gives it.
|
||||
fn box_on_slide(
|
||||
doc: &deckcraft_model::Presentation,
|
||||
sel: &crate::Selection,
|
||||
shapes: &[Shape],
|
||||
id: ShapeId,
|
||||
x: &deckcraft_geom::Xfrm,
|
||||
) -> Option<deckcraft_geom::Xfrm> {
|
||||
fn rec(
|
||||
doc: &deckcraft_model::Presentation,
|
||||
sel: &crate::Selection,
|
||||
shapes: &[Shape],
|
||||
id: ShapeId,
|
||||
x: &deckcraft_geom::Xfrm,
|
||||
depth: usize,
|
||||
) -> Option<deckcraft_geom::Xfrm> {
|
||||
if depth > 64 {
|
||||
return None;
|
||||
}
|
||||
shapes.iter().find_map(|sh| {
|
||||
let deckcraft_model::ShapeKind::Group { children, child } = &sh.kind else {
|
||||
return None;
|
||||
};
|
||||
let inner = if children.iter().any(|c| c.id == id) { *x } else { rec(doc, sel, children, id, x, depth + 1)? };
|
||||
Some(super::arrange::child_to_parent(&xfrm_of(doc, sel, sh), child, &inner))
|
||||
})
|
||||
}
|
||||
rec(doc, sel, shapes, id, x, 0)
|
||||
}
|
||||
|
||||
fn copying_caret(s: &Session) -> bool {
|
||||
s.active().is_some_and(|d| d.selection.text.as_ref().is_some_and(|t| !t.is_range()))
|
||||
}
|
||||
@@ -559,6 +598,16 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (new_ids, made) = s.edit(|doc, sel| {
|
||||
let list = super::current_shapes(doc, sel).cloned().unwrap_or_default();
|
||||
let mut copies: Vec<Shape> = list.iter().filter(|x| ids.contains(&x.id)).cloned().collect();
|
||||
// A shape inside a group is copied into that group, with the map from the group's space onto
|
||||
// the slide so that its copy is offset on the slide as a top-level copy is.
|
||||
let top = copies.len();
|
||||
let mut to_slide = vec![None; top];
|
||||
for id in grouped_targets(&list, &ids) {
|
||||
if let Some((m, a)) = crate::connect::locate(doc, sel, &list, id) {
|
||||
copies.push(m.clone());
|
||||
to_slide.push(Some(a));
|
||||
}
|
||||
}
|
||||
let sources: Vec<ShapeId> = copies.iter().map(|c| c.id).collect();
|
||||
let boxes: Vec<_> = copies.iter().map(|c| xfrm_of(doc, sel, c)).collect();
|
||||
detach_on_slide(doc, sel, &mut copies);
|
||||
@@ -570,10 +619,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.and_then(|(_, _, pairs)| {
|
||||
let (src, copy) = pairs.first()?;
|
||||
let a = xfrm_of(doc, sel, list.iter().find(|x| x.id == *src)?);
|
||||
let b = xfrm_of(doc, sel, list.iter().find(|x| x.id == *copy)?);
|
||||
let d = (b.x - a.x, b.y - a.y);
|
||||
(d.0.is_finite() && d.1.is_finite()).then_some(d)
|
||||
// Measured on the slide, so the copy of a shape in a group repeats its drawn move.
|
||||
let (a, to_a) = crate::connect::locate(doc, sel, &list, *src)?;
|
||||
let (b, to_b) = crate::connect::locate(doc, sel, &list, *copy)?;
|
||||
let (a, b) = (xfrm_of(doc, sel, a), xfrm_of(doc, sel, b));
|
||||
let d = to_b * deckcraft_geom::Point::new(b.x, b.y) - to_a * deckcraft_geom::Point::new(a.x, a.y);
|
||||
(d.x.is_finite() && d.y.is_finite()).then_some((d.x, d.y))
|
||||
})
|
||||
.unwrap_or((off, off));
|
||||
reid("edit.duplicate", doc, &mut copies)?;
|
||||
@@ -588,7 +639,8 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
rename_automatic(c, &mut taken, count);
|
||||
count += 1;
|
||||
});
|
||||
for (c, b) in copies.iter_mut().zip(boxes) {
|
||||
for ((c, b), to) in copies.iter_mut().zip(boxes).zip(&to_slide) {
|
||||
let (dx, dy) = to.map_or((dx, dy), |a| offset_in(a, dx, dy));
|
||||
let mut x = b;
|
||||
x.x += dx;
|
||||
x.y += dy;
|
||||
@@ -599,7 +651,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let new_ids: Vec<ShapeId> = copies.iter().map(|c| c.id).collect();
|
||||
let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad("edit.duplicate", "no slide"))?;
|
||||
shapes.extend(copies);
|
||||
let mut copies = copies.into_iter();
|
||||
shapes.extend(copies.by_ref().take(top));
|
||||
// A member's copy goes last among its group's children, as a top-level copy goes last on the slide.
|
||||
for (c, src) in copies.zip(sources.iter().skip(top)) {
|
||||
deckcraft_model::sibling_list_mut(shapes, *src).ok_or_else(|| bad("edit.duplicate", "no such shape"))?.push(c);
|
||||
}
|
||||
sel.shapes = new_ids.clone();
|
||||
let made = (sel.slide, sel.target, sources.into_iter().zip(new_ids.iter().copied()).collect());
|
||||
Ok((new_ids, made))
|
||||
@@ -608,6 +665,34 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"ids": new_ids}))
|
||||
}
|
||||
|
||||
/// The shapes in `ids` that are inside groups, in drawing order, without those in a group that is
|
||||
/// in `ids` too: they are copied along with it.
|
||||
fn grouped_targets(list: &[Shape], ids: &[ShapeId]) -> Vec<ShapeId> {
|
||||
fn rec(shapes: &[Shape], ids: &[ShapeId], nested: bool, out: &mut Vec<ShapeId>, depth: usize) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
for sh in shapes {
|
||||
if !ids.contains(&sh.id) {
|
||||
rec(sh.children(), ids, true, out, depth + 1);
|
||||
} else if nested {
|
||||
out.push(sh.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
rec(list, ids, false, &mut out, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// The offset in the space `to_slide` maps onto the slide that moves a shape by (`dx`, `dy`) on
|
||||
/// the slide. A group with no width or height draws nothing, and the offset stays as it is.
|
||||
fn offset_in(to_slide: deckcraft_geom::Affine, dx: f64, dy: f64) -> (f64, f64) {
|
||||
let back = to_slide.inverse();
|
||||
let v = back * deckcraft_geom::Point::new(dx, dy) - back * deckcraft_geom::Point::ZERO;
|
||||
if v.x.is_finite() && v.y.is_finite() { (v.x, v.y) } else { (dx, dy) }
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.doc()?.selection.text.is_some() && ids_param(p, "ids").is_none() {
|
||||
return super::text::delete_dir(s, "forward");
|
||||
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"format.textTransparency",
|
||||
"Text Transparency",
|
||||
["Shape Format", "WordArt Styles"],
|
||||
["Shape Format", "Decorative Text Styles"],
|
||||
None,
|
||||
"{value: 0..1} — 0 opaque, 1 invisible; keeps the text's colour (inherited colours included)",
|
||||
has_text_or_shapes,
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"format.textOutline",
|
||||
"Text Outline",
|
||||
["Shape Format", "WordArt Styles"],
|
||||
["Shape Format", "Decorative Text Styles"],
|
||||
None,
|
||||
"{color?, width?: pt} (no color = none)",
|
||||
has_text_or_shapes,
|
||||
@@ -137,7 +137,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"format.textWarp",
|
||||
"Text Transform",
|
||||
["Shape Format", "WordArt Styles"],
|
||||
["Shape Format", "Decorative Text Styles"],
|
||||
None,
|
||||
"{preset: a prstTxWarp name or none, adj?: [finite raw guide values, at most 8]} — none clears the transform; omitted adj uses the preset's defaults",
|
||||
has_text_or_shapes,
|
||||
|
||||
@@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("insert.audio", "Audio from File…", ["Insert", "Media", "Audio"], None, "{path? | data: base64, name?, rect?}", has_slide, audio),
|
||||
cmd!("insert.video", "Video from File…", ["Insert", "Media", "Video"], None, "{path? | data: base64, name?, rect?}", has_slide, video),
|
||||
cmd!("insert.wordArt", "WordArt", ["Insert", "Text"], None, "{text?, style?: 0..}", has_slide, word_art),
|
||||
cmd!("insert.wordArt", "Decorative Text", ["Insert", "Text"], None, "{text?, style?: 0..}", has_slide, word_art),
|
||||
cmd!("insert.slideNumber", "Slide Number", ["Insert", "Text"], None, "{}", has_slide, slide_number),
|
||||
cmd!(
|
||||
"insert.dateTime",
|
||||
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(
|
||||
"insert.smartArt",
|
||||
"SmartArt",
|
||||
"Diagram",
|
||||
["Insert", "Illustrations"],
|
||||
None,
|
||||
"{kind: list|process|cycle|hierarchy|pyramid|matrix, items?: [text] (leading tabs = sub-points), nodes?: [{text, level}]} → {id}",
|
||||
|
||||
@@ -24,12 +24,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Merge Shapes",
|
||||
["Shape Format", "Insert Shapes", "Merge Shapes"],
|
||||
None,
|
||||
"{op: union|combine|fragment|intersect|subtract, ids?: shapes in selection order (the first one's formatting is kept)} → {ids}",
|
||||
has_two,
|
||||
"{op: union|combine|fragment|intersect|subtract, ids?: shapes in selection order (the first one's formatting is kept)} → {ids} (a shape inside a group is refused; ungroup it first)",
|
||||
can_merge,
|
||||
merge
|
||||
)]
|
||||
}
|
||||
|
||||
/// Why Merge Shapes is unavailable while a shape inside a group is selected.
|
||||
pub(crate) const IN_GROUP: &str = "a shape in a group can't be merged; ungroup it first";
|
||||
|
||||
/// Two or more shapes selected, none of them inside a group: the result replaces its sources in
|
||||
/// the slide's top-level list, so a member would be drawn outside its group's scale and offset.
|
||||
fn can_merge(s: &Session) -> std::result::Result<(), String> {
|
||||
has_two(s)?;
|
||||
let in_group =
|
||||
s.active().is_some_and(|st| st.selection.shapes.iter().any(|id| st.shape(*id).is_some() && !st.shapes().iter().any(|t| t.id == *id)));
|
||||
if in_group { Err(IN_GROUP.into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The filled outline of `s` in slide points (curves flattened). A text box with no fill and no
|
||||
/// outline is its letters, as in PowerPoint (merging text with a picture fills the letters).
|
||||
fn area_of(doc: &deckcraft_model::Presentation, sel: &crate::Selection, s: &Shape) -> Area {
|
||||
@@ -197,6 +209,10 @@ fn merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = targets(s, p)?;
|
||||
let st = s.doc()?;
|
||||
let shapes: Vec<Shape> = ids.iter().filter_map(|id| st.shape(*id).cloned()).collect();
|
||||
if let Some(member) = shapes.iter().find(|x| !st.shapes().iter().any(|t| t.id == x.id)) {
|
||||
let name = if member.name.is_empty() { format!("shape {}", member.id.0) } else { format!("`{}`", member.name) };
|
||||
return Err(bad("shape.merge", format!("{name} is in a group; ungroup it first to merge it")));
|
||||
}
|
||||
let mergeable = |x: &Shape| matches!(x.kind, ShapeKind::Shape | ShapeKind::Picture { .. }) && !x.is_line();
|
||||
if shapes.len() < 2 || !shapes.iter().all(mergeable) {
|
||||
return Err(bad("shape.merge", "select two or more shapes (not lines, groups, tables or charts)"));
|
||||
@@ -379,4 +395,40 @@ mod tests {
|
||||
assert_eq!(animations[1].trigger.map(|id| id.0), Some(first));
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge Shapes refuses a shape inside a group, naming it, and is unavailable while one is
|
||||
/// selected. Before, the result went to the slide's top level with the member's box from the
|
||||
/// group's own space, so the shapes of a moved or resized group were redrawn somewhere else.
|
||||
#[test]
|
||||
fn a_shape_in_a_group_is_refused() {
|
||||
fn rect(s: &mut Session, x: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, 100, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let (a, b, c) = (rect(&mut s, 100.0), rect(&mut s, 150.0), rect(&mut s, 500.0));
|
||||
let g = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("shape.move", &json!({"ids": [g], "dx": 300})).unwrap();
|
||||
let before = s.doc().unwrap().current_slide().unwrap().shapes.clone();
|
||||
let name = s.doc().unwrap().shape(ShapeId(a as u32)).unwrap().name.clone();
|
||||
for ids in [json!([a, b]), json!([c, a])] {
|
||||
let err = s.execute("shape.merge", &json!({"op": "union", "ids": ids})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("`{name}` is in a group; ungroup it first")), "{ids}: {err}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().current_slide().unwrap().shapes, before, "a refused merge leaves the slide as it was");
|
||||
|
||||
let spec = crate::cmd::find_command("shape.merge").unwrap();
|
||||
s.execute("edit.select", &json!({"ids": [a, c]})).unwrap();
|
||||
assert_eq!((spec.enabled)(&s), Err("a shape in a group can't be merged; ungroup it first".to_string()));
|
||||
assert!(s.execute("shape.merge", &json!({"op": "union"})).is_err());
|
||||
// Named top-level shapes don't depend on the selection.
|
||||
let d = rect(&mut s, 550.0);
|
||||
s.execute("edit.select", &json!({"ids": [a, b]})).unwrap();
|
||||
assert_eq!(s.execute("shape.merge", &json!({"op": "union", "ids": [c, d]})).unwrap()["ids"].as_array().map(Vec::len), Some(1));
|
||||
|
||||
s.execute("arrange.ungroup", &json!({"ids": [g]})).unwrap();
|
||||
s.execute("edit.select", &json!({"ids": [a, b]})).unwrap();
|
||||
assert_eq!((spec.enabled)(&s), Ok(()));
|
||||
assert_eq!(s.execute("shape.merge", &json!({"op": "union"})).unwrap()["ids"].as_array().map(Vec::len), Some(1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn flip(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut graphic = false;
|
||||
deckcraft_model::walk(std::slice::from_ref(&*sh), &mut |x, _| graphic |= x.diagram.is_some());
|
||||
if graphic {
|
||||
return Err(bad("shape.flip", "Flip is not available for a SmartArt graphic; use `smartArt.layout` to change how it is laid out"));
|
||||
return Err(bad("shape.flip", "Flip is not available for a Diagram graphic; use `smartArt.layout` to change how it is laid out"));
|
||||
}
|
||||
if let Some(x) = sh.xfrm.as_mut() {
|
||||
if v {
|
||||
|
||||
@@ -162,7 +162,7 @@ pub fn preview(kind: &str, style: &str, colors: &str, nodes: Option<&[DiagramNod
|
||||
}
|
||||
Shape {
|
||||
id: ShapeId(9_999),
|
||||
name: "SmartArt preview".into(),
|
||||
name: "Diagram preview".into(),
|
||||
xfrm: Some(area),
|
||||
kind: ShapeKind::Group { children, child: area },
|
||||
..Default::default()
|
||||
@@ -178,16 +178,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
query "smartArt.nodes",
|
||||
"Text Pane",
|
||||
["SmartArt Design", "Create Graphic"],
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?} → {id, kind, nodes: [{text, level}]} (id: the SmartArt group or one of its shapes; default the selection)",
|
||||
"{id?} → {id, kind, nodes: [{text, level}]} (id: the Diagram group or one of its shapes; default the selection)",
|
||||
has_selection,
|
||||
nodes
|
||||
),
|
||||
cmd!(
|
||||
"smartArt.setNodes",
|
||||
"Edit SmartArt Text",
|
||||
["SmartArt Design", "Create Graphic"],
|
||||
"Edit Diagram Text",
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, nodes?: [{text, level}], lines?: [string] (leading tabs set the level), index?, text?, title?} (index + text edits one node; title: its Name and Title box)",
|
||||
has_selection,
|
||||
@@ -196,7 +196,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"smartArt.addNode",
|
||||
"Add Shape",
|
||||
["SmartArt Design", "Create Graphic"],
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index?, position?: after|before|below|above|assistant, text?} → {index} (default: after the last node)",
|
||||
has_selection,
|
||||
@@ -205,18 +205,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"smartArt.removeNode",
|
||||
"Remove Shape",
|
||||
["SmartArt Design", "Create Graphic"],
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index} (its sub-points move up one level)",
|
||||
has_selection,
|
||||
remove_node
|
||||
),
|
||||
cmd!("smartArt.promote", "Promote", ["SmartArt Design", "Create Graphic"], None, "{id?, index}", has_selection, promote),
|
||||
cmd!("smartArt.demote", "Demote", ["SmartArt Design", "Create Graphic"], None, "{id?, index}", has_selection, demote),
|
||||
cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, promote),
|
||||
cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, demote),
|
||||
cmd!(
|
||||
"smartArt.layout",
|
||||
"Change Layout",
|
||||
["SmartArt Design", "Layouts"],
|
||||
["Diagram Design", "Layouts"],
|
||||
None,
|
||||
"{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget}",
|
||||
has_selection,
|
||||
@@ -224,17 +224,17 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(
|
||||
"smartArt.fromText",
|
||||
"Convert to SmartArt",
|
||||
"Convert to Diagram",
|
||||
["Home", "Paragraph"],
|
||||
None,
|
||||
"{id?, kind?} → {id} (a text box or placeholder becomes a SmartArt graphic in its place: one node per paragraph, indent levels kept)",
|
||||
"{id?, kind?} → {id} (a text box or placeholder becomes a Diagram graphic in its place: one node per paragraph, indent levels kept)",
|
||||
has_selection,
|
||||
from_text
|
||||
),
|
||||
cmd!(
|
||||
"smartArt.toText",
|
||||
"Convert to Text",
|
||||
["SmartArt Design", "Reset"],
|
||||
["Diagram Design", "Reset"],
|
||||
None,
|
||||
"{id?} → {id} (the graphic becomes a text box of its outline, bulleted by level)",
|
||||
has_selection,
|
||||
@@ -243,7 +243,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"smartArt.toShapes",
|
||||
"Convert to Shapes",
|
||||
["SmartArt Design", "Reset"],
|
||||
["Diagram Design", "Reset"],
|
||||
None,
|
||||
"{id?} (the graphic becomes a plain group of its shapes; the outline is dropped)",
|
||||
has_selection,
|
||||
@@ -251,8 +251,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(
|
||||
"smartArt.picture",
|
||||
"Insert Picture in SmartArt",
|
||||
["SmartArt Design", "Create Graphic"],
|
||||
"Insert Picture in Diagram",
|
||||
["Diagram Design", "Create Graphic"],
|
||||
None,
|
||||
"{id?, index, data?: base64 | path?: string | reset?: bool} (the node's picture placeholder in picture layouts)",
|
||||
has_selection,
|
||||
@@ -260,8 +260,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!(
|
||||
"smartArt.style",
|
||||
"SmartArt Styles",
|
||||
["SmartArt Design", "SmartArt Styles"],
|
||||
"Diagram Styles",
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}",
|
||||
has_selection,
|
||||
@@ -270,7 +270,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!(
|
||||
"smartArt.colors",
|
||||
"Change Colors",
|
||||
["SmartArt Design", "SmartArt Styles"],
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}",
|
||||
has_selection,
|
||||
|
||||
@@ -38,7 +38,7 @@ fn target_group(s: &Session, p: &Value, cmd: &str) -> Result<ShapeId> {
|
||||
let st = s.doc()?;
|
||||
let shapes = current_shapes(&st.doc, &st.selection).ok_or_else(|| bad(cmd, "no slide"))?;
|
||||
let ids = targets(s, p)?;
|
||||
ids.iter().find_map(|id| diagram_group(shapes, *id)).map(|g| g.id).ok_or_else(|| bad(cmd, "select a SmartArt graphic"))
|
||||
ids.iter().find_map(|id| diagram_group(shapes, *id)).map(|g| g.id).ok_or_else(|| bad(cmd, "select a Diagram graphic"))
|
||||
}
|
||||
|
||||
/// Children with fresh ids for diagram `d` inside a group whose child space is `area`.
|
||||
@@ -55,7 +55,7 @@ fn edit_diagram<T>(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Di
|
||||
let gid = target_group(s, p, cmd)?;
|
||||
s.edit(|doc, sel| {
|
||||
let g = current_shapes(doc, sel).and_then(|v| deckcraft_model::find_shape(v, gid)).cloned().ok_or_else(|| bad(cmd, "no such shape"))?;
|
||||
let (ShapeKind::Group { children, child }, Some(mut d)) = (g.kind, g.diagram) else { return Err(bad(cmd, "not a SmartArt graphic")) };
|
||||
let (ShapeKind::Group { children, child }, Some(mut d)) = (g.kind, g.diagram) else { return Err(bad(cmd, "not a Diagram graphic")) };
|
||||
sync_text(&mut d, &children);
|
||||
let out = f(&mut d)?;
|
||||
normalize(&mut d.nodes);
|
||||
@@ -90,7 +90,7 @@ pub fn insert(s: &mut Session, kind: &str, mut nodes: Vec<DiagramNode>) -> Resul
|
||||
let id = ShapeId(doc.alloc_id().ok_or_else(|| bad("insert.smartArt", NO_ID_SPACE))?);
|
||||
let g = Shape {
|
||||
id,
|
||||
name: format!("SmartArt ({kind})"),
|
||||
name: format!("Diagram ({kind})"),
|
||||
xfrm: Some(area),
|
||||
kind: ShapeKind::Group { children, child: area },
|
||||
diagram: Some(d),
|
||||
@@ -201,7 +201,7 @@ pub(super) fn from_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let gid = ShapeId(doc.alloc_id().ok_or_else(|| bad(CMD, NO_ID_SPACE))?);
|
||||
let g = Shape {
|
||||
id: gid,
|
||||
name: format!("SmartArt ({kind})"),
|
||||
name: format!("Diagram ({kind})"),
|
||||
xfrm: Some(area),
|
||||
kind: ShapeKind::Group { children, child: area },
|
||||
diagram: Some(d),
|
||||
@@ -222,12 +222,12 @@ pub(super) fn from_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "smartArt.toText";
|
||||
let gid = target_group(s, p, CMD)?;
|
||||
let (_, d) = selected_for(s, gid).ok_or_else(|| bad(CMD, "select a SmartArt graphic"))?;
|
||||
let (_, d) = selected_for(s, gid).ok_or_else(|| bad(CMD, "select a Diagram graphic"))?;
|
||||
// The sizes the graphic's text shows at: its titles' and its bullets' (shrunk to fit included).
|
||||
let (title_pt, bullet_pt) = {
|
||||
let st = s.doc()?;
|
||||
let shapes = current_shapes(&st.doc, &st.selection).ok_or_else(|| bad(CMD, "no slide"))?;
|
||||
let g = diagram_group(shapes, gid).ok_or_else(|| bad(CMD, "select a SmartArt graphic"))?;
|
||||
let g = diagram_group(shapes, gid).ok_or_else(|| bad(CMD, "select a Diagram graphic"))?;
|
||||
text_sizes(g.children())
|
||||
};
|
||||
let new = s.edit(|doc, sel| {
|
||||
|
||||
@@ -166,21 +166,21 @@ pub(super) fn text_shape(preset: &str, x: Xfrm, lines: &[&DiagramNode], title: b
|
||||
if !title {
|
||||
body.body.anchor = Some(deckcraft_model::text::Anchor::Top);
|
||||
}
|
||||
Shape { name: "SmartArt shape".into(), xfrm: Some(x), geom: Geom::preset(preset), text: Some(body), ..Default::default() }
|
||||
Shape { name: "Diagram shape".into(), xfrm: Some(x), geom: Geom::preset(preset), text: Some(body), ..Default::default() }
|
||||
}
|
||||
|
||||
/// A plain shape with no text (arrows between steps).
|
||||
pub(super) fn deco(preset: &str, x: Xfrm, rot: f64) -> Shape {
|
||||
let mut x = x;
|
||||
x.rot = rot;
|
||||
Shape { name: "SmartArt arrow".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() }
|
||||
Shape { name: "Diagram arrow".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() }
|
||||
}
|
||||
|
||||
pub(super) fn line_shape(a: (f64, f64), b: (f64, f64)) -> Shape {
|
||||
let mut x = Xfrm::new(a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs());
|
||||
x.flip_h = (b.0 < a.0) != (b.1 < a.1);
|
||||
Shape {
|
||||
name: "SmartArt connector".into(),
|
||||
name: "Diagram connector".into(),
|
||||
xfrm: Some(x),
|
||||
geom: Geom::preset("line"),
|
||||
fill: Some(Fill::None),
|
||||
@@ -257,7 +257,7 @@ fn fit_words(sh: &mut Shape) {
|
||||
|
||||
/// A picture placeholder for node `node`: its picture when it has one, else a pale box.
|
||||
pub(super) fn picture_shape(d: &Diagram, preset: &str, x: Xfrm, i: usize, node: usize) -> Shape {
|
||||
let mut sh = Shape { name: "SmartArt picture".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() };
|
||||
let mut sh = Shape { name: "Diagram picture".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() };
|
||||
paint(d, &mut sh, i, true);
|
||||
if let Some(m) = d.nodes.get(node).and_then(|n| n.picture) {
|
||||
sh.fill = Some(Fill::Picture(deckcraft_model::style::PictureFill { media: m, ..Default::default() }));
|
||||
|
||||
@@ -56,7 +56,7 @@ pub(crate) fn delete_dir(s: &mut Session, dir: &str) -> Result<Value> {
|
||||
ed::delete(body, a, b)
|
||||
} else {
|
||||
let other = match dir.as_str() {
|
||||
"forward" => ed::char_move(body, a, true),
|
||||
"forward" => ed::cluster_end(body, a),
|
||||
_ => {
|
||||
// Backspace at the start of an indented/bulleted paragraph outdents first.
|
||||
if a.1 == 0
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! 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.
|
||||
//! `/work`), exactly: on Windows what exists is resolved to its real case first.
|
||||
//! - 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
|
||||
@@ -249,30 +249,19 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `path` (resolved) `root` or inside it, component by component (without regard to case on
|
||||
/// Windows, whose file systems ignore it)?
|
||||
/// Is `path` (resolved) `root` or inside it, component by component? Exactly, on Windows too: what
|
||||
/// exists has its real case from [`resolve`], and a folder that doesn't exist yet may be a different
|
||||
/// one from the root where a parent folder is case sensitive.
|
||||
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)))
|
||||
root.components().all(|r| path.next() == Some(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.
|
||||
/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), 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"));
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -377,6 +366,7 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A root and a path reached through links are compared after the links are followed.
|
||||
#[test]
|
||||
fn links_are_followed_before_comparing() {
|
||||
let (base, roots) = folders("links");
|
||||
@@ -413,20 +403,67 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A name that differs in case is another name until the file system says otherwise.
|
||||
#[test]
|
||||
fn names_are_compared_exactly() {
|
||||
let root = Path::new("/work/In");
|
||||
assert!(inside(Path::new("/work/In/new/a.deckcraft"), root));
|
||||
assert!(!inside(Path::new("/work/IN/a.deckcraft"), root));
|
||||
assert!(!inside(Path::new("/WORK/In/a.deckcraft"), root));
|
||||
assert!(!inside(Path::new("/work/in\u{212A}/a.deckcraft"), Path::new("/work/ink")), "the Kelvin sign folds to k");
|
||||
if cfg!(windows) {
|
||||
let root = Path::new(r"C:\work\In");
|
||||
assert!(inside(Path::new(r"c:\work\In\a.deckcraft"), root), "a drive letter is one drive in either case");
|
||||
assert!(!inside(Path::new(r"C:\work\IN\a.deckcraft"), root));
|
||||
}
|
||||
}
|
||||
|
||||
/// In a case-sensitive folder, `IN` beside the root `in` is another folder, there or not yet.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_ignores_case_and_refuses_devices() {
|
||||
fn a_case_sensitive_folder_keeps_a_differently_cased_name_out() {
|
||||
let base = std::env::temp_dir().join(format!("dc-file-access-case-sensitive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let set = std::process::Command::new("fsutil").args(["file", "setCaseSensitiveInfo"]).arg(&base).arg("enable").output();
|
||||
if !set.as_ref().is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: a case-sensitive folder can't be made here: {set:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
return;
|
||||
}
|
||||
std::fs::create_dir(base.join("in")).unwrap();
|
||||
let root = [base.join("in")];
|
||||
let roots = AutomationRoots::new(&root, &root).unwrap().unwrap();
|
||||
assert_eq!(roots.check(&s(base.join("in/new.deckcraft")), Access::Write), Ok(()));
|
||||
let e = roots.check(&s(base.join("IN/new.deckcraft")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("outside the write root"), "{e}");
|
||||
std::fs::create_dir(base.join("IN")).unwrap();
|
||||
std::fs::write(base.join("IN/secret.deckcraft"), "x").unwrap();
|
||||
let e = roots.check(&s(base.join("IN/secret.deckcraft")), Access::Read).unwrap_err();
|
||||
assert!(e.contains("outside the read root"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
/// On Windows a path finds its real case on disk, and device names are refused.
|
||||
#[test]
|
||||
fn windows_finds_the_real_case_and_refuses_devices() {
|
||||
let (base, roots) = folders("case");
|
||||
let upper = s(base.join("IN/a.deckcraft"));
|
||||
assert_eq!(roots.check(&upper, Access::Read), Ok(()), "{upper}");
|
||||
assert_eq!(roots.check(&s(base.join("In/Sub/New.deckcraft")), Access::Read), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT/New.deckcraft")), Access::Write), Ok(()));
|
||||
assert_eq!(roots.check(&s(base.join("OUT")), Access::Write), 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());
|
||||
let e = roots.check(&s(base.join("out/COM¹.txt")), Access::Write).unwrap_err();
|
||||
assert!(e.contains("reserved device names"), "{e}");
|
||||
assert_eq!(roots.check(&s(base.join("out/console.txt")), Access::Write), Ok(()));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Scopes nest, and a scope applies only on the thread that set it.
|
||||
#[test]
|
||||
fn scopes_nest_and_stay_on_their_thread() {
|
||||
let (base, roots) = folders("scopes");
|
||||
@@ -448,12 +485,13 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// What is a device name, with superscript digits and a name before a colon, and what isn't.
|
||||
#[test]
|
||||
fn device_names() {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.deckcraft", "NUL "] {
|
||||
for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.deckcraft", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] {
|
||||
assert!(is_device_name(d), "{d}");
|
||||
}
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.deckcraft", "nul-x"] {
|
||||
for f in ["console", "com10", "COM0", "lpt", "a.deckcraft", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] {
|
||||
assert!(!is_device_name(f), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -646,7 +646,9 @@ impl Session {
|
||||
self.settle_composition();
|
||||
}
|
||||
if let Err(e) = (spec.enabled)(self) {
|
||||
let named = (e == cmd::NOTHING_SELECTED || e == cmd::SELECT_TWO) && (params.get("ids").is_some() || params.get("id").is_some());
|
||||
// A command told which shapes to act on doesn't depend on what is selected.
|
||||
let named = (e == cmd::NOTHING_SELECTED || e == cmd::SELECT_TWO || e == cmd::merge::IN_GROUP)
|
||||
&& (params.get("ids").is_some() || params.get("id").is_some());
|
||||
if !named {
|
||||
return Err(EngineError::Disabled(id.into(), e));
|
||||
}
|
||||
|
||||
+305
-5
@@ -98,6 +98,33 @@ fn text_editing_flow() {
|
||||
assert_eq!(s.doc().unwrap().selection.shapes.len(), 1);
|
||||
}
|
||||
|
||||
/// Forward Delete removes a whole grapheme cluster, not just its first scalar.
|
||||
#[test]
|
||||
fn forward_delete_removes_whole_grapheme_cluster() {
|
||||
for (input, rest) in [("\u{1F44D}\u{1F3FD}y", "y"), ("e\u{301}x", "x")] {
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
s.execute("text.selectAll", &json!({})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": input})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "start"})).unwrap();
|
||||
s.execute("text.delete", &json!({"dir": "forward"})).unwrap();
|
||||
let t = s.execute("text.get", &json!({"id": title})).unwrap();
|
||||
assert_eq!(t["text"], rest);
|
||||
}
|
||||
// Inside a cluster, Delete stops at that cluster's end and leaves the next flag intact.
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
s.execute("text.selectAll", &json!({})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "\u{1F1FA}\u{1F1F8}\u{1F1E8}\u{1F1E6}"})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "start"})).unwrap();
|
||||
s.execute("text.move", &json!({"to": "right"})).unwrap();
|
||||
s.execute("text.delete", &json!({"dir": "forward"})).unwrap();
|
||||
let t = s.execute("text.get", &json!({"id": title})).unwrap();
|
||||
assert_eq!(t["text"], "\u{1F1FA}\u{1F1E8}\u{1F1E6}");
|
||||
}
|
||||
|
||||
/// `text.set` treats CRLF (or a lone CR) as one paragraph break and keeps no `\r` in the text.
|
||||
#[test]
|
||||
fn text_set_crlf_makes_clean_paragraphs() {
|
||||
@@ -214,6 +241,71 @@ fn clipboard_copy_paste_shapes_and_slides() {
|
||||
assert!(s.doc().unwrap().doc.validate().is_empty());
|
||||
}
|
||||
|
||||
/// A shape copied or cut from inside a group pastes where it was drawn: on another slide in the
|
||||
/// same place, on its own slide offset as any paste there is. Its box is mapped out through each
|
||||
/// group around it, however the groups were moved, stretched, turned or flipped. Before, the
|
||||
/// clipboard kept the box inside the group, so the shape pasted where it had been before the group
|
||||
/// was moved or stretched.
|
||||
#[test]
|
||||
fn a_shape_copied_from_a_group_pastes_where_it_was_drawn() {
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let sid = |id: u64| ShapeId(u32::try_from(id).unwrap());
|
||||
let sites = |s: &Session, id: ShapeId| {
|
||||
let st = s.doc().unwrap();
|
||||
connect::sites_of(&st.doc, &st.selection, st.shapes(), id).unwrap()
|
||||
};
|
||||
type Edits<'a> = &'a [(&'a str, Value)];
|
||||
let edit = |s: &mut Session, id: u64, edits: Edits<'_>| {
|
||||
for (cmd, p) in edits {
|
||||
let mut p = p.clone();
|
||||
p["ids"] = json!([id]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
}
|
||||
};
|
||||
// Edits to the shape's group, then to a group around that one (none: no outer group).
|
||||
let cases: [(Edits<'_>, Edits<'_>); 4] = [
|
||||
(&[("shape.move", json!({"dx": 200}))], &[]),
|
||||
(&[("shape.resize", json!({"w": 600}))], &[]),
|
||||
(&[("shape.rotate", json!({"deg": 30})), ("shape.flip", json!({"axis": "vertical"})), ("shape.move", json!({"dx": 50, "dy": 20}))], &[]),
|
||||
(&[("shape.move", json!({"dx": 200}))], &[("shape.resize", json!({"w": 450})), ("shape.move", json!({"dy": 60}))]),
|
||||
];
|
||||
let off = session().prefs.duplicate_offset;
|
||||
for (n, (inner_edits, outer_edits)) in cases.into_iter().enumerate() {
|
||||
for (cmd, same_slide) in [("edit.copy", false), ("edit.cut", false), ("edit.copy", true)] {
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let (a, b) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 100.0));
|
||||
let g = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
edit(&mut s, g, inner_edits);
|
||||
if !outer_edits.is_empty() {
|
||||
let c = rect(&mut s, 100.0, 300.0);
|
||||
let outer = s.execute("arrange.group", &json!({"ids": [g, c]})).unwrap()["id"].as_u64().unwrap();
|
||||
edit(&mut s, outer, outer_edits);
|
||||
}
|
||||
let was = sites(&s, sid(a));
|
||||
s.doc_mut().unwrap().selection.shapes = vec![sid(a)];
|
||||
s.execute(cmd, &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().shape(sid(a)).is_some(), cmd == "edit.copy", "case {n}: {cmd}");
|
||||
if !same_slide {
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
}
|
||||
let r = s.execute("edit.paste", &json!({})).unwrap();
|
||||
let pasted = sid(r["ids"][0].as_u64().unwrap());
|
||||
assert!(s.doc().unwrap().shapes().iter().any(|x| x.id == pasted), "case {n}: {cmd} pastes on the top level");
|
||||
let d = if same_slide { off } else { 0.0 };
|
||||
let now = sites(&s, pasted);
|
||||
assert_eq!(was.len(), now.len(), "case {n}: {cmd}");
|
||||
assert!(
|
||||
was.iter().zip(&now).all(|(p, q)| (q.x - p.x - d).hypot(q.y - p.y - d) < 1e-6),
|
||||
"case {n}: {cmd} on the same slide {same_slide}: drawn at {was:?}, pasted at {now:?}"
|
||||
);
|
||||
assert_eq!(s.doc().unwrap().doc.validate(), Vec::<String>::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolved look of every paragraph and run of shape `id` on the current slide: size, font,
|
||||
/// colour, bold, bullet, indent, alignment, and the box's insets and anchor.
|
||||
fn resolved_look(s: &Session, id: ShapeId) -> String {
|
||||
@@ -885,6 +977,154 @@ fn group_ungroup_roundtrip_positions() {
|
||||
assert!((v["box"]["x"].as_f64().unwrap() - 310.0).abs() < 1e-6, "{v}");
|
||||
}
|
||||
|
||||
/// Ungrouping a group inside another group frees its shapes into the outer group, in its place
|
||||
/// in the outer group's order, drawn where they were, and selects them. Before, arrange.ungroup
|
||||
/// looked only at the slide's top level: it answered `{ids: []}` and changed nothing.
|
||||
#[test]
|
||||
fn ungrouping_a_nested_group_frees_its_shapes_into_the_outer_group() {
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let sid = |id: u64| ShapeId(u32::try_from(id).unwrap());
|
||||
let sites = |s: &Session, id: u64| {
|
||||
let st = s.doc().unwrap();
|
||||
connect::sites_of(&st.doc, &st.selection, st.shapes(), sid(id)).unwrap()
|
||||
};
|
||||
// The outer group moved and stretched; then an inner group turned and flipped, inside an outer
|
||||
// group that is turned and moved.
|
||||
type Edits<'a> = &'a [(&'a str, Value)];
|
||||
let cases: [(Edits<'_>, Edits<'_>); 2] = [
|
||||
(&[], &[("shape.move", json!({"dx": 200})), ("shape.resize", json!({"w": 450}))]),
|
||||
(
|
||||
&[("shape.rotate", json!({"deg": 30})), ("shape.flip", json!({"axis": "horizontal"}))],
|
||||
&[("shape.rotate", json!({"deg": 45})), ("shape.move", json!({"dx": 120, "dy": 40}))],
|
||||
),
|
||||
];
|
||||
let edit = |s: &mut Session, id: u64, edits: Edits<'_>| {
|
||||
for (cmd, p) in edits {
|
||||
let mut p = p.clone();
|
||||
p["ids"] = json!([id]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
}
|
||||
};
|
||||
for (n, (inner_edits, outer_edits)) in cases.into_iter().enumerate() {
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let (a, b, c) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 100.0), rect(&mut s, 100.0, 300.0));
|
||||
let inner = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
edit(&mut s, inner, inner_edits);
|
||||
let outer = s.execute("arrange.group", &json!({"ids": [inner, c]})).unwrap()["id"].as_u64().unwrap();
|
||||
edit(&mut s, outer, outer_edits);
|
||||
let before = [sites(&s, a), sites(&s, b), sites(&s, c)];
|
||||
let r = s.execute("arrange.ungroup", &json!({"ids": [inner]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([a, b]), "case {n}");
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, [sid(a), sid(b)]);
|
||||
let st = s.doc().unwrap();
|
||||
let order: Vec<ShapeId> = deckcraft_model::find_shape(st.shapes(), sid(outer)).unwrap().children().iter().map(|x| x.id).collect();
|
||||
assert_eq!(order, [sid(a), sid(b), sid(c)], "case {n}");
|
||||
for (id, was) in [a, b, c].into_iter().zip(before) {
|
||||
let now = sites(&s, id);
|
||||
assert_eq!(was.len(), now.len(), "case {n}: shape {id}");
|
||||
assert!(was.iter().zip(&now).all(|(p, q)| (*p - *q).hypot() < 1e-6), "case {n}: shape {id} moved from {was:?} to {now:?}");
|
||||
}
|
||||
}
|
||||
// Two named groups, one inside the other, inside a third: the shapes of both go to the third,
|
||||
// each listed once.
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let (a, b, c, d) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 100.0), rect(&mut s, 100.0, 300.0), rect(&mut s, 300.0, 300.0));
|
||||
let inner = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
let middle = s.execute("arrange.group", &json!({"ids": [inner, c]})).unwrap()["id"].as_u64().unwrap();
|
||||
let outer = s.execute("arrange.group", &json!({"ids": [middle, d]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("shape.resize", &json!({"ids": [outer], "w": 600})).unwrap();
|
||||
let before = [a, b, c, d].map(|id| sites(&s, id));
|
||||
let r = s.execute("arrange.ungroup", &json!({"ids": [inner, middle]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([a, b, c]));
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, [sid(a), sid(b), sid(c)]);
|
||||
let st = s.doc().unwrap();
|
||||
let order: Vec<ShapeId> = deckcraft_model::find_shape(st.shapes(), sid(outer)).unwrap().children().iter().map(|x| x.id).collect();
|
||||
assert_eq!(order, [sid(a), sid(b), sid(c), sid(d)]);
|
||||
for (id, was) in [a, b, c, d].into_iter().zip(before) {
|
||||
let now = sites(&s, id);
|
||||
assert_eq!(was.len(), now.len(), "shape {id}");
|
||||
assert!(was.iter().zip(&now).all(|(p, q)| (*p - *q).hypot() < 1e-6), "shape {id} moved from {was:?} to {now:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Ungrouping nested groups in one call returns each freed shape once, whatever order the groups
|
||||
/// are named in. Before, a group freed into a group that the same call freed next was listed twice
|
||||
/// and replaced once, so the call returned the id of a group that no longer existed.
|
||||
#[test]
|
||||
fn ungrouping_nested_groups_in_any_order_returns_only_freed_shapes() {
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
fn group(s: &mut Session, ids: [u64; 2]) -> u64 {
|
||||
s.execute("arrange.group", &json!({"ids": ids})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let sid = |id: u64| ShapeId(u32::try_from(id).unwrap());
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let [a, b, c, d, e] = [(100.0, 100.0), (300.0, 100.0), (100.0, 300.0), (300.0, 300.0), (500.0, 300.0)].map(|(x, y)| rect(&mut s, x, y));
|
||||
let inner = group(&mut s, [a, b]);
|
||||
let middle = group(&mut s, [inner, c]);
|
||||
let upper = group(&mut s, [middle, d]);
|
||||
let outer = group(&mut s, [upper, e]);
|
||||
let r = s.execute("arrange.ungroup", &json!({"ids": [middle, upper, inner]})).unwrap();
|
||||
assert_eq!(r["ids"], json!([a, b, c, d]));
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, [sid(a), sid(b), sid(c), sid(d)]);
|
||||
let st = s.doc().unwrap();
|
||||
let order: Vec<ShapeId> = deckcraft_model::find_shape(st.shapes(), sid(outer)).unwrap().children().iter().map(|x| x.id).collect();
|
||||
assert_eq!(order, [sid(a), sid(b), sid(c), sid(d), sid(e)]);
|
||||
}
|
||||
|
||||
/// Ungrouping a top-level group and a group inside it in one call frees the shapes of both onto
|
||||
/// the slide, in the top-level group's place and drawn where they were, whichever is named first.
|
||||
#[test]
|
||||
fn ungrouping_a_top_level_group_with_a_group_inside_it_frees_both() {
|
||||
fn rect(s: &mut Session, x: f64, y: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
fn group(s: &mut Session, ids: [u64; 2]) -> u64 {
|
||||
s.execute("arrange.group", &json!({"ids": ids})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let sid = |id: u64| ShapeId(u32::try_from(id).unwrap());
|
||||
let sites = |s: &Session, id: u64| {
|
||||
let st = s.doc().unwrap();
|
||||
connect::sites_of(&st.doc, &st.selection, st.shapes(), sid(id)).unwrap()
|
||||
};
|
||||
let roots = |s: &Session| -> Vec<ShapeId> { s.doc().unwrap().shapes().iter().map(|x| x.id).collect() };
|
||||
for outer_first in [true, false] {
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let [a, b, c, z] = [(100.0, 100.0), (300.0, 100.0), (100.0, 300.0), (500.0, 500.0)].map(|(x, y)| rect(&mut s, x, y));
|
||||
let inner = group(&mut s, [a, b]);
|
||||
let outer = group(&mut s, [inner, c]);
|
||||
s.execute("shape.resize", &json!({"ids": [outer], "w": 600})).unwrap();
|
||||
let before = [a, b, c].map(|id| sites(&s, id));
|
||||
let freed = [sid(a), sid(b), sid(c)];
|
||||
let mut expected = vec![];
|
||||
for x in roots(&s) {
|
||||
if x == sid(outer) {
|
||||
expected.extend(freed);
|
||||
} else {
|
||||
expected.push(x);
|
||||
}
|
||||
}
|
||||
assert!(expected.contains(&sid(z)));
|
||||
let ids = if outer_first { [outer, inner] } else { [inner, outer] };
|
||||
let r = s.execute("arrange.ungroup", &json!({"ids": ids})).unwrap();
|
||||
assert_eq!(r["ids"], json!([a, b, c]), "{ids:?}");
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, freed, "{ids:?}");
|
||||
assert_eq!(roots(&s), expected, "{ids:?}");
|
||||
for (id, was) in [a, b, c].into_iter().zip(before) {
|
||||
let now = sites(&s, id);
|
||||
assert_eq!(was.len(), now.len(), "{ids:?}: shape {id}");
|
||||
assert!(was.iter().zip(&now).all(|(p, q)| (*p - *q).hypot() < 1e-6), "{ids:?}: shape {id} moved from {was:?} to {now:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Grouping a group again and again stops at `MAX_GROUP_DEPTH`: past about 39 levels a saved
|
||||
/// .deckcraft file no longer opens, and past 64 commands such as format.languageAll miss the text.
|
||||
#[test]
|
||||
@@ -4160,10 +4400,10 @@ fn smartart_round_trips_through_pptx_as_a_diagram() {
|
||||
}
|
||||
let back = deckcraft_pptx::import(&bytes).unwrap();
|
||||
assert!(back.validate().is_empty());
|
||||
let g = back.slides[1].shapes.iter().find(|x| x.diagram.is_some()).expect("a SmartArt group");
|
||||
let g = back.slides[1].shapes.iter().find(|x| x.diagram.is_some()).expect("a Diagram group");
|
||||
let d = g.diagram.as_ref().unwrap();
|
||||
assert_eq!(d.kind, "hierarchy");
|
||||
assert_eq!((d.style.as_str(), d.colors.as_str()), ("intense", "accent3"), "SmartArt style and colours come back");
|
||||
assert_eq!((d.style.as_str(), d.colors.as_str()), ("intense", "accent3"), "Diagram style and colours come back");
|
||||
assert!(d.imported);
|
||||
let outline: Vec<(&str, u8)> = d.nodes.iter().map(|n| (n.text.as_str(), n.level)).collect();
|
||||
assert_eq!(outline, [("CEO", 0), ("CTO", 1), ("Dev", 2), ("CFO", 1)]);
|
||||
@@ -4191,7 +4431,7 @@ fn smartart_pictures_3d_styles_and_colour_variants() {
|
||||
let pics = |s: &Session| -> Vec<deckcraft_model::Shape> {
|
||||
let st = s.doc().unwrap();
|
||||
let g = st.doc.slides[1].shapes.iter().find(|x| x.diagram.is_some()).unwrap().clone();
|
||||
g.children().iter().filter(|c| c.name == "SmartArt picture").cloned().collect()
|
||||
g.children().iter().filter(|c| c.name == "Diagram picture").cloned().collect()
|
||||
};
|
||||
assert_eq!(pics(&s).len(), 2, "one picture placeholder per top-level node");
|
||||
assert!(pics(&s).iter().all(|p| !matches!(p.fill, Some(deckcraft_model::Fill::Picture(_)))));
|
||||
@@ -6594,6 +6834,66 @@ fn duplicating_a_moved_copy_repeats_the_move() {
|
||||
assert_eq!(s.doc().unwrap().doc.validate(), Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// Duplicating a shape inside a group puts the copy in that group, last among its children, and
|
||||
/// selects it. The copy is offset on the slide as a top-level copy is, however the group is moved,
|
||||
/// stretched or turned, and duplicating a moved copy repeats the move (#966). A shape whose group is
|
||||
/// duplicated as well goes along with the group's copy. Before, Duplicate looked only at the slide's
|
||||
/// top level: it answered `{ids: []}` and changed nothing.
|
||||
#[test]
|
||||
fn duplicating_a_shape_in_a_group_copies_it_into_the_group() {
|
||||
fn rect(s: &mut Session, x: f64) -> u64 {
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, 100, 100, 100]})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
let sid = |id: u64| ShapeId(u32::try_from(id).unwrap());
|
||||
// How far shape `to` is drawn from shape `from` on the slide, the same for each of its sites.
|
||||
let offset = |s: &Session, from: u64, to: u64| {
|
||||
let st = s.doc().unwrap();
|
||||
let sites = |id| connect::sites_of(&st.doc, &st.selection, st.shapes(), sid(id)).unwrap();
|
||||
let (p, q) = (sites(from), sites(to));
|
||||
assert_eq!(p.len(), q.len(), "{p:?} {q:?}");
|
||||
let d = q[0] - p[0];
|
||||
assert!(p.iter().zip(&q).all(|(p, q)| (*q - *p - d).hypot() < 1e-6), "{p:?} {q:?}");
|
||||
(d.x, d.y)
|
||||
};
|
||||
let grouped = |edit: &str, p: Value| {
|
||||
let mut s = session();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 300.0));
|
||||
let g = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();
|
||||
let mut p = p;
|
||||
p["ids"] = json!([g]);
|
||||
s.execute(edit, &p).unwrap();
|
||||
(s, a, b, g)
|
||||
};
|
||||
for (edit, p) in [("shape.move", json!({"dx": 200})), ("shape.resize", json!({"w": 600})), ("shape.rotate", json!({"deg": 90}))] {
|
||||
let (mut s, a, b, g) = grouped(edit, p);
|
||||
let off = s.prefs.duplicate_offset;
|
||||
let r = s.execute("edit.duplicate", &json!({"ids": [a]})).unwrap();
|
||||
assert_eq!(r["ids"].as_array().map(Vec::len), Some(1), "{edit}: {r}");
|
||||
let c = r["ids"][0].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, [sid(c)]);
|
||||
let st = s.doc().unwrap();
|
||||
let order: Vec<ShapeId> = deckcraft_model::find_shape(st.shapes(), sid(g)).unwrap().children().iter().map(|x| x.id).collect();
|
||||
assert_eq!(order, [sid(a), sid(b), sid(c)], "{edit}");
|
||||
let (dx, dy) = offset(&s, a, c);
|
||||
assert!((dx - off).abs() < 1e-6 && (dy - off).abs() < 1e-6, "{edit}: the copy is drawn ({dx}, {dy}) from the original");
|
||||
// Moved, then duplicated again: the next copy is drawn as far from it again.
|
||||
s.execute("shape.move", &json!({"ids": [c], "dx": 30})).unwrap();
|
||||
let (mx, my) = offset(&s, a, c);
|
||||
let d = s.execute("edit.duplicate", &json!({"ids": [c]})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
let (nx, ny) = offset(&s, c, d);
|
||||
assert!((nx - mx).abs() < 1e-6 && (ny - my).abs() < 1e-6, "{edit}: moved ({mx}, {my}), then ({nx}, {ny})");
|
||||
assert_eq!(s.doc().unwrap().doc.validate(), Vec::<String>::new());
|
||||
}
|
||||
let (mut s, a, _, g) = grouped("shape.move", json!({"dx": 200}));
|
||||
let r = s.execute("edit.duplicate", &json!({"ids": [a, g]})).unwrap();
|
||||
assert_eq!(r["ids"].as_array().map(Vec::len), Some(1), "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
let count = |id: u64| deckcraft_model::find_shape(st.shapes(), sid(id)).unwrap().children().len();
|
||||
assert_eq!((count(g), count(r["ids"][0].as_u64().unwrap())), (2, 2));
|
||||
assert_eq!(st.shapes().len(), 2);
|
||||
}
|
||||
|
||||
fn chart_of(s: &Session, id: u64) -> deckcraft_model::Chart {
|
||||
match &s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().kind {
|
||||
deckcraft_model::ShapeKind::Chart(c) => (**c).clone(),
|
||||
@@ -7085,13 +7385,13 @@ fn flip_is_refused_on_a_smartart_graphic_and_leaves_it_a_graphic() {
|
||||
let gid = s.execute("smartArt.fromText", &json!({"kind": "blockList"})).unwrap()["id"].as_u64().unwrap();
|
||||
for cmd in ["arrange.flipHorizontal", "arrange.flipVertical", "shape.flip"] {
|
||||
let e = s.execute(cmd, &json!({"ids": [gid]})).unwrap_err().to_string();
|
||||
assert!(e.contains("SmartArt") && e.contains("smartArt.layout"), "{cmd}: {e}");
|
||||
assert!(e.contains("Diagram") && e.contains("smartArt.layout"), "{cmd}: {e}");
|
||||
}
|
||||
// Grouped with another shape it cannot be flipped either: ungrouping would hand it the flip.
|
||||
let other = s.execute("insert.textBox", &json!({"text": "x"})).unwrap()["id"].as_u64().unwrap();
|
||||
let group = s.execute("arrange.group", &json!({"ids": [gid, other]})).unwrap()["id"].as_u64().unwrap();
|
||||
let e = s.execute("shape.flip", &json!({"ids": [group]})).unwrap_err().to_string();
|
||||
assert!(e.contains("SmartArt"), "{e}");
|
||||
assert!(e.contains("Diagram"), "{e}");
|
||||
s.execute("arrange.ungroup", &json!({"ids": [group]})).unwrap();
|
||||
// Still a SmartArt graphic: smartArt commands keep working.
|
||||
s.execute("smartArt.layout", &json!({"id": gid, "kind": "cycle"})).unwrap();
|
||||
|
||||
@@ -353,7 +353,7 @@ impl Session {
|
||||
bp.warp.map(|n| (n, bp.warp_adj))
|
||||
});
|
||||
if let Some((name, base)) = found {
|
||||
self.begin("Adjust WordArt");
|
||||
self.begin("Adjust Decorative Text");
|
||||
self.tool.drag = Some(Drag::Warp { id, index, name, base, orig });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,10 @@ description = "DeckCraft native file format (.deckcraft: zip of a JSON manifest
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-deckcraft-format = { workspace = true }
|
||||
craft-rtf = { workspace = true }
|
||||
deckcraft-model = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Keep opaque chart payloads out of the JSON manifest and within the media load budget.
|
||||
use std::collections::HashSet;
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_deckcraft_format::{MAX_ENTRY, Package, chart_part_entry, is_chart_part_entry};
|
||||
|
||||
use deckcraft_model::chart::ChartPart;
|
||||
use deckcraft_model::{Master, Presentation, Shape, ShapeKind};
|
||||
|
||||
use crate::{FormatError, MAX_ENTRY, Result, read_entry_max};
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
const PREFIX: &str = "chart-parts/";
|
||||
type Payload = (String, String, Vec<u8>);
|
||||
|
||||
pub(super) fn separate(p: &mut Presentation) -> Result<Vec<Payload>> {
|
||||
@@ -16,7 +16,7 @@ pub(super) fn separate(p: &mut Presentation) -> Result<Vec<Payload>> {
|
||||
visit_parts(p, |part| {
|
||||
// The native namespace is independent of the original OPC names, which may repeat
|
||||
// when charts from several decks are combined. No user-supplied path is extracted.
|
||||
let entry = format!("{PREFIX}{}", payloads.len());
|
||||
let entry = chart_part_entry(payloads.len());
|
||||
part.native_entry = Some(entry.clone());
|
||||
payloads.push((entry, part.content_type.clone(), std::mem::take(&mut part.bytes)));
|
||||
Ok(())
|
||||
@@ -26,7 +26,7 @@ pub(super) fn separate(p: &mut Presentation) -> Result<Vec<Payload>> {
|
||||
|
||||
pub(super) fn restore(
|
||||
p: &mut Presentation,
|
||||
z: &mut zip::ZipArchive<Cursor<&[u8]>>,
|
||||
z: &mut Package<'_>,
|
||||
left: &mut u64,
|
||||
mut items: usize,
|
||||
max_items: usize,
|
||||
@@ -40,21 +40,21 @@ pub(super) fn restore(
|
||||
items += 1;
|
||||
if let Some(entry) = part.native_entry.take() {
|
||||
// Accept only names produced by separate(), and inflate each member once.
|
||||
let canonical = entry.strip_prefix(PREFIX).and_then(|s| s.parse::<usize>().ok()).is_some_and(|n| entry == format!("{PREFIX}{n}"));
|
||||
let canonical = is_chart_part_entry(&entry);
|
||||
if !canonical || !seen.insert(entry.clone()) || !part.bytes.is_empty() {
|
||||
return Err(FormatError::Damaged("invalid or ambiguous chart part reference".into()));
|
||||
}
|
||||
if z.index_for_name(&entry).is_none() {
|
||||
if !z.contains(&entry) {
|
||||
// Missing members consume no inflation work and can be reported for recovery.
|
||||
damaged.push(format!("{entry}: missing chart part"));
|
||||
return Ok(());
|
||||
}
|
||||
if z.by_name(&entry).is_ok_and(|f| f.size() > *left) {
|
||||
if z.declared_size(&entry).is_some_and(|size| size > *left) {
|
||||
return Err(FormatError::Damaged("embedded media and chart parts are larger than DeckCraft can open".into()));
|
||||
}
|
||||
// A CRC/decode error may already have inflated bytes. Stop on that first error
|
||||
// rather than letting later corrupt members reuse the unchanged byte budget.
|
||||
let bytes = read_entry_max(z, &entry, (*left).min(MAX_ENTRY))?;
|
||||
let bytes = z.read_max(&entry, (*left).min(MAX_ENTRY))?;
|
||||
*left -= bytes.len() as u64;
|
||||
part.bytes = bytes;
|
||||
} else {
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
//! A serde serializer adapter that writes non-finite floats as 0.
|
||||
//!
|
||||
//! serde_json writes NaN and ±infinity as `null`, which doesn't read back as a number: a single
|
||||
//! NaN anywhere in the model (a rotation, a crop, a stroke width) made a saved file fail to open
|
||||
//! as "damaged". [`Finite`] wraps any `Serialize` value and replaces those floats on the way out;
|
||||
//! everything else passes through unchanged.
|
||||
|
||||
use serde::ser::{self, Serialize, Serializer};
|
||||
|
||||
/// `T`, serialized with non-finite floats written as 0.
|
||||
pub struct Finite<'a, T: ?Sized>(pub &'a T);
|
||||
|
||||
impl<T: ?Sized + Serialize> Serialize for Finite<'_, T> {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize(Wrap(s))
|
||||
}
|
||||
}
|
||||
|
||||
struct Wrap<S>(S);
|
||||
|
||||
macro_rules! pass {
|
||||
($($m:ident($t:ty)),* $(,)?) => {
|
||||
$(fn $m(self, v: $t) -> Result<S::Ok, S::Error> { self.0.$m(v) })*
|
||||
};
|
||||
}
|
||||
|
||||
impl<S: Serializer> Serializer for Wrap<S> {
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
type SerializeSeq = Wrap<S::SerializeSeq>;
|
||||
type SerializeTuple = Wrap<S::SerializeTuple>;
|
||||
type SerializeTupleStruct = Wrap<S::SerializeTupleStruct>;
|
||||
type SerializeTupleVariant = Wrap<S::SerializeTupleVariant>;
|
||||
type SerializeMap = Wrap<S::SerializeMap>;
|
||||
type SerializeStruct = Wrap<S::SerializeStruct>;
|
||||
type SerializeStructVariant = Wrap<S::SerializeStructVariant>;
|
||||
|
||||
pass!(
|
||||
serialize_bool(bool),
|
||||
serialize_i8(i8),
|
||||
serialize_i16(i16),
|
||||
serialize_i32(i32),
|
||||
serialize_i64(i64),
|
||||
serialize_i128(i128),
|
||||
serialize_u8(u8),
|
||||
serialize_u16(u16),
|
||||
serialize_u32(u32),
|
||||
serialize_u64(u64),
|
||||
serialize_u128(u128),
|
||||
serialize_char(char),
|
||||
serialize_str(&str),
|
||||
serialize_bytes(&[u8]),
|
||||
);
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_f32(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
fn serialize_f64(self, v: f64) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_f64(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
fn serialize_none(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_none()
|
||||
}
|
||||
fn serialize_some<T: ?Sized + Serialize>(self, v: &T) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_some(&Finite(v))
|
||||
}
|
||||
fn serialize_unit(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit()
|
||||
}
|
||||
fn serialize_unit_struct(self, name: &'static str) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit_struct(name)
|
||||
}
|
||||
fn serialize_unit_variant(self, name: &'static str, i: u32, variant: &'static str) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_unit_variant(name, i, variant)
|
||||
}
|
||||
fn serialize_newtype_struct<T: ?Sized + Serialize>(self, name: &'static str, v: &T) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_newtype_struct(name, &Finite(v))
|
||||
}
|
||||
fn serialize_newtype_variant<T: ?Sized + Serialize>(self, name: &'static str, i: u32, variant: &'static str, v: &T) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize_newtype_variant(name, i, variant, &Finite(v))
|
||||
}
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, S::Error> {
|
||||
self.0.serialize_seq(len).map(Wrap)
|
||||
}
|
||||
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, S::Error> {
|
||||
self.0.serialize_tuple(len).map(Wrap)
|
||||
}
|
||||
fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeTupleStruct, S::Error> {
|
||||
self.0.serialize_tuple_struct(name, len).map(Wrap)
|
||||
}
|
||||
fn serialize_tuple_variant(self, name: &'static str, i: u32, variant: &'static str, len: usize) -> Result<Self::SerializeTupleVariant, S::Error> {
|
||||
self.0.serialize_tuple_variant(name, i, variant, len).map(Wrap)
|
||||
}
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, S::Error> {
|
||||
self.0.serialize_map(len).map(Wrap)
|
||||
}
|
||||
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct, S::Error> {
|
||||
self.0.serialize_struct(name, len).map(Wrap)
|
||||
}
|
||||
fn serialize_struct_variant(
|
||||
self,
|
||||
name: &'static str,
|
||||
i: u32,
|
||||
variant: &'static str,
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant, S::Error> {
|
||||
self.0.serialize_struct_variant(name, i, variant, len).map(Wrap)
|
||||
}
|
||||
fn is_human_readable(&self) -> bool {
|
||||
self.0.is_human_readable()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! compound {
|
||||
($tr:ident, $m:ident) => {
|
||||
impl<S: ser::$tr> ser::$tr for Wrap<S> {
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn $m<T: ?Sized + Serialize>(&mut self, v: &T) -> Result<(), S::Error> {
|
||||
self.0.$m(&Finite(v))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
compound!(SerializeSeq, serialize_element);
|
||||
compound!(SerializeTuple, serialize_element);
|
||||
compound!(SerializeTupleStruct, serialize_field);
|
||||
compound!(SerializeTupleVariant, serialize_field);
|
||||
|
||||
impl<S: ser::SerializeMap> ser::SerializeMap for Wrap<S> {
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_key<T: ?Sized + Serialize>(&mut self, k: &T) -> Result<(), S::Error> {
|
||||
self.0.serialize_key(&Finite(k))
|
||||
}
|
||||
fn serialize_value<T: ?Sized + Serialize>(&mut self, v: &T) -> Result<(), S::Error> {
|
||||
self.0.serialize_value(&Finite(v))
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! fields {
|
||||
($tr:ident) => {
|
||||
impl<S: ser::$tr> ser::$tr for Wrap<S> {
|
||||
type Ok = S::Ok;
|
||||
type Error = S::Error;
|
||||
fn serialize_field<T: ?Sized + Serialize>(&mut self, key: &'static str, v: &T) -> Result<(), S::Error> {
|
||||
self.0.serialize_field(key, &Finite(v))
|
||||
}
|
||||
fn skip_field(&mut self, key: &'static str) -> Result<(), S::Error> {
|
||||
self.0.skip_field(key)
|
||||
}
|
||||
fn end(self) -> Result<S::Ok, S::Error> {
|
||||
self.0.end()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
fields!(SerializeStruct);
|
||||
fields!(SerializeStructVariant);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn non_finite_floats_are_written_as_zero_and_nothing_else_changes() {
|
||||
#[derive(serde::Serialize)]
|
||||
struct T {
|
||||
a: f64,
|
||||
b: Option<f64>,
|
||||
c: Vec<(f32, f64)>,
|
||||
d: Option<String>,
|
||||
e: std::collections::BTreeMap<String, f64>,
|
||||
}
|
||||
let t = T { a: f64::NAN, b: Some(f64::INFINITY), c: vec![(f32::NEG_INFINITY, 1.5)], d: None, e: [("k".to_string(), f64::NAN)].into() };
|
||||
let s = serde_json::to_string(&Finite(&t)).unwrap_or_default();
|
||||
assert_eq!(s, r#"{"a":0.0,"b":0.0,"c":[[0.0,1.5]],"d":null,"e":{"k":0.0}}"#);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Byte-for-byte checks on the `.deckcraft` package. The files in `tests/golden` were written by
|
||||
//! the format code as it was before the package layer moved to `craft-deckcraft-format`
|
||||
//! (storytold/craft-libs). A save of the same deck must give the same bytes, and a load must give
|
||||
//! the same presentation and the same damage report.
|
||||
//! `DECKCRAFT_BLESS_GOLDEN=1` rewrites them. Only do that for a deliberate format change.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_model::chart::{Chart, ChartPart, ChartType};
|
||||
use deckcraft_model::text::TextBody;
|
||||
use deckcraft_model::{MediaId, MediaItem, Presentation, Shape, ShapeId, ShapeKind, Xfrm, defaults};
|
||||
|
||||
use super::{load_checked, save_as};
|
||||
|
||||
/// A fixed generator, so the golden bytes don't change with the app's version.
|
||||
const GENERATOR: &str = "DeckCraft golden";
|
||||
|
||||
fn golden(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("golden").join(name)
|
||||
}
|
||||
|
||||
fn media(id: u32, name: &str, content_type: &str, data: &[u8], link: Option<&str>) -> MediaItem {
|
||||
MediaItem { id: MediaId(id), name: name.into(), content_type: content_type.into(), data: Arc::new(data.to_vec()), link: link.map(Into::into) }
|
||||
}
|
||||
|
||||
/// A deck that reaches every kind of package member: stored and deflated media, linked media
|
||||
/// without bytes (not written), stored and deflated chart parts, and a non-finite number.
|
||||
fn deck() -> Presentation {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let slide = Arc::make_mut(&mut p.slides[0]);
|
||||
if let Some(title) = slide.shapes.first_mut() {
|
||||
title.text = Some(TextBody::from_text("Golden «deck» ✓"));
|
||||
}
|
||||
let mut chart = Chart::sample(ChartType::Bar);
|
||||
for (i, (content_type, bytes)) in
|
||||
[("application/zip", vec![80, 75, 3, 4, 1, 2, 3]), ("application/vnd.ms-office.chartstyle+xml", b"<cs:chartStyle id=\"201\"/>".repeat(8))]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
chart.kept.parts.push(ChartPart { name: format!("ppt/charts/part{i}"), content_type: content_type.into(), bytes, native_entry: None });
|
||||
}
|
||||
let chart_id = ShapeId(p.alloc_id().unwrap_or(9000));
|
||||
let odd_id = ShapeId(p.alloc_id().unwrap_or(9001));
|
||||
let slide = Arc::make_mut(&mut p.slides[0]);
|
||||
slide.shapes.push(Shape {
|
||||
id: chart_id,
|
||||
xfrm: Some(Xfrm::new(10.0, 20.0, 300.0, 200.0)),
|
||||
kind: ShapeKind::Chart(Box::new(chart)),
|
||||
..Default::default()
|
||||
});
|
||||
// Written as 0 by the NaN-safe writer, then clamped on load.
|
||||
slide.shapes.push(Shape { id: odd_id, xfrm: Some(Xfrm::new(f64::NAN, 5.0, f64::INFINITY, 7.5)), ..Default::default() });
|
||||
p.media = vec![
|
||||
media(1, "image1.png", "image/png", &[0x89, b'P', b'N', b'G', 13, 10, 26, 10, 0, 0, 0, 0], None),
|
||||
media(
|
||||
2,
|
||||
"drawing.svg",
|
||||
"image/svg+xml",
|
||||
&b"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"4\" height=\"4\"/></svg>".repeat(4),
|
||||
None,
|
||||
),
|
||||
media(3, "clip.mp4", "video/mp4", &[0, 0, 0, 24, b'f', b't', b'y', b'p'], Some("https://example.invalid/clip.mp4")),
|
||||
media(4, "linked.png", "image/png", &[], Some("file:///nowhere/linked.png")),
|
||||
];
|
||||
p
|
||||
}
|
||||
|
||||
/// The loaded deck and its damage report, as JSON. Media bytes are not in the model's JSON, so
|
||||
/// each item's bytes follow it in hex. `with_model: false` leaves the presentation out.
|
||||
fn loaded_json(bytes: &[u8], with_model: bool) -> String {
|
||||
let (p, damaged) = load_checked(bytes).unwrap_or_else(|e| panic!("load: {e}"));
|
||||
let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
|
||||
let media: Vec<(u32, String)> = p.media.iter().map(|m| (m.id.0, hex(&m.data))).collect();
|
||||
let mut value = serde_json::json!({ "damaged": damaged, "media": media });
|
||||
if with_model {
|
||||
value["presentation"] = serde_json::to_value(&p).unwrap_or_default();
|
||||
}
|
||||
serde_json::to_string(&value).unwrap_or_default() + "\n"
|
||||
}
|
||||
|
||||
fn check(name: &str, actual: &[u8]) {
|
||||
let path = golden(name);
|
||||
if std::env::var_os("DECKCRAFT_BLESS_GOLDEN").is_some() {
|
||||
std::fs::write(&path, actual).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
return;
|
||||
}
|
||||
let expected = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
assert!(expected == actual, "{name} changed ({} bytes, golden has {})", actual.len(), expected.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_writes_the_golden_package_bytes() {
|
||||
let bytes = save_as(&deck(), GENERATOR).unwrap_or_else(|e| panic!("save: {e}"));
|
||||
check("deck.deckcraft", &bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_load_of_the_golden_package_gives_the_golden_presentation() {
|
||||
let bytes = std::fs::read(golden("deck.deckcraft")).unwrap_or_else(|e| panic!("{e}"));
|
||||
check("deck.loaded.json", loaded_json(&bytes, true).as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_load_of_a_damaged_package_gives_the_golden_report() {
|
||||
// The PNG member and the second chart part removed: both are reported, nothing is refused.
|
||||
let bytes = std::fs::read(golden("deck.deckcraft")).unwrap_or_else(|e| panic!("{e}"));
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap_or_else(|e| panic!("{e}"));
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let Ok(f) = z.by_index_raw(i) else { continue };
|
||||
if f.name() != "media/1" && f.name() != "chart-parts/1" {
|
||||
out.raw_copy_file(f).unwrap_or_else(|e| panic!("{e}"));
|
||||
}
|
||||
}
|
||||
let damaged = out.finish().unwrap_or_else(|e| panic!("{e}")).into_inner();
|
||||
check("damaged.loaded.json", loaded_json(&damaged, false).as_bytes());
|
||||
}
|
||||
+35
-232
@@ -5,158 +5,63 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod chart_parts;
|
||||
mod finite;
|
||||
pub mod rtf;
|
||||
|
||||
#[cfg(test)]
|
||||
mod chart_parts_tests;
|
||||
#[cfg(test)]
|
||||
mod golden_tests;
|
||||
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_model::text::{Paragraph, TextBody};
|
||||
use deckcraft_model::{LayoutType, Presentation, ShapeKind, defaults};
|
||||
|
||||
pub const MIMETYPE: &str = "application/vnd.storyteller.deckcraft+zip";
|
||||
/// Files written before the SlideCraft → DeckCraft rename (`.slidecraft`) are still read.
|
||||
pub const LEGACY_MIMETYPE: &str = concat!("application/vnd.storyteller.", "slide", "craft+zip");
|
||||
pub const EXTENSION: &str = "deckcraft";
|
||||
/// Format version written into the manifest.
|
||||
pub const VERSION: u32 = 1;
|
||||
/// Largest entry we will inflate (guards against zip bombs).
|
||||
const MAX_ENTRY: u64 = 2 << 30;
|
||||
/// All embedded media and chart sidecars together, inflated (#393).
|
||||
const MAX_TOTAL_MEDIA: u64 = 4 << 30;
|
||||
/// Media items and chart sidecar parts one file may list.
|
||||
const MAX_MEDIA_ITEMS: usize = 100_000;
|
||||
/// Largest `presentation.json` we will inflate. The manifest holds no media bytes, so it is far
|
||||
/// smaller than a media entry may be; inflating and parsing one is what dominates memory.
|
||||
const MAX_MANIFEST: u64 = 256 << 20;
|
||||
|
||||
/// What one load may inflate.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Budget {
|
||||
total: u64,
|
||||
items: usize,
|
||||
manifest: u64,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Budget {
|
||||
/// A media budget with the default manifest limit.
|
||||
fn media(total: u64, items: usize) -> Self {
|
||||
Budget { total, items, manifest: MAX_MANIFEST }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum FormatError {
|
||||
#[error("not a DeckCraft file: {0}")]
|
||||
NotOurs(String),
|
||||
#[error("damaged file: {0}")]
|
||||
Damaged(String),
|
||||
#[error("write failed: {0}")]
|
||||
Write(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, FormatError>;
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct Manifest {
|
||||
format: String,
|
||||
version: u32,
|
||||
generator: String,
|
||||
presentation: Presentation,
|
||||
}
|
||||
// The package itself (identity, manifest, member names, bounded reads) is shared.
|
||||
pub use craft_deckcraft_format::{Budget, EXTENSION, FormatError, LEGACY_MIMETYPE, MIMETYPE, Result, VERSION, sniff};
|
||||
use craft_deckcraft_format::{Member, Package, media_entry};
|
||||
|
||||
/// Serialize a presentation.
|
||||
pub fn save(p: &Presentation) -> Result<Vec<u8>> {
|
||||
let mut buf = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut z = zip::ZipWriter::new(&mut buf);
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
let w = |e: zip::result::ZipError| FormatError::Write(e.to_string());
|
||||
z.start_file("mimetype", stored).map_err(w)?;
|
||||
z.write_all(MIMETYPE.as_bytes()).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
let mut presentation = p.clone();
|
||||
let parts = chart_parts::separate(&mut presentation)?;
|
||||
let m =
|
||||
Manifest { format: "deckcraft".into(), version: VERSION, generator: format!("DeckCraft {}", env!("CARGO_PKG_VERSION")), presentation };
|
||||
let json = serde_json::to_vec(&finite::Finite(&m)).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
z.start_file("presentation.json", deflate).map_err(w)?;
|
||||
z.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
for item in &p.media {
|
||||
if item.link.is_some() && item.data.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Already-compressed media is stored, not deflated again.
|
||||
let opts = if is_compressed(&item.content_type) { stored } else { deflate };
|
||||
z.start_file(format!("media/{}", item.id.0), opts).map_err(w)?;
|
||||
z.write_all(&item.data).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
for (name, content_type, bytes) in parts {
|
||||
let opts = if is_compressed(&content_type) { stored } else { deflate };
|
||||
z.start_file(name, opts).map_err(w)?;
|
||||
z.write_all(&bytes).map_err(|e| FormatError::Write(e.to_string()))?;
|
||||
}
|
||||
z.finish().map_err(w)?;
|
||||
}
|
||||
Ok(buf.into_inner())
|
||||
save_as(p, &format!("DeckCraft {}", env!("CARGO_PKG_VERSION")))
|
||||
}
|
||||
|
||||
fn is_compressed(ct: &str) -> bool {
|
||||
ct.starts_with("image/jpeg")
|
||||
|| ct.starts_with("image/png")
|
||||
|| ct.starts_with("video/")
|
||||
|| ct.starts_with("audio/mpeg")
|
||||
|| ct.starts_with("audio/mp4")
|
||||
|| ct.contains("zip")
|
||||
}
|
||||
|
||||
/// Does this look like a `.deckcraft` file?
|
||||
pub fn sniff(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(b"PK") && [MIMETYPE, LEGACY_MIMETYPE].iter().any(|m| bytes.windows(m.len()).take(200).any(|w| w == m.as_bytes()))
|
||||
/// [`save`] naming `generator` in the manifest.
|
||||
fn save_as(p: &Presentation, generator: &str) -> Result<Vec<u8>> {
|
||||
let mut presentation = p.clone();
|
||||
let parts = chart_parts::separate(&mut presentation)?;
|
||||
// Linked media saved without its bytes has no member.
|
||||
let media: Vec<(String, &deckcraft_model::MediaItem)> =
|
||||
p.media.iter().filter(|item| !(item.link.is_some() && item.data.is_empty())).map(|item| (media_entry(item.id.0), item)).collect();
|
||||
let members: Vec<Member<'_>> = media
|
||||
.iter()
|
||||
.map(|(name, item)| Member { name, content_type: &item.content_type, bytes: &item.data })
|
||||
.chain(parts.iter().map(|(name, content_type, bytes)| Member { name, content_type, bytes }))
|
||||
.collect();
|
||||
craft_deckcraft_format::write(&presentation, generator, &members)
|
||||
}
|
||||
|
||||
/// A member of a package a test built or rewrote with `zip`, within `max` bytes.
|
||||
#[cfg(test)]
|
||||
fn read_entry(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str) -> Result<Vec<u8>> {
|
||||
read_entry_max(z, name, MAX_ENTRY)
|
||||
}
|
||||
|
||||
/// Read one member, refusing it before inflating if it declares more than `max` bytes, and
|
||||
/// stopping at `max` if it inflates further than it declared.
|
||||
fn read_entry_max(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, max: u64) -> Result<Vec<u8>> {
|
||||
read_entry_counted(z, name, max, &mut 0)
|
||||
}
|
||||
|
||||
/// [`read_entry_max`] within `left` (and [`MAX_ENTRY`]), charging `left` for every byte inflated,
|
||||
/// including those inflated before a decode or CRC error, so a member that fails late still
|
||||
/// spends the shared budget it used.
|
||||
fn read_entry_charged(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, left: &mut u64) -> Result<Vec<u8>> {
|
||||
let mut spent = 0;
|
||||
let out = read_entry_counted(z, name, (*left).min(MAX_ENTRY), &mut spent);
|
||||
*left = left.saturating_sub(spent);
|
||||
out
|
||||
}
|
||||
|
||||
/// [`read_entry_max`], adding the bytes inflated to `spent` whether or not the read succeeds.
|
||||
fn read_entry_counted(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str, max: u64, spent: &mut u64) -> Result<Vec<u8>> {
|
||||
fn read_entry_max(z: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str, max: u64) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let f = z.by_name(name).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
if f.size() > max {
|
||||
return Err(FormatError::Damaged(format!("{name} is too large")));
|
||||
}
|
||||
let mut out = Vec::with_capacity(f.size().min(64 << 20) as usize);
|
||||
let mut f = f.take(max.saturating_add(1));
|
||||
let read = f.read_to_end(&mut out);
|
||||
*spent = spent.saturating_add(out.len() as u64);
|
||||
read.map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
let mut out = vec![];
|
||||
f.take(max.saturating_add(1)).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||
if out.len() as u64 > max {
|
||||
return Err(FormatError::Damaged(format!("{name} is too large")));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn read_entry(z: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str) -> Result<Vec<u8>> {
|
||||
read_entry_max(z, name, craft_deckcraft_format::MAX_ENTRY)
|
||||
}
|
||||
|
||||
/// Read a presentation. Missing media/chart parts are left empty; use [`load_checked`] to
|
||||
/// learn which. A damaged chart member refuses the file before further chart inflation.
|
||||
pub fn load(bytes: &[u8]) -> Result<Presentation> {
|
||||
@@ -167,19 +72,11 @@ pub fn load(bytes: &[u8]) -> Result<Presentation> {
|
||||
/// A chart member that is present but fails decoding, CRC or its entry limit refuses the file.
|
||||
/// Linked media saved without its bytes isn't damage.
|
||||
pub fn load_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
|
||||
load_within(bytes, Budget { total: MAX_TOTAL_MEDIA, items: MAX_MEDIA_ITEMS, manifest: MAX_MANIFEST })
|
||||
load_within(bytes, Budget::default())
|
||||
}
|
||||
|
||||
fn load_within(bytes: &[u8], budget: Budget) -> Result<(Presentation, Vec<String>)> {
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::NotOurs(e.to_string()))?;
|
||||
if z.index_for_name("presentation.json").is_none() {
|
||||
return Err(FormatError::NotOurs("no presentation.json".into()));
|
||||
}
|
||||
let json = read_entry_max(&mut z, "presentation.json", budget.manifest)?;
|
||||
let m = parse_manifest(&json)?;
|
||||
if m.format != "deckcraft" {
|
||||
return Err(FormatError::NotOurs(m.format));
|
||||
}
|
||||
let (m, mut z) = Package::open_manifest::<Presentation>(bytes, budget.manifest)?;
|
||||
let mut p = m.presentation;
|
||||
let mut damaged = vec![];
|
||||
let items = p.media.len();
|
||||
@@ -192,13 +89,13 @@ fn load_within(bytes: &[u8], budget: Budget) -> Result<(Presentation, Vec<String
|
||||
p.media.retain(|m| seen.insert(m.id));
|
||||
let mut left = budget.total;
|
||||
for item in &mut p.media {
|
||||
let name = format!("media/{}", item.id.0);
|
||||
let linked_only = item.link.is_some() && z.index_for_name(&name).is_none();
|
||||
if z.by_name(&name).is_ok_and(|f| f.size() > left) {
|
||||
let name = media_entry(item.id.0);
|
||||
let linked_only = item.link.is_some() && !z.contains(&name);
|
||||
if z.declared_size(&name).is_some_and(|size| size > left) {
|
||||
return Err(FormatError::Damaged("embedded media is larger than DeckCraft can open".into()));
|
||||
}
|
||||
// A failed read is charged for what it inflated, so later members can't reuse that budget.
|
||||
match read_entry_charged(&mut z, &name, &mut left) {
|
||||
match z.read_charged(&name, &mut left) {
|
||||
Ok(data) => item.data = Arc::new(data),
|
||||
Err(_) if linked_only => {}
|
||||
Err(e) => damaged.push(e.to_string()),
|
||||
@@ -346,100 +243,6 @@ fn add_outline_slides(p: &mut Presentation, slides: OutlineSlides) -> usize {
|
||||
made
|
||||
}
|
||||
|
||||
/// Most `null`s standing in for numbers that [`parse_manifest`] patches in one file, and the
|
||||
/// candidates it tries for each.
|
||||
const MAX_NULL_FIXES: usize = 256;
|
||||
const MAX_TRIES_PER_FIX: usize = 32;
|
||||
/// Bytes [`parse_manifest`] may re-parse in all while patching, so a hostile file full of `null`s
|
||||
/// can't keep it busy: past this the file is reported damaged.
|
||||
const MAX_REPARSE_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Where a parse failed, comparable: later is progress.
|
||||
fn failure(src: &[u8]) -> std::result::Result<Manifest, (String, (usize, usize))> {
|
||||
serde_json::from_slice::<Manifest>(src).map_err(|e| (e.to_string(), (e.line(), e.column())))
|
||||
}
|
||||
|
||||
/// Parse `presentation.json`. serde_json writes a NaN or infinite number as `null`, which then
|
||||
/// fails to read back as a number ("invalid type: null, expected f64"), so DeckCraft could save
|
||||
/// a file it couldn't open. Each such `null` is read as 0 instead ([`repair`] then brings the
|
||||
/// value into range); anything else that doesn't parse is damage.
|
||||
///
|
||||
/// serde reports the failing `null` exactly, except inside tagged enums (buffered), where it
|
||||
/// reports the end of the enclosing object: there the `null`s before that point are tried
|
||||
/// nearest first, and a patch is kept only if the parse then gets further. (Files saved since
|
||||
/// [`finite::Finite`] never contain such `null`s; this reads older ones.)
|
||||
fn parse_manifest(json: &[u8]) -> Result<Manifest> {
|
||||
// Parse the inflated text as it is: only a file that fails on a `null` number is copied for
|
||||
// patching (the copy is bounded by `MAX_MANIFEST`).
|
||||
let mut last = match failure(json) {
|
||||
Ok(m) => return Ok(m),
|
||||
Err(f) => f,
|
||||
};
|
||||
if !is_null_number(&last.0) {
|
||||
return Err(FormatError::Damaged(last.0));
|
||||
}
|
||||
let mut src = json.to_vec();
|
||||
let mut budget = MAX_REPARSE_BYTES;
|
||||
'fixes: for _ in 0..MAX_NULL_FIXES {
|
||||
let (msg, pos) = &last;
|
||||
if !is_null_number(msg) {
|
||||
break;
|
||||
}
|
||||
let end = offset(&src, pos.0, pos.1).unwrap_or(src.len());
|
||||
let mut progressed = false;
|
||||
let candidates: Vec<usize> = value_nulls_before(&src, end + 4).take(MAX_TRIES_PER_FIX).collect();
|
||||
for at in candidates {
|
||||
let (Some(head), Some(tail)) = (src.get(..at), src.get(at.saturating_add(4)..)) else { continue };
|
||||
let Some(left) = budget.checked_sub(src.len()) else { break 'fixes };
|
||||
budget = left;
|
||||
let mut next = Vec::with_capacity(src.len());
|
||||
next.extend_from_slice(head);
|
||||
next.push(b'0');
|
||||
next.extend_from_slice(tail);
|
||||
match failure(&next) {
|
||||
Ok(m) => return Ok(m),
|
||||
// The patch shortened the text by 3 bytes before the error: compare positions
|
||||
// allowing for that.
|
||||
Err(f) if f.1 > (pos.0, pos.1.saturating_sub(3)) => {
|
||||
src = next;
|
||||
last = f;
|
||||
progressed = true;
|
||||
break;
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
if !progressed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(FormatError::Damaged(last.0))
|
||||
}
|
||||
|
||||
/// Is this parse error a `null` where a number belongs (a NaN or infinity serde_json wrote)?
|
||||
fn is_null_number(msg: &str) -> bool {
|
||||
msg.starts_with("invalid type: null, expected f") || msg.starts_with("invalid type: null, expected a number")
|
||||
}
|
||||
|
||||
/// Byte offset of a 1-based `line`:`column`.
|
||||
fn offset(src: &[u8], line: usize, column: usize) -> Option<usize> {
|
||||
let mut start = 0;
|
||||
for _ in 1..line {
|
||||
start += src.get(start..)?.iter().position(|b| *b == b'\n')? + 1;
|
||||
}
|
||||
Some((start + column).min(src.len()))
|
||||
}
|
||||
|
||||
/// Starts of `null` tokens in value position (after `:`, `[` or `,`) before `end`, nearest first.
|
||||
fn value_nulls_before(src: &[u8], end: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
let end = end.min(src.len());
|
||||
(0..end.saturating_sub(3)).rev().filter(move |&i| {
|
||||
src.get(i..i + 4) == Some(b"null")
|
||||
&& src[..i].iter().rev().find(|b| !b.is_ascii_whitespace()).is_some_and(|b| matches!(b, b':' | b'[' | b','))
|
||||
&& src.get(i + 4).is_none_or(|b| !b.is_ascii_alphanumeric())
|
||||
})
|
||||
}
|
||||
|
||||
/// Largest coordinate or size kept, in points (about 350 m; PowerPoint's own limit is far smaller).
|
||||
const MAX_COORD: f64 = 1.0e6;
|
||||
|
||||
|
||||
+102
-29
@@ -10,24 +10,24 @@ use deckcraft_model::text::{Paragraph, RunKind};
|
||||
|
||||
/// RTF-escape `s` (non-ASCII as `\uN?`, UTF-16, signed as RTF wants).
|
||||
fn escape(out: &mut String, s: &str) {
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' | '{' | '}' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\t' => out.push_str("\\tab "),
|
||||
'\u{b}' | '\n' => out.push_str("\\line "),
|
||||
c if c.is_ascii() && !c.is_ascii_control() => out.push(c),
|
||||
c if c.is_ascii() => {}
|
||||
c => {
|
||||
let mut buf = [0u16; 2];
|
||||
for u in c.encode_utf16(&mut buf) {
|
||||
out.push_str(&format!("\\u{}?", *u as i16));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Keep outline text literal: the shared writer also supports page/column breaks and
|
||||
// shorthand controls that this app's deliberately small outline reader does not consume.
|
||||
// Delegate ordinary spans, including UTF-16 escaping, without allocating a second string.
|
||||
let mut start = 0;
|
||||
for (i, c) in s.char_indices() {
|
||||
let replacement = match c {
|
||||
'\u{000C}' | '\u{000E}' => "",
|
||||
'\u{00A0}' => "\\u160?",
|
||||
'\u{00AD}' => "\\u173?",
|
||||
'\u{2011}' => "\\u8209?",
|
||||
'\u{2028}' => "\\u8232?",
|
||||
_ => continue,
|
||||
};
|
||||
craft_rtf::push_esc(out, &s[start..i]);
|
||||
out.push_str(replacement);
|
||||
start = i + c.len_utf8();
|
||||
}
|
||||
craft_rtf::push_esc(out, &s[start..]);
|
||||
}
|
||||
|
||||
fn runs(out: &mut String, p: &Paragraph) {
|
||||
@@ -276,6 +276,9 @@ impl Outline<'_> {
|
||||
while k > 0 && self.i < self.b.len() {
|
||||
if self.b[self.i] == b'\\' && self.b.get(self.i + 1) == Some(&b'\'') {
|
||||
self.i = advance(self.rtf, self.i, 4);
|
||||
} else if self.b[self.i] == b'\\' && self.b.get(self.i + 1).is_some_and(|b| !b.is_ascii_alphabetic()) {
|
||||
// An escaped control symbol counts as one Unicode fallback character.
|
||||
self.i = advance(self.rtf, self.i + 1, 1);
|
||||
} else if matches!(self.b[self.i], b'{' | b'}' | b'\\') {
|
||||
break;
|
||||
} else {
|
||||
@@ -294,7 +297,7 @@ impl Outline<'_> {
|
||||
&& let Some(h) = hex
|
||||
&& h != 0
|
||||
{
|
||||
self.line.push(cp1252(h));
|
||||
self.line.push(craft_rtf::codepage::cp1252(h));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,22 +384,75 @@ fn finish_surrogates(s: String) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn cp1252(b: u8) -> char {
|
||||
const HIGH: [char; 32] = [
|
||||
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—',
|
||||
'˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ',
|
||||
];
|
||||
match b {
|
||||
0x80..=0x9f => HIGH[(b - 0x80) as usize],
|
||||
_ => b as char,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
// Frozen pre-cutover implementations are test oracles, not production parsers.
|
||||
fn legacy_escape(out: &mut String, s: &str) {
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' | '{' | '}' => {
|
||||
out.push('\\');
|
||||
out.push(c);
|
||||
}
|
||||
'\t' => out.push_str("\\tab "),
|
||||
'\u{b}' | '\n' => out.push_str("\\line "),
|
||||
c if c.is_ascii() && !c.is_ascii_control() => out.push(c),
|
||||
c if c.is_ascii() => {}
|
||||
c => {
|
||||
let mut buf = [0u16; 2];
|
||||
for u in c.encode_utf16(&mut buf) {
|
||||
out.push_str(&format!("\\u{}?", *u as i16));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn legacy_cp1252(b: u8) -> char {
|
||||
const HIGH: [char; 32] = [
|
||||
'€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–',
|
||||
'—', '˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ',
|
||||
];
|
||||
match b {
|
||||
0x80..=0x9f => HIGH[(b - 0x80) as usize],
|
||||
_ => b as char,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_escape_preserves_every_unicode_scalar() {
|
||||
for value in 0..=0x10ffff {
|
||||
let Some(c) = char::from_u32(value) else { continue };
|
||||
let mut buf = [0; 4];
|
||||
let text = c.encode_utf8(&mut buf);
|
||||
let mut expected = String::new();
|
||||
let mut actual = String::new();
|
||||
legacy_escape(&mut expected, text);
|
||||
escape(&mut actual, text);
|
||||
assert_eq!(actual, expected, "U+{value:04X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_escape_preserves_mixed_spans_and_append() {
|
||||
let text = "a\t中\u{a0}b\u{ad}c\u{2011}d\u{2028}e\u{c}f\u{e}g\n😀{}\\";
|
||||
let mut expected = String::from("prefix:");
|
||||
let mut actual = expected.clone();
|
||||
legacy_escape(&mut expected, text);
|
||||
escape(&mut actual, text);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_cp1252_preserves_all_bytes() {
|
||||
for b in 0..=u8::MAX {
|
||||
assert_eq!(craft_rtf::codepage::cp1252(b), legacy_cp1252(b));
|
||||
}
|
||||
}
|
||||
|
||||
/// A sign in a `\'hh` escape is not a hex digit and must be ignored.
|
||||
#[test]
|
||||
fn hex_escape_rejects_sign() {
|
||||
@@ -422,6 +478,23 @@ mod tests {
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1 x\u-70000?y\par}"), "x\u{ee90}y\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_fallback_control_symbols_are_skipped() {
|
||||
for (rtf, expected) in [
|
||||
(r"{\rtf1\uc1 \u92\\X\par}", "\\X\n"),
|
||||
(r"{\rtf1\uc1 \u123\{X\par}", "{X\n"),
|
||||
(r"{\rtf1\uc1 \u125\}X\par}", "}X\n"),
|
||||
(r"{\rtf1\uc2 \u233\{\}X\par}", "éX\n"),
|
||||
(r"{\rtf1\uc0 \u92\\X\par}", "\\\\X\n"),
|
||||
(r"{\rtf1 \\ \{ \}X\par}", "\\ { }X\n"),
|
||||
(r"{\rtf1\uc1 \u233{X}\par}", "éX\n"),
|
||||
(r"{\rtf1\uc1 \u233\éX\par}", "éX\n"),
|
||||
(r"{\rtf1\uc1 \u233\", "é\n"),
|
||||
] {
|
||||
assert_eq!(rtf_to_outline(rtf), expected, "{rtf:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multibyte_control_symbol_keeps_character_and_following_text() {
|
||||
assert_eq!(rtf_to_outline("{\\rtf1 A\\éB\\par}"), "AéB\n");
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::*;
|
||||
use craft_deckcraft_format::{Manifest, parse_manifest};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
#[test]
|
||||
fn chart_sidecars_are_optional_for_older_native_files() {
|
||||
@@ -364,7 +366,7 @@ fn reflection_transform_survives_two_native_saves_and_absent_fields_stay_absent(
|
||||
assert_eq!(reopened.slides[0].shapes.last().and_then(|s| s.effects.as_ref()).and_then(|e| e.reflection.as_ref()), Some(&absent));
|
||||
}
|
||||
|
||||
/// Files written before [`finite::Finite`] (plain serde_json: NaN as `null`) open too,
|
||||
/// Files written before [`craft_deckcraft_format::Finite`] (plain serde_json: NaN as `null`) open too,
|
||||
/// including a `null` inside a tagged enum, where serde reports only the enclosing object.
|
||||
#[test]
|
||||
fn older_files_with_null_numbers_open() {
|
||||
@@ -387,7 +389,7 @@ fn older_files_with_null_numbers_open() {
|
||||
let m = Manifest { format: "deckcraft".into(), version: VERSION, generator: "old".into(), presentation: p };
|
||||
let json = serde_json::to_vec(&m).unwrap();
|
||||
assert!(json.windows(4).any(|w| w == b"null"));
|
||||
let back = parse_manifest(&json).unwrap_or_else(|e| panic!("case {case}: {e}"));
|
||||
let back = parse_manifest::<Presentation>(&json).unwrap_or_else(|e| panic!("case {case}: {e}"));
|
||||
assert_eq!(back.presentation.slides[0].shapes.len(), m.presentation.slides[0].shapes.len(), "case {case}");
|
||||
}
|
||||
}
|
||||
@@ -419,14 +421,14 @@ fn a_bare_normautofit_body_round_trips() {
|
||||
#[test]
|
||||
fn other_damage_is_still_reported() {
|
||||
let ok = serde_json::to_vec(&serde_json::json!({"format": "deckcraft", "version": 1, "generator": "t", "presentation": {}})).unwrap();
|
||||
assert!(parse_manifest(&ok).is_ok());
|
||||
assert!(parse_manifest::<Presentation>(&ok).is_ok());
|
||||
let bad = br#"{"format": null, "version": 1, "generator": "t", "presentation": {}}"#;
|
||||
assert!(parse_manifest(bad).is_err());
|
||||
assert!(parse_manifest::<Presentation>(bad).is_err());
|
||||
let truncated = &ok[..ok.len() - 3];
|
||||
assert!(parse_manifest(truncated).is_err());
|
||||
assert!(parse_manifest::<Presentation>(truncated).is_err());
|
||||
// A null number on a later line (pretty-printed by another tool) is found too.
|
||||
let pretty = b"{\n \"format\": \"deckcraft\",\n \"version\": 1,\n \"generator\": \"t\",\n \"presentation\": {\"slides\": [{\"shapes\": [{\"xfrm\": {\"x\": null, \"y\": 1, \"w\": 2, \"h\": 3}}]}]}\n}";
|
||||
let m = parse_manifest(pretty).unwrap_or_else(|e| panic!("{e}"));
|
||||
let m = parse_manifest::<Presentation>(pretty).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(m.presentation.slides[0].shapes[0].xfrm.unwrap().x, 0.0);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Golden files are compared byte for byte: no line-ending conversion on checkout.
|
||||
* -text
|
||||
@@ -0,0 +1 @@
|
||||
{"damaged":["damaged file: media/1: specified file not found in archive","chart-parts/1: missing chart part"],"media":[[1,""],[2,"3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e"],[3,"0000001866747970"],[4,""]]}
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -10,8 +10,8 @@
|
||||
/// Cyrillic, CJK…) give `false`. Neutral, weak, and whitespace characters are skipped.
|
||||
pub fn first_strong_is_rtl(text: &str) -> bool {
|
||||
for c in text.chars() {
|
||||
if c == '\u{200F}' {
|
||||
// Right-to-Left Mark (RLM)
|
||||
if c == '\u{200F}' || c == '\u{061C}' {
|
||||
// RLM and ALM are strong RTL controls, although neither is alphabetic.
|
||||
return true;
|
||||
}
|
||||
if c == '\u{200E}' {
|
||||
@@ -76,6 +76,10 @@ mod tests {
|
||||
#[test]
|
||||
fn honours_directional_marks() {
|
||||
assert!(first_strong_is_rtl("\u{200F}Hello"));
|
||||
assert!(first_strong_is_rtl("\u{061C}Hello"));
|
||||
assert!(first_strong_is_rtl("\u{061C}"));
|
||||
assert!(!first_strong_is_rtl("Hello\u{061C}"));
|
||||
assert!(!first_strong_is_rtl("\u{200E}\u{061C}"));
|
||||
assert!(!first_strong_is_rtl("\u{200E}مرحبا"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::text::{Paragraph, Run, RunKind, RunProps, TextBody};
|
||||
use crate::words;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
/// (paragraph, char offset in the paragraph).
|
||||
pub type Pos = (usize, usize);
|
||||
@@ -419,6 +420,21 @@ fn smart_space(body: &mut TextBody, at: Pos) -> Pos {
|
||||
at
|
||||
}
|
||||
|
||||
/// The position after the grapheme cluster at `pos`, or the next paragraph's start at a paragraph end.
|
||||
pub fn cluster_end(body: &TextBody, pos: Pos) -> Pos {
|
||||
let (pi, ch) = clamp(body, pos);
|
||||
let text = body.paragraphs.get(pi).map(Paragraph::text).unwrap_or_default();
|
||||
// Boundaries come from the whole paragraph, so a caret inside a cluster deletes only to its end.
|
||||
let mut end = 0;
|
||||
for g in text.graphemes(true) {
|
||||
end += g.chars().count();
|
||||
if end > ch {
|
||||
return (pi, end);
|
||||
}
|
||||
}
|
||||
char_move(body, pos, true)
|
||||
}
|
||||
|
||||
/// One character left/right across paragraph boundaries.
|
||||
pub fn char_move(body: &TextBody, pos: Pos, forward: bool) -> Pos {
|
||||
let (pi, ch) = clamp(body, pos);
|
||||
@@ -512,6 +528,12 @@ pub fn change_case(s: &str, mode: &str) -> String {
|
||||
/// `title` and `sentence` carry their word/sentence state across piece boundaries. Each output
|
||||
/// piece is the changed form of the matching input piece, even where a character changes length.
|
||||
pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec<String> {
|
||||
if mode == "lower" {
|
||||
let lower = parts.concat().to_lowercase();
|
||||
let mut chars = lower.chars();
|
||||
// Context changes sigma's form, while each character's expansion length stays the same.
|
||||
return parts.iter().map(|s| chars.by_ref().take(s.chars().map(|c| c.to_lowercase().count()).sum()).collect()).collect();
|
||||
}
|
||||
let mut start = true;
|
||||
// All characters of all pieces, so word-final sigma sees neighbours across piece boundaries.
|
||||
let all: Vec<char> = parts.iter().flat_map(|s| s.chars()).collect();
|
||||
@@ -520,7 +542,6 @@ pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec<String> {
|
||||
.iter()
|
||||
.map(|s| match mode {
|
||||
"upper" => s.to_uppercase(),
|
||||
"lower" => s.to_lowercase(),
|
||||
"toggle" => s.chars().map(|c| if c.is_uppercase() { c.to_lowercase().collect::<String>() } else { c.to_uppercase().collect() }).collect(),
|
||||
_ => {
|
||||
// `title` restarts after whitespace, sentence case after sentence punctuation.
|
||||
@@ -577,6 +598,18 @@ mod tests {
|
||||
assert_eq!(change_case_parts(&["ΟΔΟΣ", " ΜΟΥ"], "title"), ["Οδος", " Μου"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowercase_keeps_context_and_run_boundaries() {
|
||||
assert_eq!(change_case_parts(&["ΟΔΟ", "Σ"], "lower"), ["οδο", "ς"]);
|
||||
assert_eq!(change_case_parts(&["ΟΣ", "Α"], "lower"), ["οσ", "α"]);
|
||||
assert_eq!(change_case_parts(&["", "ΟΔΟ", "", "Σ", ""], "lower"), ["", "οδο", "", "ς", ""]);
|
||||
assert_eq!(change_case_parts(&["İΟΔΟ", "Σ"], "lower"), ["i\u{307}οδο", "ς"]);
|
||||
assert_eq!(change_case_parts(&["Ο", "\u{301}", "Σ"], "lower"), ["ο", "\u{301}", "ς"]);
|
||||
assert_eq!(change_case_parts(&["ΟΣ", "\u{301}", "Α"], "lower"), ["οσ", "\u{301}", "α"]);
|
||||
assert_eq!(change_case_parts(&["", "", ""], "lower"), ["", "", ""]);
|
||||
assert!(change_case_parts(&[], "lower").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_and_split() {
|
||||
let mut b = body("Hello");
|
||||
|
||||
@@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option<String> {
|
||||
m *= 10.0;
|
||||
exp -= 1;
|
||||
}
|
||||
// Rounding the mantissa to its digits can reach 10 (9.999 as `0.00`).
|
||||
if format!("{m:.mant_frac$}").starts_with("10") {
|
||||
m /= 10.0;
|
||||
exp += 1;
|
||||
}
|
||||
}
|
||||
let step = mant.iter().take_while(|t| **t != Tok::Dot).filter(|t| matches!(t, Tok::Digit(_))).count().max(1) as i32;
|
||||
let shift = exp.rem_euclid(step);
|
||||
exp -= shift;
|
||||
m *= 10f64.powi(shift);
|
||||
// Round after forming the engineering mantissa: 999.94 as `##0.0` stays 999.9.
|
||||
// Carry only when rounding exceeds all of the format's integer placeholders.
|
||||
let carry = 10f64.powi(step);
|
||||
if format!("{m:.mant_frac$}").parse::<f64>().is_ok_and(|rounded| rounded >= carry) {
|
||||
m /= carry;
|
||||
exp += step;
|
||||
}
|
||||
let mantissa = fixed(mant, mfirst, mlast, m, sep, dec);
|
||||
let sign = if exp < 0 {
|
||||
"-"
|
||||
@@ -404,6 +406,21 @@ mod tests {
|
||||
assert_eq!(format("##0.0E+0", 999.96, None), "1.0E+3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engineering_formats_round_the_full_mantissa() {
|
||||
for (code, value, expected) in [
|
||||
("##0.0E+00", 999.94, "999.9E+00"),
|
||||
("##0.0E+00", 0.99994, "999.9E-03"),
|
||||
("##0.0E+00", -999.94, "-999.9E+00"),
|
||||
("#0.0E+00", 99.94, "99.9E+00"),
|
||||
("##0.0E+00", 999.96, "1.0E+03"),
|
||||
("#0.0E+00", 99.96, "1.0E+02"),
|
||||
] {
|
||||
assert_eq!(format(code, value, None), expected, "{code}, {value}");
|
||||
}
|
||||
assert_eq!(format("##0.0E+00", 999.94, Some("de-DE")), "999,9E+00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_panics() {
|
||||
for code in ["", ";", ";;;", "\"", "[", "\\", "0.", ".", "#,", "%", "_", "*", "@", "0E+00", "[$", "\"unterminated"] {
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-xml.workspace = true
|
||||
deckcraft-model = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
|
||||
|
||||
/// [`import`], plus the part names of slides the file lists but that couldn't be read and were
|
||||
/// left out.
|
||||
/// Files with more than 10,000 slide-list entries return [`PptxError::Unsupported`] instead of a truncated presentation.
|
||||
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
|
||||
read::import_checked(bytes)
|
||||
}
|
||||
|
||||
+24
-6
@@ -554,12 +554,15 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
|
||||
import_checked(bytes).map(|(p, _)| p)
|
||||
}
|
||||
|
||||
/// [`import`], plus the parts of the slide list the file names but that couldn't be read (a
|
||||
/// missing or truncated slide): those slides are left out, so a caller can say so (#203).
|
||||
/// [`import`], plus the slides the file's slide list names but that couldn't be read (a missing
|
||||
/// or truncated slide part, or an entry whose relationship is missing): those slides are left
|
||||
/// out, so a caller can say so (#203).
|
||||
pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxError> {
|
||||
import_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS)
|
||||
}
|
||||
|
||||
const MAX_SLIDE_ENTRIES: usize = 10_000;
|
||||
|
||||
/// [`import_checked`] with the presentation's chart point budget set (tests lower it).
|
||||
pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec<String>), PptxError> {
|
||||
let mut lost_slides: Vec<String> = vec![];
|
||||
@@ -571,9 +574,15 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
|
||||
if !pres_el.is("presentation") {
|
||||
return Err(PptxError::NotPptx(format!("{pres_path} is not a presentation part")));
|
||||
}
|
||||
// Refuse an oversized list before reading slide parts: truncating it would look like a
|
||||
// complete import and allow a later save to overwrite the omitted slides (#1910).
|
||||
// Looking only for the first entry past the cap keeps this check bounded.
|
||||
if pres_el.child("sldIdLst").is_some_and(|list| list.children_named("sldId").nth(MAX_SLIDE_ENTRIES).is_some()) {
|
||||
return Err(PptxError::Unsupported(format!("PPTX slide list exceeds the {MAX_SLIDE_ENTRIES}-entry import limit")));
|
||||
}
|
||||
let pres_part = Part::new(&pkg, &pres_path, &pres_doc);
|
||||
|
||||
let (master_paths, slide_entries) = master_and_slide_paths(pres_el, &pres_part);
|
||||
let (master_paths, slide_entries) = master_and_slide_paths(pres_el, &pres_part, &mut lost_slides);
|
||||
let (docs, max_id) = load_part_docs(&pkg, &master_paths, &slide_entries);
|
||||
|
||||
let mut imp = Imp {
|
||||
@@ -630,7 +639,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) ->
|
||||
|
||||
/// Masters, layouts and slides to read, in file order and without duplicates: (master paths,
|
||||
/// (file slide id, slide path)).
|
||||
fn master_and_slide_paths(pres_el: &El, pres_part: &Part) -> (Vec<String>, Vec<(u32, String)>) {
|
||||
fn master_and_slide_paths(pres_el: &El, pres_part: &Part, lost_slides: &mut Vec<String>) -> (Vec<String>, Vec<(u32, String)>) {
|
||||
let master_paths: Vec<String> = pres_el
|
||||
.child("sldMasterIdLst")
|
||||
.map(|l| l.children_named("sldMasterId").filter_map(|m| pres_part.rels.target(m.attr("r:id").unwrap_or(""))).map(String::from).collect())
|
||||
@@ -641,8 +650,17 @@ fn master_and_slide_paths(pres_el: &El, pres_part: &Part) -> (Vec<String>, Vec<(
|
||||
.child("sldIdLst")
|
||||
.map(|l| {
|
||||
l.children_named("sldId")
|
||||
.take(10_000)
|
||||
.filter_map(|s| Some((s.u32("id").unwrap_or(0), pres_part.rels.target(s.attr("r:id").unwrap_or(""))?.to_string())))
|
||||
.take(MAX_SLIDE_ENTRIES)
|
||||
.filter_map(|s| {
|
||||
let rid = s.attr("r:id").unwrap_or("");
|
||||
let Some(path) = pres_part.rels.target(rid) else {
|
||||
// A missing relationship still represents a lost slide. Report it so
|
||||
// the engine opens a repaired copy instead of overwriting the original.
|
||||
lost_slides.push(format!("slide {} (missing relationship {rid})", s.u32("id").unwrap_or(0)));
|
||||
return None;
|
||||
};
|
||||
Some((s.u32("id").unwrap_or(0), path.to_string()))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -389,8 +389,11 @@ fn read_series(s: &El, g: &El, group: (ChartType, bool, Option<bool>), categorie
|
||||
secondary_axis: secondary,
|
||||
..Default::default()
|
||||
};
|
||||
// `<c:dLbls><c:delete val="1"/>` hides every label of the series, whatever the group says.
|
||||
if s.path(&["dLbls", "delete"]).map(|v| v.bool("val").unwrap_or(true)) == Some(true) {
|
||||
ser.data_labels = Some(false);
|
||||
// `<c:showVal/>` without a val attribute means true, as in the schema's default.
|
||||
if let Some(d) = s.child("dLbls").and_then(|d| d.child("showVal")).map(|v| v.bool("val").unwrap_or(true)) {
|
||||
} else if let Some(d) = s.child("dLbls").and_then(|d| d.child("showVal")).map(|v| v.bool("val").unwrap_or(true)) {
|
||||
ser.data_labels = Some(d);
|
||||
} else if let Some(false) = group_labels {
|
||||
// The group asks for no labels and the series does not say otherwise.
|
||||
|
||||
@@ -126,7 +126,7 @@ fn flat_starts(anims: &[&Animation]) -> Vec<u32> {
|
||||
/// a click group listed out of time order, whose flat reading disagrees with the file, is sorted by
|
||||
/// start time and its starts and delays rewritten to land every effect where PowerPoint plays it.
|
||||
/// Every other group is left untouched.
|
||||
fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool)], at: &[(Option<u32>, usize, u32)]) {
|
||||
fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool, usize, u32)], at: &[(Option<u32>, usize, u32)]) {
|
||||
let mut groups: Vec<Vec<usize>> = vec![];
|
||||
let mut slot: std::collections::HashMap<(Option<u32>, usize), usize> = std::collections::HashMap::new();
|
||||
for (i, &(t, g, _)) in at.iter().enumerate() {
|
||||
@@ -155,7 +155,7 @@ fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool)], at: &[(Opt
|
||||
let had_click = out[idx[0]].0.start == AnimStart::OnClick;
|
||||
let mut order: Vec<usize> = (0..idx.len()).collect();
|
||||
order.sort_by_key(|&k| abs[k]);
|
||||
let mut sorted: Vec<(Animation, u32, String, bool)> = order.iter().map(|&k| out[idx[k]].clone()).collect();
|
||||
let mut sorted: Vec<(Animation, u32, String, bool, usize, u32)> = order.iter().map(|&k| out[idx[k]].clone()).collect();
|
||||
let (mut begin, mut end) = (0u32, 0u32);
|
||||
for (n, (&k, item)) in order.iter().zip(sorted.iter_mut()).enumerate() {
|
||||
let a = &mut item.0;
|
||||
@@ -170,6 +170,7 @@ fn place_by_parent_delays(out: &mut [(Animation, u32, String, bool)], at: &[(Opt
|
||||
a.start = AnimStart::WithPrevious;
|
||||
a.delay_ms = t.saturating_sub(begin);
|
||||
}
|
||||
item.5 = 0;
|
||||
end = end.max(t.saturating_add(span_ms(a)));
|
||||
}
|
||||
for (&i, item) in idx.iter().zip(sorted) {
|
||||
@@ -239,17 +240,19 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes:
|
||||
let Some(tn) = timing.child("tnLst") else { return vec![] };
|
||||
let mut found = vec![];
|
||||
collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0);
|
||||
// Paragraph builds (`bldP build="p"`) by (spid, grpId).
|
||||
let by_para: Vec<(u32, String)> = timing
|
||||
// Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`.
|
||||
let bld_p: std::collections::HashMap<(u32, String), bool> = timing
|
||||
.child("bldLst")
|
||||
.map(|b| {
|
||||
b.children_named("bldP")
|
||||
.filter(|p| p.attr("build") == Some("p"))
|
||||
.filter_map(|p| Some((p.u32("spid")?, p.attr("grpId").unwrap_or("0").to_string())))
|
||||
.collect()
|
||||
.filter_map(|p| Some(((p.u32("spid")?, p.attr("grpId").unwrap_or("0").to_string()), p.attr("build") == Some("p"))))
|
||||
.fold(std::collections::HashMap::new(), |mut m, (k, v)| {
|
||||
m.entry(k).and_modify(|e| *e |= v).or_insert(v);
|
||||
m
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut out: Vec<(Animation, u32, String, bool)> = vec![];
|
||||
let mut out: Vec<(Animation, u32, String, bool, usize, u32)> = vec![];
|
||||
let mut at: Vec<(Option<u32>, usize, u32)> = vec![];
|
||||
for f in found {
|
||||
let c = f.ctn;
|
||||
@@ -314,23 +317,27 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes:
|
||||
a.color = dml::color(clr);
|
||||
}
|
||||
let grp = c.attr("grpId").unwrap_or("0").to_string();
|
||||
let build = paragraph.is_some() && by_para.iter().any(|(s, g)| *s == file_id && *g == grp);
|
||||
out.push((a, file_id, grp, build));
|
||||
let build = paragraph.is_some() && bld_p.get(&(file_id, grp.clone())) != Some(&false);
|
||||
out.push((a, file_id, grp, build, f.group, f.offset));
|
||||
at.push((f.trigger, f.group, f.offset));
|
||||
}
|
||||
place_by_parent_delays(&mut out, &at);
|
||||
// A paragraph build's effects, one per paragraph, become one by-paragraph animation only when
|
||||
// the timeline plays that back exactly: PowerPoint lets each paragraph keep its own start and
|
||||
// effect, and other shapes' effects can sit between them (#844).
|
||||
let same_build =
|
||||
|x: &(Animation, u32, String, bool), y: &(Animation, u32, String, bool)| x.3 && y.3 && x.1 == y.1 && x.2 == y.2 && x.0.trigger == y.0.trigger;
|
||||
let same_build = |x: &(Animation, u32, String, bool, usize, u32), y: &(Animation, u32, String, bool, usize, u32)| {
|
||||
x.3 && y.3 && x.1 == y.1 && x.2 == y.2 && x.0.trigger == y.0.trigger
|
||||
};
|
||||
let mut anims = Vec::with_capacity(out.len());
|
||||
for run in out.chunk_by(same_build) {
|
||||
let effects: Vec<&Animation> = run.iter().map(|(a, ..)| a).collect();
|
||||
let offsets: Vec<u32> = run.iter().map(|r| r.5).collect();
|
||||
let build = run.first().is_some_and(|r| r.3);
|
||||
let explicit_bld = run.first().is_some_and(|r| bld_p.get(&(r.1, r.2.clone())) == Some(&true));
|
||||
let same_click_group = run.first().is_some_and(|first| first.0.start == AnimStart::OnClick || run.iter().all(|r| r.4 == first.4));
|
||||
let text = effects.first().and_then(|a| find_shape(shapes, a.shape)).and_then(|s| s.text.as_ref());
|
||||
match (effects.first(), text) {
|
||||
(Some(first), Some(text)) if build && plays_as_build(&effects, text) => {
|
||||
(Some(first), Some(text)) if build && (explicit_bld || same_click_group) && plays_as_build(&effects, &offsets, text, explicit_bld) => {
|
||||
anims.push(Animation { text_build: TextBuild::ByParagraph, paragraph: None, ..(*first).clone() });
|
||||
}
|
||||
_ => anims.extend(effects.into_iter().cloned()),
|
||||
@@ -343,7 +350,7 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes:
|
||||
/// first one plays: one effect per paragraph the build animates, in paragraph order, later top
|
||||
/// paragraphs on click (after previous when the build doesn't start on click), deeper ones with
|
||||
/// their parent, all with the same settings?
|
||||
fn plays_as_build(effects: &[&Animation], text: &TextBody) -> bool {
|
||||
fn plays_as_build(effects: &[&Animation], offsets: &[u32], text: &TextBody, explicit_bld: bool) -> bool {
|
||||
let roles = paragraph_build_roles(text);
|
||||
let expected = roles.iter().enumerate().filter(|(i, r)| match r {
|
||||
BuildRole::Top => true,
|
||||
@@ -351,6 +358,16 @@ fn plays_as_build(effects: &[&Animation], text: &TextBody) -> bool {
|
||||
BuildRole::Unowned => false,
|
||||
});
|
||||
let Some(first) = effects.first() else { return false };
|
||||
let off0 = offsets.first().copied().unwrap_or(0);
|
||||
let flat = flat_starts(effects);
|
||||
let parent_starts_match = offsets
|
||||
.iter()
|
||||
.zip(effects.iter())
|
||||
.zip(flat.iter())
|
||||
.all(|((&off, a), &ft)| off == off0 || off.saturating_add(a.delay_ms) == off0.saturating_add(ft));
|
||||
if !explicit_bld && (!parent_starts_match || (first.start != AnimStart::OnClick && (span_ms(first) != 500 || first.delay_ms != 0 || off0 != 0))) {
|
||||
return false;
|
||||
}
|
||||
let settings = |a: &Animation| Animation { start: AnimStart::OnClick, paragraph: None, ..a.clone() };
|
||||
let base = settings(first);
|
||||
let mut matched = 0;
|
||||
|
||||
@@ -794,11 +794,11 @@ fn master_xml(x: &mut Exp, o: &mut Out, m: &Master, layouts: &[(u64, String)]) -
|
||||
}
|
||||
w.close("p:sldLayoutIdLst");
|
||||
w.open0("p:txStyles");
|
||||
let (dt, db, dother) = defaults::master_styles();
|
||||
let pick = |s: &deckcraft_model::text::ListStyle, d: deckcraft_model::text::ListStyle| if s.is_empty() { d } else { s.clone() };
|
||||
dml::list_style(&mut w, x, o, "p:titleStyle", &pick(&m.title_style, dt));
|
||||
dml::list_style(&mut w, x, o, "p:bodyStyle", &pick(&m.body_style, db));
|
||||
dml::list_style(&mut w, x, o, "p:otherStyle", &pick(&m.other_style, dother));
|
||||
// An imported empty body style has no bullets; saving must not author defaults into it.
|
||||
// New decks already carry their populated master styles in the model.
|
||||
dml::list_style(&mut w, x, o, "p:titleStyle", &m.title_style);
|
||||
dml::list_style(&mut w, x, o, "p:bodyStyle", &m.body_style);
|
||||
dml::list_style(&mut w, x, o, "p:otherStyle", &m.other_style);
|
||||
w.close("p:txStyles");
|
||||
ext_list(&mut w, ext_children(m.raw_ext.as_deref()).as_deref());
|
||||
w.close("p:sldMaster");
|
||||
|
||||
@@ -106,7 +106,9 @@ pub fn geometry(w: &mut W, g: &Geom) {
|
||||
let single = !adj1 && if defaults.is_empty() { vals.len() == 1 } else { defaults.len() == 1 };
|
||||
for (i, v) in vals.iter().enumerate() {
|
||||
let n = if single && i == 0 { "adj".to_string() } else { format!("adj{}", i + 1) };
|
||||
let v = if v.is_finite() { v.round().clamp(-2.0e9, 2.0e9) as i64 } else { 0 };
|
||||
// A near-zero-width connector can need a large ratio for an ordinary-size bend.
|
||||
// Keep guide literals bounded to the signed integer serialization domain.
|
||||
let v = if v.is_finite() { v.round().clamp(i64::MIN as f64, i64::MAX as f64) as i64 } else { 0 };
|
||||
w.empty("a:gd", A::new().a("name", n).a("fmla", format!("val {v}")));
|
||||
}
|
||||
for (n, v) in extra_guides(name) {
|
||||
@@ -303,7 +305,8 @@ pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth
|
||||
w.close("p:nvPicPr");
|
||||
dml::blip_fill(w, x, o, "p:blipFill", fill);
|
||||
let mut s2 = s.clone();
|
||||
if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background | Fill::Group)) {
|
||||
// Group fill is a separate backing behind transparent image pixels.
|
||||
if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background)) {
|
||||
s2.fill = None;
|
||||
}
|
||||
sp_pr(w, x, o, &s2, true);
|
||||
@@ -940,7 +943,7 @@ fn shape_with_id(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, i
|
||||
// As for any picture, a colour or pattern fill shows behind the image (an object's preview
|
||||
// keeps its fallback picture's fill).
|
||||
let mut s2 = s.clone();
|
||||
if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background | Fill::Group)) {
|
||||
if matches!(s2.fill, Some(Fill::Picture(_) | Fill::Background)) {
|
||||
s2.fill = None;
|
||||
}
|
||||
sp_pr(w, x, o, &s2, true);
|
||||
@@ -1031,6 +1034,23 @@ pub fn tree_header(w: &mut W) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn guide_literals_remain_finite_bounded_integers() {
|
||||
for (guide, expected) in [
|
||||
(f64::NAN, 0),
|
||||
(f64::INFINITY, 0),
|
||||
(f64::NEG_INFINITY, 0),
|
||||
(f64::MAX, i64::MAX),
|
||||
(f64::MIN, i64::MIN),
|
||||
(12500.6, 12501),
|
||||
(-12500.6, -12501),
|
||||
] {
|
||||
let mut w = W::frag();
|
||||
geometry(&mut w, &Geom::Preset { name: "bentConnector3".into(), adj: vec![guide] });
|
||||
assert!(w.s.contains(&format!(r#"fmla="val {expected}""#)), "{}", w.s);
|
||||
}
|
||||
}
|
||||
|
||||
/// PowerPoint asks to repair a `star5` whose guide list lacks `hf`/`vf` (found black-box).
|
||||
#[test]
|
||||
fn preset_guides_are_complete() {
|
||||
|
||||
+33
-39
@@ -354,45 +354,8 @@ fn decode_utf16(bytes: &[u8]) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `c` allowed in XML 1.0 text?
|
||||
fn xml_char(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\r') || (c >= ' ' && c != '\u{FFFE}' && c != '\u{FFFF}')
|
||||
}
|
||||
|
||||
/// Escape text content (and drop characters XML 1.0 forbids).
|
||||
pub fn esc(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'\r' => o.push_str(" "),
|
||||
c if xml_char(c) => o.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Escape an attribute value.
|
||||
pub fn esc_attr(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'"' => o.push_str("""),
|
||||
'\n' => o.push_str(" "),
|
||||
'\r' => o.push_str(" "),
|
||||
'\t' => o.push_str("	"),
|
||||
c if xml_char(c) => o.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
// Preserve the public writer helpers while sharing the XML 1.0 escaping rules.
|
||||
pub use craft_xml::{esc, esc_attr};
|
||||
|
||||
/// A string builder for XML parts.
|
||||
#[derive(Default)]
|
||||
@@ -542,6 +505,37 @@ mod tests {
|
||||
assert_eq!(esc_attr("\"x\"\n"), ""x" ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_escaping_preserves_xml_wire_bytes() {
|
||||
let text = "&<>\"'\t\n\r\0\u{b}\u{fffe}\u{ffff}é😀 ";
|
||||
assert_eq!(esc(text), "&<>\"'\t\n é😀&#13;");
|
||||
assert_eq!(esc_attr(text), "&<>"'	 é😀&#13;");
|
||||
assert_eq!(esc(""), "");
|
||||
assert_eq!(esc_attr(""), "");
|
||||
for code in 0..32 {
|
||||
let c = char::from_u32(code).unwrap();
|
||||
let text = c.to_string();
|
||||
match c {
|
||||
'\t' => {
|
||||
assert_eq!(esc(&text), "\t");
|
||||
assert_eq!(esc_attr(&text), "	");
|
||||
}
|
||||
'\n' => {
|
||||
assert_eq!(esc(&text), "\n");
|
||||
assert_eq!(esc_attr(&text), " ");
|
||||
}
|
||||
'\r' => {
|
||||
assert_eq!(esc(&text), " ");
|
||||
assert_eq!(esc_attr(&text), " ");
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(esc(&text), "");
|
||||
assert_eq!(esc_attr(&text), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_serialize() {
|
||||
let d = parse(b"<p:sp a=\"1\"><p:t>x & y</p:t><e/></p:sp>").unwrap();
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A series-level `c:dLbls/c:delete val="1"` hides that series' labels although the
|
||||
//! chart-wide `showVal` is on (#1977).
|
||||
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_geom::Xfrm;
|
||||
use deckcraft_model::chart::{Chart, ChartType};
|
||||
use deckcraft_model::{LayoutType, Presentation, Shape, ShapeId, ShapeKind, defaults};
|
||||
|
||||
fn bar_chart_pptx() -> Vec<u8> {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
p.slides.clear();
|
||||
let layout = defaults::layout_of_kind(&p, LayoutType::Blank).unwrap_or_default();
|
||||
let mut slide = defaults::new_slide(&mut p, layout).expect("slide");
|
||||
let mut shape =
|
||||
Shape { id: ShapeId(p.alloc_id().expect("id")), name: "Bars".into(), xfrm: Some(Xfrm::new(40.0, 40.0, 400.0, 300.0)), ..Default::default() };
|
||||
let mut chart = Chart::sample(ChartType::Column);
|
||||
chart.data_labels = false;
|
||||
for s in &mut chart.series {
|
||||
s.data_labels = None;
|
||||
}
|
||||
shape.kind = ShapeKind::Chart(Box::new(chart));
|
||||
slide.shapes.push(shape);
|
||||
p.slides.push(Arc::new(slide));
|
||||
deckcraft_pptx::export(&p).expect("export")
|
||||
}
|
||||
|
||||
fn reimport(bytes: &[u8], f: impl Fn(&str) -> String) -> Presentation {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let opts = zip::write::SimpleFileOptions::default();
|
||||
for i in 0..zip.len() {
|
||||
let mut entry = zip.by_index(i).expect("entry");
|
||||
let name = entry.name().to_string();
|
||||
let mut data = vec![];
|
||||
entry.read_to_end(&mut data).expect("read");
|
||||
if name.starts_with("ppt/charts/chart") && name.ends_with(".xml") && !name.contains("_rels") {
|
||||
let xml = String::from_utf8(data).expect("chart xml");
|
||||
data = f(&xml).into_bytes();
|
||||
}
|
||||
out.start_file(&name, opts).expect("start");
|
||||
out.write_all(&data).expect("write");
|
||||
}
|
||||
let patched = out.finish().expect("finish").into_inner();
|
||||
deckcraft_pptx::import(&patched).expect("import")
|
||||
}
|
||||
|
||||
fn chart_of(p: &Presentation) -> &Chart {
|
||||
let s = p.slides.first().expect("slide");
|
||||
for sh in &s.shapes {
|
||||
if let ShapeKind::Chart(c) = &sh.kind {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
panic!("no chart in the deck");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn series_dlbls_delete_hides_that_series_labels() {
|
||||
let p = reimport(&bar_chart_pptx(), |xml| {
|
||||
xml.replacen("<c:cat>", r#"<c:dLbls><c:delete val="1"/></c:dLbls><c:cat>"#, 1).replacen(
|
||||
"<c:gapWidth",
|
||||
r#"<c:dLbls><c:showVal val="1"/></c:dLbls><c:gapWidth"#,
|
||||
1,
|
||||
)
|
||||
});
|
||||
let c = chart_of(&p);
|
||||
assert!(c.data_labels, "the group-level showVal turns labels on");
|
||||
assert_eq!(c.series[0].data_labels, Some(false), "the deleted series has no labels");
|
||||
assert!(!c.series_data_labels(&c.series[0]), "so its labels are not drawn");
|
||||
assert!(c.series_data_labels(&c.series[1]), "the next series shows the chart-wide labels");
|
||||
}
|
||||
@@ -316,3 +316,99 @@ fn left_of(p: &Presentation) -> ShapeId {
|
||||
fn right_of(p: &Presentation) -> ShapeId {
|
||||
by_name(p, "Right").id
|
||||
}
|
||||
|
||||
/// Return a copy of the `.pptx` archive `bytes` with `entry_name` rewritten by `f`.
|
||||
fn rewrite_zip_entry(bytes: &[u8], entry_name: &str, f: impl Fn(&str) -> String) -> Vec<u8> {
|
||||
use std::io::{Cursor, Read, Write};
|
||||
let mut r = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut w = zip::ZipWriter::new(&mut out);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
for i in 0..r.len() {
|
||||
let mut file = r.by_index(i).unwrap();
|
||||
let name = file.name().to_string();
|
||||
let mut buf = Vec::new();
|
||||
file.read_to_end(&mut buf).unwrap();
|
||||
w.start_file(&name, opts).unwrap();
|
||||
if name == entry_name {
|
||||
let text = String::from_utf8(buf).unwrap();
|
||||
w.write_all(f(&text).as_bytes()).unwrap();
|
||||
} else {
|
||||
w.write_all(&buf).unwrap();
|
||||
}
|
||||
}
|
||||
w.finish().unwrap();
|
||||
}
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_build_without_bld_lst_still_folds_into_by_paragraph() {
|
||||
use deckcraft_model::anim::{AnimClass, AnimStart, Animation, TextBuild};
|
||||
let mut pres = defaults::new_presentation(None);
|
||||
let mut sh = shape(&mut pres, "Title 1", 50.0, 50.0, 400.0, 200.0);
|
||||
let shape_id = sh.id;
|
||||
sh.text = Some(TextBody { paragraphs: vec![Paragraph::new("First"), Paragraph::new("Second")], ..Default::default() });
|
||||
let s0 = Arc::make_mut(&mut pres.slides[0]);
|
||||
s0.shapes.push(sh);
|
||||
s0.animations.push(Animation {
|
||||
shape: shape_id,
|
||||
class: AnimClass::Entrance,
|
||||
effect: "fade".into(),
|
||||
start: AnimStart::OnClick,
|
||||
duration_ms: 500,
|
||||
text_build: TextBuild::ByParagraph,
|
||||
..Default::default()
|
||||
});
|
||||
let bytes = deckcraft_pptx::export(&pres).unwrap();
|
||||
let without_bld = rewrite_zip_entry(&bytes, "ppt/slides/slide1.xml", |xml| {
|
||||
let start = xml.find("<p:bldLst>").expect("bldLst");
|
||||
let end = xml.find("</p:bldLst>").expect("/bldLst") + "</p:bldLst>".len();
|
||||
format!("{}{}", &xml[..start], &xml[end..])
|
||||
});
|
||||
let back = deckcraft_pptx::import(&without_bld).unwrap();
|
||||
assert_eq!(back.slides[0].animations.len(), 1);
|
||||
assert_eq!(back.slides[0].animations[0].text_build, TextBuild::ByParagraph);
|
||||
|
||||
// Explicit bldP build="p" folds non-500ms After Previous builds, while without bldLst an 800ms
|
||||
// After Previous run stays separate so playback does not alter its 800ms stagger to 500ms.
|
||||
let mut pres_after = pres.clone();
|
||||
let s_after = Arc::make_mut(&mut pres_after.slides[0]);
|
||||
s_after.animations[0].start = AnimStart::AfterPrevious;
|
||||
s_after.animations[0].duration_ms = 800;
|
||||
let bytes_after = deckcraft_pptx::export(&pres_after).unwrap();
|
||||
let back_explicit_after = deckcraft_pptx::import(&bytes_after).unwrap();
|
||||
assert_eq!(back_explicit_after.slides[0].animations.len(), 1);
|
||||
assert_eq!(back_explicit_after.slides[0].animations[0].text_build, TextBuild::ByParagraph);
|
||||
assert_eq!(back_explicit_after.slides[0].animations[0].duration_ms, 800);
|
||||
|
||||
let without_bld_after = rewrite_zip_entry(&bytes_after, "ppt/slides/slide1.xml", |xml| {
|
||||
let start = xml.find("<p:bldLst>").expect("bldLst");
|
||||
let end = xml.find("</p:bldLst>").expect("/bldLst") + "</p:bldLst>".len();
|
||||
format!("{}{}", &xml[..start], &xml[end..])
|
||||
});
|
||||
let back_after = deckcraft_pptx::import(&without_bld_after).unwrap();
|
||||
assert_eq!(back_after.slides[0].animations.len(), 2);
|
||||
assert!(back_after.slides[0].animations.iter().all(|a| a.text_build == TextBuild::default()));
|
||||
// Explicit bldP with build!="p" (e.g. build="cust") opts out of folding.
|
||||
let custom_bld = rewrite_zip_entry(&bytes, "ppt/slides/slide1.xml", |xml| xml.replace(r#"build="p""#, r#"build="cust""#));
|
||||
let back_cust = deckcraft_pptx::import(&custom_bld).unwrap();
|
||||
assert_eq!(back_cust.slides[0].animations.len(), 2);
|
||||
assert!(back_cust.slides[0].animations.iter().all(|a| a.text_build == TextBuild::default()));
|
||||
|
||||
// Without bldLst, an AfterPrevious second paragraph whose parent container delay (1000ms)
|
||||
// disagrees with the 500ms first paragraph span must not fold into a 500ms build.
|
||||
let mut pres_with = pres.clone();
|
||||
Arc::make_mut(&mut pres_with.slides[0]).animations[0].start = AnimStart::WithPrevious;
|
||||
let bytes_with = deckcraft_pptx::export(&pres_with).unwrap();
|
||||
let mismatched_offset = rewrite_zip_entry(&bytes_with, "ppt/slides/slide1.xml", |xml| {
|
||||
let start = xml.find("<p:bldLst>").expect("bldLst");
|
||||
let end = xml.find("</p:bldLst>").expect("/bldLst") + "</p:bldLst>".len();
|
||||
let stripped = format!("{}{}", &xml[..start], &xml[end..]);
|
||||
stripped.replacen(r#"<p:cond delay="500"/>"#, r#"<p:cond delay="1000"/>"#, 1)
|
||||
});
|
||||
let back_mismatch = deckcraft_pptx::import(&mismatched_offset).unwrap();
|
||||
assert_eq!(back_mismatch.slides[0].animations.len(), 2);
|
||||
assert!(back_mismatch.slides[0].animations.iter().all(|a| a.text_build == TextBuild::default()));
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ mod fills;
|
||||
mod kept_parts;
|
||||
mod locks;
|
||||
mod malformed;
|
||||
mod master_text_styles;
|
||||
mod math_ns;
|
||||
mod media_timing;
|
||||
mod notes;
|
||||
@@ -29,3 +30,5 @@ mod table_styles;
|
||||
mod tags;
|
||||
mod transition_xml;
|
||||
mod trigger_steps;
|
||||
|
||||
mod picture_backing;
|
||||
|
||||
@@ -288,6 +288,94 @@ fn unreadable_slide_is_reported() {
|
||||
assert_eq!(deckcraft_pptx::import(&broken).expect("import").slides.len(), 1);
|
||||
}
|
||||
|
||||
/// Missing slide relationships must not turn a damaged deck into a clean partial load (#1910).
|
||||
#[test]
|
||||
fn missing_slide_relationships_are_reported() {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let layout = p.slides[0].layout;
|
||||
for _ in 1..13 {
|
||||
let slide = defaults::new_slide(&mut p, layout).expect("slide");
|
||||
p.slides.push(std::sync::Arc::new(slide));
|
||||
}
|
||||
let mut es = entries(&deckcraft_pptx::export(&p).expect("export"));
|
||||
let pres = es.iter_mut().find(|(n, _)| n == "ppt/presentation.xml").expect("presentation");
|
||||
let xml = String::from_utf8(pres.1.clone()).expect("utf8");
|
||||
let doc = deckcraft_pptx::parse_xml(xml.as_bytes()).expect("xml");
|
||||
let slides = doc.root.child("sldIdLst").expect("slide list");
|
||||
let mut broken = xml.clone();
|
||||
for slide in slides.children_named("sldId").skip(6) {
|
||||
let rid = slide.attr("r:id").expect("relationship id");
|
||||
broken = broken.replace(&format!("r:id=\"{rid}\""), &format!("r:id=\"missing-{rid}\""));
|
||||
}
|
||||
pres.1 = broken.into_bytes();
|
||||
let damaged = rezip(&es);
|
||||
let (q, lost) = deckcraft_pptx::import_checked(&damaged).expect("import");
|
||||
assert_eq!(q.slides.len(), 6);
|
||||
assert_eq!(lost.len(), 7, "every omitted slide must be reported: {lost:?}");
|
||||
let loaded = deckcraft_engine::cmd::file::loaded_file("Original.pptx", &damaged).expect("load");
|
||||
let mut session = deckcraft_engine::Session::new();
|
||||
let token = session.stage_loaded(loaded);
|
||||
let result = session.execute("file.adopt", &serde_json::json!({"path": "Original.pptx", "token": token})).expect("adopt");
|
||||
assert_eq!(result["lostSlides"].as_array().expect("lost slides").len(), 7);
|
||||
assert!(session.doc().expect("doc").path.is_none(), "Save must not overwrite the damaged source");
|
||||
assert!(session.doc().expect("doc").title.ends_with("(Repaired)"));
|
||||
let (q, lost) = deckcraft_pptx::import_checked(&deckcraft_pptx::export(&p).expect("export")).expect("import");
|
||||
assert_eq!(q.slides.len(), 13);
|
||||
assert!(lost.is_empty());
|
||||
}
|
||||
|
||||
/// Every listed entry has its own slide part and relationship: the resource cap must not
|
||||
/// silently turn an otherwise readable large deck into a complete-looking partial load.
|
||||
#[test]
|
||||
fn over_limit_slide_lists_are_refused() {
|
||||
fn deck(count: usize) -> Vec<u8> {
|
||||
let mut es = entries(&valid());
|
||||
let pres = es.iter_mut().find(|(n, _)| n == "ppt/presentation.xml").expect("presentation");
|
||||
let mut xml = String::from_utf8(pres.1.clone()).expect("utf8");
|
||||
let start = xml.find("<p:sldIdLst>").expect("slide list");
|
||||
let end = xml.find("</p:sldIdLst>").expect("slide list end") + "</p:sldIdLst>".len();
|
||||
let ids: String = (1..=count).map(|i| format!(r#"<p:sldId id="{}" r:id="capSlide{i}"/>"#, 255 + i)).collect();
|
||||
xml.replace_range(start..end, &format!("<p:sldIdLst>{ids}</p:sldIdLst>"));
|
||||
pres.1 = xml.into_bytes();
|
||||
let rels = es.iter_mut().find(|(n, _)| n == "ppt/_rels/presentation.xml.rels").expect("relationships");
|
||||
let mut xml = String::from_utf8(rels.1.clone()).expect("utf8");
|
||||
let targets: String = (1..=count).map(|i| format!(r#"<Relationship Id="capSlide{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide{i}.xml"/>"#)).collect();
|
||||
xml = xml.replace("</Relationships>", &format!("{targets}</Relationships>"));
|
||||
rels.1 = xml.into_bytes();
|
||||
let types = es.iter_mut().find(|(n, _)| n == "[Content_Types].xml").expect("content types");
|
||||
let xml = String::from_utf8(types.1.clone()).expect("utf8");
|
||||
let overrides: String = (2..=count).map(|i| format!(r#"<Override PartName="/ppt/slides/slide{i}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>"#)).collect();
|
||||
types.1 = xml.replace("</Types>", &format!("{overrides}</Types>")).into_bytes();
|
||||
let blank = br#"<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree></p:cSld></p:sld>"#.to_vec();
|
||||
es.iter_mut().find(|(n, _)| n == "ppt/slides/slide1.xml").expect("slide").1 = blank.clone();
|
||||
let slide_rels = es.iter().find(|(n, _)| n == "ppt/slides/_rels/slide1.xml.rels").expect("slide relationships").1.clone();
|
||||
for i in 2..=count {
|
||||
es.push((format!("ppt/slides/slide{i}.xml"), blank.clone()));
|
||||
es.push((format!("ppt/slides/_rels/slide{i}.xml.rels"), slide_rels.clone()));
|
||||
}
|
||||
rezip(&es)
|
||||
}
|
||||
let at_limit = deck(10_000);
|
||||
let (p, lost) = deckcraft_pptx::import_checked(&at_limit).expect("exactly at the limit");
|
||||
assert_eq!(p.slides.len(), 10_000);
|
||||
assert!(lost.is_empty());
|
||||
drop(p);
|
||||
|
||||
let over_limit = deck(10_001);
|
||||
for error in [
|
||||
deckcraft_pptx::import_checked(&over_limit).expect_err("must refuse a partial load"),
|
||||
deckcraft_pptx::import(&over_limit).expect_err("plain import must also refuse"),
|
||||
] {
|
||||
assert!(matches!(error, deckcraft_pptx::PptxError::Unsupported(_)));
|
||||
assert!(error.to_string().contains("10000"), "{error}");
|
||||
assert!(error.to_string().contains("slide"), "{error}");
|
||||
}
|
||||
assert!(
|
||||
deckcraft_engine::cmd::file::loaded_file("Original.pptx", &over_limit).is_err(),
|
||||
"no partial file may be adopted with the original save path"
|
||||
);
|
||||
}
|
||||
|
||||
/// Many slides naming one notes part: it is read for the first slide only, not copied onto every
|
||||
/// slide that names it.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Imported empty master styles must not become the defaults used to author new decks.
|
||||
use std::io::{Cursor, Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_geom::Xfrm;
|
||||
use deckcraft_model::resolve::{self, Ctx};
|
||||
use deckcraft_model::text::{Align, Bullet, ParaProps, TextBody};
|
||||
use deckcraft_model::{PhType, Placeholder, Presentation, Shape, ShapeId, defaults};
|
||||
|
||||
fn subtitle(text: &str) -> Shape {
|
||||
let mut body = TextBody::from_text(text);
|
||||
body.paragraphs[0].props.align = Some(Align::Center);
|
||||
Shape {
|
||||
id: ShapeId(102),
|
||||
name: "Centered subtitle".into(),
|
||||
ph: Some(Placeholder { kind: PhType::SubTitle, idx: 1, ..Default::default() }),
|
||||
xfrm: Some(Xfrm::new(120.0, 120.0, 720.0, 90.0)),
|
||||
text: Some(body),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Author an input with empty title/other styles and the specified body style, without asking
|
||||
/// the serializer under test to supply its own master text styles in the input.
|
||||
fn imported(body_style: &str) -> Presentation {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let m = Arc::make_mut(&mut p.masters[0]);
|
||||
m.shapes.clear();
|
||||
for l in &mut m.layouts {
|
||||
l.shapes = vec![subtitle("")];
|
||||
}
|
||||
Arc::make_mut(&mut p.slides[0]).shapes = vec![subtitle("Centered subtitle")];
|
||||
let bytes = deckcraft_pptx::export(&p).expect("base package");
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..z.len() {
|
||||
let mut part = z.by_index(i).expect("part");
|
||||
let name = part.name().to_string();
|
||||
let mut data = Vec::new();
|
||||
part.read_to_end(&mut data).expect("read");
|
||||
if name.starts_with("ppt/slideMasters/slideMaster") && name.ends_with(".xml") {
|
||||
let mut xml = String::from_utf8(data).expect("generated XML");
|
||||
let start = xml.find("<p:txStyles>").expect("styles start");
|
||||
let end = xml.find("</p:txStyles>").expect("styles end") + "</p:txStyles>".len();
|
||||
xml.replace_range(start..end, &format!("<p:txStyles><p:titleStyle/><p:bodyStyle>{body_style}</p:bodyStyle><p:otherStyle/></p:txStyles>"));
|
||||
data = xml.into_bytes();
|
||||
}
|
||||
out.start_file(name, zip::write::SimpleFileOptions::default()).expect("start");
|
||||
out.write_all(&data).expect("write");
|
||||
}
|
||||
deckcraft_pptx::import(&out.finish().expect("finish").into_inner()).expect("import fixture")
|
||||
}
|
||||
|
||||
fn resolved_subtitle(p: &Presentation) -> ParaProps {
|
||||
let slide = &p.slides[0];
|
||||
let shape = slide.shapes.iter().find(|s| s.name == "Centered subtitle").expect("subtitle");
|
||||
assert_eq!(shape.ph_type(), Some(PhType::SubTitle));
|
||||
assert_eq!(shape.xfrm, Some(Xfrm::new(120.0, 120.0, 720.0, 90.0)));
|
||||
let text = shape.text.as_ref().expect("text");
|
||||
assert_eq!(text.text(), "Centered subtitle");
|
||||
resolve::para(&Ctx::for_slide(p, slide).expect("context"), shape, &text.paragraphs[0])
|
||||
}
|
||||
|
||||
fn saved(p: &Presentation) -> Presentation {
|
||||
deckcraft_pptx::import(&deckcraft_pptx::export(p).expect("export")).expect("reopen")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_empty_master_keeps_its_unbulleted_subtitle_after_two_saves() {
|
||||
let mut p = imported("");
|
||||
let before = resolved_subtitle(&p);
|
||||
assert_eq!(before.bullet, None);
|
||||
assert_eq!(before.align, Some(Align::Center));
|
||||
for _ in 0..2 {
|
||||
p = saved(&p);
|
||||
assert_eq!(resolved_subtitle(&p).bullet, None, "saving must not add a subtitle bullet");
|
||||
let master = &p.masters[0];
|
||||
assert!(master.title_style.is_empty(), "do not invent an imported title style");
|
||||
assert!(master.body_style.is_empty(), "do not invent bullets in an imported body style");
|
||||
assert!(master.other_style.is_empty(), "do not invent an imported other-text style");
|
||||
assert_eq!(resolved_subtitle(&p), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_unbulleted_body_style_keeps_its_properties() {
|
||||
let mut p = imported(r#"<a:lvl1pPr><a:buNone/><a:defRPr sz="1900"><a:latin typeface="Carlito"/></a:defRPr></a:lvl1pPr>"#);
|
||||
let expected = p.masters[0].body_style.clone();
|
||||
assert_eq!(resolved_subtitle(&p).bullet, Some(Bullet::None));
|
||||
for _ in 0..2 {
|
||||
p = saved(&p);
|
||||
assert_eq!(p.masters[0].body_style, expected);
|
||||
assert_eq!(resolved_subtitle(&p).bullet, Some(Bullet::None));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newly_authored_presentations_keep_their_populated_master_defaults() {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let m = &p.masters[0];
|
||||
let expected = (m.title_style.clone(), m.body_style.clone(), m.other_style.clone());
|
||||
assert!(!expected.0.is_empty() && !expected.1.is_empty() && !expected.2.is_empty());
|
||||
assert_eq!(expected.1.levels.len(), 9);
|
||||
assert!(matches!(expected.1.level(0).expect("body level").para.bullet, Some(Bullet::Char { .. })));
|
||||
for _ in 0..2 {
|
||||
p = saved(&p);
|
||||
let m = &p.masters[0];
|
||||
assert_eq!((&m.title_style, &m.body_style, &m.other_style), (&expected.0, &expected.1, &expected.2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! A picture's fill is a backing behind its transparent image, independent of its blip fill.
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_color::Rgba;
|
||||
use deckcraft_model::style::{Fill, PictureFill, PictureMode};
|
||||
use deckcraft_model::{ColorRef, Presentation, Shape, ShapeId, ShapeKind, Xfrm, defaults};
|
||||
|
||||
fn deck(fill: Option<Fill>, object: bool) -> Presentation {
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let image = image::RgbaImage::from_fn(8, 4, |x, _| if x < 4 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([0, 0, 128, 255]) });
|
||||
let mut png = std::io::Cursor::new(Vec::new());
|
||||
image::DynamicImage::ImageRgba8(image).write_to(&mut png, image::ImageFormat::Png).expect("PNG");
|
||||
let media = p.add_media("transparent.png", "image/png", png.into_inner()).expect("media");
|
||||
let kind = if object {
|
||||
ShapeKind::Opaque { xml: String::new(), preview: Some(media), label: "synthetic preview".into(), parts: vec![] }
|
||||
} else {
|
||||
ShapeKind::Picture { fill: PictureFill { media, ..Default::default() } }
|
||||
};
|
||||
let pic = Shape { id: ShapeId(102), name: "Picture".into(), xfrm: Some(Xfrm::new(20.0, 10.0, 80.0, 40.0)), fill, kind, ..Default::default() };
|
||||
let group = Shape {
|
||||
id: ShapeId(101),
|
||||
name: "Group".into(),
|
||||
xfrm: Some(Xfrm::new(100.0, 150.0, 400.0, 180.0)),
|
||||
fill: Some(Fill::solid(ColorRef::rgb(Rgba::WHITE))),
|
||||
kind: ShapeKind::Group { children: vec![pic], child: Xfrm::new(0.0, 0.0, 200.0, 120.0) },
|
||||
..Default::default()
|
||||
};
|
||||
Arc::make_mut(&mut p.slides[0]).shapes.push(group);
|
||||
p
|
||||
}
|
||||
|
||||
fn picture(p: &Presentation) -> &Shape {
|
||||
let g = p.slides[0].shapes.iter().find(|s| s.name == "Group").expect("group");
|
||||
let ShapeKind::Group { children, child } = &g.kind else { panic!("group kind") };
|
||||
assert_eq!(*child, Xfrm::new(0.0, 0.0, 200.0, 120.0));
|
||||
assert_eq!(g.xfrm, Some(Xfrm::new(100.0, 150.0, 400.0, 180.0)));
|
||||
assert_eq!(g.fill, Some(Fill::solid(ColorRef::rgb(Rgba::WHITE))));
|
||||
children.iter().find(|s| s.name == "Picture").expect("picture")
|
||||
}
|
||||
|
||||
fn check_saves(mut p: Presentation, fill: Option<Fill>) {
|
||||
let expected_media = p.media[0].data.clone();
|
||||
for _ in 0..2 {
|
||||
p = deckcraft_pptx::import(&deckcraft_pptx::export(&p).expect("export")).expect("import");
|
||||
let pic = picture(&p);
|
||||
assert_eq!(pic.fill, fill, "keep the backing separate from the picture's blip fill");
|
||||
assert_eq!(pic.xfrm, Some(Xfrm::new(20.0, 10.0, 80.0, 40.0)));
|
||||
let ShapeKind::Picture { fill: image } = &pic.kind else { panic!("picture kind") };
|
||||
assert!(matches!(image.mode, PictureMode::Stretch { .. }));
|
||||
let media = p.media.iter().find(|m| m.id == image.media).expect("referenced image");
|
||||
assert_eq!(media.data, expected_media, "keep transparent PNG bytes unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transparent_picture_keeps_its_inherited_group_backing() {
|
||||
check_saves(deck(Some(Fill::Group), false), Some(Fill::Group));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_saved_as_its_picture_preview_keeps_its_inherited_group_backing() {
|
||||
// Empty kept XML deliberately exercises shape_with_id's preview fallback, not the ordinary
|
||||
// picture writer. Both must keep the same backing when they serialize p:pic.
|
||||
check_saves(deck(Some(Fill::Group), true), Some(Fill::Group));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfilled_and_directly_filled_pictures_keep_their_own_backing() {
|
||||
for fill in [None, Some(Fill::None), Some(Fill::solid(ColorRef::rgb(Rgba::rgb(200, 100, 20))))] {
|
||||
check_saves(deck(fill.clone(), false), fill);
|
||||
}
|
||||
}
|
||||
@@ -1396,6 +1396,45 @@ fn single_guide_names_follow_the_preset() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Large finite guides position a visible bend even when the connector is only one EMU wide.
|
||||
#[test]
|
||||
fn large_connector_adjustments_keep_their_elbows_through_two_saves() {
|
||||
let cases = [
|
||||
("ordinary", 80.0, 50000.0),
|
||||
("near control", 1588.0 / 12700.0, -12800000.0),
|
||||
("near negative", 1.0 / 12700.0, -20320000000.0),
|
||||
("near positive", 1.0 / 12700.0, 20320000000.0),
|
||||
("zero width", 0.0, 20320000000.0),
|
||||
("ordinary negative", 80.0, -20000.0),
|
||||
];
|
||||
let mut p = defaults::new_presentation(None);
|
||||
p.slides.clear();
|
||||
let mut s = new_slide(&mut p, "Connectors");
|
||||
s.shapes.clear();
|
||||
for (name, width, guide) in cases {
|
||||
let mut sh = shape(&mut p, name, 100.0, 80.0, width, 140.0);
|
||||
sh.kind = ShapeKind::Connector { start: None, end: None };
|
||||
sh.geom = Geom::Preset { name: "bentConnector3".into(), adj: vec![guide] };
|
||||
s.shapes.push(sh);
|
||||
}
|
||||
p.slides.push(Arc::new(s));
|
||||
for generation in 1..=2 {
|
||||
p = deckcraft_pptx::import(&deckcraft_pptx::export(&p).expect("export")).expect("reopen");
|
||||
for (name, width, guide) in cases {
|
||||
let sh = p.slides[0].shapes.iter().find(|sh| sh.name == name).expect("connector");
|
||||
let Geom::Preset { name: preset, adj } = &sh.geom else {
|
||||
panic!("preset connector");
|
||||
};
|
||||
assert_eq!(adj, &[guide], "{name}, save {generation}");
|
||||
let xfrm = sh.xfrm.expect("transform");
|
||||
assert_eq!((xfrm.w, xfrm.h), (width, 140.0));
|
||||
let expected = deckcraft_geom::preset::build("bentConnector3", width, 140.0, &[guide]).expect("expected geometry");
|
||||
let actual = deckcraft_geom::preset::build(preset, xfrm.w, xfrm.h, adj).expect("reopened geometry");
|
||||
assert_eq!(actual.outline(), expected.outline(), "{name}, save {generation}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #147: PowerPoint's Float Down is preset 47 (Float Up is 42); it imported as a plain fade.
|
||||
#[test]
|
||||
fn float_down_is_preset_47_both_ways() {
|
||||
|
||||
@@ -72,6 +72,7 @@ impl SlideApp {
|
||||
synthetic_injected_time: None,
|
||||
ribbon_scroll: HashMap::new(),
|
||||
show_instance: 0,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
opening_generation: 0,
|
||||
canvas_rect: None,
|
||||
eyedropper: None,
|
||||
|
||||
@@ -238,7 +238,7 @@ impl SlideApp {
|
||||
"app.insertPictureDialog" => self.pick_and_insert("picture", "insert.picture"),
|
||||
"app.smartArtPictureDialog" => {
|
||||
if self.services.pick_open.is_none() {
|
||||
return Err("picking a SmartArt picture needs the desktop app".into());
|
||||
return Err("picking a Diagram picture needs the desktop app".into());
|
||||
}
|
||||
self.pick_and_run("picture", "smartArt.picture", p);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ fn title(id: &str) -> &'static str {
|
||||
"customShow" => "Custom Shows",
|
||||
"chartData" => "Chart Data",
|
||||
"trim" => "Trim Media",
|
||||
"smartart" => "Choose a SmartArt Graphic",
|
||||
"smartart" => "Choose a Diagram Graphic",
|
||||
"bullets" => "Bullets and Numbering",
|
||||
"action" => "Action Settings",
|
||||
"quit" => "DeckCraft",
|
||||
|
||||
@@ -1260,7 +1260,7 @@ fn dlg_smartart(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
});
|
||||
let mut v = d.get("text", "Plan\nBuild\nLaunch");
|
||||
ui.add(egui::TextEdit::multiline(&mut v).hint_text("SmartArt items").desired_rows(5).desired_width(320.0));
|
||||
ui.add(egui::TextEdit::multiline(&mut v).hint_text("Diagram items").desired_rows(5).desired_width(320.0));
|
||||
d.fields.insert("text".into(), v.clone());
|
||||
let (ok, cancel) = buttons(ui, "Insert");
|
||||
if ok {
|
||||
|
||||
@@ -143,7 +143,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
|
||||
("app.preferences", "Preferences…", Some("Cmd+,"), "{}"),
|
||||
("app.openDialog", "Open…", None, "{purpose?}"),
|
||||
("app.insertPictureDialog", "Picture from File…", None, "{}"),
|
||||
("app.smartArtPictureDialog", "Insert Picture in SmartArt…", None, "{id?, index}"),
|
||||
("app.smartArtPictureDialog", "Insert Picture in Diagram…", None, "{id?, index}"),
|
||||
("app.changePictureDialog", "Change Picture…", None, "{}"),
|
||||
("app.insertAudioDialog", "Audio from File…", None, "{}"),
|
||||
("app.reuseSlidesDialog", "Reuse Slides…", None, "{keepFormatting?: bool}"),
|
||||
@@ -276,7 +276,8 @@ pub struct SlideApp {
|
||||
ribbon_scroll: HashMap<String, u32>,
|
||||
/// Monotonic identity for a new slide show instance (`start_show`).
|
||||
show_instance: u64,
|
||||
/// Monotonic identity for a new background-open attempt.
|
||||
/// Monotonic identity for a new background-open attempt (the web build has no threads).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
opening_generation: u64,
|
||||
/// Canvas screen rect and points-per-slide-point scale (for control & tests).
|
||||
pub canvas_rect: Option<egui::Rect>,
|
||||
|
||||
@@ -248,7 +248,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> {
|
||||
("-", ""),
|
||||
("Section", "section.add"),
|
||||
("Text Box", "insert.textBox"),
|
||||
("WordArt", "insert.wordArt"),
|
||||
("Decorative Text", "insert.wordArt"),
|
||||
("Date and Time", "insert.dateTime"),
|
||||
("Slide Number", "insert.slideNumber"),
|
||||
("-", ""),
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{SlideApp, Tokens, Ui, Value, json, run};
|
||||
/// Shift+Tab demote and promote, Backspace in an empty line removes it.
|
||||
pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) {
|
||||
let Some((gid, d)) = app.session.active().and_then(deckcraft_engine::cmd::smartart::selected) else {
|
||||
ui.label("Select a SmartArt graphic to edit its text.");
|
||||
ui.label("Select a Diagram graphic to edit its text.");
|
||||
return;
|
||||
};
|
||||
let texts: Vec<String> = d.nodes.iter().map(|n| n.text.clone()).collect();
|
||||
@@ -24,7 +24,7 @@ pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(16.0 * node.level as f32);
|
||||
ui.label("•");
|
||||
let te = egui::TextEdit::singleline(draft).id(id).hint_text("SmartArt text").desired_width(f32::INFINITY);
|
||||
let te = egui::TextEdit::singleline(draft).id(id).hint_text("Diagram text").desired_width(f32::INFINITY);
|
||||
let r = ui.add(te);
|
||||
if app.ui.smartart_focus == Some(i) {
|
||||
r.request_focus();
|
||||
|
||||
@@ -66,12 +66,12 @@ fn home_convert_to_smartart_gallery_converts_the_text() {
|
||||
app,
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.get_by_label("Convert to SmartArt").click();
|
||||
h.get_by_label("Convert to Diagram").click();
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, "Basic Block List").click();
|
||||
h.run_steps(3);
|
||||
let st = h.state().session.active().unwrap();
|
||||
let (_, d) = deckcraft_engine::cmd::smartart::selected(st).expect("the text became a SmartArt graphic");
|
||||
let (_, d) = deckcraft_engine::cmd::smartart::selected(st).expect("the text became a Diagram graphic");
|
||||
assert_eq!(d.kind, "blockList");
|
||||
assert_eq!(d.nodes.len(), 3);
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ fn contextual(app: &SlideApp) -> Vec<&'static str> {
|
||||
v.push("Layout");
|
||||
}
|
||||
if deckcraft_engine::cmd::smartart::selected(st).is_some() {
|
||||
v.push("SmartArt Design");
|
||||
v.push(DIAGRAM_TAB_ID);
|
||||
}
|
||||
if shapes.iter().any(|s| matches!(s.kind, ShapeKind::Chart(_))) {
|
||||
v.push("Chart Design");
|
||||
@@ -117,6 +117,13 @@ fn contextual(app: &SlideApp) -> Vec<&'static str> {
|
||||
v
|
||||
}
|
||||
|
||||
// This is an existing saved/control-channel key, not the displayed label.
|
||||
const DIAGRAM_TAB_ID: &str = "SmartArt Design";
|
||||
|
||||
fn tab_label(id: &str) -> &str {
|
||||
if id == DIAGRAM_TAB_ID { "Diagram Design" } else { id }
|
||||
}
|
||||
|
||||
const TABS: [&str; 10] = ["Home", "Insert", "Draw", "Design", "Transitions", "Animations", "Slide Show", "Record", "Review", "View"];
|
||||
|
||||
/// Tab row and the ribbon card.
|
||||
@@ -149,18 +156,19 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) {
|
||||
}
|
||||
let all: Vec<(&str, bool)> = TABS.iter().map(|s| (*s, false)).chain(ctx_tabs.iter().map(|s| (*s, true))).collect();
|
||||
for (name, contextual) in all {
|
||||
let label = tab_label(name);
|
||||
let font = theme::font(13.0);
|
||||
let w = ui.fonts_mut(|f| f.layout_no_wrap(name.to_string(), font.clone(), t.text).size().x) + 18.0;
|
||||
let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_string(), font.clone(), t.text).size().x) + 18.0;
|
||||
let r = Rect::from_min_size(pos2(x, y), vec2(w, 24.0));
|
||||
let resp = ui.interact(r, ui.scope_id().with(("tab", name)), Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name));
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
|
||||
let active = app.ui.tab == name;
|
||||
if resp.hovered() && !active {
|
||||
ui.painter().rect_filled(r.shrink2(vec2(2.0, 2.0)), CornerRadius::same(4), t.hover);
|
||||
}
|
||||
let col = if contextual { t.contextual } else { t.text };
|
||||
let f = if active { theme::bold(13.0) } else { font };
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, name, f, col);
|
||||
ui.painter().text(r.center(), Align2::CENTER_CENTER, label, f, col);
|
||||
if active {
|
||||
let uw = (w - 20.0).max(16.0);
|
||||
ui.painter().rect_filled(Rect::from_center_size(pos2(r.center().x, r.max.y - 1.0), vec2(uw, 3.0)), CornerRadius::same(1), t.accent);
|
||||
@@ -227,7 +235,7 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) {
|
||||
"Table Design" => table_design(app, ui),
|
||||
"Layout" => table_layout(app, ui),
|
||||
"Chart Design" => chart_design(app, ui),
|
||||
"SmartArt Design" => smartart_design(app, ui),
|
||||
DIAGRAM_TAB_ID => smartart_design(app, ui),
|
||||
"Playback" => playback(app, ui),
|
||||
"Slide Master" => slide_master(app, ui),
|
||||
"Handout Master" => handout_master(app, ui),
|
||||
@@ -462,3 +470,13 @@ mod inktoshape_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod picture_styles_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod feature_name_tests {
|
||||
#[test]
|
||||
fn diagram_tab_keeps_its_saved_identity() {
|
||||
assert_eq!(super::DIAGRAM_TAB_ID, "SmartArt Design");
|
||||
assert_eq!(super::tab_label(super::DIAGRAM_TAB_ID), "Diagram Design");
|
||||
assert_eq!(super::tab_label("Home"), "Home");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -384,7 +384,7 @@ fn paragraph_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) {
|
||||
}
|
||||
}
|
||||
});
|
||||
let r = icon_toggle(ui, Icon::SmartArt, "Convert to SmartArt", enabled(app, "smartArt.fromText"), false);
|
||||
let r = icon_toggle(ui, Icon::SmartArt, "Convert to Diagram", enabled(app, "smartArt.fromText"), false);
|
||||
egui::Popup::menu(&r).show(|ui| smartart_gallery(app, ui, "smartArt.fromText", json!({}), "", ("", ""), None));
|
||||
if ui.add_enabled(en, egui::Button::new("Paragraph…").min_size(vec2(88.0, 22.0))).on_hover_text("Paragraph").clicked() {
|
||||
run(app, "format.paragraphDialog", json!({}));
|
||||
|
||||
@@ -72,7 +72,7 @@ pub(super) fn insert(app: &mut SlideApp, ui: &mut Ui) {
|
||||
});
|
||||
let r = big_button(ui, Icon::Icons, "Icons", enabled(app, "insert.icon"));
|
||||
egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).width(340.0).show(|ui| icon_library(app, ui));
|
||||
big(app, ui, Icon::SmartArt, "SmartArt", "app.dialog", json!({"id": "smartart"}));
|
||||
big(app, ui, Icon::SmartArt, "Diagram", "app.dialog", json!({"id": "smartart"}));
|
||||
let r = big_button(ui, Icon::Chart, "Chart", enabled(app, "insert.chart"));
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for k in chart_menu_types() {
|
||||
@@ -111,10 +111,10 @@ pub(super) fn insert(app: &mut SlideApp, ui: &mut Ui) {
|
||||
group(ui, |ui| {
|
||||
big(app, ui, Icon::TextBox, "Text\nBox", "insert.textBox", json!({}));
|
||||
big(app, ui, Icon::HeaderFooter, "Header &\nFooter", "app.dialog", json!({"id": "headerFooter"}));
|
||||
let r = big_button(ui, Icon::WordArt, "WordArt", enabled(app, "insert.wordArt"));
|
||||
let r = big_button(ui, Icon::WordArt, "Decorative Text", enabled(app, "insert.wordArt"));
|
||||
egui::Popup::menu(&r).show(|ui| {
|
||||
for i in 0..6 {
|
||||
if ui.button(format!("WordArt style {}", i + 1)).clicked() {
|
||||
if ui.button(format!("Decorative Text style {}", i + 1)).clicked() {
|
||||
run(app, "insert.wordArt", json!({"style": i}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ pub(super) fn smartart_design(app: &mut SlideApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
}
|
||||
let (main, arrow) = small_button_ex(ui, Icon::SmartArt, "SmartArt Styles", gid.is_some(), false, true);
|
||||
let (main, arrow) = small_button_ex(ui, Icon::SmartArt, "Diagram Styles", gid.is_some(), false, true);
|
||||
if let Some(arrow) = arrow {
|
||||
widgets::split_menu(&main, &arrow, |ui| {
|
||||
for (k, label) in deckcraft_engine::cmd::smartart::STYLES {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Guard the production display surfaces without banning compatibility identifiers or notices.
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const BANNED: &[&str] = &["SmartArt", "WordArt"];
|
||||
const ALLOWED: &[&str] = &["SmartArt Design"];
|
||||
const ROOTS: &[&str] = &["src", "../engine/src/cmd"];
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
fn banned_display(text: &str) -> bool {
|
||||
if ALLOWED.contains(&text) {
|
||||
return false;
|
||||
}
|
||||
BANNED.iter().any(|banned| {
|
||||
text.match_indices(banned)
|
||||
.any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word))
|
||||
})
|
||||
}
|
||||
|
||||
// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is
|
||||
// needed, so this guard can also run by itself when a full application build is unavailable.
|
||||
#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together.
|
||||
fn literals(source: &str) -> Vec<String> {
|
||||
let chars: Vec<char> = source.chars().collect();
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
let mut test_module = false;
|
||||
let mut test_depth = 0_usize;
|
||||
while at < chars.len() {
|
||||
if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) {
|
||||
at += 12;
|
||||
let rest: String = chars[at..].iter().collect();
|
||||
if rest.trim_start().starts_with("mod ") {
|
||||
test_module = true;
|
||||
}
|
||||
} else if chars.get(at..at + 2) == Some(&['/', '/']) {
|
||||
while at < chars.len() && chars[at] != '\n' {
|
||||
at += 1;
|
||||
}
|
||||
} else if chars.get(at..at + 2) == Some(&['/', '*']) {
|
||||
at += 2;
|
||||
let mut depth = 1;
|
||||
while at < chars.len() && depth > 0 {
|
||||
if chars.get(at..at + 2) == Some(&['/', '*']) {
|
||||
depth += 1;
|
||||
at += 2;
|
||||
} else if chars.get(at..at + 2) == Some(&['*', '/']) {
|
||||
depth -= 1;
|
||||
at += 2;
|
||||
} else {
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
} else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) {
|
||||
let start = at;
|
||||
at += 1;
|
||||
while chars.get(at) == Some(&'#') {
|
||||
at += 1;
|
||||
}
|
||||
let hashes = at - start - 1;
|
||||
if chars.get(at) != Some(&'"') {
|
||||
continue;
|
||||
}
|
||||
at += 1;
|
||||
let begin = at;
|
||||
while at < chars.len() {
|
||||
if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) {
|
||||
break;
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
if !test_module {
|
||||
out.push(chars[begin..at].iter().collect());
|
||||
}
|
||||
at += 1 + hashes;
|
||||
} else if chars[at] == '"' {
|
||||
at += 1;
|
||||
let mut text = String::new();
|
||||
while at < chars.len() {
|
||||
let c = chars[at];
|
||||
at += 1;
|
||||
if c == '"' {
|
||||
break;
|
||||
}
|
||||
if c == '\\' && at < chars.len() {
|
||||
let escaped = chars[at];
|
||||
at += 1;
|
||||
match escaped {
|
||||
'n' => text.push('\n'),
|
||||
't' => text.push('\t'),
|
||||
'r' => text.push('\r'),
|
||||
'0' => text.push('\0'),
|
||||
'\n' | '\r' => {
|
||||
while chars.get(at).is_some_and(|c| c.is_whitespace()) {
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
other => text.push(other),
|
||||
}
|
||||
} else {
|
||||
text.push(c);
|
||||
}
|
||||
}
|
||||
if !test_module {
|
||||
out.push(text);
|
||||
}
|
||||
} else if chars[at] == '\'' && chars.get(at + 1) == Some(&'\\') {
|
||||
// Skip the escape and its payload, including hexadecimal/Unicode escapes.
|
||||
at += 3;
|
||||
while at < chars.len() && chars[at] != '\'' {
|
||||
at += 1;
|
||||
}
|
||||
at += 1;
|
||||
} else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') {
|
||||
at += 3; // A character literal such as '"', not the start of a string.
|
||||
} else {
|
||||
if test_module {
|
||||
match chars[at] {
|
||||
'{' => test_depth += 1,
|
||||
'}' => {
|
||||
test_depth = test_depth.saturating_sub(1);
|
||||
if test_depth == 0 {
|
||||
test_module = false;
|
||||
}
|
||||
}
|
||||
';' if test_depth == 0 => test_module = false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn check_tree(path: &Path, failures: &mut Vec<String>) {
|
||||
if path.is_dir() {
|
||||
for entry in std::fs::read_dir(path).expect("source directory") {
|
||||
let path = entry.expect("source entry").path();
|
||||
if path.file_name().is_some_and(|name| name == "tests") {
|
||||
continue;
|
||||
}
|
||||
check_tree(&path, failures);
|
||||
}
|
||||
} else if path.extension().is_some_and(|ext| ext == "rs") {
|
||||
let name = path.file_name().expect("source filename").to_string_lossy();
|
||||
if name == "tests.rs" || name.ends_with("_tests.rs") {
|
||||
return;
|
||||
}
|
||||
let source = std::fs::read_to_string(path).expect("UTF-8 Rust source");
|
||||
// Skip only inline test modules, not later production following test-only imports.
|
||||
for text in literals(&source) {
|
||||
if banned_display(&text) {
|
||||
failures.push(format!("{}: {text:?}", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_display_names_stay_neutral() {
|
||||
let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let mut failures = Vec::new();
|
||||
for root in ROOTS {
|
||||
let root = base.join(root);
|
||||
assert!(root.exists(), "missing display source: {}", root.display());
|
||||
check_tree(&root, &mut failures);
|
||||
}
|
||||
assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_distinguishes_labels_from_identifiers_and_comments() {
|
||||
for name in BANNED {
|
||||
assert!(banned_display(name), "{name}");
|
||||
}
|
||||
for name in ALLOWED {
|
||||
assert!(!banned_display(name), "{name}");
|
||||
}
|
||||
assert!(!banned_display("filter.cameraRaw"));
|
||||
assert!(!banned_display("tool.guidedUpright"));
|
||||
assert!(!banned_display("insert.smartArt"));
|
||||
assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]);
|
||||
assert_eq!(literals("r#\"raw label\"#"), ["raw label"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_scans_production_after_test_only_items() {
|
||||
let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; }
|
||||
#[cfg(test)] use fixtures::Helper;
|
||||
fn production() { let _ = r#"live label"#; }
|
||||
"###;
|
||||
assert_eq!(literals(source), ["live label"]);
|
||||
assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_skips_escaped_character_literals() {
|
||||
assert_eq!(literals(r#"let q = '\"'; "label""#), ["label"]);
|
||||
assert_eq!(literals(r#"let q = '\''; "label""#), ["label"]);
|
||||
assert_eq!(literals(r#"let q = '\\'; "label""#), ["label"]);
|
||||
assert_eq!(literals(r#"let q = '\u{22}'; "label""#), ["label"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_decodes_whitespace_escapes() {
|
||||
assert_eq!(literals(r#""one\ntwo\tthree\rfour\0""#), ["one\ntwo\tthree\rfour\0"]);
|
||||
assert_eq!(literals("\"joined\\\n label\""), ["joinedlabel"]);
|
||||
for name in BANNED {
|
||||
let source = format!("\"\\t{name}\\n\"");
|
||||
assert!(literals(&source).iter().any(|label| banned_display(label)));
|
||||
}
|
||||
}
|
||||
@@ -32,16 +32,11 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note
|
||||
| `engine.execute` / `ui.menu.invoke` / `command` | `{command, params}` | Run any command (see `engine.commands`; `deckcraft-cli describe COMMAND` documents one) |
|
||||
| `engine.commands` | — | Every command: id, label, menu path, shortcut, params doc, enabled / disabled reason |
|
||||
| `document.inspect` | — | Slides, sections, layouts, shapes, selection |
|
||||
| `slide.actions` | `{index?}` | Actions on one slide; returns `{index, slideId, actions}`. Each action has an `owner` (shape id/name and group path; text actions also include paragraph/run indexes and run text, plus table row/cell indexes for table text), `event` (`click`, `hover`, `textLink`, or `textHover`), action `type`, `target`, and the full `hyperlink`. Listing is read-only and never executes an action. An empty slide returns `"actions": []`. |
|
||||
| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab open over a presentation), `backstage` (its page, also the start screen), slide show state (`grid`, `zoomArm`, `zoom`, `blank`, `presenterPaused`, `presenterSecs`, `notesPx`, `custom`, `goto`; `cells` while See All Slides is open), documents, perf (fps, render ms) |
|
||||
| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab open over a presentation), `backstage` (its page, also the start screen), slide show state, `animPreview` (canvas playback: slide, time, duration), documents, perf (fps, render ms) |
|
||||
| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab over an open presentation), `backstage` (the current File page, including the start screen), slide show state (`grid`, `zoomArm`, `zoom`, `blank`, `presenterPaused`, `presenterSecs`, `notesPx`, `custom`, `goto`; `cells` when See All Slides is open), `animPreview` (canvas playback: slide, time, duration), documents, perf (fps, render ms) |
|
||||
| `ui.tool.select` | `{tool, preset?}` | `select`, `text`, `shape` + preset, any preset name, `curve`, `freeform`, `scribble`, `pen`, `highlighter`, `eraser` |
|
||||
| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick\|contextclick, x, y, mods?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse (`contextclick`: the right-button press that selects before the context menu) |
|
||||
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show: digits then Enter go to that slide, G is See All Slides, Z arms zoom, T pauses the presenter timer, R resets it, `[` and `]` change notes size, Esc clears a slide number, the grid and zoom before it leaves the show) |
|
||||
| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, mods?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse |
|
||||
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show; Escape stops the canvas animation preview) |
|
||||
| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, mods?, pressure?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse. `pressure` is `0..=1` for a pen; omit it for a mouse |
|
||||
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show) |
|
||||
| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick\|contextclick, x, y, mods?, pressure?}], mods?}` | Send slide-point pointer events through the active tool's mouse path. `contextclick` performs the right-click selection used by context menus; `pressure` is `0..=1` for a pen and can be omitted for a mouse |
|
||||
| `ui.key` | `{key, shift?, alt?, cmd?}` | Send a key press. During an active slide show, digits followed by Enter jump to that slide; G opens See All Slides, Z arms zoom, T toggles the presenter timer's pause, R resets it, and `[` / `]` resize notes. Esc clears a typed slide number or backs out of the grid/zoom before ending the active show. Close See All Slides with Esc or G before using the other listed show shortcuts. Slide-show keys ignore modifier flags; use `show.end` to leave the end-of-show screen. Outside a show, Escape stops canvas animation preview |
|
||||
| `ui.text` | `{text}` | Insert into the current text edit. With one shape selected and no active text edit, begin editing and replace the shape's existing text |
|
||||
| `ui.ime` | `{preedit, active?: [start, end]}` / `{commit}` | An input method's composition through egui, as a real one arrives: shown in place on the slide or in a focused field; `{"preedit": ""}` cancels |
|
||||
| `ui.move` / `ui.click` / `ui.drag` | screen points | Real egui pointer input — reaches every widget, menu and pane |
|
||||
| `ui.set` | `{tab?, view?, pane?, notes?, zoom?, brightness?, ruler?, gridlines?, guides?, …}` | UI state (returns the full state) |
|
||||
@@ -54,3 +49,18 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note
|
||||
|
||||
The MCP server (`deckcraft-cli mcp`, see [mcp.md](mcp.md)) wraps the same methods for Claude
|
||||
and other agents; `deckcraft-cli app --method METHOD [PARAMS]` sends one request from a shell.
|
||||
|
||||
## Inspecting slide actions
|
||||
|
||||
Run the `slide.actions` engine command through `engine.execute`:
|
||||
|
||||
```json
|
||||
{"id": 2, "method": "engine.execute", "params": {"command": "slide.actions", "params": {"index": 0}}}
|
||||
```
|
||||
|
||||
`index` is zero-based and optional; omitting it inspects the selected slide. The reply's `result`
|
||||
contains `{index, slideId, actions}`. Each action includes an `owner` with the shape id/name and
|
||||
its group path; text actions also identify the paragraph/run and run text, plus the table row/cell
|
||||
for table text. Actions report their `event` (`click`, `hover`, `textLink`, or `textHover`),
|
||||
`type`, `target`, and full `hyperlink`. Inspection never runs an action. A slide without actions
|
||||
returns `"actions": []`.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Feature naming
|
||||
|
||||
DeckCraft uses **Diagram**, **Diagram Design**, and **Diagram Styles** for its diagram feature, and **Decorative Text** / **Decorative Text Styles** for styled text. Menus, dialogs, tooltips, command labels, errors and newly generated object names use these names.
|
||||
|
||||
## Compatibility boundary
|
||||
|
||||
The existing `smartArt.*`, `insert.smartArt`, `insert.wordArt`, dialog and icon IDs remain stable. The persisted/control-channel tab key `SmartArt Design` still opens the same tab; only its displayed and accessible label is Diagram Design. Dispatch does not depend on the new display text.
|
||||
|
||||
Existing document-owned object names are not rewritten. PPTX diagram parts, DrawingML names, public data types, import/export code and attribution remain unchanged.
|
||||
|
||||
DeckCraft currently authors these interface strings directly in English. Shared DeckCraft catalogs exist in craft-i18n, but this change does not add a catalog loader. Before enabling that integration, catalog keys must include the new Diagram and Decorative Text labels rather than only their retired English names. Diagram/format round-trip tests, UI tests and visual checks remain part of application verification.
|
||||
|
||||
## Regression coverage
|
||||
|
||||
The standard-library-only `display_names` integration tests scan production Rust string literals for the retired display names and preserve explicit compatibility exceptions. They also test identifier, comment and raw-string handling. These focused checks do not replace application or visual testing.
|
||||
@@ -1,6 +1,6 @@
|
||||
# File-format parity with PowerPoint
|
||||
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233)) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-07 · **Change:** trivial (a slide whose relationship is missing is reported in `lostSlides`; previous: minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233))) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365)
|
||||
|
||||
Every format PowerPoint reads or writes, DeckCraft's support, fidelity and how it is tested.
|
||||
Gaps are itemized in [gaps.md](gaps.md#file-formats). Dimension score: **~58% ready**
|
||||
@@ -119,6 +119,7 @@ the round trip even though DeckCraft doesn't model it.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-07 | trivial | A slide-list entry whose relationship is missing is reported in `lostSlides` like an unreadable slide part, so the deck opens as a repaired copy; slide lists over 10,000 entries are refused with an import-limit error rather than silently truncated (#1910) |
|
||||
| 2026-11-02 | minor | Optional table RTL direction is read and written as `a:tblPr/@rtl`; native and two PPTX saves preserve true, false and absent values with distinguishable column text |
|
||||
| 2026-11-02 | minor | Text runs preserve alternate-language metadata in native and PPTX round trips |
|
||||
| 2026-11-03 | trivial | Reuse Slides transfers referenced custom table styles from native and PPTX sources; grouped tables, undo, native save/reopen and style-id conflicts are covered |
|
||||
|
||||
+2
-2
@@ -56,8 +56,8 @@ folders:
|
||||
its nearest existing folder's links are followed and the rest must be plain names, so `..` below a
|
||||
folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would
|
||||
create its target). The result is compared with the root by whole folder names: `/work2/x` is not
|
||||
inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like
|
||||
drive-letter ones, and device names (`CON`, `NUL`, `COM1`...) are refused.
|
||||
inside `/work`. On Windows names are compared exactly after what exists is resolved to its real case (so `OUT\x` reaches the root `out` on an ordinary volume, but not in a case-sensitive folder), UNC paths (`\\server\share\...`) are resolved like
|
||||
drive-letter ones, and device names (`CON`, `NUL`, `COM1`, `COM¹`..., also followed by an extension or a colon) are refused.
|
||||
- A refused path is an ordinary tool error the agent can read and correct, for example
|
||||
`automation path rejected: outside the write root /work/project/out: /etc/x.pptx` or
|
||||
`automation filesystem access is not granted: write authority is absent: /work/project/out/x.pptx`.
|
||||
|
||||
+24
-3
@@ -45,11 +45,20 @@ pub fn validate(v: &str) -> Result<(), String> {
|
||||
None => (v, None),
|
||||
};
|
||||
let nums: Vec<&str> = core.split('.').collect();
|
||||
if nums.len() != 3 || nums.iter().any(|n| n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0'))) {
|
||||
if nums.len() != 3
|
||||
|| nums
|
||||
.iter()
|
||||
.any(|n| n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || n.parse::<u64>().is_err() || (n.len() > 1 && n.starts_with('0')))
|
||||
{
|
||||
return bad();
|
||||
}
|
||||
if let Some(p) = pre
|
||||
&& (p.is_empty() || p.split('.').any(|id| id.is_empty() || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')))
|
||||
&& (p.is_empty()
|
||||
|| p.split('.').any(|id| {
|
||||
id.is_empty()
|
||||
|| !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
|| (id.len() > 1 && id.starts_with('0') && id.bytes().all(|b| b.is_ascii_digit()))
|
||||
}))
|
||||
{
|
||||
return bad();
|
||||
}
|
||||
@@ -138,12 +147,24 @@ mod tests {
|
||||
for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] {
|
||||
assert!(validate(ok).is_ok(), "{ok}");
|
||||
}
|
||||
for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", ""] {
|
||||
for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", "18446744073709551616.0.0", ""] {
|
||||
assert!(validate(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(replace(MANIFEST, "nope").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_prerelease_identifiers_have_no_leading_zeroes() {
|
||||
for bad in ["1.0.0-00", "1.0.0-01", "1.0.0-rc.01"] {
|
||||
assert!(validate(bad).is_err(), "{bad}");
|
||||
assert!(replace(MANIFEST, bad).is_err(), "{bad} must not reach the manifest");
|
||||
}
|
||||
for ok in ["1.0.0-0", "1.0.0-rc.0", "1.0.0-01a", "1.0.0-0-1"] {
|
||||
assert!(validate(ok).is_ok(), "{ok}");
|
||||
assert_eq!(read(&replace(MANIFEST, ok).unwrap()).unwrap(), ok);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_real_manifest_has_a_valid_version() {
|
||||
let text = std::fs::read_to_string(crate::root().join("Cargo.toml")).unwrap();
|
||||
|
||||
Reference in New Issue
Block a user