mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-20 12:54:47 -06:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d30834cca | ||
|
|
97423d80fd | ||
|
|
9e7fa3b571 | ||
|
|
bb2c2254ee | ||
|
|
0d5c0b854b | ||
|
|
349d3d1c24 | ||
|
|
f33d22001c | ||
|
|
d842a0cc2a | ||
|
|
e51ff1a6a8 | ||
|
|
6bbb593d82 | ||
|
|
187afbd4e5 |
@@ -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-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/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/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 |
|
| 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
|
## Bundled through dependencies
|
||||||
|
|||||||
Generated
+62
-10
@@ -222,7 +222,7 @@ dependencies = [
|
|||||||
"objc2-foundation 0.3.2",
|
"objc2-foundation 0.3.2",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
"wl-clipboard-rs",
|
"wl-clipboard-rs",
|
||||||
"x11rb",
|
"x11rb",
|
||||||
]
|
]
|
||||||
@@ -853,6 +853,28 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"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]]
|
[[package]]
|
||||||
name = "craft-fonts-build"
|
name = "craft-fonts-build"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -900,6 +922,16 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"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]]
|
[[package]]
|
||||||
name = "craft-pdf"
|
name = "craft-pdf"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -909,6 +941,15 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"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]]
|
[[package]]
|
||||||
name = "craft-ui"
|
name = "craft-ui"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -995,6 +1036,16 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"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]]
|
[[package]]
|
||||||
name = "crc32fast"
|
name = "crc32fast"
|
||||||
version = "1.5.2"
|
version = "1.5.2"
|
||||||
@@ -1119,6 +1170,7 @@ name = "deckcraft-engine"
|
|||||||
version = "0.19.0"
|
version = "0.19.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"craft-mime",
|
||||||
"deckcraft-anim",
|
"deckcraft-anim",
|
||||||
"deckcraft-color",
|
"deckcraft-color",
|
||||||
"deckcraft-fonts",
|
"deckcraft-fonts",
|
||||||
@@ -1156,10 +1208,10 @@ dependencies = [
|
|||||||
name = "deckcraft-format"
|
name = "deckcraft-format"
|
||||||
version = "0.19.0"
|
version = "0.19.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"craft-deckcraft-format",
|
||||||
|
"craft-rtf",
|
||||||
"deckcraft-model",
|
"deckcraft-model",
|
||||||
"serde",
|
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.21",
|
|
||||||
"zip 3.0.0",
|
"zip 3.0.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1697,7 +1749,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3059,7 +3111,7 @@ version = "0.50.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4087,7 +4139,7 @@ dependencies = [
|
|||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys 0.12.1",
|
"linux-raw-sys 0.12.1",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4144,7 +4196,7 @@ dependencies = [
|
|||||||
"security-framework",
|
"security-framework",
|
||||||
"security-framework-sys",
|
"security-framework-sys",
|
||||||
"webpki-root-certs",
|
"webpki-root-certs",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4815,10 +4867,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"fastrand",
|
"fastrand",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.3.4",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"rustix 1.1.5",
|
"rustix 1.1.5",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5769,7 +5821,7 @@ version = "0.1.11"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -50,7 +50,12 @@ harfrust = "0.13"
|
|||||||
vello_cpu = "0.2"
|
vello_cpu = "0.2"
|
||||||
vello_common = { version = "0.2", default-features = false }
|
vello_common = { version = "0.2", default-features = false }
|
||||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
|
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.
|
# 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-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"] }
|
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.
|
# H.264, HEVC, VP9 and AV1 decoders.
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ description = "DeckCraft engine: sessions, undo history, selection, the command
|
|||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
craft-mime = { workspace = true }
|
||||||
deckcraft-geom = { workspace = true }
|
deckcraft-geom = { workspace = true }
|
||||||
deckcraft-color = { workspace = true }
|
deckcraft-color = { workspace = true }
|
||||||
deckcraft-model = { workspace = true }
|
deckcraft-model = { workspace = true }
|
||||||
|
|||||||
+84
-40
@@ -607,61 +607,105 @@ fn param_optional(alt: &str) -> Option<bool> {
|
|||||||
|
|
||||||
/// Base64 (standard alphabet) for binary payloads in JSON params and results.
|
/// Base64 (standard alphabet) for binary payloads in JSON params and results.
|
||||||
pub fn base64_encode(data: &[u8]) -> String {
|
pub fn base64_encode(data: &[u8]) -> String {
|
||||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
craft_mime::base64::STANDARD.encode(data)
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||||
let s = s.split_once("base64,").map(|(_, b)| b).unwrap_or(s);
|
let s = s.split_once("base64,").map(|(_, b)| b).unwrap_or(s);
|
||||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
// Preserve the command transport's admission rules before the shared legacy decoder:
|
||||||
let mut acc = 0u32;
|
// padding ends the payload and one trailing symbol cannot encode a byte.
|
||||||
let mut bits = 0;
|
let (mut symbols_mod_four, mut padded) = (0u8, false);
|
||||||
let mut padded = false;
|
|
||||||
for c in s.bytes() {
|
for c in s.bytes() {
|
||||||
let v = match c {
|
match c {
|
||||||
b'A'..=b'Z' => c - b'A',
|
b'=' => padded = true,
|
||||||
b'a'..=b'z' => c - b'a' + 26,
|
b'\n' | b'\r' | b' ' => {}
|
||||||
b'0'..=b'9' => c - b'0' + 52,
|
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'/' | b'_' if !padded => {
|
||||||
b'+' | b'-' => 62,
|
symbols_mod_four = (symbols_mod_four + 1) % 4;
|
||||||
b'/' | b'_' => 63,
|
|
||||||
b'=' => {
|
|
||||||
padded = true;
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
b'\n' | b'\r' | b' ' => continue,
|
|
||||||
_ => return None,
|
_ => 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.
|
if symbols_mod_four == 1 {
|
||||||
(bits != 6).then_some(out)
|
return None;
|
||||||
|
}
|
||||||
|
craft_mime::base64_compat::decode(s).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn base64_rejects_a_single_character_tail() {
|
fn base64_rejects_a_single_character_tail() {
|
||||||
for (encoded, decoded) in [
|
for (encoded, decoded) in [
|
||||||
|
|||||||
@@ -9,8 +9,10 @@ description = "DeckCraft native file format (.deckcraft: zip of a JSON manifest
|
|||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
craft-deckcraft-format = { workspace = true }
|
||||||
|
craft-rtf = { workspace = true }
|
||||||
deckcraft-model = { workspace = true }
|
deckcraft-model = { workspace = true }
|
||||||
serde = { workspace = true }
|
|
||||||
|
[dev-dependencies]
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
zip = { 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.
|
//! Keep opaque chart payloads out of the JSON manifest and within the media load budget.
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::io::Cursor;
|
|
||||||
use std::sync::Arc;
|
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::chart::ChartPart;
|
||||||
use deckcraft_model::{Master, Presentation, Shape, ShapeKind};
|
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>);
|
type Payload = (String, String, Vec<u8>);
|
||||||
|
|
||||||
pub(super) fn separate(p: &mut Presentation) -> Result<Vec<Payload>> {
|
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| {
|
visit_parts(p, |part| {
|
||||||
// The native namespace is independent of the original OPC names, which may repeat
|
// 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.
|
// 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());
|
part.native_entry = Some(entry.clone());
|
||||||
payloads.push((entry, part.content_type.clone(), std::mem::take(&mut part.bytes)));
|
payloads.push((entry, part.content_type.clone(), std::mem::take(&mut part.bytes)));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -26,7 +26,7 @@ pub(super) fn separate(p: &mut Presentation) -> Result<Vec<Payload>> {
|
|||||||
|
|
||||||
pub(super) fn restore(
|
pub(super) fn restore(
|
||||||
p: &mut Presentation,
|
p: &mut Presentation,
|
||||||
z: &mut zip::ZipArchive<Cursor<&[u8]>>,
|
z: &mut Package<'_>,
|
||||||
left: &mut u64,
|
left: &mut u64,
|
||||||
mut items: usize,
|
mut items: usize,
|
||||||
max_items: usize,
|
max_items: usize,
|
||||||
@@ -40,21 +40,21 @@ pub(super) fn restore(
|
|||||||
items += 1;
|
items += 1;
|
||||||
if let Some(entry) = part.native_entry.take() {
|
if let Some(entry) = part.native_entry.take() {
|
||||||
// Accept only names produced by separate(), and inflate each member once.
|
// 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() {
|
if !canonical || !seen.insert(entry.clone()) || !part.bytes.is_empty() {
|
||||||
return Err(FormatError::Damaged("invalid or ambiguous chart part reference".into()));
|
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.
|
// Missing members consume no inflation work and can be reported for recovery.
|
||||||
damaged.push(format!("{entry}: missing chart part"));
|
damaged.push(format!("{entry}: missing chart part"));
|
||||||
return Ok(());
|
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()));
|
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
|
// 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.
|
// 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;
|
*left -= bytes.len() as u64;
|
||||||
part.bytes = bytes;
|
part.bytes = bytes;
|
||||||
} else {
|
} 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)]
|
#![forbid(unsafe_code)]
|
||||||
|
|
||||||
mod chart_parts;
|
mod chart_parts;
|
||||||
mod finite;
|
|
||||||
pub mod rtf;
|
pub mod rtf;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod chart_parts_tests;
|
mod chart_parts_tests;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod golden_tests;
|
||||||
|
|
||||||
use std::io::{Cursor, Read, Write};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use deckcraft_model::text::{Paragraph, TextBody};
|
use deckcraft_model::text::{Paragraph, TextBody};
|
||||||
use deckcraft_model::{LayoutType, Presentation, ShapeKind, defaults};
|
use deckcraft_model::{LayoutType, Presentation, ShapeKind, defaults};
|
||||||
|
|
||||||
pub const MIMETYPE: &str = "application/vnd.storyteller.deckcraft+zip";
|
// The package itself (identity, manifest, member names, bounded reads) is shared.
|
||||||
/// Files written before the SlideCraft → DeckCraft rename (`.slidecraft`) are still read.
|
pub use craft_deckcraft_format::{Budget, EXTENSION, FormatError, LEGACY_MIMETYPE, MIMETYPE, Result, VERSION, sniff};
|
||||||
pub const LEGACY_MIMETYPE: &str = concat!("application/vnd.storyteller.", "slide", "craft+zip");
|
use craft_deckcraft_format::{Member, Package, media_entry};
|
||||||
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,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Serialize a presentation.
|
/// Serialize a presentation.
|
||||||
pub fn save(p: &Presentation) -> Result<Vec<u8>> {
|
pub fn save(p: &Presentation) -> Result<Vec<u8>> {
|
||||||
let mut buf = Cursor::new(Vec::new());
|
save_as(p, &format!("DeckCraft {}", env!("CARGO_PKG_VERSION")))
|
||||||
{
|
|
||||||
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())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_compressed(ct: &str) -> bool {
|
/// [`save`] naming `generator` in the manifest.
|
||||||
ct.starts_with("image/jpeg")
|
fn save_as(p: &Presentation, generator: &str) -> Result<Vec<u8>> {
|
||||||
|| ct.starts_with("image/png")
|
let mut presentation = p.clone();
|
||||||
|| ct.starts_with("video/")
|
let parts = chart_parts::separate(&mut presentation)?;
|
||||||
|| ct.starts_with("audio/mpeg")
|
// Linked media saved without its bytes has no member.
|
||||||
|| ct.starts_with("audio/mp4")
|
let media: Vec<(String, &deckcraft_model::MediaItem)> =
|
||||||
|| ct.contains("zip")
|
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()
|
||||||
/// Does this look like a `.deckcraft` file?
|
.map(|(name, item)| Member { name, content_type: &item.content_type, bytes: &item.data })
|
||||||
pub fn sniff(bytes: &[u8]) -> bool {
|
.chain(parts.iter().map(|(name, content_type, bytes)| Member { name, content_type, bytes }))
|
||||||
bytes.starts_with(b"PK") && [MIMETYPE, LEGACY_MIMETYPE].iter().any(|m| bytes.windows(m.len()).take(200).any(|w| w == m.as_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)]
|
#[cfg(test)]
|
||||||
fn read_entry(z: &mut zip::ZipArchive<Cursor<&[u8]>>, name: &str) -> Result<Vec<u8>> {
|
fn read_entry_max(z: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str, max: u64) -> Result<Vec<u8>> {
|
||||||
read_entry_max(z, name, MAX_ENTRY)
|
use std::io::Read;
|
||||||
}
|
|
||||||
|
|
||||||
/// 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>> {
|
|
||||||
let f = z.by_name(name).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
let f = z.by_name(name).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||||
if f.size() > max {
|
if f.size() > max {
|
||||||
return Err(FormatError::Damaged(format!("{name} is too large")));
|
return Err(FormatError::Damaged(format!("{name} is too large")));
|
||||||
}
|
}
|
||||||
let mut out = Vec::with_capacity(f.size().min(64 << 20) as usize);
|
let mut out = vec![];
|
||||||
let mut f = f.take(max.saturating_add(1));
|
f.take(max.saturating_add(1)).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
|
||||||
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}")))?;
|
|
||||||
if out.len() as u64 > max {
|
if out.len() as u64 > max {
|
||||||
return Err(FormatError::Damaged(format!("{name} is too large")));
|
return Err(FormatError::Damaged(format!("{name} is too large")));
|
||||||
}
|
}
|
||||||
Ok(out)
|
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
|
/// 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.
|
/// learn which. A damaged chart member refuses the file before further chart inflation.
|
||||||
pub fn load(bytes: &[u8]) -> Result<Presentation> {
|
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.
|
/// 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.
|
/// Linked media saved without its bytes isn't damage.
|
||||||
pub fn load_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>)> {
|
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>)> {
|
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()))?;
|
let (m, mut z) = Package::open_manifest::<Presentation>(bytes, budget.manifest)?;
|
||||||
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 mut p = m.presentation;
|
let mut p = m.presentation;
|
||||||
let mut damaged = vec![];
|
let mut damaged = vec![];
|
||||||
let items = p.media.len();
|
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));
|
p.media.retain(|m| seen.insert(m.id));
|
||||||
let mut left = budget.total;
|
let mut left = budget.total;
|
||||||
for item in &mut p.media {
|
for item in &mut p.media {
|
||||||
let name = format!("media/{}", item.id.0);
|
let name = media_entry(item.id.0);
|
||||||
let linked_only = item.link.is_some() && z.index_for_name(&name).is_none();
|
let linked_only = item.link.is_some() && !z.contains(&name);
|
||||||
if z.by_name(&name).is_ok_and(|f| f.size() > left) {
|
if z.declared_size(&name).is_some_and(|size| size > left) {
|
||||||
return Err(FormatError::Damaged("embedded media is larger than DeckCraft can open".into()));
|
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.
|
// 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),
|
Ok(data) => item.data = Arc::new(data),
|
||||||
Err(_) if linked_only => {}
|
Err(_) if linked_only => {}
|
||||||
Err(e) => damaged.push(e.to_string()),
|
Err(e) => damaged.push(e.to_string()),
|
||||||
@@ -346,100 +243,6 @@ fn add_outline_slides(p: &mut Presentation, slides: OutlineSlides) -> usize {
|
|||||||
made
|
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).
|
/// Largest coordinate or size kept, in points (about 350 m; PowerPoint's own limit is far smaller).
|
||||||
const MAX_COORD: f64 = 1.0e6;
|
const MAX_COORD: f64 = 1.0e6;
|
||||||
|
|
||||||
|
|||||||
+82
-29
@@ -10,24 +10,24 @@ use deckcraft_model::text::{Paragraph, RunKind};
|
|||||||
|
|
||||||
/// RTF-escape `s` (non-ASCII as `\uN?`, UTF-16, signed as RTF wants).
|
/// RTF-escape `s` (non-ASCII as `\uN?`, UTF-16, signed as RTF wants).
|
||||||
fn escape(out: &mut String, s: &str) {
|
fn escape(out: &mut String, s: &str) {
|
||||||
for c in s.chars() {
|
// Keep outline text literal: the shared writer also supports page/column breaks and
|
||||||
match c {
|
// 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.
|
||||||
out.push('\\');
|
let mut start = 0;
|
||||||
out.push(c);
|
for (i, c) in s.char_indices() {
|
||||||
}
|
let replacement = match c {
|
||||||
'\t' => out.push_str("\\tab "),
|
'\u{000C}' | '\u{000E}' => "",
|
||||||
'\u{b}' | '\n' => out.push_str("\\line "),
|
'\u{00A0}' => "\\u160?",
|
||||||
c if c.is_ascii() && !c.is_ascii_control() => out.push(c),
|
'\u{00AD}' => "\\u173?",
|
||||||
c if c.is_ascii() => {}
|
'\u{2011}' => "\\u8209?",
|
||||||
c => {
|
'\u{2028}' => "\\u8232?",
|
||||||
let mut buf = [0u16; 2];
|
_ => continue,
|
||||||
for u in c.encode_utf16(&mut buf) {
|
};
|
||||||
out.push_str(&format!("\\u{}?", *u as i16));
|
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) {
|
fn runs(out: &mut String, p: &Paragraph) {
|
||||||
@@ -297,7 +297,7 @@ impl Outline<'_> {
|
|||||||
&& let Some(h) = hex
|
&& let Some(h) = hex
|
||||||
&& h != 0
|
&& h != 0
|
||||||
{
|
{
|
||||||
self.line.push(cp1252(h));
|
self.line.push(craft_rtf::codepage::cp1252(h));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,22 +384,75 @@ fn finish_surrogates(s: String) -> String {
|
|||||||
out
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
#![allow(clippy::unwrap_used)]
|
#![allow(clippy::unwrap_used)]
|
||||||
use super::*;
|
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.
|
/// A sign in a `\'hh` escape is not a hex digit and must be ignored.
|
||||||
#[test]
|
#[test]
|
||||||
fn hex_escape_rejects_sign() {
|
fn hex_escape_rejects_sign() {
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
use craft_deckcraft_format::{Manifest, parse_manifest};
|
||||||
|
use std::io::{Cursor, Read, Write};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn chart_sidecars_are_optional_for_older_native_files() {
|
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));
|
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.
|
/// including a `null` inside a tagged enum, where serde reports only the enclosing object.
|
||||||
#[test]
|
#[test]
|
||||||
fn older_files_with_null_numbers_open() {
|
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 m = Manifest { format: "deckcraft".into(), version: VERSION, generator: "old".into(), presentation: p };
|
||||||
let json = serde_json::to_vec(&m).unwrap();
|
let json = serde_json::to_vec(&m).unwrap();
|
||||||
assert!(json.windows(4).any(|w| w == b"null"));
|
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}");
|
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]
|
#[test]
|
||||||
fn other_damage_is_still_reported() {
|
fn other_damage_is_still_reported() {
|
||||||
let ok = serde_json::to_vec(&serde_json::json!({"format": "deckcraft", "version": 1, "generator": "t", "presentation": {}})).unwrap();
|
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": {}}"#;
|
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];
|
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.
|
// 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 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);
|
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
Reference in New Issue
Block a user