mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-22 05:52:29 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0886f09453 |
Generated
+291
-311
File diff suppressed because it is too large
Load Diff
+7
-7
@@ -56,10 +56,10 @@ unicode-linebreak = "0.1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["std"] }
|
||||
|
||||
# text / rendering / formats
|
||||
skrifa = "0.47"
|
||||
harfrust = "0.13"
|
||||
vello_cpu = "0.2"
|
||||
vello_common = { version = "0.2", default-features = false }
|
||||
skrifa = "0.50"
|
||||
harfrust = "0.16"
|
||||
vello_cpu = "0.4"
|
||||
vello_common = { version = "0.4", 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" }
|
||||
@@ -78,8 +78,8 @@ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "63196e66f3033a6623eb629af95a104d26986725", features = ["egui"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" }
|
||||
i_overlay = "9"
|
||||
quick-xml = "0.41"
|
||||
zip = { version = "3", default-features = false, features = ["deflate"] }
|
||||
quick-xml = "0.42"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] }
|
||||
|
||||
# ui
|
||||
@@ -88,7 +88,7 @@ egui_extras = { version = "0.37", default-features = false }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
web-time = "1.1"
|
||||
rfd = "0.17"
|
||||
rfd = "0.18"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
|
||||
@@ -31,7 +31,7 @@ craft-update = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
arboard = { workspace = true, features = ["image-data"] }
|
||||
image = { workspace = true }
|
||||
cpal = "0.16"
|
||||
cpal = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a
|
||||
|
||||
+144
-114
@@ -91,6 +91,12 @@ const SKIP: &[&str] = &[
|
||||
"pntxtb",
|
||||
];
|
||||
|
||||
/// `i + n`, or one character on when that would land inside a multi-byte character (a fallback
|
||||
/// run after `\uN` or `\'hh` may be followed by non-ASCII text).
|
||||
fn advance(rtf: &str, i: usize, n: usize) -> usize {
|
||||
if rtf.is_char_boundary(i + n) { i + n } else { i + rtf.get(i..).and_then(|r| r.chars().next()).map_or(1, char::len_utf8) }
|
||||
}
|
||||
|
||||
/// Group state: whether the text is being skipped, and the `\uc` fallback count.
|
||||
#[derive(Clone, Copy)]
|
||||
struct St {
|
||||
@@ -99,7 +105,10 @@ struct St {
|
||||
}
|
||||
|
||||
/// Parser state for [`rtf_to_outline`]: the cursor, the group stack and the outline so far.
|
||||
struct Outline {
|
||||
struct Outline<'a> {
|
||||
rtf: &'a str,
|
||||
b: &'a [u8],
|
||||
i: usize,
|
||||
stack: Vec<St>,
|
||||
st: St,
|
||||
level: Option<u32>,
|
||||
@@ -109,9 +118,6 @@ struct Outline {
|
||||
/// Which `\s1`-`\s9` the stylesheet names "heading N"; any other `\sN` is a body style.
|
||||
headings: [bool; 10],
|
||||
pending_skip: usize,
|
||||
/// Remaining UTF-8 continuation bytes to skip from the next `Token::Text` after a
|
||||
/// non-ASCII `Token::Symbol`.
|
||||
skip_cont: usize,
|
||||
line: String,
|
||||
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
|
||||
out: Vec<(usize, String)>,
|
||||
@@ -147,49 +153,60 @@ pub fn rtf_to_slides(p: &mut Presentation, rtf: &str) -> usize {
|
||||
/// The `\sN` styles the stylesheet calls "heading N": `{\s1\li360 heading 1;}`.
|
||||
fn heading_styles(rtf: &str) -> [bool; 10] {
|
||||
let mut out = [false; 10];
|
||||
let mut depth = 0usize;
|
||||
let mut stylesheet_depth: Option<usize> = None;
|
||||
let mut style: Option<i32> = None;
|
||||
let mut name = String::new();
|
||||
for token in craft_rtf::Tokens::new(rtf.as_bytes()) {
|
||||
match token {
|
||||
craft_rtf::Token::Open => {
|
||||
let Some(at) = rtf.find("\\stylesheet") else { return out };
|
||||
let b = rtf.as_bytes();
|
||||
let (mut i, mut depth) = (at + "\\stylesheet".len(), 1);
|
||||
let (mut style, mut name): (Option<usize>, String) = (None, String::new());
|
||||
while i < b.len() && depth > 0 {
|
||||
match b[i] {
|
||||
b'{' => {
|
||||
depth += 1;
|
||||
if stylesheet_depth.is_some_and(|sd| depth == sd + 1) {
|
||||
style = None;
|
||||
name.clear();
|
||||
}
|
||||
(style, name) = (None, String::new());
|
||||
}
|
||||
craft_rtf::Token::Close => {
|
||||
if stylesheet_depth.is_some_and(|sd| depth == sd + 1)
|
||||
&& let Some(n) = style.filter(|&n| (1..=9).contains(&n))
|
||||
b'}' => {
|
||||
depth -= 1;
|
||||
if depth == 1
|
||||
&& let Some(n) = style.filter(|n| (1..=9).contains(n))
|
||||
{
|
||||
out[n as usize] = name.trim().to_ascii_lowercase().starts_with("heading");
|
||||
}
|
||||
depth = depth.saturating_sub(1);
|
||||
if stylesheet_depth.is_some_and(|sd| depth < sd) {
|
||||
break;
|
||||
out[n] = name.trim().to_ascii_lowercase().starts_with("heading");
|
||||
}
|
||||
}
|
||||
craft_rtf::Token::Word { name: "stylesheet", .. } if stylesheet_depth.is_none() && depth > 0 => {
|
||||
stylesheet_depth = Some(depth);
|
||||
}
|
||||
craft_rtf::Token::Word { name: "s", param: Some(n) } if stylesheet_depth.is_some_and(|sd| depth == sd + 1) => {
|
||||
style = Some(n);
|
||||
}
|
||||
craft_rtf::Token::Text(t) if stylesheet_depth.is_some_and(|sd| depth == sd + 1) => {
|
||||
for &b in t {
|
||||
name.push(b as char);
|
||||
b'\\' => {
|
||||
let w = i + 1;
|
||||
let mut j = w;
|
||||
while j < b.len() && b[j].is_ascii_alphabetic() {
|
||||
j += 1;
|
||||
}
|
||||
let k = j;
|
||||
while j < b.len() && (b[j].is_ascii_digit() || j == k && b[j] == b'-') {
|
||||
j += 1;
|
||||
}
|
||||
if depth == 2 && &rtf[w..k] == "s" {
|
||||
style = rtf[k..j].parse().ok();
|
||||
}
|
||||
// A control symbol is one character; a control word may be followed by a space.
|
||||
i = if k == w {
|
||||
w + 1
|
||||
} else if b.get(j) == Some(&b' ') {
|
||||
j + 1
|
||||
} else {
|
||||
j
|
||||
};
|
||||
continue;
|
||||
}
|
||||
c if depth == 2 && !matches!(c, b'\r' | b'\n') => name.push(c as char),
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
let mut p = Outline {
|
||||
rtf,
|
||||
b: rtf.as_bytes(),
|
||||
i: 0,
|
||||
stack: vec![],
|
||||
st: St { skip: false, uc: 1 },
|
||||
level: None,
|
||||
@@ -197,56 +214,79 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
indent: 0,
|
||||
headings: heading_styles(rtf),
|
||||
pending_skip: 0,
|
||||
skip_cont: 0,
|
||||
line: String::new(),
|
||||
out: vec![],
|
||||
};
|
||||
p.run(rtf);
|
||||
p.run();
|
||||
p.flush(false);
|
||||
p.out.into_iter().map(|(n, t)| (n, finish_surrogates(t))).collect()
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
fn run(&mut self, rtf: &str) {
|
||||
let mut tokens = craft_rtf::Tokens::new(rtf.as_bytes());
|
||||
while let Some(token) = tokens.next() {
|
||||
match token {
|
||||
craft_rtf::Token::Open => self.open_group(),
|
||||
craft_rtf::Token::Close => self.close_group(),
|
||||
craft_rtf::Token::Star => {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.st.skip = true;
|
||||
impl Outline<'_> {
|
||||
fn run(&mut self) {
|
||||
while self.i < self.b.len() {
|
||||
match self.b[self.i] {
|
||||
b'{' => self.open_group(),
|
||||
b'}' => self.close_group(),
|
||||
b'\\' => {
|
||||
self.i += 1;
|
||||
if !self.escape() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
craft_rtf::Token::Word { name, param } => {
|
||||
self.skip_cont = 0;
|
||||
self.word(name, param);
|
||||
}
|
||||
craft_rtf::Token::Hex(h) => {
|
||||
self.skip_cont = 0;
|
||||
self.hex_escape(h);
|
||||
}
|
||||
craft_rtf::Token::Symbol(n) => self.symbol(n, rtf, tokens.offset()),
|
||||
craft_rtf::Token::Text(t) => self.text(t),
|
||||
craft_rtf::Token::Bin(_) => self.skip_cont = 0,
|
||||
b'\r' | b'\n' => self.i += 1,
|
||||
_ => self.text(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `{`: push the group; `{\*\dest …}` is an ignorable destination.
|
||||
fn open_group(&mut self) {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.stack.push(self.st);
|
||||
self.i += 1;
|
||||
if self.b[self.i..].starts_with(b"\\*") {
|
||||
self.st.skip = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn close_group(&mut self) {
|
||||
self.pending_skip = 0;
|
||||
self.skip_cont = 0;
|
||||
self.st = self.stack.pop().unwrap_or(St { skip: false, uc: 1 });
|
||||
self.i += 1;
|
||||
}
|
||||
|
||||
fn word(&mut self, word: &str, arg: Option<i32>) {
|
||||
if self.pending_skip > 0 && word != "u" {
|
||||
/// The character after a backslash: a control word, a hex escape or a symbol. False at the
|
||||
/// end of the input.
|
||||
fn escape(&mut self) -> bool {
|
||||
let Some(&n) = self.b.get(self.i) else { return false };
|
||||
if n.is_ascii_alphabetic() {
|
||||
self.control_word();
|
||||
} else if n == b'\'' {
|
||||
self.hex_escape();
|
||||
} else {
|
||||
self.symbol(n);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn control_word(&mut self) {
|
||||
let rtf = self.rtf;
|
||||
let s = self.i;
|
||||
while self.i < self.b.len() && self.b[self.i].is_ascii_alphabetic() {
|
||||
self.i += 1;
|
||||
}
|
||||
let word = &rtf[s..self.i];
|
||||
let ns = self.i;
|
||||
if self.i < self.b.len() && (self.b[self.i] == b'-' || self.b[self.i].is_ascii_digit()) {
|
||||
self.i += 1;
|
||||
while self.i < self.b.len() && self.b[self.i].is_ascii_digit() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
let arg: Option<i64> = rtf[ns..self.i].parse().ok();
|
||||
if self.i < self.b.len() && self.b[self.i] == b' ' {
|
||||
self.i += 1;
|
||||
}
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
@@ -258,7 +298,7 @@ impl Outline {
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, word: &str, arg: Option<i32>) {
|
||||
fn apply(&mut self, word: &str, arg: Option<i64>) {
|
||||
match word {
|
||||
"par" => self.flush(true),
|
||||
"pard" => {
|
||||
@@ -272,10 +312,10 @@ impl Outline {
|
||||
"s" => {
|
||||
self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1);
|
||||
}
|
||||
"li" => self.indent = i64::from(arg.unwrap_or(0)),
|
||||
"li" => self.indent = arg.unwrap_or(0),
|
||||
"tab" | "line" => self.line.push(' '),
|
||||
"uc" => self.st.uc = arg.unwrap_or(1).clamp(0, 8) as usize,
|
||||
"u" => self.unicode(i64::from(arg.unwrap_or(0))),
|
||||
"u" => self.unicode(arg.unwrap_or(0)),
|
||||
"emdash" => self.line.push('—'),
|
||||
"endash" => self.line.push('–'),
|
||||
"bullet" => self.line.push('•'),
|
||||
@@ -291,32 +331,40 @@ impl Outline {
|
||||
fn unicode(&mut self, v: i64) {
|
||||
// RTF writes UTF-16 units as signed 16-bit values.
|
||||
push_utf16(&mut self.line, (v & 0xffff) as u32);
|
||||
self.pending_skip = self.st.uc;
|
||||
self.pending_skip = 0;
|
||||
let mut k = self.st.uc;
|
||||
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 {
|
||||
self.i = advance(self.rtf, self.i, 1);
|
||||
}
|
||||
k -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// `\'hh`: one cp1252 byte.
|
||||
fn hex_escape(&mut self, h: u8) {
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
if !self.st.skip && h != 0 {
|
||||
fn hex_escape(&mut self) {
|
||||
let hex =
|
||||
self.rtf.get(self.i + 1..self.i + 3).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())).and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
self.i = advance(self.rtf, self.i, 3);
|
||||
if !self.st.skip
|
||||
&& let Some(h) = hex
|
||||
&& h != 0
|
||||
{
|
||||
self.line.push(craft_rtf::codepage::cp1252(h));
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-character control symbol (`\\`, `\{`, `\~`, ...).
|
||||
fn symbol(&mut self, n: u8, rtf: &str, offset: usize) {
|
||||
let cont = if !n.is_ascii() {
|
||||
rtf.get(offset.saturating_sub(1)..).and_then(|r| r.chars().next()).map(|c| (c, c.len_utf8().saturating_sub(1)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.skip_cont = cont.map_or(0, |(_, k)| k);
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
fn symbol(&mut self, n: u8) {
|
||||
let c = self.rtf.get(self.i..).and_then(|r| r.chars().next());
|
||||
self.i = advance(self.rtf, self.i, 1);
|
||||
if self.st.skip {
|
||||
return;
|
||||
}
|
||||
@@ -325,30 +373,21 @@ impl Outline {
|
||||
b'~' => self.line.push('\u{a0}'),
|
||||
b'_' => self.line.push('\u{2011}'),
|
||||
b'\n' | b'\r' => self.flush(true),
|
||||
_ => {
|
||||
if let Some((c, _)) = cont {
|
||||
self.line.push(c);
|
||||
}
|
||||
}
|
||||
_ if !n.is_ascii() => self.line.extend(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plain text up to the next special character.
|
||||
fn text(&mut self, t: &[u8]) {
|
||||
let skip_cont = std::mem::take(&mut self.skip_cont);
|
||||
let t = t.get(skip_cont..).unwrap_or_default();
|
||||
let Ok(mut s) = std::str::from_utf8(t) else { return };
|
||||
if self.pending_skip > 0 {
|
||||
if let Some((idx, _)) = s.char_indices().nth(self.pending_skip) {
|
||||
self.pending_skip = 0;
|
||||
s = &s[idx..];
|
||||
} else {
|
||||
self.pending_skip -= s.chars().count();
|
||||
return;
|
||||
}
|
||||
fn text(&mut self) {
|
||||
let s = self.i;
|
||||
while self.i < self.b.len() && !matches!(self.b[self.i], b'{' | b'}' | b'\\' | b'\r' | b'\n') {
|
||||
self.i += 1;
|
||||
}
|
||||
if !self.st.skip {
|
||||
self.line.push_str(s);
|
||||
if !self.st.skip
|
||||
&& let Some(t) = self.rtf.get(s..self.i)
|
||||
{
|
||||
self.line.push_str(&t.replace('\u{0}', ""));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -496,7 +535,7 @@ mod tests {
|
||||
/// A sign in a `\'hh` escape is not a hex digit and must be ignored.
|
||||
#[test]
|
||||
fn hex_escape_rejects_sign() {
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1 a\'+5b\par}"), "a+5b\n");
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1 a\'+5b\par}"), "ab\n");
|
||||
}
|
||||
|
||||
/// Non-ASCII text after a `\\uN` or `\\'hh` escape used to split a character and panic.
|
||||
@@ -546,10 +585,10 @@ mod tests {
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1\pard Year\_end review\par}"), "Year\u{2011}end review\n");
|
||||
}
|
||||
|
||||
/// A hostile `\li` near `i32::MAX` (clamped from 10 digits by `craft_rtf::Tokens`) must not overflow.
|
||||
/// A hostile `\li` near `i64::MAX` overflowed the rounding addend in debug builds.
|
||||
#[test]
|
||||
fn huge_left_indent_gives_the_deepest_level() {
|
||||
let out = rtf_to_outline(r"{\rtf1\pard\li9999999999 deep\par\pard\li-9999999999 flat\par}");
|
||||
let out = rtf_to_outline(r"{\rtf1\pard\li9223372036854775807 deep\par\pard\li-9223372036854775808 flat\par}");
|
||||
assert_eq!(out, format!("{}deep\nflat\n", "\t".repeat(9)));
|
||||
}
|
||||
|
||||
@@ -642,13 +681,4 @@ mod tests {
|
||||
let rtf = r"{\rtf1\ansi\pard Title\par\pard\fi-360\li720{\listtext\pard\plain\f1\'b7\tab}Point\par\pard\li720{\pntext\f1\'b7\tab}Old\par}";
|
||||
assert_eq!(rtf_to_outline(rtf), "Title\n\t\tPoint\n\t\tOld\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surrogate_pairs_bullets_and_binary_groups_survive_tokenization() {
|
||||
let rtf = "{\\rtf1\\ansi{\\stylesheet{\\s1\\li360 heading 1;}{\\s2\\li1080 heading 2;}}\\pard\\s1 \\u-10179?\\u-8704? \\u-10179?\\par\\pard\\s1 \\par\\pard\\s2 \\bullet item\\par{\\pict\\bin5 {\\}\0\\x}\\pard\\s1 - title\\par}";
|
||||
assert_eq!(rtf_to_outline(rtf), "😀 \u{fffd}\n\t• item\n- title\n");
|
||||
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
|
||||
assert_eq!(rtf_to_slides(&mut p, rtf), 3);
|
||||
assert_eq!(crate::slides_to_outline(&p), "😀 \u{fffd}\n\n\t• item\n- title\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,73 +304,3 @@ fn export_tool_lists_gif_and_its_options() {
|
||||
assert_eq!(r["result"]["isError"], true, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_initialize_negotiation_transcript() {
|
||||
let mut lines: Vec<Value> = craft_mcp_server::SUPPORTED_VERSIONS
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, version)| {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": i + 1,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": version, "capabilities": {}, "clientInfo": {"name": "parity-client", "version": "1.0"}},
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
lines.push(json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 99,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": "1999-01-01", "capabilities": {}, "clientInfo": {"name": "parity-client", "version": "1.0"}},
|
||||
}));
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
|
||||
lines.push(json!({"jsonrpc": "2.0", "id": 100, "method": "ping", "params": {}}));
|
||||
let input: String = lines.iter().map(|v| v.to_string() + "\n").collect();
|
||||
|
||||
let mut s = Server::new(Box::new(Headless::new()));
|
||||
let mut out = Vec::new();
|
||||
s.serve(std::io::Cursor::new(input), &mut out).unwrap();
|
||||
assert!(s.is_initialized());
|
||||
|
||||
let replies: Vec<Value> = std::str::from_utf8(&out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), craft_mcp_server::SUPPORTED_VERSIONS.len() + 2);
|
||||
for (i, version) in craft_mcp_server::SUPPORTED_VERSIONS.iter().enumerate() {
|
||||
assert_eq!(replies[i]["id"], i + 1);
|
||||
assert_eq!(replies[i]["result"]["protocolVersion"], *version);
|
||||
assert_eq!(replies[i]["result"]["serverInfo"]["name"], "deckcraft");
|
||||
}
|
||||
let fallback = &replies[craft_mcp_server::SUPPORTED_VERSIONS.len()];
|
||||
assert_eq!(fallback["id"], 99);
|
||||
assert_eq!(fallback["result"]["protocolVersion"], craft_mcp_server::PROTOCOL_VERSION);
|
||||
let ping = &replies[craft_mcp_server::SUPPORTED_VERSIONS.len() + 1];
|
||||
assert_eq!(ping["id"], 100);
|
||||
assert_eq!(ping["result"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdio_cancel_and_batch_transcript() {
|
||||
let input = concat!(
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\"}}\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":1,\"reason\":\"client\"}}\n",
|
||||
"[]\n",
|
||||
"[{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\"params\":{\"requestId\":9}}]\n",
|
||||
"[{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"},{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\"}]\n",
|
||||
"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"ping\",\"params\":{}}\n"
|
||||
);
|
||||
let mut s = Server::new(Box::new(Headless::new()));
|
||||
let mut out = Vec::new();
|
||||
s.serve(std::io::Cursor::new(input), &mut out).unwrap();
|
||||
assert!(s.is_initialized());
|
||||
|
||||
let replies: Vec<Value> = std::str::from_utf8(&out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||||
assert_eq!(replies.len(), 4, "{replies:?}");
|
||||
assert_eq!(replies[0]["id"], 1);
|
||||
assert_eq!(replies[0]["result"]["serverInfo"]["name"], "deckcraft");
|
||||
assert_eq!(replies[1]["id"], Value::Null);
|
||||
assert_eq!(replies[1]["error"]["code"], -32600);
|
||||
assert_eq!(replies[2], json!([{"jsonrpc": "2.0", "id": 2, "result": {}}]));
|
||||
assert_eq!(replies[3], json!({"jsonrpc": "2.0", "id": 3, "result": {}}));
|
||||
}
|
||||
|
||||
@@ -18,4 +18,4 @@ log = { workspace = true }
|
||||
image = { workspace = true }
|
||||
# Audio decoding for the formats we have no decoder of our own for (MPL-2.0, used unmodified,
|
||||
# as in FilmCraft).
|
||||
symphonia = { version = "0.5.5", default-features = false, features = ["aac", "adpcm", "alac", "flac", "mp1", "mp2", "mp3", "pcm", "vorbis", "wav", "aiff", "caf", "ogg", "mkv", "isomp4"] }
|
||||
symphonia = { version = "0.6.1", default-features = false, features = ["aac", "adpcm", "alac", "flac", "mp1", "mp2", "mp3", "pcm", "vorbis", "wav", "aiff", "caf", "ogg", "mkv", "isomp4"] }
|
||||
|
||||
@@ -20,7 +20,7 @@ thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std"] }
|
||||
hayro-syntax = { version = "=0.9.0", default-features = false, features = ["std"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
|
||||
+11
-230
@@ -519,9 +519,7 @@ fn shapes_have_over_cap_table(shapes: &[Shape]) -> bool {
|
||||
|
||||
fn check_table_caps(p: &Presentation) -> Result<(), PptxError> {
|
||||
let over = p.slides.iter().any(|s| shapes_have_over_cap_table(&s.shapes))
|
||||
|| p.masters.iter().any(|m| shapes_have_over_cap_table(&m.shapes) || m.layouts.iter().any(|l| shapes_have_over_cap_table(&l.shapes)))
|
||||
|| p.notes_master.as_ref().is_some_and(|m| shapes_have_over_cap_table(&m.shapes))
|
||||
|| p.handout_master.as_ref().is_some_and(|m| shapes_have_over_cap_table(&m.shapes));
|
||||
|| p.masters.iter().any(|m| shapes_have_over_cap_table(&m.shapes) || m.layouts.iter().any(|l| shapes_have_over_cap_table(&l.shapes)));
|
||||
if over {
|
||||
return Err(PptxError::Unsupported(format!(
|
||||
"a table has more than {} cells; export refused rather than drop rows",
|
||||
@@ -541,7 +539,7 @@ fn media_needs_timing(clip: &deckcraft_model::MediaClip) -> bool {
|
||||
|| (clip.video && clip.full_screen)
|
||||
}
|
||||
|
||||
fn assign_spids<'a>(shapes: &'a [Shape], mut visit: impl FnMut(u32, &'a Shape)) {
|
||||
fn collect_export_media<'a>(shapes: &'a [Shape]) -> Vec<(u32, &'a deckcraft_model::MediaClip)> {
|
||||
let mut used = std::collections::HashSet::new();
|
||||
let mut max = 1u32;
|
||||
deckcraft_model::walk(shapes, &mut |s, _| {
|
||||
@@ -550,6 +548,7 @@ fn assign_spids<'a>(shapes: &'a [Shape], mut visit: impl FnMut(u32, &'a Shape))
|
||||
}
|
||||
});
|
||||
let mut next = max;
|
||||
let mut media = Vec::new();
|
||||
deckcraft_model::walk(shapes, &mut |s, _| {
|
||||
let spid = if s.id.0 >= 2 && s.id.0 < i32::MAX as u32 && !used.contains(&s.id.0) {
|
||||
s.id.0
|
||||
@@ -558,13 +557,6 @@ fn assign_spids<'a>(shapes: &'a [Shape], mut visit: impl FnMut(u32, &'a Shape))
|
||||
next
|
||||
};
|
||||
used.insert(spid);
|
||||
visit(spid, s);
|
||||
});
|
||||
}
|
||||
|
||||
fn collect_export_media(shapes: &[Shape]) -> Vec<(u32, &deckcraft_model::MediaClip)> {
|
||||
let mut media = Vec::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if let ShapeKind::Media(clip) = &s.kind
|
||||
&& media_needs_timing(clip)
|
||||
{
|
||||
@@ -574,18 +566,6 @@ fn collect_export_media(shapes: &[Shape]) -> Vec<(u32, &deckcraft_model::MediaCl
|
||||
media
|
||||
}
|
||||
|
||||
fn collect_grp_fill_pic_spids(shapes: &[Shape]) -> std::collections::HashSet<u32> {
|
||||
let mut spids = std::collections::HashSet::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if s.fill == Some(deckcraft_model::style::Fill::Group)
|
||||
&& matches!(s.kind, ShapeKind::Picture { .. } | ShapeKind::Opaque { preview: Some(_), .. })
|
||||
{
|
||||
spids.insert(spid);
|
||||
}
|
||||
});
|
||||
spids
|
||||
}
|
||||
|
||||
fn write_media_node(w: &mut craft_xml::Writer, id: &mut u32, spid: u32, clip: &deckcraft_model::MediaClip) {
|
||||
let tag = if clip.video { "p:video" } else { "p:audio" };
|
||||
let mut t = w.tag(tag);
|
||||
@@ -662,144 +642,9 @@ fn patch_slide_media_timing(xml_bytes: &[u8], media: &[(u32, &deckcraft_model::M
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ShapeOwner {
|
||||
Sp,
|
||||
CxnSp,
|
||||
Pic,
|
||||
}
|
||||
|
||||
/// Returns the owning shape kind and closing-tag byte offset for a `<p:cNvPr id="…">` at
|
||||
/// `start..after`, or `None` if it belongs to a non-shape container (`<p:grpSp>`,
|
||||
/// `<p:graphicFrame>`) or would cross into another shape.
|
||||
fn owning_shape_end(xml: &str, start: usize, after: usize) -> Option<(ShapeOwner, usize)> {
|
||||
let before = &xml[..start];
|
||||
let (nv_pos, owner) = [(ShapeOwner::Sp, "<p:nvSpPr>"), (ShapeOwner::CxnSp, "<p:nvCxnSpPr>"), (ShapeOwner::Pic, "<p:nvPicPr>")]
|
||||
.into_iter()
|
||||
.filter_map(|(owner, tag)| before.rfind(tag).map(|pos| (pos, owner)))
|
||||
.max_by_key(|(pos, _)| *pos)?;
|
||||
let between = &before[nv_pos..];
|
||||
if ["<p:nvGrpSpPr>", "<p:nvGraphicFramePr>", "</p:nvSpPr>", "</p:nvCxnSpPr>", "</p:nvPicPr>"].iter().any(|t| between.contains(t)) {
|
||||
return None;
|
||||
}
|
||||
let close_tag = match owner {
|
||||
ShapeOwner::Sp => "</p:sp>",
|
||||
ShapeOwner::CxnSp => "</p:cxnSp>",
|
||||
ShapeOwner::Pic => "</p:pic>",
|
||||
};
|
||||
let end_rel = xml[after..].find(close_tag)?;
|
||||
let span = &xml[after..after + end_rel];
|
||||
if ["<p:sp>", "<p:sp ", "<p:cxnSp>", "<p:cxnSp ", "<p:pic>", "<p:pic ", "<p:grpSp>", "<p:grpSp ", "<p:graphicFrame>", "<p:graphicFrame "]
|
||||
.iter()
|
||||
.any(|t| span.contains(t))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((owner, after + end_rel))
|
||||
}
|
||||
|
||||
fn patch_pic_grp_fill(xml_bytes: &[u8], spids: &std::collections::HashSet<u32>) -> Vec<u8> {
|
||||
let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else {
|
||||
return xml_bytes.to_vec();
|
||||
};
|
||||
for &spid in spids {
|
||||
let needle = format!(r#"<p:cNvPr id="{spid}""#);
|
||||
let mut search_from = 0;
|
||||
while let Some(rel) = xml[search_from..].find(&needle) {
|
||||
let start = search_from + rel;
|
||||
let after = start + needle.len();
|
||||
let boundary_ok = xml.as_bytes().get(after).is_some_and(|b| matches!(b, b' ' | b'/' | b'>'));
|
||||
if boundary_ok
|
||||
&& let Some((ShapeOwner::Pic, pic_end)) = owning_shape_end(&xml, start, after)
|
||||
&& let Some(sp_pr_rel) = xml[after..pic_end].find("<p:spPr>")
|
||||
{
|
||||
let sp_pr_start = after + sp_pr_rel + "<p:spPr>".len();
|
||||
if let Some(sp_pr_end_rel) = xml[sp_pr_start..pic_end].find("</p:spPr>") {
|
||||
let sp_pr_end = sp_pr_start + sp_pr_end_rel;
|
||||
let inner = &xml[sp_pr_start..sp_pr_end];
|
||||
if !inner.contains("<a:grpFill") {
|
||||
let insert_rel = ["<a:ln", "<a:effectLst", "<a:effectDag", "<a:scene3d", "<a:sp3d", "<a:extLst"]
|
||||
.iter()
|
||||
.filter_map(|tag| inner.find(tag))
|
||||
.min()
|
||||
.unwrap_or(sp_pr_end_rel);
|
||||
xml.insert_str(sp_pr_start + insert_rel, "<a:grpFill/>");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
search_from = after;
|
||||
}
|
||||
}
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
fn collect_large_geom_adjs(shapes: &[Shape]) -> Vec<(u32, &[f64])> {
|
||||
let mut out = Vec::new();
|
||||
assign_spids(shapes, |spid, s| {
|
||||
if let deckcraft_model::Geom::Preset { adj, .. } = &s.geom
|
||||
&& adj.iter().any(|v| v.is_finite() && (v.round() < -2.0e9 || v.round() > 2.0e9))
|
||||
{
|
||||
out.push((spid, adj.as_slice()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn patch_shape_av_lst(xml: &mut String, after: usize, shape_end: usize, adj: &[f64]) {
|
||||
let Some(av_rel) = xml[after..shape_end].find("<a:avLst>") else { return };
|
||||
let av_start = after + av_rel + "<a:avLst>".len();
|
||||
let Some(av_end_rel) = xml[av_start..shape_end].find("</a:avLst>") else { return };
|
||||
let mut av_end = av_start + av_end_rel;
|
||||
for (i, &v) in adj.iter().take(16).enumerate() {
|
||||
if !v.is_finite() || (v.round() >= -2.0e9 && v.round() <= 2.0e9) {
|
||||
continue;
|
||||
}
|
||||
let clamped = v.round().clamp(-2.0e9, 2.0e9) as i64;
|
||||
let actual = v.round() as i64;
|
||||
let single_name = format!(r#"<a:gd name="adj" fmla="val {clamped}"/>"#);
|
||||
let idx_name = format!(r#"<a:gd name="adj{}" fmla="val {clamped}"/>"#, i + 1);
|
||||
let (target, repl) = if i == 0 && xml[av_start..av_end].contains(&single_name) {
|
||||
(single_name, format!(r#"<a:gd name="adj" fmla="val {actual}"/>"#))
|
||||
} else {
|
||||
(idx_name, format!(r#"<a:gd name="adj{}" fmla="val {actual}"/>"#, i + 1))
|
||||
};
|
||||
if let Some(rel) = xml[av_start..av_end].find(&target) {
|
||||
let pos = av_start + rel;
|
||||
xml.replace_range(pos..pos + target.len(), &repl);
|
||||
av_end = av_end + repl.len() - target.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn patch_large_geom_adjs(xml_bytes: &[u8], adjs: &[(u32, &[f64])]) -> Vec<u8> {
|
||||
let Ok(mut xml) = String::from_utf8(xml_bytes.to_vec()) else {
|
||||
return xml_bytes.to_vec();
|
||||
};
|
||||
for &(spid, adj) in adjs {
|
||||
let needle = format!(r#"<p:cNvPr id="{spid}""#);
|
||||
let mut search_from = 0;
|
||||
while let Some(rel) = xml[search_from..].find(&needle) {
|
||||
let start = search_from + rel;
|
||||
let after = start + needle.len();
|
||||
if xml.as_bytes().get(after).is_some_and(|b| matches!(b, b' ' | b'/' | b'>'))
|
||||
&& let Some((_, shape_end)) = owning_shape_end(&xml, start, after)
|
||||
{
|
||||
patch_shape_av_lst(&mut xml, after, shape_end, adj);
|
||||
break;
|
||||
}
|
||||
search_from = after;
|
||||
}
|
||||
}
|
||||
xml.into_bytes()
|
||||
}
|
||||
|
||||
fn patch_exported_slides(p: &Presentation, bytes: Vec<u8>) -> Result<Vec<u8>, PptxError> {
|
||||
fn patch_exported_media_timing(p: &Presentation, bytes: Vec<u8>) -> Result<Vec<u8>, PptxError> {
|
||||
let slide_media: Vec<Vec<(u32, &deckcraft_model::MediaClip)>> = p.slides.iter().map(|s| collect_export_media(&s.shapes)).collect();
|
||||
let slide_grp_pics: Vec<std::collections::HashSet<u32>> = p.slides.iter().map(|s| collect_grp_fill_pic_spids(&s.shapes)).collect();
|
||||
let slide_adjs: Vec<Vec<(u32, &[f64])>> = p.slides.iter().map(|s| collect_large_geom_adjs(&s.shapes)).collect();
|
||||
if slide_media.iter().all(Vec::is_empty) && slide_grp_pics.iter().all(std::collections::HashSet::is_empty) && slide_adjs.iter().all(Vec::is_empty)
|
||||
{
|
||||
if slide_media.iter().all(Vec::is_empty) {
|
||||
return Ok(bytes);
|
||||
}
|
||||
let pkg = craft_opc::Package::open(&bytes, &craft_pptx::LIMITS).map_err(|e| PptxError::Write(e.to_string()))?;
|
||||
@@ -812,26 +657,14 @@ fn patch_exported_slides(p: &Presentation, bytes: Vec<u8>) -> Result<Vec<u8>, Pp
|
||||
&& let Some(list) = pres_el.child(craft_xml::Local("sldIdLst"))
|
||||
{
|
||||
for (i, s) in list.children(craft_xml::Local("sldId")).enumerate() {
|
||||
let media = slide_media.get(i).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let grp_pics = slide_grp_pics.get(i);
|
||||
let adjs = slide_adjs.get(i).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let need_grp = grp_pics.is_some_and(|g| !g.is_empty());
|
||||
if media.is_empty() && !need_grp && adjs.is_empty() {
|
||||
let Some(media) = slide_media.get(i) else { break };
|
||||
if media.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(target) = s.attr_local("r:id").and_then(|rid| pres_rels.target(rid))
|
||||
&& let Some(sb) = pkg.get(target)
|
||||
{
|
||||
let mut patched = if media.is_empty() { sb.to_vec() } else { patch_slide_media_timing(sb, media) };
|
||||
if let Some(g) = grp_pics
|
||||
&& !g.is_empty()
|
||||
{
|
||||
patched = patch_pic_grp_fill(&patched, g);
|
||||
}
|
||||
if !adjs.is_empty() {
|
||||
patched = patch_large_geom_adjs(&patched, adjs);
|
||||
}
|
||||
patches.insert(target.to_string(), patched);
|
||||
patches.insert(target.to_string(), patch_slide_media_timing(sb, media));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -852,16 +685,15 @@ fn patch_exported_slides(p: &Presentation, bytes: Vec<u8>) -> Result<Vec<u8>, Pp
|
||||
pub fn export(p: &Presentation) -> Result<Vec<u8>, PptxError> {
|
||||
check_table_caps(p)?;
|
||||
let bytes = craft_pptx::export(&convert::pres_to_craft(p), &DeckDefaults)?;
|
||||
patch_exported_slides(p, bytes)
|
||||
patch_exported_media_timing(p, bytes)
|
||||
}
|
||||
|
||||
/// Write a package for `ext`: `potx` (template) and `ppsx` (slide show) differ from `pptx` only in
|
||||
/// the main part's content type.
|
||||
pub fn export_as(p: &Presentation, ext: &str) -> Result<Vec<u8>, PptxError> {
|
||||
check_table_caps(p)?;
|
||||
let ext = ext.trim_start_matches('.').to_ascii_lowercase();
|
||||
let bytes = craft_pptx::export_as(&convert::pres_to_craft(p), &DeckDefaults, &ext)?;
|
||||
patch_exported_slides(p, bytes)
|
||||
let bytes = craft_pptx::export_as(&convert::pres_to_craft(p), &DeckDefaults, ext)?;
|
||||
patch_exported_media_timing(p, bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -970,55 +802,4 @@ mod table_direction_tests {
|
||||
let err = crate::export(&p).expect_err("over-cap table must be refused");
|
||||
assert!(matches!(err, crate::PptxError::Unsupported(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_cap_table_on_notes_and_handout_master_is_refused() {
|
||||
let mut t = Table::new(1, 2, 200.0, 30.0);
|
||||
t.rows.resize_with(deckcraft_model::table::MAX_CELLS / 2 + 1, || deckcraft_model::table::Row {
|
||||
height: 20.0,
|
||||
cells: vec![Cell::new("x"), Cell::new("y")],
|
||||
});
|
||||
let mut p_notes = defaults::new_presentation(None);
|
||||
let shape = Shape { id: ShapeId(p_notes.alloc_id().expect("id")), kind: ShapeKind::Table(t.clone()), ..Default::default() };
|
||||
p_notes.notes_master = Some(Arc::new(deckcraft_model::Master { name: "Notes".into(), shapes: vec![shape], ..Default::default() }));
|
||||
assert!(matches!(crate::export(&p_notes), Err(crate::PptxError::Unsupported(_))));
|
||||
|
||||
let mut p_handout = defaults::new_presentation(None);
|
||||
let shape = Shape { id: ShapeId(p_handout.alloc_id().expect("id")), kind: ShapeKind::Table(t), ..Default::default() };
|
||||
p_handout.handout_master = Some(Arc::new(deckcraft_model::Master { name: "Handout".into(), shapes: vec![shape], ..Default::default() }));
|
||||
assert!(matches!(crate::export(&p_handout), Err(crate::PptxError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shape_owner_scoping_tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn patch_pic_grp_fill_does_not_cross_into_following_pic() {
|
||||
let xml = concat!(
|
||||
r#"<p:sp><p:nvSpPr><p:cNvPr id="5" name="Box"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr/></p:sp>"#,
|
||||
r#"<p:pic><p:nvPicPr><p:cNvPr id="6" name="Pic"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr><p:spPr><a:ln/></p:spPr></p:pic>"#,
|
||||
);
|
||||
let spids = HashSet::from([5]);
|
||||
let out = String::from_utf8(super::patch_pic_grp_fill(xml.as_bytes(), &spids)).expect("utf8");
|
||||
assert!(!out.contains("<a:grpFill/>"), "non-pic owner id=5 must not patch pic id=6: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patch_large_geom_adjs_does_not_leak_from_group_into_child_shape() {
|
||||
let xml = concat!(
|
||||
r#"<p:grpSp><p:nvGrpSpPr><p:cNvPr id="10" name="Group"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>"#,
|
||||
r#"<p:sp><p:nvSpPr><p:cNvPr id="11" name="Child"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>"#,
|
||||
r#"<p:spPr><a:prstGeom prst="roundRect"><a:avLst><a:gd name="adj" fmla="val 2000000000"/></a:avLst></a:prstGeom></p:spPr></p:sp>"#,
|
||||
r#"</p:grpSp>"#,
|
||||
);
|
||||
let adjs = [(10_u32, &[3_000_000_000.0_f64][..])];
|
||||
let out = String::from_utf8(super::patch_large_geom_adjs(xml.as_bytes(), &adjs)).expect("utf8");
|
||||
assert!(out.contains(r#"fmla="val 2000000000""#), "group id=10 must not patch child id=11: {out}");
|
||||
|
||||
let child_adjs = [(11_u32, &[3_000_000_000.0_f64][..])];
|
||||
let patched = String::from_utf8(super::patch_large_geom_adjs(xml.as_bytes(), &child_adjs)).expect("utf8");
|
||||
assert!(patched.contains(r#"fmla="val 3000000000""#), "child id=11 should be patched: {patched}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,33 +444,3 @@ fn a_shared_notes_part_is_read_once() {
|
||||
assert_eq!(q.slides[0].notes.text(), "notes 0");
|
||||
assert!(q.slides[1..].iter().all(|s| s.notes.text().is_empty()), "a shared notes part is not copied");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_master_and_handout_master_shape_count_bounds() {
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
let mut p = defaults::new_presentation(None);
|
||||
Arc::make_mut(&mut p.slides[0]).notes = deckcraft_model::text::TextBody::from_text("note");
|
||||
p.handout_master = Some(Arc::new(deckcraft_model::Master { name: "Handouts".into(), ..Default::default() }));
|
||||
let mut es = entries(&deckcraft_pptx::export(&p).expect("export"));
|
||||
let mut many = String::new();
|
||||
for i in 2..=20_050 {
|
||||
let _ = write!(many, r#"<p:sp><p:nvSpPr><p:cNvPr id="{i}" name="S{i}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr/></p:sp>"#);
|
||||
}
|
||||
for (n, d) in es.iter_mut() {
|
||||
if n == "ppt/notesMasters/notesMaster1.xml" || n == "ppt/handoutMasters/handoutMaster1.xml" {
|
||||
let xml = String::from_utf8(d.clone()).expect("utf8");
|
||||
if let Some(pos) = xml.rfind("</p:spTree>") {
|
||||
let mut patched = String::with_capacity(xml.len() + many.len());
|
||||
patched.push_str(&xml[..pos]);
|
||||
patched.push_str(&many);
|
||||
patched.push_str(&xml[pos..]);
|
||||
*d = patched.into_bytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
let q = deckcraft_pptx::import(&rezip(&es)).expect("bounded import");
|
||||
assert_eq!(q.notes_master.as_ref().expect("notes_master").shapes.len(), 20_000);
|
||||
assert_eq!(q.handout_master.as_ref().expect("handout_master").shapes.len(), 20_000);
|
||||
deckcraft_pptx::export(&q).expect("re-export");
|
||||
}
|
||||
|
||||
@@ -2347,62 +2347,3 @@ fn reflection_angles_and_skews_out_of_range_are_written_inside_the_schema() {
|
||||
let r = round(&p).slides.last().and_then(|sl| by_name(sl, "Reflected").effects.clone()).and_then(|fx| fx.reflection).expect("reflection");
|
||||
assert_eq!((r.st_pos, r.dir, r.fade_dir, r.kx, r.ky), (Some(100_000), Some(21_599_995), Some(0), Some(5_399_999), Some(-5_399_999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pptx_potx_ppsx_export_parity_preserves_masters_charts_themes_and_timing() {
|
||||
let mut p = rich_deck();
|
||||
let m0 = Arc::make_mut(&mut p.masters[0]);
|
||||
m0.theme.name = "ParityTheme".into();
|
||||
m0.theme.colors.set(deckcraft_color::SchemeSlot::Accent1, deckcraft_color::Rgba::rgb(0x11, 0x22, 0x33));
|
||||
p.notes_master = Some(Arc::new(deckcraft_model::Master { name: "NotesParity".into(), ..Default::default() }));
|
||||
p.handout_master = Some(Arc::new(deckcraft_model::Master { name: "HandoutParity".into(), ..Default::default() }));
|
||||
|
||||
let audio = p.add_media("cue.m4a", "audio/mp4", b"audio-bytes".to_vec()).expect("media");
|
||||
let aud_id = ShapeId(p.alloc_id().expect("id"));
|
||||
Arc::make_mut(&mut p.slides[0]).shapes.push(Shape {
|
||||
id: aud_id,
|
||||
name: "Cue".into(),
|
||||
xfrm: Some(Xfrm::new(20.0, 20.0, 40.0, 40.0)),
|
||||
kind: ShapeKind::Media(deckcraft_model::MediaClip {
|
||||
media: audio,
|
||||
video: false,
|
||||
autoplay: true,
|
||||
loop_play: true,
|
||||
volume: 0.5,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let edited_values = vec![Some(111.5), Some(222.25), Some(333.75), Some(444.0)];
|
||||
let chart_slide_idx = p.slides.iter().position(|sl| sl.shapes.iter().any(|s| s.name == "Chart 0")).expect("chart slide");
|
||||
{
|
||||
let ch_shape = Arc::make_mut(&mut p.slides[chart_slide_idx]).shapes.iter_mut().find(|s| s.name == "Chart 0").expect("Chart 0");
|
||||
ch_shape.name = "Revenue Chart".into();
|
||||
let ShapeKind::Chart(ch) = &mut ch_shape.kind else { panic!("expected chart") };
|
||||
ch.series[0].values = edited_values.clone();
|
||||
}
|
||||
|
||||
for (ext, expected_ct) in [
|
||||
("pptx", "presentationml.presentation.main+xml"),
|
||||
("potx", "presentationml.template.main+xml"),
|
||||
("POTX", "presentationml.template.main+xml"),
|
||||
(".ppsx", "presentationml.slideshow.main+xml"),
|
||||
] {
|
||||
let bytes = deckcraft_pptx::export_as(&p, ext).expect("export_as");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).expect("zip");
|
||||
let ct = std::io::read_to_string(z.by_name("[Content_Types].xml").expect("content types")).expect("read");
|
||||
assert!(ct.contains(expected_ct), "{ext}: {ct}");
|
||||
let reopened = deckcraft_pptx::import(&bytes).expect("reopen");
|
||||
assert_eq!(reopened.masters[0].theme.name, "ParityTheme");
|
||||
assert_eq!(reopened.masters[0].theme.colors.get(deckcraft_color::SchemeSlot::Accent1), deckcraft_color::Rgba::rgb(0x11, 0x22, 0x33));
|
||||
assert!(reopened.notes_master.is_some());
|
||||
assert_eq!(reopened.handout_master.as_ref().map(|m| m.name.as_str()), Some("HandoutParity"));
|
||||
let cue = reopened.slides[0].shapes.iter().find(|s| s.name == "Cue").expect("cue");
|
||||
let ShapeKind::Media(clip) = &cue.kind else { panic!("expected media") };
|
||||
assert!(clip.autoplay && clip.loop_play && (clip.volume - 0.5).abs() < 1e-3);
|
||||
let chart_shape = reopened.slides[chart_slide_idx].shapes.iter().find(|s| s.name == "Revenue Chart").expect("named chart");
|
||||
let ShapeKind::Chart(chart) = &chart_shape.kind else { panic!("expected chart") };
|
||||
assert_eq!(chart.series[0].values, edited_values, "{ext}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user