From 64d3127fe85cfdab48fd56ce2d888cec24b91676 Mon Sep 17 00:00:00 2001 From: Hamza Date: Sun, 18 Oct 2026 00:03:38 +0500 Subject: [PATCH 01/76] Header & Footer: an automatic date's format comes back on import MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `header_footer()` recorded a Date placeholder's text only when it held no field, and never looked at the field itself, so an automatic date's format was dropped on import: `date_format` stayed empty whatever the deck used. With the dialog of the previous commit that is not only cosmetic. Opening a deck whose dates are `datetime5` showed `datetime1` selected, and pressing Apply then sent that back and reformatted the deck's dates — a silent change to a file the user only opened to look at. The reader now remembers which of the thirteen formats the field is, so the dialog opens on the deck's own choice. An unknown spelling (`datetime`, `datetimeFigureOut`, which both render as the short date) is left as no choice rather than guessed at, since the command only accepts the thirteen and would refuse it. A fixed date still comes back as its text, as before. `crates/pptx` gains a dependency on `crates/text` for `datetime::DATE_KINDS`, which layer 3 may take on layer 2; `cargo xtask layers` passes. --- Cargo.lock | 1 + crates/pptx/Cargo.toml | 1 + crates/pptx/src/read.rs | 27 ++++++++++++--- crates/pptx/tests/header_footer_date.rs | 45 +++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 crates/pptx/tests/header_footer_date.rs diff --git a/Cargo.lock b/Cargo.lock index 01a92e4a5..5aa455924 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1217,6 +1217,7 @@ dependencies = [ "deckcraft-engine", "deckcraft-geom", "deckcraft-model", + "deckcraft-text", "image", "log", "quick-xml 0.41.0", diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index 0ea79d6b4..8d1e0fc34 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] deckcraft-model = { workspace = true } +deckcraft-text = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } quick-xml = { workspace = true } diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 18e8eb92f..412bc8f25 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -1332,11 +1332,28 @@ fn header_footer(p: &Presentation) -> HeaderFooter { Some(PhType::SlideNum) => hf.slide_number = true, Some(PhType::Date) => { hf.date = true; - if let Some(t) = &sh.text - && !t.paragraphs.iter().flat_map(|p| &p.runs).any(|r| matches!(r.kind, deckcraft_model::text::RunKind::Field { .. })) - && hf.date_text.is_empty() - { - hf.date_text = t.text(); + let field = sh.text.iter().flat_map(|t| t.paragraphs.iter()).flat_map(|p| p.runs.iter()).find_map(|r| match &r.kind { + deckcraft_model::text::RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.as_str()), + _ => None, + }); + match field { + // An automatic date: remember which of the thirteen formats it is, so the + // Header and Footer dialog opens on the deck's own choice instead of the + // default. An unknown spelling (`datetime`, `datetimeFigureOut`) is left + // as no choice rather than guessed at. + Some(kind) => { + if hf.date_format.is_empty() && deckcraft_text::datetime::DATE_KINDS.contains(&kind) { + hf.date_format = kind.to_string(); + } + } + // A fixed date: its text, as before. + None => { + if hf.date_text.is_empty() + && let Some(t) = &sh.text + { + hf.date_text = t.text(); + } + } } } Some(PhType::Footer) => { diff --git a/crates/pptx/tests/header_footer_date.rs b/crates/pptx/tests/header_footer_date.rs new file mode 100644 index 000000000..99b263082 --- /dev/null +++ b/crates/pptx/tests/header_footer_date.rs @@ -0,0 +1,45 @@ +//! The Header & Footer date through PPTX: an automatic date's format comes back on import, so the +//! dialog opens on the deck's own choice; a fixed date still comes back as its text. + +use deckcraft_model::{Presentation, defaults}; +use serde_json::json; + +/// A deck whose Date placeholders are set up by the engine, exported and imported again. +fn round_trip(args: serde_json::Value) -> Presentation { + let mut s = deckcraft_engine::Session::with_new(); + s.execute("design.headerFooter", &args).expect("headerFooter"); + let p = s.doc().expect("doc").doc.clone(); + let bytes = deckcraft_pptx::export(&p).expect("export"); + deckcraft_pptx::import(&bytes).expect("import") +} + +#[test] +fn an_automatic_dates_format_survives_a_round_trip() { + // A chosen format comes back as the remembered choice. + let q = round_trip(json!({"date": true, "dateFormat": "datetime5", "all": true})); + assert!(q.header_footer.date, "the date placeholder is there"); + assert_eq!(q.header_footer.date_format, "datetime5", "the format is remembered"); + assert_eq!(q.header_footer.date_text, "", "an automatic date has no fixed text"); + + // A different one, so the test cannot pass by always reading datetime5. + let q = round_trip(json!({"date": true, "dateFormat": "datetime11", "all": true})); + assert_eq!(q.header_footer.date_format, "datetime11"); + + // The default: no format asked for, so nothing to remember beyond the field itself. + let q = round_trip(json!({"date": true, "all": true})); + assert_eq!(q.header_footer.date_format, "datetime1", "the placeholder's own field is datetime1"); + + // A fixed date is text, not a field: its text comes back and no format is claimed. + let q = round_trip(json!({"date": true, "dateText": "4 July 1776", "all": true})); + assert_eq!(q.header_footer.date_text, "4 July 1776"); + assert_eq!(q.header_footer.date_format, "", "a fixed date has no format"); +} + +#[test] +fn a_deck_without_a_date_placeholder_claims_no_format() { + let p = defaults::new_presentation(None); + let bytes = deckcraft_pptx::export(&p).expect("export"); + let q = deckcraft_pptx::import(&bytes).expect("import"); + assert!(!q.header_footer.date); + assert_eq!(q.header_footer.date_format, ""); +} From 3a1a74d2aa83f9c17ab602f5e62afb5c67046951 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 20:39:57 +0500 Subject: [PATCH 02/76] format.font: set the East Asian and complex-script typefaces (#786) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A run carries a typeface per script (ECMA-376 §21.1.2.3): `a:latin`, `a:ea` and `a:cs`. `format.font` set only the Latin one, so a CJK run kept drawing -- and saving -- in whatever `a:ea` named before, and there was no way to change it. `eastAsia` and `complexScript` set the other two. Left out they keep their value, which is what the command has always done. A name that is empty or longer than the Font dialog allows is refused rather than stored. Rebased onto main, 637 commits on: engine's format.rs is split, so `font` and `typeface_param` are in cmd/format/font.rs, the command's registry entry stays in cmd/format.rs, and the tests went to cmd/text.rs. --- crates/engine/src/cmd/format.rs | 10 +++- crates/engine/src/cmd/format/font.rs | 32 +++++++++++- crates/engine/src/cmd/text.rs | 73 ++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 6e9e75ce8..25c15c92a 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -62,7 +62,15 @@ pub fn specs() -> Vec { ), cmd!("format.superscript", "Superscript", ["Home", "Font"], Some("Cmd+Shift+="), "{on?: bool}", has_text_or_shapes, superscript), cmd!("format.subscript", "Subscript", ["Home", "Font"], Some("Cmd+="), "{on?: bool}", has_text_or_shapes, subscript), - cmd!("format.font", "Font", ["Home", "Font"], None, "{family}", has_text_or_shapes, font), + cmd!( + "format.font", + "Font", + ["Home", "Font"], + None, + "{family, eastAsia?: family, complexScript?: family} — `family` is the Latin typeface (`a:latin`); the other two set the East Asian (`a:ea`) and complex-script (`a:cs`) typefaces, which are left alone when not given", + has_text_or_shapes, + font + ), cmd!("format.size", "Font Size", ["Home", "Font"], None, "{size: pt}", has_text_or_shapes, size), cmd!("format.grow", "Increase Font Size", ["Home", "Font"], Some("Cmd+Shift+."), "{}", has_text_or_shapes, grow), cmd!("format.shrink", "Decrease Font Size", ["Home", "Font"], Some("Cmd+Shift+,"), "{}", has_text_or_shapes, shrink), diff --git a/crates/engine/src/cmd/format/font.rs b/crates/engine/src/cmd/format/font.rs index 11af99b7e..db7e4ec6e 100644 --- a/crates/engine/src/cmd/format/font.rs +++ b/crates/engine/src/cmd/format/font.rs @@ -45,9 +45,37 @@ pub(super) fn subscript(s: &mut Session, p: &Value) -> Result { format_run(s, &move |r| r.baseline = Some(if v { -0.25 } else { 0.0 })) } +/// A typeface name from `key`: trimmed, and the length `format.fontDialog` allows. +fn typeface_param(p: &Value, key: &str) -> Result> { + match str_param(p, key) { + None => Ok(None), + Some(v) => { + let t = v.trim(); + if t.is_empty() || t.chars().count() > 200 { + return Err(bad("format.font", format!("`{key}` must be 1-200 characters"))); + } + Ok(Some(t.to_string())) + } + } +} + pub(super) fn font(s: &mut Session, p: &Value) -> Result { - let f = str_param(p, "family").ok_or_else(|| bad("format.font", "missing `family`"))?.to_string(); - format_run(s, &move |r| r.font = Some(f.clone())) + let f = typeface_param(p, "family")?.ok_or_else(|| bad("format.font", "missing `family`"))?; + // A run carries a typeface per script (ECMA-376 §21.1.2.3): `a:latin`, `a:ea` and `a:cs`. + // Setting only the Latin one leaves a CJK run drawing -- and saving -- in whatever `a:ea` + // named before, so the two are settable (#786). Left out, they keep their value, which is + // what `format.font` has always done. + let ea = typeface_param(p, "eastAsia")?; + let cs = typeface_param(p, "complexScript")?; + format_run(s, &move |r| { + r.font = Some(f.clone()); + if let Some(v) = &ea { + r.font_ea = Some(v.clone()); + } + if let Some(v) = &cs { + r.font_cs = Some(v.clone()); + } + }) } pub(super) fn size(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 6f85df870..d441e6421 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -186,3 +186,76 @@ pub(crate) fn edit_text(s: &mut Session, f: impl FnOnce(&mut TextBody, &mut T } Ok(r) } + +#[cfg(test)] +mod font_script_tests { + use super::*; + + /// Every run's (latin, east asian, complex script) typefaces in the deck. + fn typefaces(s: &mut Session) -> Vec<(Option, Option, Option)> { + s.doc() + .unwrap() + .doc + .slides + .iter() + .flat_map(|sl| sl.shapes.iter()) + .filter_map(|sh| sh.text.as_ref()) + .flat_map(|t| t.paragraphs.iter()) + .flat_map(|para| para.runs.iter()) + .map(|r| (r.props.font.clone(), r.props.font_ea.clone(), r.props.font_cs.clone())) + .collect() + } + + #[test] + fn format_font_sets_the_east_asian_and_complex_script_typefaces() { + // A run carries a typeface per script; setting only the Latin one leaves a CJK run + // drawing, and saving, in whatever `a:ea` named before (#786). + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap(); + s.execute("text.exit", &json!({})).unwrap(); + + // All three at once. + s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC", "complexScript": "Noto Sans Arabic"})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]); + + // The Latin-only call keeps its old meaning: the other two are left alone, which is + // what makes the new parameters additive. + s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]); + + // And they reach the file: the issue is that a saved deck kept asking for the old + // East Asian font. + let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + // The text box is on whichever slide was current, so look across all of them. + let mut xml = String::new(); + for i in 0..zip.len() { + let mut f = zip.by_index(i).unwrap(); + if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") { + std::io::Read::read_to_string(&mut f, &mut xml).unwrap(); + } + } + assert!(xml.contains(r#""#), "no a:ea in the saved slides"); + assert!(xml.contains(r#""#), "no a:cs in the saved slides"); + assert!(xml.contains(r#""#), "no a:latin in the saved slides"); + + // Read back, they are still there. + s.execute("file.openBytes", &json!({"name": "f.pptx", "data": crate::cmd::base64_encode(&bytes)})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]); + } + + #[test] + fn format_font_rejects_an_unusable_typeface_name() { + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "Hello"})).unwrap(); + s.execute("text.exit", &json!({})).unwrap(); + for p in [json!({"family": " "}), json!({"family": "Lato", "eastAsia": ""}), json!({"family": "Lato", "complexScript": "x".repeat(201)})] { + assert!(s.execute("format.font", &p).is_err(), "{p} should be rejected"); + } + // A name with spaces around it is kept, trimmed. + s.execute("format.font", &json!({"family": " Lato ", "eastAsia": " Noto Sans CJK SC "})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]); + } +} From 372c0e6c4445fd6aa029a8f11bfca1ec03124c87 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 16:48:32 +0500 Subject: [PATCH 03/76] Apply only a date format the caller asked for The dialog always sends `dateText`, so an Apply with no format selection reached `set_date` carrying the deck's global format, and rewrote a slide's own date field to it. Measured on two slides, the first on the time format and the second on the short date: before [datetime11, datetime5] apply {"date": true, "dateText": "", "all": true} after [datetime5, datetime5] The first slide's format was never mentioned by the caller, and it was gone. `set_date` already keeps an existing field when the format is empty, so it now gets an empty format unless `dateFormat` was supplied; a format that is supplied still reaches every slide, which the test checks so the guard cannot quietly become a block. --- crates/engine/src/cmd/design/slide_setup.rs | 33 ++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/design/slide_setup.rs b/crates/engine/src/cmd/design/slide_setup.rs index 86d9317b7..ed91d3253 100644 --- a/crates/engine/src/cmd/design/slide_setup.rs +++ b/crates/engine/src/cmd/design/slide_setup.rs @@ -176,7 +176,12 @@ pub(super) fn header_footer(s: &mut Session, p: &Value) -> Result { } (Some(pos), true) if k == PhType::Date && (date_given || format_given) => { if let Some(sh) = sl.shapes.get_mut(pos) { - set_date(sh, &hf.date_text, &hf.date_format); + // Only a format the caller asked for. The dialog always sends + // `dateText`, so an Apply with no format selection reached here and + // rewrote a slide's own `datetime11` field to the deck's global + // format, which the caller never mentioned (noted in review). No + // format means the field keeps the one it has. + set_date(sh, &hf.date_text, if format_given { &hf.date_format } else { "" }); } } _ => {} @@ -298,6 +303,32 @@ mod header_footer_date_tests { got[0].0.clone() } + /// The dialog always sends `dateText`, so an Apply with no format selection reached + /// `set_date` with the deck's global format and rewrote a slide's own date field to it. The + /// format the caller did not mention is not a format the caller asked for (noted in review). + #[test] + fn an_apply_with_no_format_leaves_each_slides_own_format_alone() { + let mut s = Session::with_new(); + s.execute("slide.new", &json!({})).unwrap(); + s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime11", "all": true})).unwrap(); + let kinds = |s: &Session| dates(s).into_iter().map(|(_, k)| k).collect::>(); + assert_eq!(kinds(&s), vec![Some("datetime11".to_string()); 2], "both slides start on the time format"); + + // One slide alone takes a different format, which also becomes the deck's global one. + s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime5", "all": false})).unwrap(); + assert_eq!(kinds(&s), vec![Some("datetime11".to_string()), Some("datetime5".to_string())]); + assert_eq!(s.doc().unwrap().doc.header_footer.date_format, "datetime5"); + + // Apply with no `dateFormat`: the first slide keeps datetime11 rather than being rewritten + // to the global datetime5. + s.execute("design.headerFooter", &json!({"date": true, "dateText": "", "all": true})).unwrap(); + assert_eq!(kinds(&s), vec![Some("datetime11".to_string()), Some("datetime5".to_string())], "neither slide was rewritten"); + + // And a format that *is* given still reaches every slide, so the guard is not a block. + s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime2", "all": true})).unwrap(); + assert_eq!(kinds(&s), vec![Some("datetime2".to_string()); 2], "a format the caller asked for still applies"); + } + /// Header & Footer's automatic date takes the format it is given. `HeaderFooter::date_format` /// existed for this and was never read: the placeholder was always `datetime1`, and a /// `dateFormat` parameter was accepted and silently dropped. From 1a16bf975c8416e668ca33d77a91de3d466ffe31 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 15:43:23 +0500 Subject: [PATCH 04/76] format.font: a script typeface that is not a string is refused `str_param` answers `None` both for an absent key and for a key holding something that is not a string, so `typeface_param` read the two as the same thing. With `{"family": "Lato", "eastAsia": 42}` the command set the Latin typeface, left the East Asian one as it was and reported success -- the one thing the caller asked for was the one thing that did not happen (noted in review). Read through `p.get(key)` instead, the way `opt_usize_param` and `id_param` already read theirs: an absent key, and an explicit `null`, still mean the script keeps its typeface; anything else present has to be a string. `family` is judged the same way, so `{"family": 42}` now says the key is not a typeface name rather than that it is missing. --- crates/engine/src/cmd/format/font.rs | 23 ++++++++++++++--------- crates/engine/src/cmd/text.rs | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/format/font.rs b/crates/engine/src/cmd/format/font.rs index db7e4ec6e..b8bc622f8 100644 --- a/crates/engine/src/cmd/format/font.rs +++ b/crates/engine/src/cmd/format/font.rs @@ -46,17 +46,22 @@ pub(super) fn subscript(s: &mut Session, p: &Value) -> Result { } /// A typeface name from `key`: trimmed, and the length `format.fontDialog` allows. +/// +/// Absent, as `opt_usize_param` and `id_param` read an absent key, so a call that leaves a script +/// out keeps that typeface. Present but not a string is refused: `str_param` answers `None` to +/// both, so `{"family": "Lato", "eastAsia": 42}` used to set the Latin typeface, leave the East +/// Asian one alone and report success -- the one thing the caller asked for silently not done +/// (noted in review). fn typeface_param(p: &Value, key: &str) -> Result> { - match str_param(p, key) { - None => Ok(None), - Some(v) => { - let t = v.trim(); - if t.is_empty() || t.chars().count() > 200 { - return Err(bad("format.font", format!("`{key}` must be 1-200 characters"))); - } - Ok(Some(t.to_string())) - } + let v = match p.get(key) { + None | Some(Value::Null) => return Ok(None), + Some(v) => v.as_str().ok_or_else(|| bad("format.font", format!("`{key}` is not a typeface name: {v}")))?, + }; + let t = v.trim(); + if t.is_empty() || t.chars().count() > 200 { + return Err(bad("format.font", format!("`{key}` must be 1-200 characters"))); } + Ok(Some(t.to_string())) } pub(super) fn font(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index d441e6421..b922bf8d9 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -254,6 +254,30 @@ mod font_script_tests { for p in [json!({"family": " "}), json!({"family": "Lato", "eastAsia": ""}), json!({"family": "Lato", "complexScript": "x".repeat(201)})] { assert!(s.execute("format.font", &p).is_err(), "{p} should be rejected"); } + + // A script key that is present but not a string is refused, not read as absent. It used + // to set `family` and report success with the script typeface untouched, so the one thing + // the call asked for was the one thing that did not happen (noted in review). + for p in [ + json!({"family": "Lato", "eastAsia": 42}), + json!({"family": "Lato", "complexScript": true}), + json!({"family": "Lato", "eastAsia": ["Noto Sans CJK SC"]}), + json!({"family": "Lato", "complexScript": {"name": "Noto Sans Arabic"}}), + json!({"family": 42}), + ] { + let e = s.execute("format.font", &p).expect_err(&format!("{p} should be rejected")); + assert!(format!("{e}").contains("is not a typeface name"), "{p}: {e}"); + } + // Nothing above changed a run: the first call in this test left `family` unset, and a + // refused call must not have set it on the way to the error. + assert_eq!(typefaces(&mut s), vec![(None, None, None)]); + + // An explicit `null` reads as absent, as it does for an index or a shape id, so the + // script keeps whatever typeface it had. + s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap(); + s.execute("format.font", &json!({"family": "Lato", "eastAsia": null})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]); + // A name with spaces around it is kept, trimmed. s.execute("format.font", &json!({"family": " Lato ", "eastAsia": " Noto Sans CJK SC "})).unwrap(); assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]); From 370b38e69ad007e115da5b0b8168e23659c05b5d Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 15:57:14 +0500 Subject: [PATCH 05/76] A date with no field to keep takes the deck's remembered format My previous commit withheld the format from `set_date` whenever the caller had not named one, so a field the slide already had would not be rewritten. That is right where there is a field. A placeholder showing a fixed date holds plain text and no date field at all, so there was no format to preserve and the withheld format left `date_kind("")` to build a `datetime1`: a slide taken from `datetime11` to fixed text and back came away on the short date (noted in review). The deck's format now always reaches `set_date`, and `format_given` is what decides whether it may rewrite an existing field. With no field, there is nothing to preserve and the remembered format is what a new one takes. `a_fixed_date_turned_automatic_again_comes_back_on_the_remembered_format` walks that transition with no `dateFormat` in the call, which is what the dialog sends, and goes on to assert the guard still holds where a field does exist. It is a test of its own rather than more of `the_automatic_date_takes_the_format_it_is_given`, because setting a format for one slide also moves the deck's global one, which that test's later assertions depend on. --- crates/engine/src/cmd/design/slide_setup.rs | 49 +++++++++++++++++---- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/design/slide_setup.rs b/crates/engine/src/cmd/design/slide_setup.rs index ed91d3253..32534255a 100644 --- a/crates/engine/src/cmd/design/slide_setup.rs +++ b/crates/engine/src/cmd/design/slide_setup.rs @@ -176,12 +176,10 @@ pub(super) fn header_footer(s: &mut Session, p: &Value) -> Result { } (Some(pos), true) if k == PhType::Date && (date_given || format_given) => { if let Some(sh) = sl.shapes.get_mut(pos) { - // Only a format the caller asked for. The dialog always sends - // `dateText`, so an Apply with no format selection reached here and - // rewrote a slide's own `datetime11` field to the deck's global - // format, which the caller never mentioned (noted in review). No - // format means the field keeps the one it has. - set_date(sh, &hf.date_text, if format_given { &hf.date_format } else { "" }); + // The deck's format always travels; whether the caller asked for it + // is what decides if it may rewrite a field the slide already has + // (see `set_date`). + set_date(sh, &hf.date_text, &hf.date_format, format_given); } } _ => {} @@ -205,8 +203,19 @@ fn date_now(format: &str) -> String { } /// Point a slide's date placeholder at a fixed date (its own plain text) or, for an empty -/// `fixed`, at an automatic date field (one it already has keeps its format). -fn set_date(sh: &mut Shape, fixed: &str, format: &str) { +/// `fixed`, at an automatic date field. +/// +/// `format_given` is whether the caller named a format. The dialog always sends `dateText`, so an +/// Apply with no format selection reached here carrying the deck's global format and rewrote a +/// slide's own `datetime11` field to it -- a format the caller never mentioned. A field the slide +/// already has therefore keeps its own format unless one was asked for. +/// +/// That holds only where there *is* a field to keep. A placeholder showing a fixed date has no +/// date field and no format of its own, so clearing `dateText` without naming a format used to +/// build a `datetime1`: a slide that went from `datetime11` to fixed text and back came away on +/// the short date. With nothing to preserve, the deck's remembered format is the right one to +/// take (noted in review). +fn set_date(sh: &mut Shape, fixed: &str, format: &str, format_given: bool) { let runs = || sh.text.iter().flat_map(|t| &t.paragraphs).flat_map(|p| &p.runs); let field_now = runs().find_map(|r| match &r.kind { RunKind::Field { field } if deckcraft_text::datetime::is_date_field(field) => Some(field.clone()), @@ -214,6 +223,7 @@ fn set_date(sh: &mut Shape, fixed: &str, format: &str) { }); let has_field = field_now.is_some(); let props = runs().next().map(|r| r.props.clone()).unwrap_or_default(); + let format = if format_given || !has_field { format } else { "" }; let want = date_kind(format); let (text, kind) = match fixed { // Automatic: keep the field, but follow a format that has changed. @@ -329,6 +339,29 @@ mod header_footer_date_tests { assert_eq!(kinds(&s), vec![Some("datetime2".to_string()); 2], "a format the caller asked for still applies"); } + /// A fixed date is plain text, so the placeholder has no date field and no format of its + /// own. Clearing `dateText` without naming a format therefore has nothing to preserve, and + /// built a `datetime1`: a slide that went from `datetime11` to fixed text and back came away + /// on the short date (noted in review). + #[test] + fn a_fixed_date_turned_automatic_again_comes_back_on_the_remembered_format() { + let mut s = Session::with_new(); + run_automatic(&mut s, json!({"date": true, "dateFormat": "datetime11", "all": true}), "datetime11"); + + s.execute("design.headerFooter", &json!({"date": true, "dateText": "4 July 1776", "all": true})).unwrap(); + assert_eq!(dates(&s), vec![("4 July 1776".to_string(), None)], "fixed: plain text, no field"); + + // No `dateFormat` in this call, which is what the dialog sends on an Apply. + run_automatic(&mut s, json!({"date": true, "dateText": "", "all": true}), "datetime11"); + + // And the guard this must not undo: where there *is* a field, an Apply naming no format + // still leaves the slide's own format alone, although the deck's format now reaches + // `set_date` either way. + s.execute("design.headerFooter", &json!({"date": true, "dateFormat": "datetime5", "all": false})).unwrap(); + s.execute("design.headerFooter", &json!({"date": true, "dateText": "", "all": true})).unwrap(); + assert_eq!(dates(&s)[0].1.as_deref(), Some("datetime5"), "the slide's own format survives"); + } + /// Header & Footer's automatic date takes the format it is given. `HeaderFooter::date_format` /// existed for this and was never read: the placeholder was always `datetime1`, and a /// `dateFormat` parameter was accepted and silently dropped. From e39e693dab723bba6a0fa83a0cf39b0c98b83a1b Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 3 Nov 2026 17:07:28 +0500 Subject: [PATCH 06/76] format.font: a CJK run takes its East Asian typeface, and each script is set on its own --- crates/engine/src/cmd/text.rs | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index b922bf8d9..6872c3501 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -282,4 +282,40 @@ mod font_script_tests { s.execute("format.font", &json!({"family": " Lato ", "eastAsia": " Noto Sans CJK SC "})).unwrap(); assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]); } + + /// Each script's typeface is set on its own, and a run whose text is entirely CJK takes its + /// East Asian one: that is the run #786 is about, where `a:latin` alone changes nothing that + /// is drawn (noted in review). + #[test] + fn a_cjk_run_takes_the_east_asian_typeface_and_each_script_is_set_on_its_own() { + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + s.execute("insert.textBox", &json!({"rect": [10, 10, 300, 50], "text": "你好世界"})).unwrap(); + s.execute("text.exit", &json!({})).unwrap(); + + // `eastAsia` alone (with the required `family`): the complex-script typeface is untouched. + s.execute("format.font", &json!({"family": "Lato", "eastAsia": "Noto Sans CJK SC"})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), None)]); + + // `complexScript` alone: the East Asian typeface just set is kept, not cleared. + s.execute("format.font", &json!({"family": "Lato", "complexScript": "Noto Sans Arabic"})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Lato".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]); + + // A Latin-only call on the CJK run changes `a:latin` and nothing a CJK glyph is drawn in. + s.execute("format.font", &json!({"family": "Comic Neue"})).unwrap(); + assert_eq!(typefaces(&mut s), vec![(Some("Comic Neue".into()), Some("Noto Sans CJK SC".into()), Some("Noto Sans Arabic".into()))]); + + // The saved run carries its text and the East Asian typeface together. + let bytes = crate::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let mut xml = String::new(); + for i in 0..zip.len() { + let mut f = zip.by_index(i).unwrap(); + if f.name().starts_with("ppt/slides/slide") && f.name().ends_with(".xml") { + std::io::Read::read_to_string(&mut f, &mut xml).unwrap(); + } + } + let run = xml.find("你好世界").and_then(|at| xml[..at].rfind("").map(|start| &xml[start..at])).unwrap_or_default(); + assert!(run.contains(r#""#), "the CJK run has no a:ea: {run}"); + } } From 9e7fab103882cd1c3b8274389d1b858f11f1ad71 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 21:05:30 +0000 Subject: [PATCH 07/76] PPTX import: budget preserved theme XML, SmartArt drawing shapes and diagram definitions across the presentation --- crates/pptx/src/read.rs | 12 ++++++++++++ crates/pptx/src/read/shapes.rs | 34 ++++++++++++++++++++++++++++------ crates/pptx/src/read/theme.rs | 11 ++++++++++- 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 288e497f8..958058be1 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -46,6 +46,12 @@ pub struct Imp<'a> { pub tag_bytes: usize, /// The tag budget ran out and the warning was given. pub tags_capped: bool, + /// Bytes of preserved theme XML kept by the masters read so far. + pub theme_extra_bytes: usize, + /// Shapes read from SmartArt drawings so far (see `shapes::MAX_SMARTART_SHAPES`). + pub smartart_shapes: usize, + /// Bytes of SmartArt layout, style and colour definitions copied into diagrams so far. + pub diagram_xml_bytes: usize, } impl Imp<'_> { @@ -446,6 +452,9 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec< tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + theme_extra_bytes: 0, + smartart_shapes: 0, + diagram_xml_bytes: 0, }; let part = Part::new(&pkg, &theme_path, &doc); let theme = theme::read_theme(&mut imp, &part, &doc.root); @@ -487,6 +496,9 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxE tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + theme_extra_bytes: 0, + smartart_shapes: 0, + diagram_xml_bytes: 0, }; // Slide ids first so hyperlinks anywhere can point at slides. let slide_ids = register_slides(&mut imp, &docs, &slide_entries, &mut lost_slides); diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index b3e3d48e6..142dcdb1b 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -558,9 +558,20 @@ fn diagram_data(imp: &mut Imp, target: &str) -> Option Some(id) } +/// Shapes all SmartArt drawings of one presentation may add; a frame read after that is left as a +/// placeholder. Each frame that references a drawing reads it again. +const MAX_SMARTART_SHAPES: usize = 250_000; + +/// SmartArt definition XML (layout, style, colours) all diagrams of one presentation may copy. +const MAX_DIAGRAM_XML_BYTES: usize = 32 << 20; + +fn count_shapes(shapes: &[Shape]) -> usize { + shapes.iter().map(|s| 1 + count_shapes(s.children())).sum() +} + /// SmartArt: read the pre-drawn shapes of its drawing part as a group. fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> Option { - if depth > 8 { + if depth > 8 || imp.smartart_shapes >= MAX_SMARTART_SHAPES { return None; } let rel_ids = gd.child("relIds")?; @@ -576,6 +587,8 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> if children.is_empty() { return None; } + // A drawing that frames reuse (or that nests another SmartArt) counts every time it is read. + imp.smartart_shapes = imp.smartart_shapes.saturating_add(count_shapes(&children)); let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1); let mut g = frame.clone(); let x = frame.xfrm.unwrap_or_default(); @@ -703,15 +716,22 @@ fn text_area(geom: &Geom, w: f64, h: f64) -> deckcraft_geom::Rect { /// The outline of a SmartArt graphic (for the Text Pane), with its layout, quick style and colour /// parts kept to be written back. -fn diagram_outline(imp: &Imp, part: &Part, rel_ids: &El, data: &El) -> Option { +fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Option { let nodes = crate::dgm::outline(data); if nodes.is_empty() { return None; } + let (pkg, spent) = (imp.pkg, std::cell::Cell::new(imp.diagram_xml_bytes)); let raw = |attr: &str| -> Option { let rel = part.rels.get(rel_ids.attr(attr)?)?; - let bytes = imp.pkg.get(&rel.target)?; - (bytes.len() <= 4 << 20).then(|| String::from_utf8(bytes.to_vec()).ok()).flatten() + let bytes = pkg.get(&rel.target)?; + // Every diagram copies its definitions, so the copies share one presentation-wide budget. + if bytes.len() > 4 << 20 || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES { + return None; + } + let xml = String::from_utf8(bytes.to_vec()).ok()?; + spent.set(spent.get() + xml.len()); + Some(xml) }; let layout_xml = raw("r:lo"); let (layout_id, cat) = layout_xml @@ -732,6 +752,8 @@ fn diagram_outline(imp: &Imp, part: &Part, rel_ids: &El, data: &El) -> Option Option) -> FontSet { FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts } } +/// Bytes of preserved theme XML (object defaults and extra colour schemes) all masters of one +/// presentation may keep. +const MAX_THEME_EXTRA_BYTES: usize = 16 << 20; + pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme { let mut t = Theme { name: root.attr("name").unwrap_or("Theme").to_string(), ..Default::default() }; let Some(te) = root.child("themeElements") else { return t }; @@ -89,8 +93,13 @@ pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme { .filter(|e| !super::has_rel_refs(e)) .map(|e| part.keep(e)) .collect(); - if !extra.is_empty() { + // Every master that references this theme keeps its own copy of the preserved XML, so the + // copies share one budget for the presentation. + if !extra.is_empty() && imp.theme_extra_bytes.saturating_add(extra.len()) <= MAX_THEME_EXTRA_BYTES { + imp.theme_extra_bytes += extra.len(); t.raw_extra = Some(extra); + } else if !extra.is_empty() { + log::warn!("pptx: theme object defaults not kept; the preserved-XML budget is spent"); } t } From 2dbcbc0c8a590548954368826f575723f99626a6 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:16:10 +0000 Subject: [PATCH 08/76] Apply review fixes - crates/engine/src/cmd/format.rs - crates/engine/src/cmd/format/font.rs --- crates/engine/src/cmd/format.rs | 2 +- crates/engine/src/cmd/format/font.rs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 25c15c92a..b91354117 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Font", ["Home", "Font"], None, - "{family, eastAsia?: family, complexScript?: family} — `family` is the Latin typeface (`a:latin`); the other two set the East Asian (`a:ea`) and complex-script (`a:cs`) typefaces, which are left alone when not given", + "{family, eastAsia?: family, complexScript?: family} — `family` is the Latin typeface (`a:latin`); the other two set the East Asian (`a:ea`) and complex-script (`a:cs`) typefaces, which are left alone when not given", has_text_or_shapes, font ), diff --git a/crates/engine/src/cmd/format/font.rs b/crates/engine/src/cmd/format/font.rs index b8bc622f8..2920649ae 100644 --- a/crates/engine/src/cmd/format/font.rs +++ b/crates/engine/src/cmd/format/font.rs @@ -50,8 +50,7 @@ pub(super) fn subscript(s: &mut Session, p: &Value) -> Result { /// Absent, as `opt_usize_param` and `id_param` read an absent key, so a call that leaves a script /// out keeps that typeface. Present but not a string is refused: `str_param` answers `None` to /// both, so `{"family": "Lato", "eastAsia": 42}` used to set the Latin typeface, leave the East -/// Asian one alone and report success -- the one thing the caller asked for silently not done -/// (noted in review). +/// Asian one alone and report success -- the one thing the caller asked for silently not done. fn typeface_param(p: &Value, key: &str) -> Result> { let v = match p.get(key) { None | Some(Value::Null) => return Ok(None), From 953ae8d060d7486cbd10632db2a4a3c54eeefe84 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:44:51 +0000 Subject: [PATCH 09/76] Apply review fixes - crates/pptx/src/read/shapes.rs --- crates/pptx/src/read/shapes.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index b2f058819..c2e9293fc 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -584,12 +584,13 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> let dpart = Part::new(imp.pkg, &drawing_rel, &d); let tree = d.root.child("spTree")?; let mut sub = IdCtx { fresh: true, ..Default::default() }; + let before = imp.smartart_shapes; let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1); if children.is_empty() { return None; } - // A drawing that frames reuse (or that nests another SmartArt) counts every time it is read. - imp.smartart_shapes = imp.smartart_shapes.saturating_add(count_shapes(&children)); + // Counted once here, nested SmartArt included: a drawing that frames reuse counts every time it is read. + imp.smartart_shapes = before.saturating_add(count_shapes(&children)); let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1); let mut g = frame.clone(); let x = frame.xfrm.unwrap_or_default(); From 283a1484202601689f905e4b02fc483f347f1fdf Mon Sep 17 00:00:00 2001 From: Naseq Date: Sun, 8 Nov 2026 09:07:05 +0430 Subject: [PATCH 10/76] ui-egui: cfg opening_generation off wasm32; lint the wasm set with -D warnings (#1954) --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/lib.rs | 3 ++- xtask/src/main.rs | 8 +++++--- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 178ab24ba..5c1314657 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -72,6 +72,7 @@ impl SlideApp { synthetic_injected_time: None, ribbon_scroll: HashMap::new(), show_instance: 0, + #[cfg(not(target_arch = "wasm32"))] opening_generation: 0, canvas_rect: None, eyedropper: None, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 08fcc2391..0d2f1787b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,7 +276,8 @@ pub struct SlideApp { ribbon_scroll: HashMap, /// Monotonic identity for a new slide show instance (`start_show`). show_instance: u64, - /// Monotonic identity for a new background-open attempt. + /// Monotonic identity for a new background-open attempt (the web build has no threads). + #[cfg(not(target_arch = "wasm32"))] opening_generation: u64, /// Canvas screen rect and points-per-slide-point scale (for control & tests). pub canvas_rect: Option, diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 632769fb3..15a0d604e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -147,13 +147,15 @@ fn cmd_wasm() -> Result<(), String> { if set.is_empty() { return Err("no wasm-safe crates found in the workspace metadata".into()); } + // Clippy with `-D warnings`, as the host step: a plain `check` let wasm-only dead code through (#1954). let mut c = cargo(); - c.args(["check", "--target", "wasm32-unknown-unknown", "--keep-going"]); + c.args(["clippy", "--target", "wasm32-unknown-unknown", "--keep-going"]); for pkg in &set { c.args(["-p", pkg]); } - run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going -p {}", set.join(" -p ")))?; - println!("\nwasm32-unknown-unknown check: ok ({} crates: {})", set.len(), set.join(", ")); + c.args(["--", "-D", "warnings"]); + run(c, &format!("cargo clippy --target wasm32-unknown-unknown --keep-going -p {} -- -D warnings", set.join(" -p ")))?; + println!("\nwasm32-unknown-unknown clippy: ok ({} crates: {})", set.len(), set.join(", ")); Ok(()) } From 6b1e2d6aef6da601f515e10b31d65bca2c3efc74 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 04:50:32 +0000 Subject: [PATCH 11/76] Apply review fixes - xtask/src/main.rs --- xtask/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 15a0d604e..c4d4a2429 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -22,7 +22,7 @@ commands: assets check that every icon/image/font/asset is attributed in ATTRIBUTION.md pdf-deps verify pinned writer sources and the production feature boundary layers enforce the crate dependency layering (plan/architecture.md §3) - wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call) + wasm cargo clippy --target wasm32-unknown-unknown -D warnings for the wasm-safe crates (one call) test workspace tests (cargo nextest when installed, else cargo test), then doctests ci fmt --check, pdf-deps, clippy -D warnings, test, doctest, assets, layers, wasm (stops at first failure) @@ -139,7 +139,7 @@ fn wasm_set() -> Result, String> { .collect()) } -/// One `cargo check` for the whole set: each crate is checked once, and +/// One `cargo clippy -- -D warnings` for the whole set: each crate is checked once, and /// `--keep-going` still reports every failing crate. Features unify across the /// set, so each crate is checked with the union of the features the set enables. fn cmd_wasm() -> Result<(), String> { From 0a07e9eae127f6ae7a74102c3446561ebb56c246 Mon Sep 17 00:00:00 2001 From: Naseq Date: Sun, 8 Nov 2026 15:18:27 +0430 Subject: [PATCH 12/76] Canvas: clip the canvas Ui to its own rect so the media bar and other canvas paint stay out of the notes pane (#1922) --- crates/ui-egui/src/canvas.rs | 5 +++ crates/ui-egui/src/media_bar_tests.rs | 56 +++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ca1029cbc..526d046cd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -152,6 +152,11 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let avail = ui.available_rect_before_wrap(); app.canvas_rect = Some(avail); + // The notes pane and the panes beside the canvas are editor chrome over it: nothing the + // canvas paints or hit-tests (the media bar hangs 6 pt below its clip, handles stick out of a + // shape, scroll bars) may reach into them. The parent's clip still covers the whole central + // area, so clip this `Ui` to the rect the canvas was given (#1922). + ui.set_clip_rect(avail.intersect(ui.clip_rect())); let Some(st) = app.session.active() else { return }; // The leftover fraction of a wheel line belongs to one presentation. Drop it whenever another // one is drawn here, hovered or not, so switching away and back starts from zero. diff --git a/crates/ui-egui/src/media_bar_tests.rs b/crates/ui-egui/src/media_bar_tests.rs index 8f60a03f3..975e126f8 100644 --- a/crates/ui-egui/src/media_bar_tests.rs +++ b/crates/ui-egui/src/media_bar_tests.rs @@ -70,3 +70,59 @@ fn play_on_the_editor_media_bar_plays_the_selected_clip() { click(&mut h, bar + vec2(w - 30.0, 13.0)); assert_eq!(h.state().session.active().unwrap().selection.shapes, vec![id]); } + +/// #1922: the bar hangs 6 pt under the clip, so a clip at the bottom edge of the slide put it +/// inside the speaker-notes pane, painted over the notes text. The canvas is clipped to its own +/// rect: nothing it paints reaches the notes pane, and a click there goes to the notes field. +#[test] +fn the_media_bar_never_paints_or_clicks_into_the_notes_pane() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + let r = s.execute("insert.audio", &json!({"name": "tone.wav", "data": deckcraft_engine::cmd::base64_encode(&wav(2.0))})).unwrap(); + let id = ShapeId(r["id"].as_u64().unwrap() as u32); + // Dragged across the bottom edge of the slide, onto the pasteboard. + let h_slide = s.doc().unwrap().doc.slide_size.height; + s.execute("shape.setBounds", &json!({"ids": [id.0], "x": 300.0, "y": h_slide - 10.0, "w": 120.0, "h": 60.0})).unwrap(); + let mut app = SlideApp::new(s, Services::default()); + app.ui.notes = true; + app.ui.notes_height = 140.0; + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut SlideApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + let notes = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).expect("the notes field"); + let canvas = h.state().canvas_rect.unwrap(); + assert!(canvas.max.y <= notes.min.y + 1.0, "the notes pane sits under the canvas: {canvas:?} / {notes:?}"); + let d = h.state().session.active().unwrap(); + let x = d.doc.slides[d.selection.slide].shape(id).unwrap().xfrm.unwrap(); + let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale); + let bottom = slide.min.y + (x.y + x.h) as f32 * k; + let bar_y = bottom + 6.0 + 13.0; + assert!(bar_y > notes.min.y, "the bar's row ({bar_y}) would fall inside the notes pane (top {})", notes.min.y); + + // The bar's own background (the only dark rounded rect the canvas paints there) has no + // visible area below the canvas edge: whatever the canvas paints is clipped to the canvas. + let bar_fill = egui::Color32::from_rgba_unmultiplied(28, 28, 32, 230); + let bars: Vec = h + .output() + .shapes + .iter() + .filter_map(|cs| match &cs.shape { + egui::Shape::Rect(r) if r.fill == bar_fill => Some(r.rect.intersect(cs.clip_rect)), + _ => None, + }) + .collect(); + assert!(!bars.is_empty(), "the bar is still laid out for the selected clip"); + assert!(bars.iter().all(|v| !v.is_positive() || v.max.y <= canvas.max.y + 0.5), "the bar is painted into the notes pane: {bars:?}"); + + // A click where the bar would be lands in the notes field, not on the bar. + click(&mut h, pos2(slide.min.x + (x.x + x.w / 2.0) as f32 * k, bar_y)); + assert!(h.state().media.status(id).is_none(), "Play was not hit through the notes pane"); + assert!(h.ctx.memory(|m| m.focused()).is_some(), "the notes field took the click"); +} From 8c85789cb1e71e450236099020adab40ebfcd26c Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Sat, 7 Nov 2026 18:14:24 +0000 Subject: [PATCH 13/76] pptx: round-trip p:video and p:audio media timing nodes and autoplay conditions --- crates/pptx/src/read/timing.rs | 42 +++++++++++++++++++++++--- crates/pptx/src/write.rs | 15 +++++++++- crates/pptx/src/write/timing.rs | 44 ++++++++++++++++++++++++++-- crates/pptx/tests/it/media_timing.rs | 24 +++++++++++++++ 4 files changed, 118 insertions(+), 7 deletions(-) diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs index 1b6aa8b1b..37a7ccb53 100644 --- a/crates/pptx/src/read/timing.rs +++ b/crates/pptx/src/read/timing.rs @@ -207,11 +207,41 @@ fn behaviour_auto_reverses(c: &El) -> bool { /// Volume, mute, Loop until Stopped, Hide While Not Playing and Play Full Screen live in the timing tree /// (`p:video`/`p:audio` > `p:cMediaNode`), not on the picture: copy them onto the target's `MediaClip`. pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { - let mut nodes = vec![]; - for tag in ["video", "audio"] { - timing.find_all(tag, &mut nodes); + fn collect_media<'a>(e: &'a El, deferred: bool, out: &mut Vec<(&'a El, bool)>, depth: usize) { + if depth > 64 || out.len() >= 10_000 { + return; + } + let mut deferred = deferred; + if e.is("cTn") + && e.attr("nodeType") != Some("tmRoot") + && let Some(st) = e.child("stCondLst") + { + let is_auto_begin = |c: &El| { + c.attr("evt") == Some("onBegin") + && c.attr("delay").map(str::trim) == Some("0") + && c.child("tgtEl").is_none() + && c.child("tn").is_none() + && c.child("rtn").is_none() + }; + let has_on_begin = st.children_named("cond").any(is_auto_begin); + if st + .children_named("cond") + .any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0"))) + { + deferred = true; + } + } + if e.is("video") || e.is("audio") { + out.push((e, deferred)); + return; + } + for c in e.elements() { + collect_media(c, deferred, out, depth + 1); + } } - for node in nodes.into_iter().take(10_000) { + let mut nodes = vec![]; + collect_media(timing, false, &mut nodes, 0); + for (node, deferred) in nodes { let Some(cm) = node.child("cMediaNode") else { continue }; let Some(id) = cm.path(&["tgtEl", "spTgt"]).and_then(|t| t.u32("spid")).and_then(|f| ctx.lookup(f)) else { continue }; let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) else { continue }; @@ -227,6 +257,10 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") { clip.loop_play = true; } + if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0")) + { + clip.autoplay = true; + } if node.bool("fullScrn") == Some(true) { clip.full_screen = true; } diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index e4c0858c9..888703b97 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -813,7 +813,20 @@ fn slide_xml(x: &mut Exp, o: &mut Out, s: &Slide, comment_rel: Option<&str>) -> if let Some(t) = &s.transition { timing::transition(&mut w, x, o, t); } - if !s.animations.is_empty() { + if !s.animations.is_empty() + || s.shapes.iter().any(|shape| { + fn has_nondefault(shape: &deckcraft_model::Shape) -> bool { + match &shape.kind { + deckcraft_model::ShapeKind::Media(c) => { + c.autoplay || (c.volume - 1.0).abs() > 1e-6 || c.hide_while_not_playing || c.loop_play || c.full_screen + } + deckcraft_model::ShapeKind::Group { children, .. } => children.iter().any(has_nondefault), + _ => false, + } + } + has_nondefault(shape) + }) + { timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); } slide_ext_list(&mut w, s.raw_ext.as_deref(), comment_rel); diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs index 6376e3ca0..766e3abad 100644 --- a/crates/pptx/src/write/timing.rs +++ b/crates/pptx/src/write/timing.rs @@ -592,7 +592,7 @@ fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections } } -/// Write `p:timing` for a slide's animations. +/// Write `p:timing` for a slide's animations and media settings. pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) { let mut grp_count: std::collections::HashMap = Default::default(); let mut main: Vec = vec![]; @@ -686,7 +686,8 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm None => main.extend(effs), } } - if main.is_empty() && triggered.is_empty() { + let media = collect_media(shapes, idmap); + if main.is_empty() && triggered.is_empty() && media.is_empty() { return; } let mut ids = Ids(0); @@ -757,6 +758,9 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm w.close("p:nextCondLst"); w.close("p:seq"); } + for (spid, clip) in &media { + write_media_node(w, &mut ids, *spid, clip); + } w.close("p:childTnLst"); w.close("p:cTn"); w.close("p:par"); @@ -770,3 +774,39 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm } w.close("p:timing"); } + +fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcraft_model::MediaClip)> { + let mut media = Vec::new(); + deckcraft_model::walk(shapes, &mut |shape, _| { + if let ShapeKind::Media(clip) = &shape.kind + && (clip.autoplay || (clip.volume - 1.0).abs() > 1e-6 || clip.hide_while_not_playing || clip.loop_play || clip.full_screen) + && let Some(spid) = idmap.get(shape.id) + { + media.push((spid, clip)); + } + }); + media +} + +fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model::MediaClip) { + let tag = if clip.video { "p:video" } else { "p:audio" }; + w.open(tag, A::new().t("fullScrn", clip.full_screen)); + let mut cm = A::new().a("vol", (clip.volume.clamp(0.0, 1.0) * 100_000.0).round() as u32); + if clip.volume <= 1e-6 { + cm = cm.t("mute", true); + } + if clip.hide_while_not_playing { + cm = cm.a("showWhenStopped", 0); + } + w.open("p:cMediaNode", cm); + w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold").a("display", 0).o("repeatCount", clip.loop_play.then_some("indefinite"))); + w.open0("p:stCondLst"); + w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" })); + w.close("p:stCondLst"); + w.close("p:cTn"); + w.open0("p:tgtEl"); + w.empty("p:spTgt", A::new().a("spid", spid)); + w.close("p:tgtEl"); + w.close("p:cMediaNode"); + w.close(tag); +} diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index 8fe325964..ba1fb6174 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -74,3 +74,27 @@ fn muted_audio_has_no_volume_and_other_clips_keep_theirs() { assert_eq!(c[0].volume, 1.0); assert_eq!((c[1].volume, c[1].loop_play, c[1].full_screen), (0.0, false, false)); } + +#[test] +fn media_autoplay_respects_ancestor_conditions_and_delays() { + let immediate = clips(|v, _| { + format!( + r#""# + ) + }); + assert!(immediate[0].autoplay); + + let delayed_ancestor = clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!delayed_ancestor[0].autoplay); + + let targeted_tn_ancestor = clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!targeted_tn_ancestor[0].autoplay); +} From c6e21c4fb5035399c34aa62f831b5a3418f99f29 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Sat, 7 Nov 2026 19:24:17 +0000 Subject: [PATCH 14/76] refactor(pptx): delegate empty-timing check to timing::timing --- crates/pptx/src/write.rs | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 888703b97..5a0df68f9 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -813,22 +813,7 @@ fn slide_xml(x: &mut Exp, o: &mut Out, s: &Slide, comment_rel: Option<&str>) -> if let Some(t) = &s.transition { timing::transition(&mut w, x, o, t); } - if !s.animations.is_empty() - || s.shapes.iter().any(|shape| { - fn has_nondefault(shape: &deckcraft_model::Shape) -> bool { - match &shape.kind { - deckcraft_model::ShapeKind::Media(c) => { - c.autoplay || (c.volume - 1.0).abs() > 1e-6 || c.hide_while_not_playing || c.loop_play || c.full_screen - } - deckcraft_model::ShapeKind::Group { children, .. } => children.iter().any(has_nondefault), - _ => false, - } - } - has_nondefault(shape) - }) - { - timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); - } + timing::timing(&mut w, x, &s.animations, &s.shapes, &ids); slide_ext_list(&mut w, s.raw_ext.as_deref(), comment_rel); w.close("p:sld"); w.finish() From 096b70421e7a9e3c73831dd95712590f58c30865 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Sun, 8 Nov 2026 05:24:51 +0000 Subject: [PATCH 15/76] test(pptx): cover media-only timing export round-trip and autoplay condition edge cases --- crates/pptx/tests/it/media_timing.rs | 76 ++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index ba1fb6174..1d2430370 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -77,24 +77,82 @@ fn muted_audio_has_no_volume_and_other_clips_keep_theirs() { #[test] fn media_autoplay_respects_ancestor_conditions_and_delays() { - let immediate = clips(|v, _| { + let immediate = clips(|v, a| { format!( - r#""# + r#""# ) }); - assert!(immediate[0].autoplay); + assert!(immediate[0].autoplay, "delay=0 ancestor allows autoplay"); + assert!(immediate[1].autoplay, "untargeted onBegin delay=0 ancestor allows autoplay"); - let delayed_ancestor = clips(|v, _| { + let delayed_and_onclick = clips(|v, a| { format!( - r#""# + r#""# ) }); - assert!(!delayed_ancestor[0].autoplay); + assert!(!delayed_and_onclick[0].autoplay, "delayed ancestor blocks autoplay"); + assert!(!delayed_and_onclick[1].autoplay, "onClick ancestor blocks autoplay"); - let targeted_tn_ancestor = clips(|v, _| { + let targeted_tn_and_own_cond = clips(|v, a| { format!( - r#""# + r#""# ) }); - assert!(!targeted_tn_ancestor[0].autoplay); + assert!(!targeted_tn_and_own_cond[0].autoplay, "targeted onBegin ancestor blocks autoplay"); + assert!(!targeted_tn_and_own_cond[1].autoplay, "media cond with explicit evt is not autoplay"); + + let delayed_media_cond = clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!delayed_media_cond[0].autoplay, "non-zero media cond delay is not autoplay"); +} + +#[test] +fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { + let mut p = defaults::new_presentation(None); + let video = p.add_media("clip.mp4", "video/mp4", b"video".to_vec()).expect("media"); + let audio = p.add_media("clip.m4a", "audio/mp4", b"audio".to_vec()).expect("media"); + let vid_id = ShapeId(p.alloc_id().expect("id")); + let aud_id = ShapeId(p.alloc_id().expect("id")); + let s0 = Arc::make_mut(&mut p.slides[0]); + s0.shapes.push(deckcraft_model::Shape { + id: vid_id, + name: "AutoplayVideo".into(), + xfrm: Some(Xfrm::new(40.0, 40.0, 200.0, 100.0)), + kind: ShapeKind::Media(MediaClip { + media: video, + video: true, + autoplay: true, + volume: 0.75, + hide_while_not_playing: true, + loop_play: true, + full_screen: true, + ..Default::default() + }), + ..Default::default() + }); + s0.shapes.push(deckcraft_model::Shape { + id: aud_id, + name: "ManualMutedAudio".into(), + xfrm: Some(Xfrm::new(40.0, 160.0, 200.0, 100.0)), + kind: ShapeKind::Media(MediaClip { media: audio, video: false, autoplay: false, volume: 0.0, loop_play: true, ..Default::default() }), + ..Default::default() + }); + let bytes = deckcraft_pptx::export(&p).expect("export"); + let back = deckcraft_pptx::import(&bytes).expect("import"); + let clips: Vec<&MediaClip> = back.slides[0] + .shapes + .iter() + .filter_map(|s| match &s.kind { + ShapeKind::Media(m) => Some(m), + _ => None, + }) + .collect(); + assert_eq!(clips.len(), 2); + assert!(clips[0].video && clips[0].autoplay && clips[0].hide_while_not_playing && clips[0].loop_play && clips[0].full_screen); + assert!((clips[0].volume - 0.75).abs() < 1e-4); + assert!(!clips[1].video && !clips[1].autoplay && clips[1].loop_play && !clips[1].hide_while_not_playing && !clips[1].full_screen); + assert_eq!(clips[1].volume, 0.0); } From 9fb1c5f97499fac11dd42ee04f1cc60bd1e0b774 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Sun, 8 Nov 2026 13:50:22 +0000 Subject: [PATCH 16/76] fix(pptx): round-trip media rewind/play_across_slides and detect main-sequence autoplay --- crates/pptx/src/read/timing.rs | 42 +++++++++++++++++++++++++++- crates/pptx/src/write/timing.rs | 20 +++++++++++-- crates/pptx/tests/it/media_timing.rs | 30 ++++++++++++++++++-- docs/file-format-parity.md | 2 +- 4 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs index 37a7ccb53..58d7457db 100644 --- a/crates/pptx/src/read/timing.rs +++ b/crates/pptx/src/read/timing.rs @@ -213,7 +213,6 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { } let mut deferred = deferred; if e.is("cTn") - && e.attr("nodeType") != Some("tmRoot") && let Some(st) = e.child("stCondLst") { let is_auto_begin = |c: &El| { @@ -257,6 +256,12 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { if cm.child("cTn").and_then(|c| c.attr("repeatCount")) == Some("indefinite") { clip.loop_play = true; } + if cm.child("cTn").and_then(|c| c.attr("fill")) == Some("remove") { + clip.rewind = true; + } + if cm.u32("numSld").is_some_and(|n| n > 1) { + clip.play_across_slides = true; + } if !deferred && cm.path(&["cTn", "stCondLst", "cond"]).is_some_and(|c| c.attr("evt").is_none() && c.attr("delay").map(str::trim) == Some("0")) { clip.autoplay = true; @@ -265,6 +270,41 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { clip.full_screen = true; } } + let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(|st| { + let is_auto_begin = |c: &El| { + c.attr("evt") == Some("onBegin") + && c.attr("delay").map(str::trim) == Some("0") + && c.child("tgtEl").is_none() + && c.child("tn").is_none() + && c.child("rtn").is_none() + }; + let has_on_begin = st.children_named("cond").any(is_auto_begin); + st.children_named("cond") + .any(|c| (c.attr("evt").is_some() && !is_auto_begin(c)) || (!has_on_begin && c.attr("delay").map(str::trim) != Some("0"))) + }); + if !root_deferred && let Some(tn) = timing.child("tnLst") { + let mut found = vec![]; + collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0); + for f in found.into_iter().filter(|f| f.trigger.is_none()) { + let c = f.ctn; + if c.attr("nodeType") == Some("clickEffect") { + break; + } + let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr")); + let preset = c.u32("presetID").unwrap_or(0); + let effect = maps::effect_for_preset(class, preset).unwrap_or_else(|| maps::fallback_effect(class)); + let delay = c.path(&["stCondLst", "cond"]).and_then(|d| ms_attr(d, "delay")).unwrap_or(0); + if class == AnimClass::Media + && effect == "play" + && f.offset == 0 + && delay == 0 + && let Some(id) = c.find("spTgt").and_then(|t| t.u32("spid")).and_then(|s| ctx.lookup(s)) + && let Some(ShapeKind::Media(clip)) = find_shape_mut(shapes, id).map(|s| &mut s.kind) + { + clip.autoplay = true; + } + } + } } /// Flatten the timing tree into the Animation Pane list. diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs index 766e3abad..4442109af 100644 --- a/crates/pptx/src/write/timing.rs +++ b/crates/pptx/src/write/timing.rs @@ -779,7 +779,13 @@ fn collect_media<'a>(shapes: &'a [Shape], idmap: &IdMap) -> Vec<(u32, &'a deckcr let mut media = Vec::new(); deckcraft_model::walk(shapes, &mut |shape, _| { if let ShapeKind::Media(clip) = &shape.kind - && (clip.autoplay || (clip.volume - 1.0).abs() > 1e-6 || clip.hide_while_not_playing || clip.loop_play || clip.full_screen) + && (clip.autoplay + || (clip.volume - 1.0).abs() > 1e-6 + || clip.hide_while_not_playing + || clip.loop_play + || clip.rewind + || clip.play_across_slides + || clip.full_screen) && let Some(spid) = idmap.get(shape.id) { media.push((spid, clip)); @@ -798,8 +804,18 @@ fn write_media_node(w: &mut W, ids: &mut Ids, spid: u32, clip: &deckcraft_model: if clip.hide_while_not_playing { cm = cm.a("showWhenStopped", 0); } + if clip.play_across_slides { + cm = cm.a("numSld", 999); + } w.open("p:cMediaNode", cm); - w.open("p:cTn", A::new().a("id", ids.next()).a("fill", "hold").a("display", 0).o("repeatCount", clip.loop_play.then_some("indefinite"))); + w.open( + "p:cTn", + A::new() + .a("id", ids.next()) + .a("fill", if clip.rewind { "remove" } else { "hold" }) + .a("display", 0) + .o("repeatCount", clip.loop_play.then_some("indefinite")), + ); w.open0("p:stCondLst"); w.empty("p:cond", A::new().a("delay", if clip.autoplay { "0" } else { "indefinite" })); w.close("p:stCondLst"); diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index 1d2430370..1274d8dd5 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -128,6 +128,8 @@ fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { volume: 0.75, hide_while_not_playing: true, loop_play: true, + rewind: true, + play_across_slides: true, full_screen: true, ..Default::default() }), @@ -151,8 +153,32 @@ fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { }) .collect(); assert_eq!(clips.len(), 2); - assert!(clips[0].video && clips[0].autoplay && clips[0].hide_while_not_playing && clips[0].loop_play && clips[0].full_screen); + assert!( + clips[0].video + && clips[0].autoplay + && clips[0].hide_while_not_playing + && clips[0].loop_play + && clips[0].rewind + && clips[0].play_across_slides + && clips[0].full_screen + ); assert!((clips[0].volume - 0.75).abs() < 1e-4); - assert!(!clips[1].video && !clips[1].autoplay && clips[1].loop_play && !clips[1].hide_while_not_playing && !clips[1].full_screen); + assert!( + !clips[1].video + && !clips[1].autoplay + && clips[1].loop_play + && !clips[1].rewind + && !clips[1].play_across_slides + && !clips[1].hide_while_not_playing + && !clips[1].full_screen + ); assert_eq!(clips[1].volume, 0.0); + + // Main-sequence automatic Play (mediacall) effect with indefinite media node also sets autoplay. + let main_seq_play = self::clips(|v, _| { + format!( + r#""# + ) + }); + assert!(main_seq_play[0].autoplay, "main-sequence automatic Play effect sets autoplay"); } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 70b74f7e1..67707cded 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -92,7 +92,7 @@ the round trip even though DeckCraft doesn't model it. | Charts (`cx:` chartex: waterfall, funnel, treemap, sunburst, histogram, Pareto, box) | yes | yes | Unchanged parts kept, with their embedded workbook (#335); edited and new ones written from the model with a plain-chart fallback. Treemap and sunburst hierarchy levels kept; region maps kept, drawn as tiles (no map geometry) | | SmartArt (`dgm`) | the drawing part as a group (text laid out on its `dsp:txXfrm` rectangle), and the outline from the data model (Text Pane) | as a diagram: data model from the outline; layout, quick style and colour parts (the file's own kept until the layout is switched); the group as the cached drawing | DeckCraft's layout definitions are simple; a diagram without a cached drawing isn't drawn. SmartArt kept only as XML, without its relationship parts, still loses the drawing and data parts (#203) | | Equations (OMML, `a14:m`) | no | no | PR #55 open | -| Audio / video (`p14:media`, trim, fades, bookmarks) | yes | partly | Playback options lost on save (#74) | +| Audio / video (`p14:media`, trim, fades, bookmarks, playback options) | yes | yes | Volume, mute, autoplay, loop, rewind, play across slides, hide while not playing and full screen round-trip (`media_timing.rs`) | | Ink (`contentPart`) | yes | as a group of freeform lines | PowerPoint sees shapes, not ink | | Transitions incl. p14/p15 (Vortex, Morph…) | all 48 | all 48 | `every_transition_kind_round_trips` | | Animations: timing tree, build paragraphs, triggers, motion paths | yes (flattened to the Animation Pane list) | yes (rebuilt) | `every_animation_effect_survives`; repeat, triggers, bounce end and rewind kept | From a55b73c71f4fc7a0a2fbc36dbc1c3f5eec4f19d0 Mon Sep 17 00:00:00 2001 From: Yonatan Langer Date: Mon, 9 Nov 2026 14:42:49 +0200 Subject: [PATCH 17/76] Preferences: the Interface size slider is labelled again The egui 0.37 migration (#1350) dropped the slider's own text ("Interface size") and kept only its accessible name, so the dialog showed a bare "1.00" with nothing saying what it changes. The slider now sits in a row with an "Interface size:" label, laid out like the Measurement units row below it. Its accessible name is unchanged. Test: the_interface_size_slider_is_labelled_on_screen (the label is shown, before the slider, on the same row). --- crates/ui-egui/src/dialogs/body.rs | 10 ++++++++-- crates/ui-egui/src/dialogs/preferences_tests.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/body.rs b/crates/ui-egui/src/dialogs/body.rs index 932cd469a..ce8f6e511 100644 --- a/crates/ui-egui/src/dialogs/body.rs +++ b/crates/ui-egui/src/dialogs/body.rs @@ -1351,8 +1351,14 @@ fn dlg_preferences(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { // on release, and at once from the keyboard. let pending = d.fields.get("uiScale").and_then(|v| v.parse::().ok()); let mut scale = pending.unwrap_or(app.ui.ui_scale); - let r = ui.add(egui::Slider::new(&mut scale, 0.75..=1.75)); - // No visible label here (the row is laid out to fit); the accessible name only. + // Labelled like the Measurement units row below it. The egui 0.37 migration (#1350) dropped + // the slider's own text and kept only its accessible name, which left a bare "1.00". + let r = ui + .horizontal(|ui| { + ui.label("Interface size:"); + ui.add(egui::Slider::new(&mut scale, 0.75..=1.75)) + }) + .inner; let enabled = r.enabled(); r.widget_info(|| egui::WidgetInfo::slider(enabled, f64::from(scale), "Interface size")); if r.is_pointer_button_down_on() { diff --git a/crates/ui-egui/src/dialogs/preferences_tests.rs b/crates/ui-egui/src/dialogs/preferences_tests.rs index c3a3ebfbd..549220b93 100644 --- a/crates/ui-egui/src/dialogs/preferences_tests.rs +++ b/crates/ui-egui/src/dialogs/preferences_tests.rs @@ -39,6 +39,18 @@ fn dark(app: &SlideApp) -> bool { app.ui.brightness == Brightness::Dark } +/// The interface size slider has a visible label, not just a bare "1.00" beside it. +#[test] +fn the_interface_size_slider_is_labelled_on_screen() { + let mut h = harness(); + open_options(&mut h); + let label = h.query_by_label("Interface size:").expect("the slider's label is shown"); + let slider = interface_size(&h); + let (label, slider) = (label.rect(), slider.rect()); + assert!(label.max.x <= slider.min.x, "the label sits before the slider: {label:?}, {slider:?}"); + assert!(label.center().y > slider.min.y && label.center().y < slider.max.y, "on the same row: {label:?}, {slider:?}"); +} + /// A checkbox applies as it is toggled and Cancel puts the old value back. #[test] fn options_cancel_undoes_the_changes() { From 53f09a0298bdbc44b81deaf768df2b4484387d20 Mon Sep 17 00:00:00 2001 From: jgriggs-sluh Date: Tue, 10 Nov 2026 14:30:25 -0600 Subject: [PATCH 18/76] =?UTF-8?q?Export:=20every=20slide=20as=20PNG=20or?= =?UTF-8?q?=20JPEG=20from=20File=20=E2=80=BA=20Export=20=E2=80=BA=20Change?= =?UTF-8?q?=20File=20Type=20and=20Save=20As=20(#2019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change File Type and Save As offered PNG and JPEG for the current slide only; all slides as pictures was reachable only through the Export… dialog, and only as PNG. Both File-tab pages now list "PNG Pictures, all slides" and "JPEG Pictures, all slides" (with Transparent background for PNG), and the Export… dialog adds "JPEG images (all slides)". `file.export` already wrote one file per slide with `all: true`; this is UI only. Closes #2019 --- ROADMAP.md | 2 ++ crates/ui-egui/src/app/files.rs | 3 +- crates/ui-egui/src/backstage/info.rs | 4 ++- crates/ui-egui/src/backstage/print.rs | 2 +- crates/ui-egui/src/backstage/tests.rs | 40 +++++++++++++++++++++++++++ crates/ui-egui/src/dialogs/body.rs | 1 + crates/ui-egui/src/tests.rs | 21 ++++++++++++++ 7 files changed, 70 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index edd316276..97592dd7b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -154,6 +154,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-10 | Export: every slide as its own PNG or JPEG picture from File › Export › Change File Type and File › Save As; the Export… dialog adds JPEG images (all slides) (#2019) | | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | | 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop | | 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) | @@ -340,6 +341,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | trivial | Progress log: export all slides as PNG or JPEG from the File tab (#2019); scores unchanged | | 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged | | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | | 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged | diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3ec59202e..bccd4cd42 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -182,7 +182,7 @@ impl SlideApp { format!("{name}.{ext}") } - /// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `pptx`, + /// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `jpegAll`, `pptx`, /// `deckcraft`, `outline`) through `file.export`: the save picker on the desktop, a download /// on the web. `extra` adds `file.export` params (the PDF's layout, slides…). The /// presentation keeps its own file. Returns whether a file was written or handed over. @@ -193,6 +193,7 @@ impl SlideApp { "png" => ("png", "png", false), "pngAll" => ("png", "png", true), "jpeg" | "jpg" => ("jpg", "jpeg", false), + "jpegAll" => ("jpg", "jpeg", true), "pptx" => ("pptx", "pptx", false), "outline" | "txt" => ("txt", "outline", false), "rtf" => ("rtf", "rtf", false), diff --git a/crates/ui-egui/src/backstage/info.rs b/crates/ui-egui/src/backstage/info.rs index 3ddbda1a3..98287856d 100644 --- a/crates/ui-egui/src/backstage/info.rs +++ b/crates/ui-egui/src/backstage/info.rs @@ -2,7 +2,7 @@ use super::files::task; use super::{Backstage, Icon, Outcome, Page, RichText, Sense, SlideApp, Tokens, Ui, Value, dim, heading, json, theme, vec2}; /// Save As and Change File Type: (id for [`SlideApp::export_as`], label, detail). -pub const SAVE_TYPES: [(&str, &str, &str); 7] = [ +pub const SAVE_TYPES: [(&str, &str, &str); 9] = [ ("pptx", "PowerPoint Presentation (*.pptx)", "Opens in PowerPoint and other presentation apps"), ("deckcraft", "DeckCraft Presentation (*.deckcraft)", "DeckCraft's own format: everything is kept"), ("pdf", "PDF (*.pdf)", "A fixed copy that keeps its layout on any device"), @@ -10,6 +10,8 @@ pub const SAVE_TYPES: [(&str, &str, &str); 7] = [ ("rtf", "Outline/RTF (*.rtf)", "The slide titles and bullet text for word processors"), ("png", "PNG Picture (*.png)", "The current slide as a picture"), ("jpeg", "JPEG Picture (*.jpg)", "The current slide as a compressed picture"), + ("pngAll", "PNG Pictures, all slides (*.png)", "Every slide as its own picture"), + ("jpegAll", "JPEG Pictures, all slides (*.jpg)", "Every slide as its own compressed picture"), ]; /// Info page properties: (`file.properties` key, label, hint). diff --git a/crates/ui-egui/src/backstage/print.rs b/crates/ui-egui/src/backstage/print.rs index db5d6b972..f345fb73b 100644 --- a/crates/ui-egui/src/backstage/print.rs +++ b/crates/ui-egui/src/backstage/print.rs @@ -357,7 +357,7 @@ pub(super) fn export(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage) { } } ui.add_space(12.0); - let png = bs.file_type == "png"; + let png = matches!(bs.file_type, "png" | "pngAll"); if png { ui.checkbox(&mut bs.png_transparent, "Transparent background") .on_hover_text("Leave the slide background out: only what is on the slide is drawn"); diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index a21cd3cff..76983c44f 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -349,6 +349,46 @@ fn change_file_type_png_can_leave_the_background_transparent() { let _ = std::fs::remove_dir_all(&dir); } +/// Export › Change File Type exports every slide as its own picture, PNG or JPEG (#2019). +#[test] +fn change_file_type_exports_all_slides_as_pictures() { + let dir = temp_dir("all-slides"); + let (services, asked) = saving_into(&dir); + let mut h = harness(SlideApp::new(Session::with_new(), services)); + h.state_mut().run("slide.new", json!({})).unwrap(); + h.state_mut().run("slide.new", json!({})).unwrap(); + let title = h.state().session.active().unwrap().title(); + h.state_mut().run("app.backstage", json!({"page": "export"})).unwrap(); + h.run_steps(3); + click_on_page(&h, "Change File Type"); + h.run_steps(3); + click_on_page(&h, "JPEG Pictures, all slides (*.jpg)"); + h.run_steps(2); + assert!(h.query_by_label("Transparent background").is_none(), "JPEG has no transparency"); + click_on_page(&h, "Save As"); + h.run_steps(3); + for k in 1..=3 { + let jpg = std::fs::read(dir.join(format!("{title}{k}.jpg"))).unwrap(); + assert!(jpg.starts_with(&[0xFF, 0xD8]), "slide {k} is a JPEG"); + } + assert!(!dir.join(format!("{title}4.jpg")).exists(), "one picture per slide"); + + h.state_mut().run("app.backstage", json!({"page": "export"})).unwrap(); + h.run_steps(3); + click_on_page(&h, "Change File Type"); + h.run_steps(3); + click_on_page(&h, "PNG Pictures, all slides (*.png)"); + h.run_steps(2); + assert!(h.query_by_label("Transparent background").is_some(), "all-slides PNG keeps the option"); + click_on_page(&h, "Save As"); + h.run_steps(3); + for k in 1..=3 { + assert!(dir.join(format!("{title}{k}.png")).is_file(), "slide {k} as PNG"); + } + assert_eq!(*asked.borrow(), vec![format!("{title}.jpg"), format!("{title}.png")]); + let _ = std::fs::remove_dir_all(&dir); +} + /// Close closes a saved presentation at once and asks about unsaved changes first. #[test] fn close_closes_and_asks_about_unsaved_changes() { diff --git a/crates/ui-egui/src/dialogs/body.rs b/crates/ui-egui/src/dialogs/body.rs index 932cd469a..7c51bf2f6 100644 --- a/crates/ui-egui/src/dialogs/body.rs +++ b/crates/ui-egui/src/dialogs/body.rs @@ -715,6 +715,7 @@ fn dlg_export(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { ("PNG images (current slide)", "png"), ("PNG images (all slides)", "pngAll"), ("JPEG image (current slide)", "jpeg"), + ("JPEG images (all slides)", "jpegAll"), ("PowerPoint Presentation (.pptx)", "pptx"), ("Outline (.txt)", "outline"), ("Animated GIF (.gif)", "gif"), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index d84d7d32f..40c62b38b 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -88,6 +88,27 @@ fn web_png_export_can_leave_the_background_transparent() { assert_eq!(corner_alpha(&got[2].1), 255, "JPEG has no transparency"); } +/// Every type File › Save As and Export › Change File Type list is one `export_as` writes: +/// a listed type it doesn't know would only say "can't export" (#2019). +#[test] +fn every_listed_save_type_exports() { + use std::cell::RefCell; + use std::rc::Rc; + let got: Rc>> = Rc::default(); + let log = got.clone(); + let services = Services { download: Some(Box::new(move |name: &str, _: &[u8]| log.borrow_mut().push(name.to_string()))), ..Default::default() }; + let mut app = SlideApp::new(Session::with_new(), services); + app.session.execute("slide.new", &json!({})).unwrap(); + for (id, _, _) in crate::backstage::SAVE_TYPES { + assert!(app.export_as(id, json!({})), "{id} exports"); + } + let title = app.session.active().unwrap().title(); + let got = got.borrow(); + for name in [format!("{title}1.jpg"), format!("{title}2.jpg"), format!("{title}1.png"), format!("{title}2.png")] { + assert!(got.contains(&name), "{name} downloaded, got {got:?}"); + } +} + fn title_text(app: &SlideApp) -> String { let d = app.session.active().unwrap(); let sh = &d.doc.slides[0].shapes[0]; From 55aec60818e54711c7799aa7165f0647535addb9 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:45:43 +0000 Subject: [PATCH 19/76] Apply review fixes - docs/ui-parity.md --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e5abd9cd7..29ab31510 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -60,7 +60,7 @@ menu colours taken from the theme tokens (menu `chrome`, page `card`). | Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) | | Print | Print and Copies, Printer, Print All / Selection / Current / Custom Range, Slides box, layout (Full Page Slides, Notes Pages, Outline, Handouts 1–9), sides, collation, colour, Edit Header & Footer; page preview with pager and zoom | Print, Print All Slides / Current Slide / Custom Range, Slides box (`1-3, 5`), Full Page Slides / Notes Pages / Handouts 1–9, Print Hidden Slides, Frame Slides, Edit Header & Footer; preview with pager. DeckCraft prints through a PDF (`file.export`) opened in the system viewer, which has the printers (web: downloaded). No printer list, copies, sides or colour | | Share | Cloud sharing | Not offered | -| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG with an optional transparent background, #784). No video, GIF or CD package | +| Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG or JPEG of the current slide or of every slide, #2019; PNG with an optional transparent background, #784). No video, GIF or CD package | | Close | Closes; asks Save / Don't Save / Cancel about unsaved changes | Same (`file.close` after the prompt); Ctrl+W asks too | | Account | User information, sign-in, Office Background and Office Theme, product information, About | About: product information, project links, contributor/model credits and appearance (light/dark, `view.dark`). No Account entry | | Options | Opens the PowerPoint Options dialog | Opens Preferences | From 037747739f50775f4b5a518f095427e1e895889f Mon Sep 17 00:00:00 2001 From: jgriggs-sluh Date: Tue, 10 Nov 2026 14:48:19 -0600 Subject: [PATCH 20/76] Docs: UI parity Save As row and status lines for all-slides picture export (#2019) --- ROADMAP.md | 2 +- docs/ui-parity.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 97592dd7b..1d4441d00 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** trivial (Ogg Opus recovery includes trailing packets without granules in its reported duration; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-10 · **Change:** trivial (progress log: every slide as PNG or JPEG from File › Export › Change File Type and Save As, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 29ab31510..c015d30cf 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity with PowerPoint -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-10 · **Change:** trivial (File › Export › Change File Type and Save As export every slide as PNG or JPEG, #2019; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (dragging several selected slides moves them all; previous: trivial, Edit Points: Shift, Ctrl/Cmd or Alt/Option on a handle drag sets the point type; previous: trivial, scroll bars on the zoomed slide pane, #1157; previous: major, community PR wave 2026-10-14: 14 new dialogs (41 in all), Eyedropper, Export button, New Window, Grid Options, WordArt gallery and handles, Slide Sorter sections, Quick Access Toolbar, Format Background and Format Shape depth, rich-text clipboard; duplicated rows and headers folded; previous: minor, File tab / Backstage, #76) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-22 · **Change:** trivial (group fill and outline edits reach members, #1079; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -57,7 +57,7 @@ menu colours taken from the theme tokens (menu `chrome`, page `card`). | Open | Recent, Shared with Me, OneDrive, This PC, Add a Place, Browse; Presentations / Folders; Recover Unsaved Presentations | Recent and Browse (`app.openDialog`), recent presentations with a search box (`file.open`), Recover Unsaved Presentations (`file.recovery.open`). No cloud places or Folders tab | | Info | Name and path, Upload / Share / Copy path / Open file location; Protect, Inspect, Version History, Manage Presentation; Properties, Related Dates, Related People | Name and path, Copy path, Open file location; Inspect Presentation (Accessibility Checker), Manage Presentation (Revert); Size, Slides, Hidden slides and editable Title, Subject, Tags, Categories, Company, Comments, Author (`file.info`, `file.properties`). No Protect, Version History or dates | | Save | Saves; a presentation never saved goes to Save As | Same (`file.save`) | -| Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) | +| Save As | Places, folder, file name, type, Save, More options | Type (PowerPoint, DeckCraft, PDF, Outline, PNG, JPEG, and PNG or JPEG of every slide, #2019) and Save, which opens the system Save dialog (web: Download). .pptx/.deckcraft take the new file; the others are copies (`file.saveAs`, `file.export`) | | Print | Print and Copies, Printer, Print All / Selection / Current / Custom Range, Slides box, layout (Full Page Slides, Notes Pages, Outline, Handouts 1–9), sides, collation, colour, Edit Header & Footer; page preview with pager and zoom | Print, Print All Slides / Current Slide / Custom Range, Slides box (`1-3, 5`), Full Page Slides / Notes Pages / Handouts 1–9, Print Hidden Slides, Frame Slides, Edit Header & Footer; preview with pager. DeckCraft prints through a PDF (`file.export`) opened in the system viewer, which has the printers (web: downloaded). No printer list, copies, sides or colour | | Share | Cloud sharing | Not offered | | Export | Create PDF/XPS Document, Create a Video, Create an Animated GIF, Package Presentation for CD, Create Handouts, Change File Type | Create PDF Document, Create Handouts (a PDF), Change File Type (PNG or JPEG of the current slide or of every slide, #2019; PNG with an optional transparent background, #784). No video, GIF or CD package | @@ -173,6 +173,7 @@ consistency is open (#73, #56). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | trivial | Change File Type and Save As export every slide as PNG or JPEG (#2019); scores unchanged | | 2026-11-02 | trivial | File › About replaces Account; product links, credits and appearance retained | | 2026-10-31 | trivial | No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged | | 2026-10-29 | trivial | Picture Format: the Picture Styles row shows as many styles as fit beside the groups after it (at least two) and a More arrow with all 24, as the Transitions and Animations galleries do; Crop and Size are in view in the default window (#1232) | From deb6e1707bcee05b8a62c3b83e07030d67afabbc Mon Sep 17 00:00:00 2001 From: jgriggs-sluh Date: Tue, 10 Nov 2026 15:59:47 -0600 Subject: [PATCH 21/76] Test that Transparent background reaches every slide's PNG in Change File Type (#2019) --- crates/ui-egui/src/backstage/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index 76983c44f..831cbfa25 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -379,11 +379,14 @@ fn change_file_type_exports_all_slides_as_pictures() { h.run_steps(3); click_on_page(&h, "PNG Pictures, all slides (*.png)"); h.run_steps(2); - assert!(h.query_by_label("Transparent background").is_some(), "all-slides PNG keeps the option"); + h.get_by_label("Transparent background").click(); + h.run_steps(2); click_on_page(&h, "Save As"); h.run_steps(3); for k in 1..=3 { - assert!(dir.join(format!("{title}{k}.png")).is_file(), "slide {k} as PNG"); + let png = std::fs::read(dir.join(format!("{title}{k}.png"))).unwrap(); + let img = deckcraft_render::decode_image(&png).unwrap(); + assert_eq!(img.get_pixel(2, 2).0[3], 0, "slide {k} leaves the background out"); } assert_eq!(*asked.borrow(), vec![format!("{title}.jpg"), format!("{title}.png")]); let _ = std::fs::remove_dir_all(&dir); From 2ca092c2633343b4e4917147082d2f3cd2e618ee Mon Sep 17 00:00:00 2001 From: jgriggs-sluh Date: Tue, 10 Nov 2026 16:12:52 -0600 Subject: [PATCH 22/76] =?UTF-8?q?Document=20the=20Export=E2=80=A6=20dialog?= =?UTF-8?q?'s=20body=20function=20(#2019)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/dialogs/body.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/dialogs/body.rs b/crates/ui-egui/src/dialogs/body.rs index 7c51bf2f6..e6443ca08 100644 --- a/crates/ui-egui/src/dialogs/body.rs +++ b/crates/ui-egui/src/dialogs/body.rs @@ -707,6 +707,9 @@ fn dlg_rename_section(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { ok || cancel } +/// Export…: the format (PDF, PNG or JPEG of the current slide or of every slide, PowerPoint, +/// outline, animated GIF, RTF) and its options; Export hands them to [`SlideApp::export_as`]. +/// Returns true when the dialog should close. fn dlg_export(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { ui.label("Export the presentation as:"); let fmt = d.get("fmt", "pdf"); From 8ecb818f8156d2c83b27d7d1654263b10cd84287 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 22:21:47 +0000 Subject: [PATCH 23/76] address review: layout id follows generated layout, charge text-rect shapes to smartart budget --- crates/pptx/src/read/shapes.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index c2e9293fc..860adeec6 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -679,10 +679,11 @@ fn text_on_rect(imp: &mut Imp, ctx: &mut IdCtx, s: &mut Shape, t: Xfrm) -> Optio return None; } } - if ctx.count >= MAX_SHAPES { + if ctx.count >= MAX_SHAPES || imp.smartart_shapes >= MAX_SMARTART_SHAPES { return None; } ctx.count += 1; + imp.smartart_shapes += 1; let text = s.text.take(); // No fill, outline or effects; the style keeps only the text colour and font. let style = s.style.clone().map(|mut st| { @@ -762,7 +763,8 @@ fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Optio style, colors, imported: true, - layout_id: id, + // Without the layout part the writer generates one for `kind`; empty keeps data's loTypeId in step with it. + layout_id: if layout_xml.is_some() { id } else { String::new() }, layout_xml, style_xml, colors_xml, From 40052f4b09c60d987236b9a43e422dd5b4d4c15d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 02:07:46 +0000 Subject: [PATCH 24/76] address review: budget diagram definition parts copied by the opaque fallback, refuse a SmartArt drawing over the remaining shape budget --- crates/pptx/src/read/shapes.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 860adeec6..9e0aa3e9b 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -480,6 +480,14 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S return None; } let (kind, target) = (rel.ty.clone(), rel.target.clone()); + // A diagram's definition parts copied here count against the same presentation-wide budget. + if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&target)) { + let len = pkg.get(&target).map_or(0, |b| b.len()); + if len > MAX_DIAGRAM_PART_BYTES || imp.diagram_xml_bytes.saturating_add(len) > MAX_DIAGRAM_XML_BYTES { + return None; + } + imp.diagram_xml_bytes += len; + } let media = if rel.kind == "diagramData" { diagram_data(imp, &target) } else { imp.media_for(&target) }; Some((id, kind, media?)) }) @@ -566,6 +574,9 @@ const MAX_SMARTART_SHAPES: usize = 250_000; /// SmartArt definition XML (layout, style, colours) all diagrams of one presentation may copy. const MAX_DIAGRAM_XML_BYTES: usize = 32 << 20; +/// The largest single diagram definition part copied. +const MAX_DIAGRAM_PART_BYTES: usize = 4 << 20; + fn count_shapes(shapes: &[Shape]) -> usize { shapes.iter().map(|s| 1 + count_shapes(s.children())).sum() } @@ -590,7 +601,13 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> return None; } // Counted once here, nested SmartArt included: a drawing that frames reuse counts every time it is read. - imp.smartart_shapes = before.saturating_add(count_shapes(&children)); + let total = before.saturating_add(count_shapes(&children)); + if total > MAX_SMARTART_SHAPES { + // Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included. + imp.smartart_shapes = before; + return None; + } + imp.smartart_shapes = total; let children = smartart_text_rects(imp, &mut sub, tree, children, depth + 1); let mut g = frame.clone(); let x = frame.xfrm.unwrap_or_default(); @@ -729,7 +746,7 @@ fn diagram_outline(imp: &mut Imp, part: &Part, rel_ids: &El, data: &El) -> Optio let rel = part.rels.get(rel_ids.attr(attr)?)?; let bytes = pkg.get(&rel.target)?; // Every diagram copies its definitions, so the copies share one presentation-wide budget. - if bytes.len() > 4 << 20 || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES { + if bytes.len() > MAX_DIAGRAM_PART_BYTES || spent.get().saturating_add(bytes.len()) > MAX_DIAGRAM_XML_BYTES { return None; } let xml = String::from_utf8(bytes.to_vec()).ok()?; From e4b1a609f2d19ef8e1330407ed74c233260e6927 Mon Sep 17 00:00:00 2001 From: Naseq Date: Wed, 11 Nov 2026 11:46:30 +0430 Subject: [PATCH 25/76] PPTX: preserve empty notes slides on save and reopen (#2025) When a slide has an associated notes slide with no text, PPTX export previously omitted both the notes slide part and its relationship, treating notes slides without text runs as removable. Track whether a slide has an associated notes slide (`has_notes_slide`). Import marks it when reading a notes slide relationship, and export keeps the notes slide part, its slide relationship, and notes master linkage even when its text body is empty. Native serialization preserves the presence flag, and setting notes via `slide.notes` also enables it. Regression test in `crates/pptx/tests/it/notes.rs` verifies that a slide with an empty notes slide retains its notes part and relationship across multiple import and export roundtrips. --- ROADMAP.md | 4 ++- crates/engine/src/cmd/slide.rs | 6 ++++- crates/model/src/lib.rs | 4 +++ crates/pptx/src/read.rs | 1 + crates/pptx/src/write.rs | 6 ++--- crates/pptx/tests/it/notes.rs | 48 ++++++++++++++++++++++++++++++++++ docs/file-format-parity.md | 5 ++-- 7 files changed, 67 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index edd316276..95fcf89b5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** trivial (Ogg Opus recovery includes trailing packets without granules in its reported duration; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** minor (empty notes slides are preserved through PPTX and native saves rather than dropped, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -154,6 +154,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips | | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | | 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop | | 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) | @@ -340,6 +341,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged | | 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged | | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | | 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged | diff --git a/crates/engine/src/cmd/slide.rs b/crates/engine/src/cmd/slide.rs index f15cf32fa..5f3fbc8f6 100644 --- a/crates/engine/src/cmd/slide.rs +++ b/crates/engine/src/cmd/slide.rs @@ -602,11 +602,15 @@ fn notes(s: &mut Session, p: &Value) -> Result { let text = str_param(p, "text").unwrap_or("").to_string(); s.edit(|doc, _| { if let Some(sl) = doc.slides.get_mut(i) { - let notes = &mut Arc::make_mut(sl).notes; + let sl = Arc::make_mut(sl); + let notes = &mut sl.notes; match body { Some(b) => *notes = b, None => deckcraft_model::edit::replace_text(notes, &text), } + if !notes.is_empty() { + sl.has_notes_slide = true; + } } Ok(()) })?; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 8547bc60c..5f6f996c1 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -626,6 +626,9 @@ pub struct Slide { pub animations: Vec, /// Speaker notes. pub notes: TextBody, + /// Whether the slide has an associated notes slide even if its text is empty. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub has_notes_slide: bool, pub comments: Vec, /// `clrMapOvr`: a colour map replacing the layout's or master's (`bg1`→`dk1`…); None follows /// the layout. @@ -652,6 +655,7 @@ impl Default for Slide { transition: None, animations: vec![], notes: TextBody::default(), + has_notes_slide: false, comments: vec![], color_map: None, tags: vec![], diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 47f6229c3..4e5869a51 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -678,6 +678,7 @@ fn read_slides( let mut slide = read_slide(imp, &part, doc, *id, layout); if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) { slide.notes = notes; + slide.has_notes_slide = true; } read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts); file_slide_ids.insert(*file_id, *id); diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index e4c0858c9..28e65ba32 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -427,7 +427,7 @@ struct NotesMasterWrite { fn notes_master_write(p: &Presentation) -> Option { let nm = p.notes_master.as_deref(); let kept = nm.filter(|m| !m.shapes.is_empty()); - let has_notes = p.slides.iter().any(|s| !s.notes.is_empty()); + let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide); if !has_notes && nm.is_none() { return None; } @@ -666,7 +666,7 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { if let Some(lp) = layout_parts.get(&s.layout) { so.rels.add("slideLayout", &opc::relative(&sname, lp), false); } - if !s.notes.is_empty() { + if !s.notes.is_empty() || s.has_notes_slide { let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1); so.rels.add("notesSlide", &opc::relative(&sname, &nname), false); let mut no = Out::new(&nname); @@ -1301,7 +1301,7 @@ fn app_xml(p: &Presentation) -> Vec { ); w.elt("Application", "DeckCraft"); w.elt("Slides", &p.slides.len().to_string()); - w.elt("Notes", &p.slides.iter().filter(|s| !s.notes.is_empty()).count().to_string()); + w.elt("Notes", &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string()); w.elt("HiddenSlides", &p.slides.iter().filter(|s| s.hidden).count().to_string()); if !p.props.company.is_empty() { w.elt("Company", &p.props.company); diff --git a/crates/pptx/tests/it/notes.rs b/crates/pptx/tests/it/notes.rs index b5863d510..1ae98bac2 100644 --- a/crates/pptx/tests/it/notes.rs +++ b/crates/pptx/tests/it/notes.rs @@ -14,6 +14,31 @@ const NOTES: &str = "ppt/notesSlides/notesSlide1.xml"; /// label and plain text), a level-2 paragraph with buNone, and a closing plain line. const NOTES_XML: &str = r#" Metodický prehľadŽiaci pracujú vo dvojiciach.Cieľ: vysvetliť cyklusReflexiaBez odrážkyPomôcky: počítač"#; +const EMPTY_NOTES_XML: &str = r#" +"#; + +fn empty_notes_deck() -> Vec { + let mut p = defaults::new_presentation(None); + Arc::make_mut(&mut p.slides[0]).notes = TextBody::from_text("placeholder"); + let bytes = deckcraft_pptx::export(&p).expect("export"); + let mut src = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip"); + let mut out = zip::ZipWriter::new(Cursor::new(Vec::new())); + let mut found = false; + for i in 0..src.len() { + let mut f = src.by_index(i).expect("entry"); + let name = f.name().to_string(); + let mut data = vec![]; + f.read_to_end(&mut data).expect("read"); + if name == NOTES { + data = EMPTY_NOTES_XML.as_bytes().to_vec(); + found = true; + } + out.start_file(name, zip::write::SimpleFileOptions::default()).expect("start"); + out.write_all(&data).expect("write"); + } + assert!(found, "the export has no {NOTES}"); + out.finish().expect("finish").into_inner() +} /// A deck with one notes slide, its notes replaced by [`NOTES_XML`]. fn deck() -> Vec { @@ -80,3 +105,26 @@ fn notes_formatting_survives_a_round_trip() { assert!(xml.contains(r#"lvl="1""#) && xml.contains(r#"marL="285750""#) && xml.contains(r#"indent="-285750""#), "{xml}"); assert!(xml.contains(r#""), "{xml}"); } + +#[test] +fn empty_notes_slide_is_preserved_on_save_and_reopen() { + let raw = empty_notes_deck(); + let p = deckcraft_pptx::import(&raw).expect("import"); + assert!(p.slides[0].notes.is_empty(), "imported notes text is empty"); + assert!(p.slides[0].has_notes_slide, "slide notes presence is captured"); + + let saved = deckcraft_pptx::export(&p).expect("export"); + let mut z = zip::ZipArchive::new(Cursor::new(&saved)).expect("zip"); + assert!(z.by_name(NOTES).is_ok(), "empty notes slide part is kept in saved package"); + let mut rels_xml = String::new(); + z.by_name("ppt/slides/_rels/slide1.xml.rels").expect("slide rels").read_to_string(&mut rels_xml).expect("read slide rels"); + assert!(rels_xml.contains("notesSlide"), "slide points to notes slide: {rels_xml}"); + + let again = deckcraft_pptx::import(&saved).expect("reimport"); + assert!(again.slides[0].notes.is_empty()); + assert!(again.slides[0].has_notes_slide, "notes slide presence survives roundtrip"); + + let saved_again = deckcraft_pptx::export(&again).expect("export again"); + let mut z2 = zip::ZipArchive::new(Cursor::new(saved_again)).expect("zip"); + assert!(z2.by_name(NOTES).is_ok(), "empty notes slide part is kept on subsequent export"); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 70b74f7e1..a9fa6a569 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity with PowerPoint -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233)) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-11 · **Change:** minor (empty notes slides are preserved on save and reopen, #2025; previous: cell anchorCtr, vertOverflow/horzOverflow, compatLnSpc, normalizeH, thaiDist, table rtl, run altLang and reflection transforms round-trip; Reuse Slides brings referenced custom table styles; previous: minor (native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: seven owned PPTX corpus files, embedded fonts, EMF/WMF clip regions, threaded comments (#70), chart trendlines and workbooks (#335), SmartArt written as a diagram, tags and custom XML kept, picture export DPI; duplicated rows and headers folded; previous: trivial, lines in scaled groups, #233)) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) Every format PowerPoint reads or writes, DeckCraft's support, fidelity and how it is tested. Gaps are itemized in [gaps.md](gaps.md#file-formats). Dimension score: **~58% ready** @@ -77,7 +77,7 @@ the round trip even though DeckCraft doesn't model it. | Presentation, slide size, sections (p14), custom shows | yes | yes | | | Slide masters, layouts, placeholders and inheritance | yes | yes | | | Themes: colour, font (Latin/EA/CS), effect schemes, background styles | yes | yes | Unknown theme parts kept | -| Notes slides and notes master | yes | yes | Header, footer, date and slide-number text on the notes master is kept. Edited in View ▸ Notes Master. Notes keep their run and paragraph formatting (bold, italic, underline, size, levels, indents, bullets), shown and kept when edited in the notes pane and Notes Page (`crates/pptx/tests/it/notes.rs`). PDF notes pages print them as plain text; levels and bullets inherited from a custom notes master aren't shown | +| Notes slides and notes master | yes | yes | Header, footer, date and slide-number text on the notes master is kept. Edited in View ▸ Notes Master. Notes keep their run and paragraph formatting (bold, italic, underline, size, levels, indents, bullets), shown and kept when edited in the notes pane and Notes Page (`crates/pptx/tests/it/notes.rs`). Empty notes slides are preserved on save and reopen (#2025). PDF notes pages print them as plain text; levels and bullets inherited from a custom notes master aren't shown | | Handout master | yes | yes | Header, footer, date and slide-number text is kept. Edited in View ▸ Handout Master | | Shapes: preset geometry (~180 presets), custom geometry, groups, connectors | yes | yes | Presets re-derived in `crates/geom/src/preset.rs` (and `preset/extra.rs`). Outlines, dashes, arrowheads and ink inside a group, and text, keep their size in points whatever the group's child-coordinate scale (#233). | | Fills: solid, gradient, picture (stretch/tile/crop), pattern, group | yes | yes | | @@ -121,6 +121,7 @@ the round trip even though DeckCraft doesn't model it. |---|---|---| | 2026-11-02 | minor | Optional table RTL direction is read and written as `a:tblPr/@rtl`; native and two PPTX saves preserve true, false and absent values with distinguishable column text | | 2026-11-02 | minor | Text runs preserve alternate-language metadata in native and PPTX round trips | +| 2026-11-11 | minor | Empty notes slides retain their notesSlide part and relationship on save and reopen (#2025) | | 2026-11-03 | trivial | Reuse Slides transfers referenced custom table styles from native and PPTX sources; grouped tables, undo, native save/reopen and style-id conflicts are covered | | 2026-10-18 | minor | Native chart payloads use referenced ZIP members and share media byte/item limits; old inline sidecars remain readable. Synthetic tests cover multi-megabyte layout, all shape owners, shared budgets, missing/corrupt members and invalid references. Scores and milestone scope unchanged | | 2026-11-02 | trivial | Reflection start position, affine scale/skew, direction and fade, alignment and rotation attributes survive native and PPTX saves; rendering remains partial | From 96c6b5da4cf7b9d4bac4ce9421c30b42353b2296 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 10:20:58 +0000 Subject: [PATCH 26/76] address review: refund the diagram XML budget when a fallback or a parent drawing is dropped --- crates/pptx/src/read/shapes.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 9e0aa3e9b..4e3b54398 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -471,6 +471,7 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S }; // Keep the parts it points to so a save writes it back whole (#203). A part with relationships // of its own, or an external link, can't be carried: the save then falls back to the preview. + let xml_before = imp.diagram_xml_bytes; let parts = super::rel_refs(e) .into_iter() .map(|id| { @@ -491,8 +492,12 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S let media = if rel.kind == "diagramData" { diagram_data(imp, &target) } else { imp.media_for(&target) }; Some((id, kind, media?)) }) - .collect::>>() - .unwrap_or_default(); + .collect::>>(); + // A fallback that drops its parts does not keep their bytes charged. + if parts.is_none() { + imp.diagram_xml_bytes = xml_before; + } + let parts = parts.unwrap_or_default(); s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts }; s } @@ -596,6 +601,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> let tree = d.root.child("spTree")?; let mut sub = IdCtx { fresh: true, ..Default::default() }; let before = imp.smartart_shapes; + let xml_before = imp.diagram_xml_bytes; let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1); if children.is_empty() { return None; @@ -605,6 +611,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> if total > MAX_SMARTART_SHAPES { // Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included. imp.smartart_shapes = before; + imp.diagram_xml_bytes = xml_before; return None; } imp.smartart_shapes = total; From 64c89064eae2f195c29e89e9166db5f78604453d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 15:11:54 +0000 Subject: [PATCH 27/76] address review: drop media copied by a rolled-back diagram fallback or parent drawing --- crates/pptx/src/read.rs | 9 +++++++++ crates/pptx/src/read/shapes.rs | 6 ++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 9c8756f87..886201a30 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -76,6 +76,15 @@ impl Imp<'_> { self.media_by_part.insert(key, id); Some(id) } + /// Drop the media copied since the list was `len` long, with their part-cache entries: used when + /// the content that read them is discarded, so they are neither kept nor reused uncharged. + pub fn forget_media_from(&mut self, len: usize) { + if self.media.len() > len { + let gone: std::collections::HashSet = self.media[len..].iter().map(|m| m.id).collect(); + self.media.truncate(len); + self.media_by_part.retain(|_, id| !gone.contains(id)); + } + } /// Media item for an external link. pub fn media_link(&mut self, url: &str) -> MediaId { if let Some(m) = self.media.iter().find(|m| m.link.as_deref() == Some(url)) { diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 4e3b54398..98ec3a155 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -471,7 +471,7 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S }; // Keep the parts it points to so a save writes it back whole (#203). A part with relationships // of its own, or an external link, can't be carried: the save then falls back to the preview. - let xml_before = imp.diagram_xml_bytes; + let (xml_before, media_before) = (imp.diagram_xml_bytes, imp.media.len()); let parts = super::rel_refs(e) .into_iter() .map(|id| { @@ -496,6 +496,7 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S // A fallback that drops its parts does not keep their bytes charged. if parts.is_none() { imp.diagram_xml_bytes = xml_before; + imp.forget_media_from(media_before); } let parts = parts.unwrap_or_default(); s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts }; @@ -601,7 +602,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> let tree = d.root.child("spTree")?; let mut sub = IdCtx { fresh: true, ..Default::default() }; let before = imp.smartart_shapes; - let xml_before = imp.diagram_xml_bytes; + let (xml_before, media_before) = (imp.diagram_xml_bytes, imp.media.len()); let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1); if children.is_empty() { return None; @@ -612,6 +613,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> // Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included. imp.smartart_shapes = before; imp.diagram_xml_bytes = xml_before; + imp.forget_media_from(media_before); return None; } imp.smartart_shapes = total; From 175fa54642ec6d36ee2514db09390b7b96f40a8d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 18:50:18 +0000 Subject: [PATCH 28/76] address review: roll back by journal, preflight fallback parts, restore tag and chart sidecar accounting on a rejected drawing --- crates/pptx/src/read.rs | 53 ++++++++++++++++++++---- crates/pptx/src/read/chart.rs | 1 + crates/pptx/src/read/shapes.rs | 76 +++++++++++++++++++++------------- 3 files changed, 95 insertions(+), 35 deletions(-) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 886201a30..189bd81de 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -24,11 +24,24 @@ use crate::PptxError; use crate::opc::{self, Package, Rels}; use crate::xml::{Doc, El, Node}; +/// A snapshot of the import state a discarded read rolls back to. +pub struct Mark { + diagram_xml_bytes: usize, + media: usize, + media_keys: usize, + tag_bytes: usize, + tags_capped: bool, + kept_sidecar_bytes: usize, + kept_chart_keys: usize, +} + /// Import state shared by all parts. pub struct Imp<'a> { pub pkg: &'a Package, pub media: Vec, pub media_by_part: HashMap, + /// Keys added to `media_by_part`, in order, so a rollback removes only its own. + pub media_keys: Vec, pub next: u32, pub slide_by_part: HashMap, pub custom_show_names: HashMap, @@ -40,6 +53,8 @@ pub struct Imp<'a> { pub kept_sidecar_bytes: usize, /// Cached kept sidecars by normalized chart part name. pub kept_charts: HashMap, + /// Keys added to `kept_charts`, in order, for rollback. + pub kept_chart_keys: Vec, /// Add-in tags parts, parsed once each, by normalized part name. pub tags_by_part: HashMap>, /// Bytes of tags copied into the model so far (see [`MAX_TAG_BYTES`]). @@ -73,16 +88,36 @@ impl Imp<'_> { let content_type = self.pkg.content_type(part).filter(|c| !c.is_empty()).unwrap_or_else(|| crate::mime_for(&name).to_string()); let id = MediaId(self.alloc()); self.media.push(MediaItem { id, name, content_type, data: Arc::new(data), link: None }); + self.media_keys.push(key.clone()); self.media_by_part.insert(key, id); Some(id) } - /// Drop the media copied since the list was `len` long, with their part-cache entries: used when - /// the content that read them is discarded, so they are neither kept nor reused uncharged. - pub fn forget_media_from(&mut self, len: usize) { - if self.media.len() > len { - let gone: std::collections::HashSet = self.media[len..].iter().map(|m| m.id).collect(); - self.media.truncate(len); - self.media_by_part.retain(|_, id| !gone.contains(id)); + /// What a discarded read must give back: the budgets it charged and the media and kept-chart + /// entries it added (see [`Imp::rollback`]). + pub fn mark(&self) -> Mark { + Mark { + diagram_xml_bytes: self.diagram_xml_bytes, + media: self.media.len(), + media_keys: self.media_keys.len(), + tag_bytes: self.tag_bytes, + tags_capped: self.tags_capped, + kept_sidecar_bytes: self.kept_sidecar_bytes, + kept_chart_keys: self.kept_chart_keys.len(), + } + } + /// Undo everything since `m`: only the entries added since are removed, so the cost follows + /// what the discarded read added, not the size of the caches. + pub fn rollback(&mut self, m: &Mark) { + self.diagram_xml_bytes = m.diagram_xml_bytes; + self.tag_bytes = m.tag_bytes; + self.tags_capped = m.tags_capped; + self.kept_sidecar_bytes = m.kept_sidecar_bytes; + self.media.truncate(m.media); + for k in self.media_keys.drain(m.media_keys..) { + self.media_by_part.remove(&k); + } + for k in self.kept_chart_keys.drain(m.kept_chart_keys..) { + self.kept_charts.remove(&k); } } /// Media item for an external link. @@ -454,6 +489,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec< pkg: &pkg, media: vec![], media_by_part: HashMap::new(), + media_keys: vec![], next: 0, slide_by_part: HashMap::new(), custom_show_names: HashMap::new(), @@ -461,6 +497,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec< vml_previews: HashMap::new(), kept_sidecar_bytes: 0, kept_charts: HashMap::new(), + kept_chart_keys: vec![], tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, @@ -499,6 +536,7 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxE pkg: &pkg, media: vec![], media_by_part: HashMap::new(), + media_keys: vec![], next: max_id.max(1), slide_by_part: HashMap::new(), custom_show_names: HashMap::new(), @@ -506,6 +544,7 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxE vml_previews: HashMap::new(), kept_sidecar_bytes: 0, kept_charts: HashMap::new(), + kept_chart_keys: vec![], tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, diff --git a/crates/pptx/src/read/chart.rs b/crates/pptx/src/read/chart.rs index 358f88ff5..059b79031 100644 --- a/crates/pptx/src/read/chart.rs +++ b/crates/pptx/src/read/chart.rs @@ -485,6 +485,7 @@ pub(crate) fn capture_kept(imp: &mut super::Imp, chart_part: &str) -> deckcraft_ kept.rels.push(ChartRel { id: r.id, rel_type: r.ty, target: r.target_raw, part: r.target, external: false }); } } + imp.kept_chart_keys.push(key.clone()); imp.kept_charts.insert(key, kept.clone()); kept } diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 98ec3a155..3002e4e13 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -471,33 +471,53 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S }; // Keep the parts it points to so a save writes it back whole (#203). A part with relationships // of its own, or an external link, can't be carried: the save then falls back to the preview. - let (xml_before, media_before) = (imp.diagram_xml_bytes, imp.media.len()); - let parts = super::rel_refs(e) - .into_iter() - .map(|id| { - let rel = part.rels.get(&id).filter(|r| !r.external)?; - let pkg = imp.pkg; - if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) { - return None; + // Validate every relationship (and charge the budget) before copying anything, so a fallback + // that cannot be kept whole copies no part at all. + let mark = imp.mark(); + let mut planned = Vec::new(); + let mut spent = imp.diagram_xml_bytes; + let mut ok = true; + for id in super::rel_refs(e) { + let Some(rel) = part.rels.get(&id).filter(|r| !r.external) else { + ok = false; + break; + }; + let pkg = imp.pkg; + if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) { + ok = false; + break; + } + // A diagram's definition parts copied here count against the same presentation-wide budget. + if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&rel.target)) { + let len = pkg.get(&rel.target).map_or(0, |b| b.len()); + if len > MAX_DIAGRAM_PART_BYTES || spent.saturating_add(len) > MAX_DIAGRAM_XML_BYTES { + ok = false; + break; } - let (kind, target) = (rel.ty.clone(), rel.target.clone()); - // A diagram's definition parts copied here count against the same presentation-wide budget. - if rel.kind.starts_with("diagram") && !imp.media_by_part.contains_key(&crate::opc::norm(&target)) { - let len = pkg.get(&target).map_or(0, |b| b.len()); - if len > MAX_DIAGRAM_PART_BYTES || imp.diagram_xml_bytes.saturating_add(len) > MAX_DIAGRAM_XML_BYTES { - return None; - } - imp.diagram_xml_bytes += len; - } - let media = if rel.kind == "diagramData" { diagram_data(imp, &target) } else { imp.media_for(&target) }; - Some((id, kind, media?)) - }) - .collect::>>(); - // A fallback that drops its parts does not keep their bytes charged. - if parts.is_none() { - imp.diagram_xml_bytes = xml_before; - imp.forget_media_from(media_before); + spent += len; + } + if pkg.get(&rel.target).is_none() { + ok = false; + break; + } + planned.push((id, rel.ty.clone(), rel.target.clone(), rel.kind == "diagramData")); } + let parts = if ok { + imp.diagram_xml_bytes = spent; + let copied: Option> = planned + .into_iter() + .map(|(id, kind, target, data)| { + let media = if data { diagram_data(imp, &target) } else { imp.media_for(&target) }; + Some((id, kind, media?)) + }) + .collect(); + if copied.is_none() { + imp.rollback(&mark); + } + copied + } else { + None + }; let parts = parts.unwrap_or_default(); s.kind = ShapeKind::Opaque { xml: part.keep(e), preview, label, parts }; s @@ -569,6 +589,7 @@ fn diagram_data(imp: &mut Imp, target: &str) -> Option data: std::sync::Arc::new(xml.into_bytes()), link: None, }); + imp.media_keys.push(norm_target.clone()); imp.media_by_part.insert(norm_target, id); Some(id) } @@ -602,7 +623,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> let tree = d.root.child("spTree")?; let mut sub = IdCtx { fresh: true, ..Default::default() }; let before = imp.smartart_shapes; - let (xml_before, media_before) = (imp.diagram_xml_bytes, imp.media.len()); + let mark = imp.mark(); let children = sp_tree(imp, &dpart, &mut sub, tree, depth + 1); if children.is_empty() { return None; @@ -612,8 +633,7 @@ fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> if total > MAX_SMARTART_SHAPES { // Over the presentation's remaining budget: a placeholder, and nothing charged, nested SmartArt included. imp.smartart_shapes = before; - imp.diagram_xml_bytes = xml_before; - imp.forget_media_from(media_before); + imp.rollback(&mark); return None; } imp.smartart_shapes = total; From 3746f259a03bee4936b5b4a304edc1e9067b117d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 19:22:48 +0000 Subject: [PATCH 29/76] test: rollback restores budgets and removes only what the discarded read added --- crates/pptx/src/read.rs | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 189bd81de..c638376b8 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -1482,3 +1482,47 @@ fn header_footer(p: &Presentation) -> HeaderFooter { } hf } + +#[cfg(test)] +mod rollback_tests { + use super::*; + + /// A rolled-back read gives back its budgets and removes only the media and kept-chart entries it added. + #[test] + fn rollback_restores_budgets_and_removes_only_what_was_added() { + let bytes = crate::export(&deckcraft_model::Presentation::default()).expect("export"); + let pkg = Package::open(&bytes).expect("package"); + let mut imp = Imp { + pkg: &pkg, + media: vec![], + media_by_part: HashMap::new(), + media_keys: vec![], + next: 0, + slide_by_part: HashMap::new(), + custom_show_names: HashMap::new(), + table_style_ids: Vec::new(), + vml_previews: HashMap::new(), + kept_sidecar_bytes: 0, + kept_charts: HashMap::new(), + kept_chart_keys: vec![], + tags_by_part: HashMap::new(), + tag_bytes: 0, + tags_capped: false, + theme_extra_bytes: 0, + smartart_shapes: 0, + diagram_xml_bytes: 0, + has_rels: HashMap::new(), + }; + let kept_before = imp.media_for("ppt/presentation.xml").expect("media"); + let (m, items) = (imp.mark(), imp.media.len()); + assert!(imp.media_for("ppt/presProps.xml").is_some()); + imp.kept_chart_keys.push("ppt/charts/chart1.xml".into()); + imp.kept_charts.insert("ppt/charts/chart1.xml".into(), Default::default()); + (imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes) = (7, 5, true, 9); + imp.rollback(&m); + assert_eq!(imp.media.len(), items); + assert_eq!(imp.media_by_part.get("ppt/presentation.xml"), Some(&kept_before)); + assert!(!imp.media_by_part.contains_key("ppt/presprops.xml") && imp.kept_charts.is_empty() && imp.kept_chart_keys.is_empty()); + assert_eq!((imp.diagram_xml_bytes, imp.tag_bytes, imp.tags_capped, imp.kept_sidecar_bytes), (0, 0, false, 0)); + } +} From 8d51427d1efb8d006c236ba4f7cdf6bb9a73130c Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 12 Nov 2026 11:30:53 +0500 Subject: [PATCH 30/76] Charts: line series draw their value labels A line chart whose series ask for value labels (c:dLbls/c:showVal, chart-wide or on the series) drew none: draw_lines placed the points and the line but never a label, though bar and pie charts draw theirs (#868). Each point now shows its own value (not the stacked total) just above it, in the chart's text colour and number format, as the bars place theirs. Area series still draw none. Fixes #2066 --- crates/render/src/chart.rs | 20 ++++++++++++++++++++ crates/render/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/crates/render/src/chart.rs b/crates/render/src/chart.rs index 53794987a..38943b929 100644 --- a/crates/render/src/chart.rs +++ b/crates/render/src/chart.rs @@ -477,6 +477,7 @@ fn draw_inner(ctx: &mut RenderContext, rctx: &Ctx, c: &Chart, frame: ChartFrame< to_axis: &to_axis, zero, base, + text_color: text_col, error_marks: &mut err_marks, }, ); @@ -857,6 +858,7 @@ struct LineDrawing<'a, 'ctx> { to_axis: &'a dyn Fn(bool, f64) -> f64, zero: f64, base: f64, + text_color: Rgba, error_marks: &'a mut Vec<(f64, f64, f64, f64, bool)>, } @@ -885,6 +887,8 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { let col = if area_kind { series_fill(rctx, c, si, Some(s)) } else { series_line(rctx, c, si, s) }; let series_stats = s.error_bars.as_ref().map(|_| deckcraft_model::chart::SeriesStats::of(&s.values)); let mut pts = vec![]; + // Each point's own value (not the stacked total), for its data label. + let mut values = vec![]; // Whether the series has any x value, found once rather than per point. let any_x = s.x_values.iter().flatten().next().is_some(); for i in 0..ncat { @@ -913,6 +917,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { err_marks.push((x, to_axis(sec, lo), to_axis(sec, hi), base * 0.4, s.error_bars.as_ref().is_some_and(|e| e.end_cap))); } pts.push(Point::new(x, to_axis(sec, v))); + values.push(s.values.get(i).copied().flatten().unwrap_or(v)); } if pts.is_empty() { continue; @@ -940,6 +945,21 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { ctx.fill_path(&kurbo::Circle::new(*q, 3.5).to_path(0.1)); } } + // A series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value just + // above it, as bars do theirs (#2066). Area series keep none: theirs sit inside the area. + if !area_kind && c.series_data_labels(s) { + let gap = base * 0.3 + 3.5; + for (q, v) in pts.iter().zip(&values) { + label( + ctx, + rctx, + m, + &c.data_label(s, *v), + Rect::new(q.x - 40.0, q.y - gap - base * 1.4, q.x + 40.0, q.y - gap), + LabelStyle { size: base * 0.9, align: Align::Center, anchor: Anchor::Bottom, col: draw.text_color, bold: false }, + ); + } + } } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 540a8500a..9752ab6de 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -3050,6 +3050,43 @@ fn pie_data_labels_take_the_chart_text_colour_when_it_has_one() { assert!(count(&plain, &white) > count(&coloured, &white), "the labels were white before"); } +/// #2066: a line series that asks for value labels (`c:dLbls/c:showVal`, chart-wide or its own) +/// shows each point's value above it; with the chart's text red, the labels add red ink there. +/// Area series still draw none (their labels belong inside the area, not on a point). +#[test] +fn line_chart_value_labels_are_drawn_above_their_points() { + let draw = |kind: ChartType, labels: bool, own: bool| { + let mut c = Chart::sample(kind); + c.title = None; + c.legend = None; + c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 0))); + if own { + c.series[0].data_labels = Some(labels); + } else { + c.data_labels = labels; + } + let sh = Shape { id: ShapeId(633), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() }; + render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() }) + }; + let red = |img: &Image| { + (0..400u32) + .flat_map(|x| (0..300u32).map(move |y| (x, y))) + .filter(|(x, y)| { + let p = img.pixel(*x, *y); + p[0] > 200 && p[1] < 60 && p[2] < 60 + }) + .count() + }; + for kind in [ChartType::Line, ChartType::LineMarkers] { + let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false))); + assert!(on > off + 100, "{kind:?}: labels add red ink ({off} → {on})"); + let own = red(&draw(kind, true, true)); + assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})"); + } + let (off, on) = (red(&draw(ChartType::Area, false, false)), red(&draw(ChartType::Area, true, false))); + assert_eq!(on, off, "area series keep no point labels"); +} + /// #1165: an ellipse sized at the EMU limit, crossing the slide, made vello's flattener allocate a /// buffer from its on-screen length and abort. It is skipped; the rest of the slide still draws. #[test] From 53044b2ceb757d723f4b3f026277c263a5a39152 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:43:41 +0100 Subject: [PATCH 31/76] render: text effects from a paragraph's defRPr or the default text style need filters `text_has_effects` missed a shadow or glow that text inherits from its paragraph's `a:pPr/a:defRPr` or the presentation's default text style. Such a slide was drawn on the multi-threaded vello_cpu dispatcher, which panics on filter layers; the render guard caught it and the slide came out blank. Found by the Text Shadow UI test in #1691. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/slide.rs | 8 +++++--- crates/render/src/tests.rs | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/render/src/slide.rs b/crates/render/src/slide.rs index b3e6e5dec..2630bb9a5 100644 --- a/crates/render/src/slide.rs +++ b/crates/render/src/slide.rs @@ -37,18 +37,20 @@ pub fn needs_filters(pres: &Presentation, slide: &Slide) -> bool { any } -/// Does the shape's text have a shadow or glow (on a run, in its list style, or in the master's -/// text styles it inherits)? Such text is blurred, which needs filters. +/// Does the shape's text have a shadow or glow (on a run, in its paragraph's `defRPr`, in its list +/// style, or in the master's or presentation's text styles it inherits)? Such text is blurred, +/// which needs filters. fn text_has_effects(rctx: &Ctx, s: &Shape) -> bool { use deckcraft_model::text::{ListStyle, RunProps}; let fx = |r: &RunProps| r.shadow.as_ref().is_some_and(|s| !s.inner) || r.glow.as_ref().is_some_and(|g| g.radius > 0.0); let styled = |l: &ListStyle| l.levels.iter().flatten().any(|lv| fx(&lv.run)); let Some(t) = &s.text else { return false }; - t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props)) + t.paragraphs.iter().any(|p| p.runs.iter().any(|r| fx(&r.props)) || fx(&p.end_props) || fx(&p.def_props)) || styled(&t.list_style) || styled(&rctx.master.title_style) || styled(&rctx.master.body_style) || styled(&rctx.master.other_style) + || styled(&rctx.pres.default_text_style) } /// Render slide `index` at `opts.scale` pixels per point. A panic inside the renderer becomes a diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e5cd2319e..a35500950 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1239,6 +1239,24 @@ fn effect_text(set: impl Fn(&mut deckcraft_model::text::RunProps)) -> Presentati deck_with(vec![sh]) } +/// Text whose glow comes only from its paragraph's `defRPr` needs the filters too: drawn on the +/// worker threads it panicked (vello_cpu has no filters there) and the slide came out blank. +#[test] +fn a_paragraph_default_text_glow_needs_filters() { + let mut sh = Shape { id: ShapeId(741), xfrm: Some(Xfrm::new(100.0, 100.0, 600.0, 300.0)), text_box: true, ..Default::default() }; + let mut t = TextBody::from_text("IIII"); + let p = &mut t.paragraphs[0]; + p.runs[0].props.size = Some(100.0); + p.runs[0].props.fill = Some(deckcraft_model::style::Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 0, 0)))); + p.def_props.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 }); + sh.text = Some(t); + let deck = deck_with(vec![sh]); + assert!(needs_filters(&deck, &deck.slides[0])); + let img = render_slide(&deck, 0, &RenderOpts { scale: 1.0, threads: 4, ..Default::default() }); + let halo = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[1] > 150 && p[0] < 120 && p[2] < 120).count(); + assert!(halo > 300, "green halo pixels {halo}"); +} + #[test] fn text_glow_and_shadow_are_drawn() { let count = |img: &Image, f: &dyn Fn(&[u8; 4]) -> bool| img.pixels.as_chunks::<4>().0.iter().filter(|px| f(px)).count(); From b5dfac13669615481bc787525c8e5b1f3abcc8ee Mon Sep 17 00:00:00 2001 From: Hamza Date: Fri, 13 Nov 2026 14:41:28 +0500 Subject: [PATCH 32/76] Charts: value labels only on line series, with stacked and position tests Review of #2071: scatter and bubble series, drawn by the same function, are left as they were. The label keeps the point's own value before stacking, and new tests check a stacked label shows that value and sits just above its point. --- crates/render/src/chart.rs | 10 +++-- crates/render/src/tests.rs | 78 +++++++++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 6 deletions(-) diff --git a/crates/render/src/chart.rs b/crates/render/src/chart.rs index 38943b929..837dbcf7c 100644 --- a/crates/render/src/chart.rs +++ b/crates/render/src/chart.rs @@ -893,6 +893,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { let any_x = s.x_values.iter().flatten().next().is_some(); for i in 0..ncat { let Some(v) = s.values.get(i).copied().flatten() else { continue }; + let own = v; let v = if stacked { let base_v = acc.get(i).copied().unwrap_or(0.0); if let Some(a) = acc.get_mut(i) { @@ -917,7 +918,7 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { err_marks.push((x, to_axis(sec, lo), to_axis(sec, hi), base * 0.4, s.error_bars.as_ref().is_some_and(|e| e.end_cap))); } pts.push(Point::new(x, to_axis(sec, v))); - values.push(s.values.get(i).copied().flatten().unwrap_or(v)); + values.push(own); } if pts.is_empty() { continue; @@ -945,9 +946,10 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { ctx.fill_path(&kurbo::Circle::new(*q, 3.5).to_path(0.1)); } } - // A series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value just - // above it, as bars do theirs (#2066). Area series keep none: theirs sit inside the area. - if !area_kind && c.series_data_labels(s) { + // A line series that asks for value labels (`c:dLbls/c:showVal`) shows each point's value + // just above it, as bars do theirs (#2066). Area series keep none (theirs sit inside the + // area), and scatter and bubble series, which also come here, are left as they were. + if matches!(kind, ChartType::Line | ChartType::LineMarkers | ChartType::StackedLine) && c.series_data_labels(s) { let gap = base * 0.3 + 3.5; for (q, v) in pts.iter().zip(&values) { label( diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9752ab6de..1b46b568b 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -3083,8 +3083,82 @@ fn line_chart_value_labels_are_drawn_above_their_points() { let own = red(&draw(kind, true, true)); assert!(own > off + 30, "{kind:?}: a series' own showVal shows its labels ({off} → {own})"); } - let (off, on) = (red(&draw(ChartType::Area, false, false)), red(&draw(ChartType::Area, true, false))); - assert_eq!(on, off, "area series keep no point labels"); + // Area series keep none, and scatter and bubble series (drawn by the same code) are unchanged. + for kind in [ChartType::Area, ChartType::Scatter, ChartType::Bubble] { + let (off, on) = (red(&draw(kind, false, false)), red(&draw(kind, true, false))); + assert_eq!(on, off, "{kind:?}: no point labels"); + } +} + +/// The magenta pixels the labels add to a line chart of two series, only the second labelled, +/// with the chart's text magenta (no series, gridline or axis line is): its axis labels are +/// magenta too, so they are what the unlabelled chart has. +fn line_label_ink(kind: ChartType, first: f64, second: f64) -> (Image, Vec<(u32, u32)>) { + let off: std::collections::HashSet<_> = magenta_pixels(&line_label_render(kind, first, second, false)).into_iter().collect(); + let img = line_label_render(kind, first, second, true); + let added = magenta_pixels(&img).into_iter().filter(|p| !off.contains(p)).collect(); + (img, added) +} + +fn line_label_render(kind: ChartType, first: f64, second: f64, labels: bool) -> Image { + let mut c = Chart::sample(ChartType::Line); + c.kind = kind; + c.title = None; + c.legend = None; + c.series.truncate(2); + c.series[0].values = vec![Some(first); 4]; + c.series[1].values = vec![Some(second); 4]; + c.series[1].data_labels = Some(labels); + c.text_color = Some(ColorRef::rgb(deckcraft_color::Rgba::rgb(255, 0, 255))); + let sh = Shape { id: ShapeId(634), xfrm: Some(Xfrm::new(0.0, 0.0, 400.0, 300.0)), kind: ShapeKind::Chart(Box::new(c)), ..Default::default() }; + render_slide(&deck_with(vec![sh]), 0, &RenderOpts { scale: 1.0, ..Default::default() }) +} + +/// Magenta ink on white, its anti-aliased edges included. +fn is_magenta(p: [u8; 4]) -> bool { + p[0] > 200 && p[2] > 200 && p[1] < 200 +} + +fn magenta_pixels(img: &Image) -> Vec<(u32, u32)> { + (0..img.width).flat_map(|x| (0..img.height).map(move |y| (x, y))).filter(|(x, y)| is_magenta(img.pixel(*x, *y))).collect() +} + +/// #2066: in a stacked line chart a point's label is its own value, not the running total it is +/// drawn at. The second series' 5s, stacked on 100s, are labels as wide as an unstacked series of +/// 5s, and far narrower than one of 105s (the width: the pixel columns the label ink covers). +#[test] +fn a_stacked_line_labels_each_point_with_its_own_value() { + let width = |kind, second| line_label_ink(kind, 100.0, second).1.iter().map(|(x, _)| *x).collect::>().len(); + let (stacked, fives, totals) = (width(ChartType::StackedLine, 5.0), width(ChartType::Line, 5.0), width(ChartType::Line, 105.0)); + assert!(stacked > 0 && fives > 0, "labels are drawn ({stacked}, {fives})"); + assert!(stacked.abs_diff(fives) <= 4, "stacked 5s are labelled \"5\" ({stacked} columns vs {fives} for 5s)"); + assert!(stacked * 2 < totals, "not with the total \"105\" ({stacked} columns vs {totals} for 105s)"); +} + +/// #2066: a line label sits just above its point: all its ink is above the series' line, and +/// its lowest row is close to it. +#[test] +fn a_line_label_sits_just_above_its_point() { + let (img, ink) = line_label_ink(ChartType::Line, 20.0, 50.0); + assert!(!ink.is_empty(), "labels are drawn"); + let cols: std::collections::HashSet = ink.iter().map(|(x, _)| *x).collect(); + let (first, last) = (cols.iter().min().copied().unwrap(), cols.iter().max().copied().unwrap()); + // The labelled series' flat line at 50: the topmost coloured pixel in the plot's columns + // between the labels (the other line is lower, at 20; the axis labels lie outside them). + let line_top = (first..last) + .filter(|x| !cols.iter().any(|c| c.abs_diff(*x) < 4)) + .filter_map(|x| { + (0..img.height).find(|y| { + let p = img.pixel(x, *y); + let (hi, lo) = (p[0].max(p[1]).max(p[2]), p[0].min(p[1]).min(p[2])); + hi - lo > 80 && !is_magenta(p) + }) + }) + .min() + .unwrap(); + let lowest = ink.iter().map(|(_, y)| *y).max().unwrap(); + assert!(lowest < line_top, "the labels are above the line (lowest ink row {lowest}, line at {line_top})"); + assert!(line_top - lowest < 20, "and just above it (lowest ink row {lowest}, line at {line_top})"); } /// #1165: an ellipse sized at the EMU limit, crossing the slide, made vello's flattener allocate a From 103dc9b05c2ce78fea27bb3fbd4b883020b25713 Mon Sep 17 00:00:00 2001 From: jgriggs-sluh Date: Fri, 13 Nov 2026 08:26:45 -0600 Subject: [PATCH 33/76] Save As: the type list shows all nine types without scrolling (#2019) With the two all-slides types the list outgrew the combo box's default height, and JPEG Pictures, all slides sat behind a scroll. --- crates/ui-egui/src/backstage/info.rs | 2 ++ crates/ui-egui/src/backstage/tests.rs | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/ui-egui/src/backstage/info.rs b/crates/ui-egui/src/backstage/info.rs index 98287856d..c01168467 100644 --- a/crates/ui-egui/src/backstage/info.rs +++ b/crates/ui-egui/src/backstage/info.rs @@ -158,6 +158,8 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out: ui.horizontal(|ui| { craft_ui::ComboBox::from_id_salt("backstage_save_type") .width(340.0) + // Every type in view: at the default height the last ones were behind a scroll. + .height(f32::INFINITY) .selected_text(current) .show_ui(ui, |ui| { for (id, label, _) in SAVE_TYPES { diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index 831cbfa25..9153f4c49 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -392,6 +392,21 @@ fn change_file_type_exports_all_slides_as_pictures() { let _ = std::fs::remove_dir_all(&dir); } +/// Save As shows every type in its open list: the last one is picked by a click, not hidden +/// below the list's default height (#2019). +#[test] +fn save_as_type_list_shows_every_type() { + let mut h = harness(new_app()); + h.state_mut().run("app.backstage", json!({"page": "saveAs"})).unwrap(); + h.run_steps(3); + h.get_by_label("Save as type").click(); + h.run_steps(3); + let (last, label, _) = crate::backstage::SAVE_TYPES[crate::backstage::SAVE_TYPES.len() - 1]; + h.get_by_label(label).click(); + h.run_steps(3); + assert_eq!(h.state().backstage.as_ref().map(|b| b.file_type), Some(last)); +} + /// Close closes a saved presentation at once and asks about unsaved changes first. #[test] fn close_closes_and_asks_about_unsaved_changes() { From 7a24b20c8e82fdbd3317f90f237f290e0d1c38be Mon Sep 17 00:00:00 2001 From: Vincent Cloutier Date: Fri, 13 Nov 2026 11:28:51 -0500 Subject: [PATCH 34/76] Document the PPTX slide-list import limit (#2103) * M1951: document the PPTX slide-list import limit * M1951: expose the slide-list limit in public API docs --------- Co-authored-by: cloutier <1014864+cloutier@users.noreply.github.com> --- ROADMAP.md | 2 +- crates/pptx/src/lib.rs | 1 + docs/file-format-parity.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6318e55da..a67c5e7ab 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -155,7 +155,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| | 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed | -| 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Synthetic 13-slide regression; does not establish the cause of #1910's field report. | +| 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Slide lists over 10,000 entries are explicitly refused before a partial load; exactly 10,000 remain supported. Synthetic 13-slide regression; does not establish the cause of #1910's field report. | | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | | 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop | | 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) | diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 657435821..2c86937e7 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -66,6 +66,7 @@ pub fn import(bytes: &[u8]) -> Result { /// [`import`], plus the part names of slides the file lists but that couldn't be read and were /// left out. +/// Files with more than 10,000 slide-list entries return [`PptxError::Unsupported`] instead of a truncated presentation. pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxError> { read::import_checked(bytes) } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f2209dbec..30f76cff3 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -119,7 +119,7 @@ the round trip even though DeckCraft doesn't model it. | Date | Change | Summary | |---|---|---| -| 2026-11-07 | trivial | A slide-list entry whose relationship is missing is reported in `lostSlides` like an unreadable slide part, so the deck opens as a repaired copy (#1910) | +| 2026-11-07 | trivial | A slide-list entry whose relationship is missing is reported in `lostSlides` like an unreadable slide part, so the deck opens as a repaired copy; slide lists over 10,000 entries are refused with an import-limit error rather than silently truncated (#1910) | | 2026-11-02 | minor | Optional table RTL direction is read and written as `a:tblPr/@rtl`; native and two PPTX saves preserve true, false and absent values with distinguishable column text | | 2026-11-02 | minor | Text runs preserve alternate-language metadata in native and PPTX round trips | | 2026-11-03 | trivial | Reuse Slides transfers referenced custom table styles from native and PPTX sources; grouped tables, undo, native save/reopen and style-id conflicts are covered | From 324a15bc5032898988945f18ab527b98cb1aefa7 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:40:16 +0100 Subject: [PATCH 35/76] render: test a glow from the presentation default text style A glow that text inherits only from `p:defaultTextStyle` must also put the slide on the filter canvas. The new test checks `needs_filters` and renders with worker threads requested, expecting the green halo instead of a blank slide. It fails when the `default_text_style` branch of `text_has_effects` is dropped. Both glow tests now share one assertion helper. --- crates/render/src/tests.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index b8a06523c..48f959638 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1250,9 +1250,24 @@ fn a_paragraph_default_text_glow_needs_filters() { p.runs[0].props.fill = Some(deckcraft_model::style::Fill::solid(ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 0, 0)))); p.def_props.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 }); sh.text = Some(t); - let deck = deck_with(vec![sh]); - assert!(needs_filters(&deck, &deck.slides[0])); - let img = render_slide(&deck, 0, &RenderOpts { scale: 1.0, threads: 4, ..Default::default() }); + assert_green_glow_drawn_with_threads(&deck_with(vec![sh])); +} + +/// Text whose glow comes only from the presentation's default text style (`p:defaultTextStyle`) +/// needs the filters too, or the threaded render panics and the slide comes out blank. +#[test] +fn a_presentation_default_text_style_glow_needs_filters() { + let mut deck = effect_text(|_| {}); + let level = deck.default_text_style.levels[0].as_mut().expect("the default text style sets level 1"); + level.run.glow = Some(deckcraft_model::style::Glow { color: ColorRef::rgb(deckcraft_color::Rgba::rgb(0, 255, 0)), radius: 8.0 }); + assert_green_glow_drawn_with_threads(&deck); +} + +/// Asserts that `deck`'s first slide needs filters and that, rendered with worker threads +/// requested, its text shows a green glow halo rather than a blank slide. +fn assert_green_glow_drawn_with_threads(deck: &Presentation) { + assert!(needs_filters(deck, &deck.slides[0])); + let img = render_slide(deck, 0, &RenderOpts { scale: 1.0, threads: 4, ..Default::default() }); let halo = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[1] > 150 && p[0] < 120 && p[2] < 120).count(); assert!(halo > 300, "green halo pixels {halo}"); } From 52ceb3974be0d76912f66fcd22f2b67368c84f6f Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:48:22 +0000 Subject: [PATCH 36/76] Apply review fixes - crates/model/src/chart.rs --- crates/model/src/chart.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/model/src/chart.rs b/crates/model/src/chart.rs index c93d12f25..8647109af 100644 --- a/crates/model/src/chart.rs +++ b/crates/model/src/chart.rs @@ -1342,6 +1342,7 @@ impl Chart { .collect(), kind: Some(ChartType::Line), secondary_axis: true, + data_labels: Some(false), ..Default::default() }); v.y2_min = Some(0.0); From ea85b0412aa111b24fe484e3fe8cd6cb323bb04a Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Fri, 13 Nov 2026 18:55:05 +0000 Subject: [PATCH 37/76] pptx: preserve deferred ancestor conditions in command-based autoplay inference --- crates/pptx/src/read/timing.rs | 38 ++++++++++++++++++++-------- crates/pptx/tests/it/media_timing.rs | 9 +++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs index 69a1363c4..3106c039b 100644 --- a/crates/pptx/src/read/timing.rs +++ b/crates/pptx/src/read/timing.rs @@ -57,6 +57,8 @@ struct Found<'a> { group: usize, /// Sum of the start delays of the time nodes between the click group and the effect, in ms. offset: u32, + /// Whether any ancestor time node defers start until an event (`onClick`, `onEnd`, targeted `onBegin`) or nonzero delay. + deferred: bool, } /// Where `collect` is in the time tree: the click group and the delay accumulated inside it. @@ -65,6 +67,7 @@ struct At { trigger: Option, group: usize, offset: u32, + deferred: bool, } fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, depth: usize) { @@ -73,7 +76,8 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, } for c in e.elements() { if c.is("cTn") && c.has_attr("presetClass") { - out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset }); + let deferred = at.deferred || c.child("stCondLst").is_some_and(defers_start); + out.push(Found { ctn: c, trigger: at.trigger, group: at.group, offset: at.offset, deferred }); continue; } let mut at = at; @@ -84,14 +88,26 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid")); } if c.is("cTn") - && let Some(cond) = c.path(&["stCondLst", "cond"]) + && let Some(st) = c.child("stCondLst") { - if cond.attr("delay").map(str::trim) == Some("indefinite") { - *groups += 1; - at.group = *groups; - at.offset = 0; - } else { - at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + let is_main_seq_auto = st.children_named("cond").any(|d| d.attr("delay").map(str::trim) == Some("indefinite")) + && st.children_named("cond").any(|d| { + d.attr("evt") == Some("onBegin") + && d.attr("delay").map(str::trim) == Some("0") + && d.child("tgtEl").is_none() + && d.child("rtn").is_none() + }); + if !is_main_seq_auto && defers_start(st) { + at.deferred = true; + } + if let Some(cond) = st.child("cond") { + if cond.attr("delay").map(str::trim) == Some("indefinite") { + *groups += 1; + at.group = *groups; + at.offset = 0; + } else { + at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + } } } collect(c, at, groups, out, depth + 1); @@ -277,10 +293,10 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start); if !root_deferred && let Some(tn) = timing.child("tnLst") { let mut found = vec![]; - collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0); + collect(tn, At { trigger: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); for f in found.into_iter().filter(|f| f.trigger.is_none()) { let c = f.ctn; - if c.attr("nodeType") == Some("clickEffect") { + if c.attr("nodeType") == Some("clickEffect") || f.deferred { break; } let class = AnimClass::from_xml(c.attr("presetClass").unwrap_or("entr")); @@ -305,7 +321,7 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes: let _ = (imp, part); let Some(tn) = timing.child("tnLst") else { return vec![] }; let mut found = vec![]; - collect(tn, At { trigger: None, group: 0, offset: 0 }, &mut 0, &mut found, 0); + collect(tn, At { trigger: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); // Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`. let bld_p: std::collections::HashMap<(u32, String), bool> = timing .child("bldLst") diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index 1274d8dd5..644a64b6f 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -181,4 +181,13 @@ fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { ) }); assert!(main_seq_play[0].autoplay, "main-sequence automatic Play effect sets autoplay"); + + // Command-based Play beneath an onClick or onEnd ancestor must not set autoplay. + let deferred_cmd_play = self::clips(|v, a| { + format!( + r#""# + ) + }); + assert!(!deferred_cmd_play[0].autoplay, "command-based Play under onClick ancestor is not autoplay"); + assert!(!deferred_cmd_play[1].autoplay, "command-based Play under onEnd ancestor is not autoplay"); } From 69379cf689f908d23cab9313d59fb9e1fd4b7a4f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:29:01 +0100 Subject: [PATCH 38/76] Naming: use Diagram and Decorative Text for own features (#1981) * Naming: use Diagram and Decorative Text for own features * test(naming): guard neutral display labels * test(ui): handle escaped literals in feature-name guard --------- Co-authored-by: FredApps --- crates/engine/src/cmd/format.rs | 6 +- crates/engine/src/cmd/insert.rs | 4 +- crates/engine/src/cmd/shape/size.rs | 2 +- crates/engine/src/cmd/smartart.rs | 38 ++-- crates/engine/src/cmd/smartart/edit.rs | 12 +- crates/engine/src/cmd/smartart/paint.rs | 8 +- crates/engine/src/tests.rs | 10 +- crates/engine/src/tools/pointer.rs | 2 +- crates/ui-egui/src/app/commands.rs | 2 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/dialogs/body.rs | 2 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/panels/smartart.rs | 4 +- crates/ui-egui/src/panels/smartart_tests.rs | 4 +- crates/ui-egui/src/ribbon.rs | 28 ++- crates/ui-egui/src/ribbon/home.rs | 2 +- crates/ui-egui/src/ribbon/insert.rs | 6 +- crates/ui-egui/src/ribbon/smartart.rs | 2 +- crates/ui-egui/tests/display_names.rs | 215 ++++++++++++++++++++ docs/feature-names.md | 15 ++ 21 files changed, 308 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/tests/display_names.rs create mode 100644 docs/feature-names.md diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index 4e273dc1c..4eafad20d 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -70,7 +70,7 @@ pub fn specs() -> Vec { cmd!( "format.textTransparency", "Text Transparency", - ["Shape Format", "WordArt Styles"], + ["Shape Format", "Decorative Text Styles"], None, "{value: 0..1} — 0 opaque, 1 invisible; keeps the text's colour (inherited colours included)", has_text_or_shapes, @@ -128,7 +128,7 @@ pub fn specs() -> Vec { cmd!( "format.textOutline", "Text Outline", - ["Shape Format", "WordArt Styles"], + ["Shape Format", "Decorative Text Styles"], None, "{color?, width?: pt} (no color = none)", has_text_or_shapes, @@ -137,7 +137,7 @@ pub fn specs() -> Vec { cmd!( "format.textWarp", "Text Transform", - ["Shape Format", "WordArt Styles"], + ["Shape Format", "Decorative Text Styles"], None, "{preset: a prstTxWarp name or none, adj?: [finite raw guide values, at most 8]} — none clears the transform; omitted adj uses the preset's defaults", has_text_or_shapes, diff --git a/crates/engine/src/cmd/insert.rs b/crates/engine/src/cmd/insert.rs index f7bbc0e0b..1fd6e258e 100644 --- a/crates/engine/src/cmd/insert.rs +++ b/crates/engine/src/cmd/insert.rs @@ -91,7 +91,7 @@ pub fn specs() -> Vec { ), cmd!("insert.audio", "Audio from File…", ["Insert", "Media", "Audio"], None, "{path? | data: base64, name?, rect?}", has_slide, audio), cmd!("insert.video", "Video from File…", ["Insert", "Media", "Video"], None, "{path? | data: base64, name?, rect?}", has_slide, video), - cmd!("insert.wordArt", "WordArt", ["Insert", "Text"], None, "{text?, style?: 0..}", has_slide, word_art), + cmd!("insert.wordArt", "Decorative Text", ["Insert", "Text"], None, "{text?, style?: 0..}", has_slide, word_art), cmd!("insert.slideNumber", "Slide Number", ["Insert", "Text"], None, "{}", has_slide, slide_number), cmd!( "insert.dateTime", @@ -142,7 +142,7 @@ pub fn specs() -> Vec { ), cmd!( "insert.smartArt", - "SmartArt", + "Diagram", ["Insert", "Illustrations"], None, "{kind: list|process|cycle|hierarchy|pyramid|matrix, items?: [text] (leading tabs = sub-points), nodes?: [{text, level}]} → {id}", diff --git a/crates/engine/src/cmd/shape/size.rs b/crates/engine/src/cmd/shape/size.rs index 7568a0632..44be79ecd 100644 --- a/crates/engine/src/cmd/shape/size.rs +++ b/crates/engine/src/cmd/shape/size.rs @@ -196,7 +196,7 @@ pub(super) fn flip(s: &mut Session, p: &Value) -> Result { let mut graphic = false; deckcraft_model::walk(std::slice::from_ref(&*sh), &mut |x, _| graphic |= x.diagram.is_some()); if graphic { - return Err(bad("shape.flip", "Flip is not available for a SmartArt graphic; use `smartArt.layout` to change how it is laid out")); + return Err(bad("shape.flip", "Flip is not available for a Diagram graphic; use `smartArt.layout` to change how it is laid out")); } if let Some(x) = sh.xfrm.as_mut() { if v { diff --git a/crates/engine/src/cmd/smartart.rs b/crates/engine/src/cmd/smartart.rs index 3dbcf40f9..703251c5a 100644 --- a/crates/engine/src/cmd/smartart.rs +++ b/crates/engine/src/cmd/smartart.rs @@ -162,7 +162,7 @@ pub fn preview(kind: &str, style: &str, colors: &str, nodes: Option<&[DiagramNod } Shape { id: ShapeId(9_999), - name: "SmartArt preview".into(), + name: "Diagram preview".into(), xfrm: Some(area), kind: ShapeKind::Group { children, child: area }, ..Default::default() @@ -178,16 +178,16 @@ pub fn specs() -> Vec { cmd!( query "smartArt.nodes", "Text Pane", - ["SmartArt Design", "Create Graphic"], + ["Diagram Design", "Create Graphic"], None, - "{id?} → {id, kind, nodes: [{text, level}]} (id: the SmartArt group or one of its shapes; default the selection)", + "{id?} → {id, kind, nodes: [{text, level}]} (id: the Diagram group or one of its shapes; default the selection)", has_selection, nodes ), cmd!( "smartArt.setNodes", - "Edit SmartArt Text", - ["SmartArt Design", "Create Graphic"], + "Edit Diagram Text", + ["Diagram Design", "Create Graphic"], None, "{id?, nodes?: [{text, level}], lines?: [string] (leading tabs set the level), index?, text?, title?} (index + text edits one node; title: its Name and Title box)", has_selection, @@ -196,7 +196,7 @@ pub fn specs() -> Vec { cmd!( "smartArt.addNode", "Add Shape", - ["SmartArt Design", "Create Graphic"], + ["Diagram Design", "Create Graphic"], None, "{id?, index?, position?: after|before|below|above|assistant, text?} → {index} (default: after the last node)", has_selection, @@ -205,18 +205,18 @@ pub fn specs() -> Vec { cmd!( "smartArt.removeNode", "Remove Shape", - ["SmartArt Design", "Create Graphic"], + ["Diagram Design", "Create Graphic"], None, "{id?, index} (its sub-points move up one level)", has_selection, remove_node ), - cmd!("smartArt.promote", "Promote", ["SmartArt Design", "Create Graphic"], None, "{id?, index}", has_selection, promote), - cmd!("smartArt.demote", "Demote", ["SmartArt Design", "Create Graphic"], None, "{id?, index}", has_selection, demote), + cmd!("smartArt.promote", "Promote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, promote), + cmd!("smartArt.demote", "Demote", ["Diagram Design", "Create Graphic"], None, "{id?, index}", has_selection, demote), cmd!( "smartArt.layout", "Change Layout", - ["SmartArt Design", "Layouts"], + ["Diagram Design", "Layouts"], None, "{id?, kind: list|blockList|hBulletList|process|chevron|verticalProcess|stepUp|cycle|blockCycle|radial|hierarchy|pyramid|invertedPyramid|matrix|titledMatrix|pictureList|pictureCaption|pictureProcess|pictureHList|timeline|venn|target|textCycle|continuousCycle|horizontalHierarchy|gridMatrix|gear|funnel|segmentedCycle|multidirectionalCycle|orgChart|halfCircleOrgChart|cycleMatrix|segmentedPyramid|pie|nameTitleOrgChart|verticalBoxList|trapezoidList|tableList|accentProcess|continuousBlockProcess|bendingProcess|linearVenn|stackedVenn|nestedTarget}", has_selection, @@ -224,17 +224,17 @@ pub fn specs() -> Vec { ), cmd!( "smartArt.fromText", - "Convert to SmartArt", + "Convert to Diagram", ["Home", "Paragraph"], None, - "{id?, kind?} → {id} (a text box or placeholder becomes a SmartArt graphic in its place: one node per paragraph, indent levels kept)", + "{id?, kind?} → {id} (a text box or placeholder becomes a Diagram graphic in its place: one node per paragraph, indent levels kept)", has_selection, from_text ), cmd!( "smartArt.toText", "Convert to Text", - ["SmartArt Design", "Reset"], + ["Diagram Design", "Reset"], None, "{id?} → {id} (the graphic becomes a text box of its outline, bulleted by level)", has_selection, @@ -243,7 +243,7 @@ pub fn specs() -> Vec { cmd!( "smartArt.toShapes", "Convert to Shapes", - ["SmartArt Design", "Reset"], + ["Diagram Design", "Reset"], None, "{id?} (the graphic becomes a plain group of its shapes; the outline is dropped)", has_selection, @@ -251,8 +251,8 @@ pub fn specs() -> Vec { ), cmd!( "smartArt.picture", - "Insert Picture in SmartArt", - ["SmartArt Design", "Create Graphic"], + "Insert Picture in Diagram", + ["Diagram Design", "Create Graphic"], None, "{id?, index, data?: base64 | path?: string | reset?: bool} (the node's picture placeholder in picture layouts)", has_selection, @@ -260,8 +260,8 @@ pub fn specs() -> Vec { ), cmd!( "smartArt.style", - "SmartArt Styles", - ["SmartArt Design", "SmartArt Styles"], + "Diagram Styles", + ["Diagram Design", "Diagram Styles"], None, "{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}", has_selection, @@ -270,7 +270,7 @@ pub fn specs() -> Vec { cmd!( "smartArt.colors", "Change Colors", - ["SmartArt Design", "SmartArt Styles"], + ["Diagram Design", "Diagram Styles"], None, "{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}", has_selection, diff --git a/crates/engine/src/cmd/smartart/edit.rs b/crates/engine/src/cmd/smartart/edit.rs index 77662f71a..7c6b0b934 100644 --- a/crates/engine/src/cmd/smartart/edit.rs +++ b/crates/engine/src/cmd/smartart/edit.rs @@ -38,7 +38,7 @@ fn target_group(s: &Session, p: &Value, cmd: &str) -> Result { let st = s.doc()?; let shapes = current_shapes(&st.doc, &st.selection).ok_or_else(|| bad(cmd, "no slide"))?; let ids = targets(s, p)?; - ids.iter().find_map(|id| diagram_group(shapes, *id)).map(|g| g.id).ok_or_else(|| bad(cmd, "select a SmartArt graphic")) + ids.iter().find_map(|id| diagram_group(shapes, *id)).map(|g| g.id).ok_or_else(|| bad(cmd, "select a Diagram graphic")) } /// Children with fresh ids for diagram `d` inside a group whose child space is `area`. @@ -55,7 +55,7 @@ fn edit_diagram(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Di let gid = target_group(s, p, cmd)?; s.edit(|doc, sel| { let g = current_shapes(doc, sel).and_then(|v| deckcraft_model::find_shape(v, gid)).cloned().ok_or_else(|| bad(cmd, "no such shape"))?; - let (ShapeKind::Group { children, child }, Some(mut d)) = (g.kind, g.diagram) else { return Err(bad(cmd, "not a SmartArt graphic")) }; + let (ShapeKind::Group { children, child }, Some(mut d)) = (g.kind, g.diagram) else { return Err(bad(cmd, "not a Diagram graphic")) }; sync_text(&mut d, &children); let out = f(&mut d)?; normalize(&mut d.nodes); @@ -90,7 +90,7 @@ pub fn insert(s: &mut Session, kind: &str, mut nodes: Vec) -> Resul let id = ShapeId(doc.alloc_id().ok_or_else(|| bad("insert.smartArt", NO_ID_SPACE))?); let g = Shape { id, - name: format!("SmartArt ({kind})"), + name: format!("Diagram ({kind})"), xfrm: Some(area), kind: ShapeKind::Group { children, child: area }, diagram: Some(d), @@ -201,7 +201,7 @@ pub(super) fn from_text(s: &mut Session, p: &Value) -> Result { let gid = ShapeId(doc.alloc_id().ok_or_else(|| bad(CMD, NO_ID_SPACE))?); let g = Shape { id: gid, - name: format!("SmartArt ({kind})"), + name: format!("Diagram ({kind})"), xfrm: Some(area), kind: ShapeKind::Group { children, child: area }, diagram: Some(d), @@ -222,12 +222,12 @@ pub(super) fn from_text(s: &mut Session, p: &Value) -> Result { pub(super) fn to_text(s: &mut Session, p: &Value) -> Result { const CMD: &str = "smartArt.toText"; let gid = target_group(s, p, CMD)?; - let (_, d) = selected_for(s, gid).ok_or_else(|| bad(CMD, "select a SmartArt graphic"))?; + let (_, d) = selected_for(s, gid).ok_or_else(|| bad(CMD, "select a Diagram graphic"))?; // The sizes the graphic's text shows at: its titles' and its bullets' (shrunk to fit included). let (title_pt, bullet_pt) = { let st = s.doc()?; let shapes = current_shapes(&st.doc, &st.selection).ok_or_else(|| bad(CMD, "no slide"))?; - let g = diagram_group(shapes, gid).ok_or_else(|| bad(CMD, "select a SmartArt graphic"))?; + let g = diagram_group(shapes, gid).ok_or_else(|| bad(CMD, "select a Diagram graphic"))?; text_sizes(g.children()) }; let new = s.edit(|doc, sel| { diff --git a/crates/engine/src/cmd/smartart/paint.rs b/crates/engine/src/cmd/smartart/paint.rs index 88192cad3..7da5a1576 100644 --- a/crates/engine/src/cmd/smartart/paint.rs +++ b/crates/engine/src/cmd/smartart/paint.rs @@ -166,21 +166,21 @@ pub(super) fn text_shape(preset: &str, x: Xfrm, lines: &[&DiagramNode], title: b if !title { body.body.anchor = Some(deckcraft_model::text::Anchor::Top); } - Shape { name: "SmartArt shape".into(), xfrm: Some(x), geom: Geom::preset(preset), text: Some(body), ..Default::default() } + Shape { name: "Diagram shape".into(), xfrm: Some(x), geom: Geom::preset(preset), text: Some(body), ..Default::default() } } /// A plain shape with no text (arrows between steps). pub(super) fn deco(preset: &str, x: Xfrm, rot: f64) -> Shape { let mut x = x; x.rot = rot; - Shape { name: "SmartArt arrow".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() } + Shape { name: "Diagram arrow".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() } } pub(super) fn line_shape(a: (f64, f64), b: (f64, f64)) -> Shape { let mut x = Xfrm::new(a.0.min(b.0), a.1.min(b.1), (b.0 - a.0).abs(), (b.1 - a.1).abs()); x.flip_h = (b.0 < a.0) != (b.1 < a.1); Shape { - name: "SmartArt connector".into(), + name: "Diagram connector".into(), xfrm: Some(x), geom: Geom::preset("line"), fill: Some(Fill::None), @@ -257,7 +257,7 @@ fn fit_words(sh: &mut Shape) { /// A picture placeholder for node `node`: its picture when it has one, else a pale box. pub(super) fn picture_shape(d: &Diagram, preset: &str, x: Xfrm, i: usize, node: usize) -> Shape { - let mut sh = Shape { name: "SmartArt picture".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() }; + let mut sh = Shape { name: "Diagram picture".into(), xfrm: Some(x), geom: Geom::preset(preset), ..Default::default() }; paint(d, &mut sh, i, true); if let Some(m) = d.nodes.get(node).and_then(|n| n.picture) { sh.fill = Some(Fill::Picture(deckcraft_model::style::PictureFill { media: m, ..Default::default() })); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a6dc75f8d..21b67310a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4400,10 +4400,10 @@ fn smartart_round_trips_through_pptx_as_a_diagram() { } let back = deckcraft_pptx::import(&bytes).unwrap(); assert!(back.validate().is_empty()); - let g = back.slides[1].shapes.iter().find(|x| x.diagram.is_some()).expect("a SmartArt group"); + let g = back.slides[1].shapes.iter().find(|x| x.diagram.is_some()).expect("a Diagram group"); let d = g.diagram.as_ref().unwrap(); assert_eq!(d.kind, "hierarchy"); - assert_eq!((d.style.as_str(), d.colors.as_str()), ("intense", "accent3"), "SmartArt style and colours come back"); + assert_eq!((d.style.as_str(), d.colors.as_str()), ("intense", "accent3"), "Diagram style and colours come back"); assert!(d.imported); let outline: Vec<(&str, u8)> = d.nodes.iter().map(|n| (n.text.as_str(), n.level)).collect(); assert_eq!(outline, [("CEO", 0), ("CTO", 1), ("Dev", 2), ("CFO", 1)]); @@ -4431,7 +4431,7 @@ fn smartart_pictures_3d_styles_and_colour_variants() { let pics = |s: &Session| -> Vec { let st = s.doc().unwrap(); let g = st.doc.slides[1].shapes.iter().find(|x| x.diagram.is_some()).unwrap().clone(); - g.children().iter().filter(|c| c.name == "SmartArt picture").cloned().collect() + g.children().iter().filter(|c| c.name == "Diagram picture").cloned().collect() }; assert_eq!(pics(&s).len(), 2, "one picture placeholder per top-level node"); assert!(pics(&s).iter().all(|p| !matches!(p.fill, Some(deckcraft_model::Fill::Picture(_))))); @@ -7385,13 +7385,13 @@ fn flip_is_refused_on_a_smartart_graphic_and_leaves_it_a_graphic() { let gid = s.execute("smartArt.fromText", &json!({"kind": "blockList"})).unwrap()["id"].as_u64().unwrap(); for cmd in ["arrange.flipHorizontal", "arrange.flipVertical", "shape.flip"] { let e = s.execute(cmd, &json!({"ids": [gid]})).unwrap_err().to_string(); - assert!(e.contains("SmartArt") && e.contains("smartArt.layout"), "{cmd}: {e}"); + assert!(e.contains("Diagram") && e.contains("smartArt.layout"), "{cmd}: {e}"); } // Grouped with another shape it cannot be flipped either: ungrouping would hand it the flip. let other = s.execute("insert.textBox", &json!({"text": "x"})).unwrap()["id"].as_u64().unwrap(); let group = s.execute("arrange.group", &json!({"ids": [gid, other]})).unwrap()["id"].as_u64().unwrap(); let e = s.execute("shape.flip", &json!({"ids": [group]})).unwrap_err().to_string(); - assert!(e.contains("SmartArt"), "{e}"); + assert!(e.contains("Diagram"), "{e}"); s.execute("arrange.ungroup", &json!({"ids": [group]})).unwrap(); // Still a SmartArt graphic: smartArt commands keep working. s.execute("smartArt.layout", &json!({"id": gid, "kind": "cycle"})).unwrap(); diff --git a/crates/engine/src/tools/pointer.rs b/crates/engine/src/tools/pointer.rs index e289e5c70..bf195b9f8 100644 --- a/crates/engine/src/tools/pointer.rs +++ b/crates/engine/src/tools/pointer.rs @@ -353,7 +353,7 @@ impl Session { bp.warp.map(|n| (n, bp.warp_adj)) }); if let Some((name, base)) = found { - self.begin("Adjust WordArt"); + self.begin("Adjust Decorative Text"); self.tool.drag = Some(Drag::Warp { id, index, name, base, orig }); } } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 718b95ace..75eba4b22 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -238,7 +238,7 @@ impl SlideApp { "app.insertPictureDialog" => self.pick_and_insert("picture", "insert.picture"), "app.smartArtPictureDialog" => { if self.services.pick_open.is_none() { - return Err("picking a SmartArt picture needs the desktop app".into()); + return Err("picking a Diagram picture needs the desktop app".into()); } self.pick_and_run("picture", "smartArt.picture", p); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ed33b9cd6..c7575dfd9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -67,7 +67,7 @@ fn title(id: &str) -> &'static str { "customShow" => "Custom Shows", "chartData" => "Chart Data", "trim" => "Trim Media", - "smartart" => "Choose a SmartArt Graphic", + "smartart" => "Choose a Diagram Graphic", "bullets" => "Bullets and Numbering", "action" => "Action Settings", "quit" => "DeckCraft", diff --git a/crates/ui-egui/src/dialogs/body.rs b/crates/ui-egui/src/dialogs/body.rs index 932cd469a..935823d3f 100644 --- a/crates/ui-egui/src/dialogs/body.rs +++ b/crates/ui-egui/src/dialogs/body.rs @@ -1260,7 +1260,7 @@ fn dlg_smartart(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool { } }); let mut v = d.get("text", "Plan\nBuild\nLaunch"); - ui.add(egui::TextEdit::multiline(&mut v).hint_text("SmartArt items").desired_rows(5).desired_width(320.0)); + ui.add(egui::TextEdit::multiline(&mut v).hint_text("Diagram items").desired_rows(5).desired_width(320.0)); d.fields.insert("text".into(), v.clone()); let (ok, cancel) = buttons(ui, "Insert"); if ok { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 08fcc2391..b92d088ab 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -143,7 +143,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("app.preferences", "Preferences…", Some("Cmd+,"), "{}"), ("app.openDialog", "Open…", None, "{purpose?}"), ("app.insertPictureDialog", "Picture from File…", None, "{}"), - ("app.smartArtPictureDialog", "Insert Picture in SmartArt…", None, "{id?, index}"), + ("app.smartArtPictureDialog", "Insert Picture in Diagram…", None, "{id?, index}"), ("app.changePictureDialog", "Change Picture…", None, "{}"), ("app.insertAudioDialog", "Audio from File…", None, "{}"), ("app.reuseSlidesDialog", "Reuse Slides…", None, "{keepFormatting?: bool}"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index fb4c50fc4..b1b44200e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -248,7 +248,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<(&'static str, &'static str)>)> { ("-", ""), ("Section", "section.add"), ("Text Box", "insert.textBox"), - ("WordArt", "insert.wordArt"), + ("Decorative Text", "insert.wordArt"), ("Date and Time", "insert.dateTime"), ("Slide Number", "insert.slideNumber"), ("-", ""), diff --git a/crates/ui-egui/src/panels/smartart.rs b/crates/ui-egui/src/panels/smartart.rs index aa872d1f0..a50f95070 100644 --- a/crates/ui-egui/src/panels/smartart.rs +++ b/crates/ui-egui/src/panels/smartart.rs @@ -4,7 +4,7 @@ use super::{SlideApp, Tokens, Ui, Value, json, run}; /// Shift+Tab demote and promote, Backspace in an empty line removes it. pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) { let Some((gid, d)) = app.session.active().and_then(deckcraft_engine::cmd::smartart::selected) else { - ui.label("Select a SmartArt graphic to edit its text."); + ui.label("Select a Diagram graphic to edit its text."); return; }; let texts: Vec = d.nodes.iter().map(|n| n.text.clone()).collect(); @@ -24,7 +24,7 @@ pub(super) fn smartart(app: &mut SlideApp, ui: &mut Ui) { ui.horizontal(|ui| { ui.add_space(16.0 * node.level as f32); ui.label("•"); - let te = egui::TextEdit::singleline(draft).id(id).hint_text("SmartArt text").desired_width(f32::INFINITY); + let te = egui::TextEdit::singleline(draft).id(id).hint_text("Diagram text").desired_width(f32::INFINITY); let r = ui.add(te); if app.ui.smartart_focus == Some(i) { r.request_focus(); diff --git a/crates/ui-egui/src/panels/smartart_tests.rs b/crates/ui-egui/src/panels/smartart_tests.rs index 01510197d..dfba4e6c8 100644 --- a/crates/ui-egui/src/panels/smartart_tests.rs +++ b/crates/ui-egui/src/panels/smartart_tests.rs @@ -66,12 +66,12 @@ fn home_convert_to_smartart_gallery_converts_the_text() { app, ); h.run_steps(3); - h.get_by_label("Convert to SmartArt").click(); + h.get_by_label("Convert to Diagram").click(); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Basic Block List").click(); h.run_steps(3); let st = h.state().session.active().unwrap(); - let (_, d) = deckcraft_engine::cmd::smartart::selected(st).expect("the text became a SmartArt graphic"); + let (_, d) = deckcraft_engine::cmd::smartart::selected(st).expect("the text became a Diagram graphic"); assert_eq!(d.kind, "blockList"); assert_eq!(d.nodes.len(), 3); } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 7d2ab7a23..90a3869ed 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -106,7 +106,7 @@ fn contextual(app: &SlideApp) -> Vec<&'static str> { v.push("Layout"); } if deckcraft_engine::cmd::smartart::selected(st).is_some() { - v.push("SmartArt Design"); + v.push(DIAGRAM_TAB_ID); } if shapes.iter().any(|s| matches!(s.kind, ShapeKind::Chart(_))) { v.push("Chart Design"); @@ -117,6 +117,13 @@ fn contextual(app: &SlideApp) -> Vec<&'static str> { v } +// This is an existing saved/control-channel key, not the displayed label. +const DIAGRAM_TAB_ID: &str = "SmartArt Design"; + +fn tab_label(id: &str) -> &str { + if id == DIAGRAM_TAB_ID { "Diagram Design" } else { id } +} + const TABS: [&str; 10] = ["Home", "Insert", "Draw", "Design", "Transitions", "Animations", "Slide Show", "Record", "Review", "View"]; /// Tab row and the ribbon card. @@ -149,18 +156,19 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { } let all: Vec<(&str, bool)> = TABS.iter().map(|s| (*s, false)).chain(ctx_tabs.iter().map(|s| (*s, true))).collect(); for (name, contextual) in all { + let label = tab_label(name); let font = theme::font(13.0); - let w = ui.fonts_mut(|f| f.layout_no_wrap(name.to_string(), font.clone(), t.text).size().x) + 18.0; + let w = ui.fonts_mut(|f| f.layout_no_wrap(label.to_string(), font.clone(), t.text).size().x) + 18.0; let r = Rect::from_min_size(pos2(x, y), vec2(w, 24.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", name)), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); let active = app.ui.tab == name; if resp.hovered() && !active { ui.painter().rect_filled(r.shrink2(vec2(2.0, 2.0)), CornerRadius::same(4), t.hover); } let col = if contextual { t.contextual } else { t.text }; let f = if active { theme::bold(13.0) } else { font }; - ui.painter().text(r.center(), Align2::CENTER_CENTER, name, f, col); + ui.painter().text(r.center(), Align2::CENTER_CENTER, label, f, col); if active { let uw = (w - 20.0).max(16.0); ui.painter().rect_filled(Rect::from_center_size(pos2(r.center().x, r.max.y - 1.0), vec2(uw, 3.0)), CornerRadius::same(1), t.accent); @@ -227,7 +235,7 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { "Table Design" => table_design(app, ui), "Layout" => table_layout(app, ui), "Chart Design" => chart_design(app, ui), - "SmartArt Design" => smartart_design(app, ui), + DIAGRAM_TAB_ID => smartart_design(app, ui), "Playback" => playback(app, ui), "Slide Master" => slide_master(app, ui), "Handout Master" => handout_master(app, ui), @@ -462,3 +470,13 @@ mod inktoshape_tests; #[cfg(test)] mod picture_styles_tests; + +#[cfg(test)] +mod feature_name_tests { + #[test] + fn diagram_tab_keeps_its_saved_identity() { + assert_eq!(super::DIAGRAM_TAB_ID, "SmartArt Design"); + assert_eq!(super::tab_label(super::DIAGRAM_TAB_ID), "Diagram Design"); + assert_eq!(super::tab_label("Home"), "Home"); + } +} diff --git a/crates/ui-egui/src/ribbon/home.rs b/crates/ui-egui/src/ribbon/home.rs index 78dc637f7..73a917567 100644 --- a/crates/ui-egui/src/ribbon/home.rs +++ b/crates/ui-egui/src/ribbon/home.rs @@ -384,7 +384,7 @@ fn paragraph_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) { } } }); - let r = icon_toggle(ui, Icon::SmartArt, "Convert to SmartArt", enabled(app, "smartArt.fromText"), false); + let r = icon_toggle(ui, Icon::SmartArt, "Convert to Diagram", enabled(app, "smartArt.fromText"), false); egui::Popup::menu(&r).show(|ui| smartart_gallery(app, ui, "smartArt.fromText", json!({}), "", ("", ""), None)); if ui.add_enabled(en, egui::Button::new("Paragraph…").min_size(vec2(88.0, 22.0))).on_hover_text("Paragraph").clicked() { run(app, "format.paragraphDialog", json!({})); diff --git a/crates/ui-egui/src/ribbon/insert.rs b/crates/ui-egui/src/ribbon/insert.rs index fab6e3174..ac54e2310 100644 --- a/crates/ui-egui/src/ribbon/insert.rs +++ b/crates/ui-egui/src/ribbon/insert.rs @@ -72,7 +72,7 @@ pub(super) fn insert(app: &mut SlideApp, ui: &mut Ui) { }); let r = big_button(ui, Icon::Icons, "Icons", enabled(app, "insert.icon")); egui::Popup::menu(&r).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).width(340.0).show(|ui| icon_library(app, ui)); - big(app, ui, Icon::SmartArt, "SmartArt", "app.dialog", json!({"id": "smartart"})); + big(app, ui, Icon::SmartArt, "Diagram", "app.dialog", json!({"id": "smartart"})); let r = big_button(ui, Icon::Chart, "Chart", enabled(app, "insert.chart")); egui::Popup::menu(&r).show(|ui| { for k in chart_menu_types() { @@ -111,10 +111,10 @@ pub(super) fn insert(app: &mut SlideApp, ui: &mut Ui) { group(ui, |ui| { big(app, ui, Icon::TextBox, "Text\nBox", "insert.textBox", json!({})); big(app, ui, Icon::HeaderFooter, "Header &\nFooter", "app.dialog", json!({"id": "headerFooter"})); - let r = big_button(ui, Icon::WordArt, "WordArt", enabled(app, "insert.wordArt")); + let r = big_button(ui, Icon::WordArt, "Decorative Text", enabled(app, "insert.wordArt")); egui::Popup::menu(&r).show(|ui| { for i in 0..6 { - if ui.button(format!("WordArt style {}", i + 1)).clicked() { + if ui.button(format!("Decorative Text style {}", i + 1)).clicked() { run(app, "insert.wordArt", json!({"style": i})); } } diff --git a/crates/ui-egui/src/ribbon/smartart.rs b/crates/ui-egui/src/ribbon/smartart.rs index 969cc6146..d1726217a 100644 --- a/crates/ui-egui/src/ribbon/smartart.rs +++ b/crates/ui-egui/src/ribbon/smartart.rs @@ -83,7 +83,7 @@ pub(super) fn smartart_design(app: &mut SlideApp, ui: &mut Ui) { } }); } - let (main, arrow) = small_button_ex(ui, Icon::SmartArt, "SmartArt Styles", gid.is_some(), false, true); + let (main, arrow) = small_button_ex(ui, Icon::SmartArt, "Diagram Styles", gid.is_some(), false, true); if let Some(arrow) = arrow { widgets::split_menu(&main, &arrow, |ui| { for (k, label) in deckcraft_engine::cmd::smartart::STYLES { diff --git a/crates/ui-egui/tests/display_names.rs b/crates/ui-egui/tests/display_names.rs new file mode 100644 index 000000000..5eedc9a34 --- /dev/null +++ b/crates/ui-egui/tests/display_names.rs @@ -0,0 +1,215 @@ +//! Guard the production display surfaces without banning compatibility identifiers or notices. +use std::path::{Path, PathBuf}; + +const BANNED: &[&str] = &["SmartArt", "WordArt"]; +const ALLOWED: &[&str] = &["SmartArt Design"]; +const ROOTS: &[&str] = &["src", "../engine/src/cmd"]; + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn banned_display(text: &str) -> bool { + if ALLOWED.contains(&text) { + return false; + } + BANNED.iter().any(|banned| { + text.match_indices(banned) + .any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word)) + }) +} + +// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is +// needed, so this guard can also run by itself when a full application build is unavailable. +#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together. +fn literals(source: &str) -> Vec { + let chars: Vec = source.chars().collect(); + let mut out = Vec::new(); + let mut at = 0; + let mut test_module = false; + let mut test_depth = 0_usize; + while at < chars.len() { + if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + at += 12; + let rest: String = chars[at..].iter().collect(); + if rest.trim_start().starts_with("mod ") { + test_module = true; + } + } else if chars.get(at..at + 2) == Some(&['/', '/']) { + while at < chars.len() && chars[at] != '\n' { + at += 1; + } + } else if chars.get(at..at + 2) == Some(&['/', '*']) { + at += 2; + let mut depth = 1; + while at < chars.len() && depth > 0 { + if chars.get(at..at + 2) == Some(&['/', '*']) { + depth += 1; + at += 2; + } else if chars.get(at..at + 2) == Some(&['*', '/']) { + depth -= 1; + at += 2; + } else { + at += 1; + } + } + } else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) { + let start = at; + at += 1; + while chars.get(at) == Some(&'#') { + at += 1; + } + let hashes = at - start - 1; + if chars.get(at) != Some(&'"') { + continue; + } + at += 1; + let begin = at; + while at < chars.len() { + if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) { + break; + } + at += 1; + } + if !test_module { + out.push(chars[begin..at].iter().collect()); + } + at += 1 + hashes; + } else if chars[at] == '"' { + at += 1; + let mut text = String::new(); + while at < chars.len() { + let c = chars[at]; + at += 1; + if c == '"' { + break; + } + if c == '\\' && at < chars.len() { + let escaped = chars[at]; + at += 1; + match escaped { + 'n' => text.push('\n'), + 't' => text.push('\t'), + 'r' => text.push('\r'), + '0' => text.push('\0'), + '\n' | '\r' => { + while chars.get(at).is_some_and(|c| c.is_whitespace()) { + at += 1; + } + } + other => text.push(other), + } + } else { + text.push(c); + } + } + if !test_module { + out.push(text); + } + } else if chars[at] == '\'' && chars.get(at + 1) == Some(&'\\') { + // Skip the escape and its payload, including hexadecimal/Unicode escapes. + at += 3; + while at < chars.len() && chars[at] != '\'' { + at += 1; + } + at += 1; + } else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') { + at += 3; // A character literal such as '"', not the start of a string. + } else { + if test_module { + match chars[at] { + '{' => test_depth += 1, + '}' => { + test_depth = test_depth.saturating_sub(1); + if test_depth == 0 { + test_module = false; + } + } + ';' if test_depth == 0 => test_module = false, + _ => {} + } + } + at += 1; + } + } + out +} + +fn check_tree(path: &Path, failures: &mut Vec) { + if path.is_dir() { + for entry in std::fs::read_dir(path).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.file_name().is_some_and(|name| name == "tests") { + continue; + } + check_tree(&path, failures); + } + } else if path.extension().is_some_and(|ext| ext == "rs") { + let name = path.file_name().expect("source filename").to_string_lossy(); + if name == "tests.rs" || name.ends_with("_tests.rs") { + return; + } + let source = std::fs::read_to_string(path).expect("UTF-8 Rust source"); + // Skip only inline test modules, not later production following test-only imports. + for text in literals(&source) { + if banned_display(&text) { + failures.push(format!("{}: {text:?}", path.display())); + } + } + } +} + +#[test] +fn production_display_names_stay_neutral() { + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut failures = Vec::new(); + for root in ROOTS { + let root = base.join(root); + assert!(root.exists(), "missing display source: {}", root.display()); + check_tree(&root, &mut failures); + } + assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n")); +} + +#[test] +fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.cameraRaw")); + assert!(!banned_display("tool.guidedUpright")); + assert!(!banned_display("insert.smartArt")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); +} + +#[test] +fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); +} + +#[test] +fn guard_skips_escaped_character_literals() { + assert_eq!(literals(r#"let q = '\"'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\''; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\\'; "label""#), ["label"]); + assert_eq!(literals(r#"let q = '\u{22}'; "label""#), ["label"]); +} + +#[test] +fn guard_decodes_whitespace_escapes() { + assert_eq!(literals(r#""one\ntwo\tthree\rfour\0""#), ["one\ntwo\tthree\rfour\0"]); + assert_eq!(literals("\"joined\\\n label\""), ["joinedlabel"]); + for name in BANNED { + let source = format!("\"\\t{name}\\n\""); + assert!(literals(&source).iter().any(|label| banned_display(label))); + } +} diff --git a/docs/feature-names.md b/docs/feature-names.md new file mode 100644 index 000000000..b26cfbda2 --- /dev/null +++ b/docs/feature-names.md @@ -0,0 +1,15 @@ +# Feature naming + +DeckCraft uses **Diagram**, **Diagram Design**, and **Diagram Styles** for its diagram feature, and **Decorative Text** / **Decorative Text Styles** for styled text. Menus, dialogs, tooltips, command labels, errors and newly generated object names use these names. + +## Compatibility boundary + +The existing `smartArt.*`, `insert.smartArt`, `insert.wordArt`, dialog and icon IDs remain stable. The persisted/control-channel tab key `SmartArt Design` still opens the same tab; only its displayed and accessible label is Diagram Design. Dispatch does not depend on the new display text. + +Existing document-owned object names are not rewritten. PPTX diagram parts, DrawingML names, public data types, import/export code and attribution remain unchanged. + +DeckCraft currently authors these interface strings directly in English. Shared DeckCraft catalogs exist in craft-i18n, but this change does not add a catalog loader. Before enabling that integration, catalog keys must include the new Diagram and Decorative Text labels rather than only their retired English names. Diagram/format round-trip tests, UI tests and visual checks remain part of application verification. + +## Regression coverage + +The standard-library-only `display_names` integration tests scan production Rust string literals for the retired display names and preserve explicit compatibility exceptions. They also test identifier, comment and raw-string handling. These focused checks do not replace application or visual testing. From 68a4190f952453bd4024ee29e82e6b9f8d8f4bb0 Mon Sep 17 00:00:00 2001 From: Naseq Date: Sat, 14 Nov 2026 13:52:49 +0430 Subject: [PATCH 39/76] Leave the xtask wasm gate unchanged The CI gate change (wasm step from check to clippy -D warnings) belongs in its own CI task; this PR keeps only the opening_generation cfg fix (#1954). --- xtask/src/main.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index c4d4a2429..632769fb3 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -22,7 +22,7 @@ commands: assets check that every icon/image/font/asset is attributed in ATTRIBUTION.md pdf-deps verify pinned writer sources and the production feature boundary layers enforce the crate dependency layering (plan/architecture.md §3) - wasm cargo clippy --target wasm32-unknown-unknown -D warnings for the wasm-safe crates (one call) + wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call) test workspace tests (cargo nextest when installed, else cargo test), then doctests ci fmt --check, pdf-deps, clippy -D warnings, test, doctest, assets, layers, wasm (stops at first failure) @@ -139,7 +139,7 @@ fn wasm_set() -> Result, String> { .collect()) } -/// One `cargo clippy -- -D warnings` for the whole set: each crate is checked once, and +/// One `cargo check` for the whole set: each crate is checked once, and /// `--keep-going` still reports every failing crate. Features unify across the /// set, so each crate is checked with the union of the features the set enables. fn cmd_wasm() -> Result<(), String> { @@ -147,15 +147,13 @@ fn cmd_wasm() -> Result<(), String> { if set.is_empty() { return Err("no wasm-safe crates found in the workspace metadata".into()); } - // Clippy with `-D warnings`, as the host step: a plain `check` let wasm-only dead code through (#1954). let mut c = cargo(); - c.args(["clippy", "--target", "wasm32-unknown-unknown", "--keep-going"]); + c.args(["check", "--target", "wasm32-unknown-unknown", "--keep-going"]); for pkg in &set { c.args(["-p", pkg]); } - c.args(["--", "-D", "warnings"]); - run(c, &format!("cargo clippy --target wasm32-unknown-unknown --keep-going -p {} -- -D warnings", set.join(" -p ")))?; - println!("\nwasm32-unknown-unknown clippy: ok ({} crates: {})", set.len(), set.join(", ")); + run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going -p {}", set.join(" -p ")))?; + println!("\nwasm32-unknown-unknown check: ok ({} crates: {})", set.len(), set.join(", ")); Ok(()) } From 10fef35fe641af87f47f3d7befc7996cc8835bce Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:35:21 +0100 Subject: [PATCH 40/76] M1: reject leading-zero numeric prerelease versions --- xtask/src/version.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/xtask/src/version.rs b/xtask/src/version.rs index 8c4c1fc34..7675edad6 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -49,7 +49,12 @@ pub fn validate(v: &str) -> Result<(), String> { return bad(); } if let Some(p) = pre - && (p.is_empty() || p.split('.').any(|id| id.is_empty() || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))) + && (p.is_empty() + || p.split('.').any(|id| { + id.is_empty() + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + || (id.len() > 1 && id.starts_with('0') && id.bytes().all(|b| b.is_ascii_digit())) + })) { return bad(); } @@ -144,6 +149,18 @@ mod tests { assert!(replace(MANIFEST, "nope").is_err()); } + #[test] + fn numeric_prerelease_identifiers_have_no_leading_zeroes() { + for bad in ["1.0.0-00", "1.0.0-01", "1.0.0-rc.01"] { + assert!(validate(bad).is_err(), "{bad}"); + assert!(replace(MANIFEST, bad).is_err(), "{bad} must not reach the manifest"); + } + for ok in ["1.0.0-0", "1.0.0-rc.0", "1.0.0-01a", "1.0.0-0-1"] { + assert!(validate(ok).is_ok(), "{ok}"); + assert_eq!(read(&replace(MANIFEST, ok).unwrap()).unwrap(), ok); + } + } + #[test] fn the_real_manifest_has_a_valid_version() { let text = std::fs::read_to_string(crate::root().join("Cargo.toml")).unwrap(); From e86c25af9c480b3396781d06de5b3591d357bed3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:45:54 +0100 Subject: [PATCH 41/76] Release: DeckCraft v0.19.0 on main (#2134) Co-authored-by: FredApps --- Cargo.lock | 36 ++++++++++++++++++------------------ Cargo.toml | 2 +- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ccc76c335..a34345398 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1059,7 +1059,7 @@ checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" [[package]] name = "deckcraft" -version = "0.18.1" +version = "0.19.0" dependencies = [ "arboard", "chrono", @@ -1081,7 +1081,7 @@ dependencies = [ [[package]] name = "deckcraft-anim" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-geom", "deckcraft-model", @@ -1090,7 +1090,7 @@ dependencies = [ [[package]] name = "deckcraft-cli" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-engine", "deckcraft-mcp", @@ -1100,14 +1100,14 @@ dependencies = [ [[package]] name = "deckcraft-color" -version = "0.18.1" +version = "0.19.0" dependencies = [ "serde", ] [[package]] name = "deckcraft-engine" -version = "0.18.1" +version = "0.19.0" dependencies = [ "chrono", "deckcraft-anim", @@ -1133,7 +1133,7 @@ dependencies = [ [[package]] name = "deckcraft-fonts" -version = "0.18.1" +version = "0.19.0" dependencies = [ "epaint_default_fonts", "harfrust 0.13.3", @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "deckcraft-format" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-model", "serde", @@ -1156,7 +1156,7 @@ dependencies = [ [[package]] name = "deckcraft-geom" -version = "0.18.1" +version = "0.19.0" dependencies = [ "kurbo", "serde", @@ -1164,7 +1164,7 @@ dependencies = [ [[package]] name = "deckcraft-mcp" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-engine", "deckcraft-render", @@ -1174,7 +1174,7 @@ dependencies = [ [[package]] name = "deckcraft-media" -version = "0.18.1" +version = "0.19.0" dependencies = [ "craft-audio", "craft-media", @@ -1187,7 +1187,7 @@ dependencies = [ [[package]] name = "deckcraft-model" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-color", "deckcraft-geom", @@ -1199,7 +1199,7 @@ dependencies = [ [[package]] name = "deckcraft-pdf" -version = "0.18.1" +version = "0.19.0" dependencies = [ "craft-pdf", "deckcraft-fonts", @@ -1217,7 +1217,7 @@ dependencies = [ [[package]] name = "deckcraft-pptx" -version = "0.18.1" +version = "0.19.0" dependencies = [ "deckcraft-color", "deckcraft-engine", @@ -1233,7 +1233,7 @@ dependencies = [ [[package]] name = "deckcraft-render" -version = "0.18.1" +version = "0.19.0" dependencies = [ "craft-metafile", "deckcraft-anim", @@ -1252,7 +1252,7 @@ dependencies = [ [[package]] name = "deckcraft-text" -version = "0.18.1" +version = "0.19.0" dependencies = [ "chrono", "deckcraft-color", @@ -1266,7 +1266,7 @@ dependencies = [ [[package]] name = "deckcraft-ui-egui" -version = "0.18.1" +version = "0.19.0" dependencies = [ "craft-ui", "craft-update", @@ -1292,7 +1292,7 @@ dependencies = [ [[package]] name = "deckcraft-web" -version = "0.18.1" +version = "0.19.0" dependencies = [ "craft-web-api", "craft-web-host", @@ -6277,7 +6277,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.18.1" +version = "0.19.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index f19655d52..73c7e84aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/deckcraft", "apps/deckcraft-cli"] [workspace.package] -version = "0.18.1" +version = "0.19.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 772219838e2807f0d5b0270f8993421499717f58 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:01:23 +0100 Subject: [PATCH 42/76] docs: correct the control protocol method reference (#2132) * DOC2: correct the control method reference Updated descriptions for various UI commands and actions, including clarifications on parameters and behaviors. * DOC2: clarify text replacement and slide-show key limits * DOC2: describe the grid shortcut restriction --- docs/control-protocol.md | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d1d130c77..bc11e0ea8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -32,16 +32,11 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note | `engine.execute` / `ui.menu.invoke` / `command` | `{command, params}` | Run any command (see `engine.commands`; `deckcraft-cli describe COMMAND` documents one) | | `engine.commands` | — | Every command: id, label, menu path, shortcut, params doc, enabled / disabled reason | | `document.inspect` | — | Slides, sections, layouts, shapes, selection | -| `slide.actions` | `{index?}` | Actions on one slide; returns `{index, slideId, actions}`. Each action has an `owner` (shape id/name and group path; text actions also include paragraph/run indexes and run text, plus table row/cell indexes for table text), `event` (`click`, `hover`, `textLink`, or `textHover`), action `type`, `target`, and the full `hyperlink`. Listing is read-only and never executes an action. An empty slide returns `"actions": []`. | -| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab open over a presentation), `backstage` (its page, also the start screen), slide show state (`grid`, `zoomArm`, `zoom`, `blank`, `presenterPaused`, `presenterSecs`, `notesPx`, `custom`, `goto`; `cells` while See All Slides is open), documents, perf (fps, render ms) | -| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab open over a presentation), `backstage` (its page, also the start screen), slide show state, `animPreview` (canvas playback: slide, time, duration), documents, perf (fps, render ms) | +| `ui.inspect` | — | UI state, active tool, window/canvas/slide rects, dialog, `home` (the File tab over an open presentation), `backstage` (the current File page, including the start screen), slide show state (`grid`, `zoomArm`, `zoom`, `blank`, `presenterPaused`, `presenterSecs`, `notesPx`, `custom`, `goto`; `cells` when See All Slides is open), `animPreview` (canvas playback: slide, time, duration), documents, perf (fps, render ms) | | `ui.tool.select` | `{tool, preset?}` | `select`, `text`, `shape` + preset, any preset name, `curve`, `freeform`, `scribble`, `pen`, `highlighter`, `eraser` | -| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick\|contextclick, x, y, mods?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse (`contextclick`: the right-button press that selects before the context menu) | -| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show: digits then Enter go to that slide, G is See All Slides, Z arms zoom, T pauses the presenter timer, R resets it, `[` and `]` change notes size, Esc clears a slide number, the grid and zoom before it leaves the show) | -| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, mods?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse | -| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show; Escape stops the canvas animation preview) | -| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, mods?, pressure?}], mods?}` | Drive the active tool in slide points through the same code path as the mouse. `pressure` is `0..=1` for a pen; omit it for a mouse | -| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Keyboard input (also drives a running slide show) | +| `ui.pointer` | `{events: [{kind: down\|drag\|up\|move\|doubleclick\|tripleclick\|contextclick, x, y, mods?, pressure?}], mods?}` | Send slide-point pointer events through the active tool's mouse path. `contextclick` performs the right-click selection used by context menus; `pressure` is `0..=1` for a pen and can be omitted for a mouse | +| `ui.key` | `{key, shift?, alt?, cmd?}` | Send a key press. During an active slide show, digits followed by Enter jump to that slide; G opens See All Slides, Z arms zoom, T toggles the presenter timer's pause, R resets it, and `[` / `]` resize notes. Esc clears a typed slide number or backs out of the grid/zoom before ending the active show. Close See All Slides with Esc or G before using the other listed show shortcuts. Slide-show keys ignore modifier flags; use `show.end` to leave the end-of-show screen. Outside a show, Escape stops canvas animation preview | +| `ui.text` | `{text}` | Insert into the current text edit. With one shape selected and no active text edit, begin editing and replace the shape's existing text | | `ui.ime` | `{preedit, active?: [start, end]}` / `{commit}` | An input method's composition through egui, as a real one arrives: shown in place on the slide or in a focused field; `{"preedit": ""}` cancels | | `ui.move` / `ui.click` / `ui.drag` | screen points | Real egui pointer input — reaches every widget, menu and pane | | `ui.set` | `{tab?, view?, pane?, notes?, zoom?, brightness?, ruler?, gridlines?, guides?, …}` | UI state (returns the full state) | @@ -54,3 +49,18 @@ Coordinates are slide points (1/72 inch; a 16:9 slide is 960 × 540) unless note The MCP server (`deckcraft-cli mcp`, see [mcp.md](mcp.md)) wraps the same methods for Claude and other agents; `deckcraft-cli app --method METHOD [PARAMS]` sends one request from a shell. + +## Inspecting slide actions + +Run the `slide.actions` engine command through `engine.execute`: + +```json +{"id": 2, "method": "engine.execute", "params": {"command": "slide.actions", "params": {"index": 0}}} +``` + +`index` is zero-based and optional; omitting it inspects the selected slide. The reply's `result` +contains `{index, slideId, actions}`. Each action includes an `owner` with the shape id/name and +its group path; text actions also identify the paragraph/run and run text, plus the table row/cell +for table text. Actions report their `event` (`click`, `hover`, `textLink`, or `textHover`), +`type`, `target`, and full `hyperlink`. Inspection never runs an action. A slide without actions +returns `"actions": []`. From 3c604486917d40e4abc00d1f6e471fab4a5deca4 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:20:15 +0000 Subject: [PATCH 43/76] Apply review fixes - xtask/src/version.rs --- xtask/src/version.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xtask/src/version.rs b/xtask/src/version.rs index 7675edad6..795070577 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -45,7 +45,11 @@ pub fn validate(v: &str) -> Result<(), String> { None => (v, None), }; let nums: Vec<&str> = core.split('.').collect(); - if nums.len() != 3 || nums.iter().any(|n| n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0'))) { + if nums.len() != 3 + || nums + .iter() + .any(|n| n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) || n.parse::().is_err() || (n.len() > 1 && n.starts_with('0'))) + { return bad(); } if let Some(p) = pre From 04907481c14b2e1c45e9d2e28da008b9659ffb3b Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 03:43:10 +0000 Subject: [PATCH 44/76] Apply review fixes - xtask/src/version.rs --- xtask/src/version.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/version.rs b/xtask/src/version.rs index 795070577..50fb8f040 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -147,7 +147,7 @@ mod tests { for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] { assert!(validate(ok).is_ok(), "{ok}"); } - for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", ""] { + for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", "18446744073709551616.0.0", ""] { assert!(validate(bad).is_err(), "{bad}"); } assert!(replace(MANIFEST, "nope").is_err()); From 9f7d1c426f5bf1f193b8120ab70744b0175a2f5a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:44:43 +0100 Subject: [PATCH 45/76] fix: round engineering notation after forming the mantissa (#2148) Keep chart labels such as 999.94 in ##0.0E+00 at 999.9E+00 until the full mantissa actually rounds past its available digits. Add regression coverage for widths, signs, small values, carries and decimal localization. --- crates/model/src/numfmt.rs | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/model/src/numfmt.rs b/crates/model/src/numfmt.rs index b5db9667c..7a7b86665 100644 --- a/crates/model/src/numfmt.rs +++ b/crates/model/src/numfmt.rs @@ -234,16 +234,18 @@ fn sci(toks: &[Tok], v: f64, sep: char, dec: char) -> Option { m *= 10.0; exp -= 1; } - // Rounding the mantissa to its digits can reach 10 (9.999 as `0.00`). - if format!("{m:.mant_frac$}").starts_with("10") { - m /= 10.0; - exp += 1; - } } let step = mant.iter().take_while(|t| **t != Tok::Dot).filter(|t| matches!(t, Tok::Digit(_))).count().max(1) as i32; let shift = exp.rem_euclid(step); exp -= shift; m *= 10f64.powi(shift); + // Round after forming the engineering mantissa: 999.94 as `##0.0` stays 999.9. + // Carry only when rounding exceeds all of the format's integer placeholders. + let carry = 10f64.powi(step); + if format!("{m:.mant_frac$}").parse::().is_ok_and(|rounded| rounded >= carry) { + m /= carry; + exp += step; + } let mantissa = fixed(mant, mfirst, mlast, m, sep, dec); let sign = if exp < 0 { "-" @@ -404,6 +406,21 @@ mod tests { assert_eq!(format("##0.0E+0", 999.96, None), "1.0E+3"); } + #[test] + fn engineering_formats_round_the_full_mantissa() { + for (code, value, expected) in [ + ("##0.0E+00", 999.94, "999.9E+00"), + ("##0.0E+00", 0.99994, "999.9E-03"), + ("##0.0E+00", -999.94, "-999.9E+00"), + ("#0.0E+00", 99.94, "99.9E+00"), + ("##0.0E+00", 999.96, "1.0E+03"), + ("#0.0E+00", 99.96, "1.0E+02"), + ] { + assert_eq!(format(code, value, None), expected, "{code}, {value}"); + } + assert_eq!(format("##0.0E+00", 999.94, Some("de-DE")), "999,9E+00"); + } + #[test] fn never_panics() { for code in ["", ";", ";;;", "\"", "[", "\\", "0.", ".", "#,", "%", "_", "*", "@", "0E+00", "[$", "\"unterminated"] { From 1ff3b87f5a9ac604c313791821e9bf7e08e2aa1d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:12:23 +0100 Subject: [PATCH 46/76] fix: honor Arabic Letter Mark in paragraph direction detection (#2149) Recognize U+061C alongside RLM before the alphabetic-character check. Extend directional-mark coverage to preserve first-strong precedence. --- crates/model/src/bidi.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/model/src/bidi.rs b/crates/model/src/bidi.rs index 0b113522a..1ec52dc76 100644 --- a/crates/model/src/bidi.rs +++ b/crates/model/src/bidi.rs @@ -10,8 +10,8 @@ /// Cyrillic, CJK…) give `false`. Neutral, weak, and whitespace characters are skipped. pub fn first_strong_is_rtl(text: &str) -> bool { for c in text.chars() { - if c == '\u{200F}' { - // Right-to-Left Mark (RLM) + if c == '\u{200F}' || c == '\u{061C}' { + // RLM and ALM are strong RTL controls, although neither is alphabetic. return true; } if c == '\u{200E}' { @@ -76,6 +76,10 @@ mod tests { #[test] fn honours_directional_marks() { assert!(first_strong_is_rtl("\u{200F}Hello")); + assert!(first_strong_is_rtl("\u{061C}Hello")); + assert!(first_strong_is_rtl("\u{061C}")); + assert!(!first_strong_is_rtl("Hello\u{061C}")); + assert!(!first_strong_is_rtl("\u{200E}\u{061C}")); assert!(!first_strong_is_rtl("\u{200E}مرحبا")); } } From 3bad02d1f1b05fc8494563fcf7444331a98f8ebb Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:51:32 +0100 Subject: [PATCH 47/76] fix: skip escaped symbols in RTF Unicode fallback (#2150) Count an escaped RTF control symbol as one Unicode fallback character and keep parser positions at UTF-8 boundaries. Extend the parser regressions for escaped fallback sequences. --- crates/format/src/rtf.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/format/src/rtf.rs b/crates/format/src/rtf.rs index 4e7e29583..5eac5ade9 100644 --- a/crates/format/src/rtf.rs +++ b/crates/format/src/rtf.rs @@ -276,6 +276,9 @@ impl Outline<'_> { while k > 0 && self.i < self.b.len() { if self.b[self.i] == b'\\' && self.b.get(self.i + 1) == Some(&b'\'') { self.i = advance(self.rtf, self.i, 4); + } else if self.b[self.i] == b'\\' && self.b.get(self.i + 1).is_some_and(|b| !b.is_ascii_alphabetic()) { + // An escaped control symbol counts as one Unicode fallback character. + self.i = advance(self.rtf, self.i + 1, 1); } else if matches!(self.b[self.i], b'{' | b'}' | b'\\') { break; } else { @@ -422,6 +425,23 @@ mod tests { assert_eq!(rtf_to_outline(r"{\rtf1 x\u-70000?y\par}"), "x\u{ee90}y\n"); } + #[test] + fn unicode_fallback_control_symbols_are_skipped() { + for (rtf, expected) in [ + (r"{\rtf1\uc1 \u92\\X\par}", "\\X\n"), + (r"{\rtf1\uc1 \u123\{X\par}", "{X\n"), + (r"{\rtf1\uc1 \u125\}X\par}", "}X\n"), + (r"{\rtf1\uc2 \u233\{\}X\par}", "éX\n"), + (r"{\rtf1\uc0 \u92\\X\par}", "\\\\X\n"), + (r"{\rtf1 \\ \{ \}X\par}", "\\ { }X\n"), + (r"{\rtf1\uc1 \u233{X}\par}", "éX\n"), + (r"{\rtf1\uc1 \u233\éX\par}", "éX\n"), + (r"{\rtf1\uc1 \u233\", "é\n"), + ] { + assert_eq!(rtf_to_outline(rtf), expected, "{rtf:?}"); + } + } + #[test] fn multibyte_control_symbol_keeps_character_and_following_text() { assert_eq!(rtf_to_outline("{\\rtf1 A\\éB\\par}"), "AéB\n"); From b0c532d2d1d68dbbcbde0efed192e8f6d272c193 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:08:12 +0100 Subject: [PATCH 48/76] fix: lowercase Greek sigma across formatting runs (#2151) Use whole-text lowercase context while preserving the output pieces for each formatting run, including Unicode expansion. --- crates/model/src/edit.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs index 0b02e094c..464ba6e2c 100644 --- a/crates/model/src/edit.rs +++ b/crates/model/src/edit.rs @@ -528,6 +528,12 @@ pub fn change_case(s: &str, mode: &str) -> String { /// `title` and `sentence` carry their word/sentence state across piece boundaries. Each output /// piece is the changed form of the matching input piece, even where a character changes length. pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec { + if mode == "lower" { + let lower = parts.concat().to_lowercase(); + let mut chars = lower.chars(); + // Context changes sigma's form, while each character's expansion length stays the same. + return parts.iter().map(|s| chars.by_ref().take(s.chars().map(|c| c.to_lowercase().count()).sum()).collect()).collect(); + } let mut start = true; // All characters of all pieces, so word-final sigma sees neighbours across piece boundaries. let all: Vec = parts.iter().flat_map(|s| s.chars()).collect(); @@ -536,7 +542,6 @@ pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec { .iter() .map(|s| match mode { "upper" => s.to_uppercase(), - "lower" => s.to_lowercase(), "toggle" => s.chars().map(|c| if c.is_uppercase() { c.to_lowercase().collect::() } else { c.to_uppercase().collect() }).collect(), _ => { // `title` restarts after whitespace, sentence case after sentence punctuation. @@ -593,6 +598,18 @@ mod tests { assert_eq!(change_case_parts(&["ΟΔΟΣ", " ΜΟΥ"], "title"), ["Οδος", " Μου"]); } + #[test] + fn lowercase_keeps_context_and_run_boundaries() { + assert_eq!(change_case_parts(&["ΟΔΟ", "Σ"], "lower"), ["οδο", "ς"]); + assert_eq!(change_case_parts(&["ΟΣ", "Α"], "lower"), ["οσ", "α"]); + assert_eq!(change_case_parts(&["", "ΟΔΟ", "", "Σ", ""], "lower"), ["", "οδο", "", "ς", ""]); + assert_eq!(change_case_parts(&["İΟΔΟ", "Σ"], "lower"), ["i\u{307}οδο", "ς"]); + assert_eq!(change_case_parts(&["Ο", "\u{301}", "Σ"], "lower"), ["ο", "\u{301}", "ς"]); + assert_eq!(change_case_parts(&["ΟΣ", "\u{301}", "Α"], "lower"), ["οσ", "\u{301}", "α"]); + assert_eq!(change_case_parts(&["", "", ""], "lower"), ["", "", ""]); + assert!(change_case_parts(&[], "lower").is_empty()); + } + #[test] fn insert_and_split() { let mut b = body("Hello"); From 1af57126a0a4655aa627b190647c9d209f45bee9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:55:35 +0100 Subject: [PATCH 49/76] fix: reject incomplete Base64 character tails (#2152) * fix: reject incomplete Base64 character tails Reject a final six-bit fragment that cannot form a byte while preserving existing accepted encoding forms. * fix: reject Base64 data after padding Track padding before accumulator updates and cover the reviewed Zg==A case while retaining whitespace and repeated padding. --- crates/engine/src/cmd.rs | 42 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e3a50f689..59160df14 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -628,6 +628,7 @@ pub fn base64_decode(s: &str) -> Option> { 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', @@ -635,9 +636,17 @@ pub fn base64_decode(s: &str) -> Option> { b'0'..=b'9' => c - b'0' + 52, b'+' | b'-' => 62, b'/' | b'_' => 63, - b'=' | b'\n' | b'\r' | b' ' => continue, + 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 { @@ -645,13 +654,42 @@ pub fn base64_decode(s: &str) -> Option> { out.push(((acc >> bits) & 0xff) as u8); } } - Some(out) + // A trailing lone Base64 character cannot encode another byte. + (bits != 6).then_some(out) } #[cfg(test)] mod tests { use super::*; + #[test] + fn base64_rejects_a_single_character_tail() { + for (encoded, decoded) in [ + ("", b"".as_slice()), + ("Zg==", b"f"), + ("Zg", b"f"), + ("Zm8=", b"fo"), + ("Zm8", b"fo"), + (" Zm9v \r\n", b"foo"), + ("data:text/plain;base64,Zm9v", b"foo"), + ("+/8=", &[0xfb, 0xff]), + ("-_8=", &[0xfb, 0xff]), + ] { + assert_eq!(base64_decode(encoded).as_deref(), Some(decoded), "{encoded:?}"); + } + for encoded in ["A", "AAAAA", "Zm9vZ", " Zm9vZ \r\n", "data:text/plain;base64,Z"] { + assert!(base64_decode(encoded).is_none(), "{encoded:?}"); + } + } + + #[test] + fn base64_rejects_data_after_padding() { + assert_eq!(base64_decode("Zg== \r\n=="), Some(b"f".to_vec())); + for encoded in ["Zg==A", "Zg== Zm8=", "Zm8=A", "=Zg", "Zg==\r\nA", "data:text/plain;base64,Zg==A"] { + assert!(base64_decode(encoded).is_none(), "{encoded:?}"); + } + } + #[test] fn the_palette_skips_a_command_that_needs_a_value() { assert!(needs_arguments("{path}")); From 187afbd4e5b65461842f181ff74759f2cd4ecb53 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:01:05 -0500 Subject: [PATCH 50/76] Reuse shared RTF text escaping and Windows-1252 decoding Keep outline parser and formatting policy local. Preserve exact escaping with explicit compatibility policy and exhaustive scalar/byte oracles. Original text writer and preserved oracle by Nikita Rakitin (beb883d0). Co-authored-by: Nikita Rakitin --- Cargo.lock | 15 ++++++ Cargo.toml | 1 + crates/format/Cargo.toml | 1 + crates/format/src/rtf.rs | 111 +++++++++++++++++++++++++++++---------- 4 files changed, 99 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a34345398..fefa3f3c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -853,6 +853,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -909,6 +914,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-rtf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" +dependencies = [ + "craft-codepage", + "encoding_rs", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -1147,6 +1161,7 @@ dependencies = [ name = "deckcraft-format" version = "0.19.0" dependencies = [ + "craft-rtf", "deckcraft-model", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 73c7e84aa..cd04dc1d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # craft-media, craft-audio and craft-video share types and stay on one rev. +craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" } craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] } # H.264, HEVC, VP9 and AV1 decoders. diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 252529eeb..2dc1a545c 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft native file format (.deckcraft: zip of a JSON manifest workspace = true [dependencies] +craft-rtf = { workspace = true } deckcraft-model = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/format/src/rtf.rs b/crates/format/src/rtf.rs index 5eac5ade9..202a80deb 100644 --- a/crates/format/src/rtf.rs +++ b/crates/format/src/rtf.rs @@ -10,24 +10,24 @@ use deckcraft_model::text::{Paragraph, RunKind}; /// RTF-escape `s` (non-ASCII as `\uN?`, UTF-16, signed as RTF wants). fn escape(out: &mut String, s: &str) { - for c in s.chars() { - match c { - '\\' | '{' | '}' => { - out.push('\\'); - out.push(c); - } - '\t' => out.push_str("\\tab "), - '\u{b}' | '\n' => out.push_str("\\line "), - c if c.is_ascii() && !c.is_ascii_control() => out.push(c), - c if c.is_ascii() => {} - c => { - let mut buf = [0u16; 2]; - for u in c.encode_utf16(&mut buf) { - out.push_str(&format!("\\u{}?", *u as i16)); - } - } - } + // Keep outline text literal: the shared writer also supports page/column breaks and + // shorthand controls that this app's deliberately small outline reader does not consume. + // Delegate ordinary spans, including UTF-16 escaping, without allocating a second string. + let mut start = 0; + for (i, c) in s.char_indices() { + let replacement = match c { + '\u{000C}' | '\u{000E}' => "", + '\u{00A0}' => "\\u160?", + '\u{00AD}' => "\\u173?", + '\u{2011}' => "\\u8209?", + '\u{2028}' => "\\u8232?", + _ => continue, + }; + craft_rtf::push_esc(out, &s[start..i]); + out.push_str(replacement); + start = i + c.len_utf8(); } + craft_rtf::push_esc(out, &s[start..]); } fn runs(out: &mut String, p: &Paragraph) { @@ -297,7 +297,7 @@ impl Outline<'_> { && let Some(h) = hex && 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 } -fn cp1252(b: u8) -> char { - const HIGH: [char; 32] = [ - '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', - '˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ', - ]; - match b { - 0x80..=0x9f => HIGH[(b - 0x80) as usize], - _ => b as char, - } -} - #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; + // Frozen pre-cutover implementations are test oracles, not production parsers. + fn legacy_escape(out: &mut String, s: &str) { + for c in s.chars() { + match c { + '\\' | '{' | '}' => { + out.push('\\'); + out.push(c); + } + '\t' => out.push_str("\\tab "), + '\u{b}' | '\n' => out.push_str("\\line "), + c if c.is_ascii() && !c.is_ascii_control() => out.push(c), + c if c.is_ascii() => {} + c => { + let mut buf = [0u16; 2]; + for u in c.encode_utf16(&mut buf) { + out.push_str(&format!("\\u{}?", *u as i16)); + } + } + } + } + } + + fn legacy_cp1252(b: u8) -> char { + const HIGH: [char; 32] = [ + '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž', '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', + '—', '˜', '™', 'š', '›', 'œ', '\u{9d}', 'ž', 'Ÿ', + ]; + match b { + 0x80..=0x9f => HIGH[(b - 0x80) as usize], + _ => b as char, + } + } + + #[test] + fn shared_escape_preserves_every_unicode_scalar() { + for value in 0..=0x10ffff { + let Some(c) = char::from_u32(value) else { continue }; + let mut buf = [0; 4]; + let text = c.encode_utf8(&mut buf); + let mut expected = String::new(); + let mut actual = String::new(); + legacy_escape(&mut expected, text); + escape(&mut actual, text); + assert_eq!(actual, expected, "U+{value:04X}"); + } + } + + #[test] + fn shared_escape_preserves_mixed_spans_and_append() { + let text = "a\t中\u{a0}b\u{ad}c\u{2011}d\u{2028}e\u{c}f\u{e}g\n😀{}\\"; + let mut expected = String::from("prefix:"); + let mut actual = expected.clone(); + legacy_escape(&mut expected, text); + escape(&mut actual, text); + assert_eq!(actual, expected); + } + + #[test] + fn shared_cp1252_preserves_all_bytes() { + for b in 0..=u8::MAX { + assert_eq!(craft_rtf::codepage::cp1252(b), legacy_cp1252(b)); + } + } + /// A sign in a `\'hh` escape is not a hex digit and must be ignored. #[test] fn hex_escape_rejects_sign() { From 6bbb593d82970eda2ed87fc9cf6bd4e154f607fe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:22:23 -0500 Subject: [PATCH 51/76] Use shared Base64 encoding for command payloads --- Cargo.lock | 16 ++++++++++++++++ Cargo.toml | 1 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd.rs | 31 +++++++++++++++++-------------- 4 files changed, 35 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a34345398..6b4a4acd7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -853,6 +853,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -900,6 +905,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -1110,6 +1125,7 @@ name = "deckcraft-engine" version = "0.19.0" dependencies = [ "chrono", + "craft-mime", "deckcraft-anim", "deckcraft-color", "deckcraft-fonts", diff --git a/Cargo.toml b/Cargo.toml index 73c7e84aa..bc6f15c9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # craft-media, craft-audio and craft-video share types and stay on one rev. +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" } craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] } # H.264, HEVC, VP9 and AV1 decoders. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cb1f4c29f..40569d1d6 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft engine: sessions, undo history, selection, the command workspace = true [dependencies] +craft-mime = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } deckcraft-model = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 59160df14..628571edd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -607,20 +607,7 @@ fn param_optional(alt: &str) -> Option { /// Base64 (standard alphabet) for binary payloads in JSON params and results. pub fn base64_encode(data: &[u8]) -> String { - const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk.first().copied().unwrap_or(0), chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)]; - let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; - for (i, shift) in [18, 12, 6, 0].iter().enumerate() { - if i <= chunk.len() { - out.push(A.get(((n >> shift) & 63) as usize).copied().unwrap_or(b'A') as char); - } else { - out.push('='); - } - } - } - out + craft_mime::base64::STANDARD.encode(data) } pub fn base64_decode(s: &str) -> Option> { @@ -662,6 +649,22 @@ pub fn base64_decode(s: &str) -> Option> { mod tests { use super::*; + #[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); + } + let all: Vec = (0..=255).cycle().take(513).collect(); + for len in 0..=all.len() { + let encoded = base64_encode(&all[..len]); + assert_eq!(encoded.len(), len.div_ceil(3) * 4); + assert_eq!(encoded.bytes().rev().take_while(|b| *b == b'=').count(), (3 - len % 3) % 3); + assert_eq!(base64_decode(&encoded).as_deref(), Some(&all[..len])); + } + } + #[test] fn base64_rejects_a_single_character_tail() { for (encoded, decoded) in [ From 988d721d7d5ff102d92f78649d8ff42e5490c325 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:57:20 -0500 Subject: [PATCH 52/76] Reuse shared XML escaping in PPTX writer --- Cargo.lock | 10 ++++++ Cargo.toml | 2 ++ crates/pptx/Cargo.toml | 1 + crates/pptx/src/xml.rs | 72 +++++++++++++++++++----------------------- 4 files changed, 46 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a34345398..118568dd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -986,6 +986,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1219,6 +1228,7 @@ dependencies = [ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ + "craft-xml", "deckcraft-color", "deckcraft-engine", "deckcraft-geom", diff --git a/Cargo.toml b/Cargo.toml index 73c7e84aa..508bac797 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,8 @@ rust-version = "1.95" repository = "https://github.com/storytold/deckcraft" [workspace.dependencies] +# XML writer primitives; parser admission and OOXML policy stay app-local. +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index 0ea79d6b4..fd9a6fc4e 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import workspace = true [dependencies] +craft-xml.workspace = true deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/pptx/src/xml.rs b/crates/pptx/src/xml.rs index b1160a639..640844ad6 100644 --- a/crates/pptx/src/xml.rs +++ b/crates/pptx/src/xml.rs @@ -354,45 +354,8 @@ fn decode_utf16(bytes: &[u8]) -> String { } } -/// Is `c` allowed in XML 1.0 text? -fn xml_char(c: char) -> bool { - matches!(c, '\t' | '\n' | '\r') || (c >= ' ' && c != '\u{FFFE}' && c != '\u{FFFF}') -} - -/// Escape text content (and drop characters XML 1.0 forbids). -pub fn esc(s: &str) -> String { - let mut o = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => o.push_str("&"), - '<' => o.push_str("<"), - '>' => o.push_str(">"), - '\r' => o.push_str(" "), - c if xml_char(c) => o.push(c), - _ => {} - } - } - o -} - -/// Escape an attribute value. -pub fn esc_attr(s: &str) -> String { - let mut o = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => o.push_str("&"), - '<' => o.push_str("<"), - '>' => o.push_str(">"), - '"' => o.push_str("""), - '\n' => o.push_str(" "), - '\r' => o.push_str(" "), - '\t' => o.push_str(" "), - c if xml_char(c) => o.push(c), - _ => {} - } - } - o -} +// Preserve the public writer helpers while sharing the XML 1.0 escaping rules. +pub use craft_xml::{esc, esc_attr}; /// A string builder for XML parts. #[derive(Default)] @@ -542,6 +505,37 @@ mod tests { assert_eq!(esc_attr("\"x\"\n"), ""x" "); } + #[test] + fn shared_escaping_preserves_xml_wire_bytes() { + let text = "&<>\"'\t\n\r\0\u{b}\u{fffe}\u{ffff}é😀 "; + assert_eq!(esc(text), "&<>\"'\t\n é😀&#13;"); + assert_eq!(esc_attr(text), "&<>"' é😀&#13;"); + assert_eq!(esc(""), ""); + assert_eq!(esc_attr(""), ""); + for code in 0..32 { + let c = char::from_u32(code).unwrap(); + let text = c.to_string(); + match c { + '\t' => { + assert_eq!(esc(&text), "\t"); + assert_eq!(esc_attr(&text), " "); + } + '\n' => { + assert_eq!(esc(&text), "\n"); + assert_eq!(esc_attr(&text), " "); + } + '\r' => { + assert_eq!(esc(&text), " "); + assert_eq!(esc_attr(&text), " "); + } + _ => { + assert_eq!(esc(&text), ""); + assert_eq!(esc_attr(&text), ""); + } + } + } + } + #[test] fn roundtrip_serialize() { let d = parse(b"x & y").unwrap(); From 455a3fdc3511be4219f5c2280441c72ced597d93 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:14:46 -0500 Subject: [PATCH 53/76] Reuse shared OPC part-name primitives --- Cargo.lock | 31 +++++++++++++++++++++ Cargo.toml | 2 ++ crates/pptx/Cargo.toml | 1 + crates/pptx/src/opc.rs | 62 ++++++++++++++++-------------------------- 4 files changed, 58 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a34345398..ca18f0e8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -900,6 +900,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-opc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +dependencies = [ + "craft-xml", + "craft-zip", + "log", + "thiserror 2.0.21", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -986,6 +997,25 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.0", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1219,6 +1249,7 @@ dependencies = [ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ + "craft-opc", "deckcraft-color", "deckcraft-engine", "deckcraft-geom", diff --git a/Cargo.toml b/Cargo.toml index 73c7e84aa..b77174c7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,8 @@ rust-version = "1.95" repository = "https://github.com/storytold/deckcraft" [workspace.dependencies] +# OPC part-name primitives; relationship admission stays app-local. +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index 0ea79d6b4..d914794a8 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft PPTX: Office Open XML (PresentationML/DrawingML) import workspace = true [dependencies] +craft-opc.workspace = true deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/pptx/src/opc.rs b/crates/pptx/src/opc.rs index 807443b91..f8e582438 100644 --- a/crates/pptx/src/opc.rs +++ b/crates/pptx/src/opc.rs @@ -255,46 +255,11 @@ pub fn sidecar_part(name: &str) -> bool { } pub fn dir_of(part: &str) -> String { - let p = part.trim_start_matches('/'); - match p.rfind('/') { - Some(i) => p.get(..i).unwrap_or("").to_string(), - None => String::new(), - } + craft_opc::dir_of(part).to_owned() } -pub fn file_of(part: &str) -> &str { - part.rsplit('/').next().unwrap_or(part) -} - -pub fn rels_path(part: &str) -> String { - let p = part.trim_start_matches('/'); - let dir = dir_of(p); - let file = file_of(p); - if dir.is_empty() { format!("_rels/{file}.rels") } else { format!("{dir}/_rels/{file}.rels") } -} - -fn percent_decode(s: &str) -> String { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while i < b.len() { - let c = b.get(i).copied().unwrap_or(0); - if c == b'%' - && let Some(h) = b - .get(i + 1..i + 3) - .filter(|h| h.iter().all(u8::is_ascii_hexdigit)) - .and_then(|h| std::str::from_utf8(h).ok()) - .and_then(|h| u8::from_str_radix(h, 16).ok()) - { - out.push(h); - i += 3; - continue; - } - out.push(c); - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} +use craft_opc::percent_decode; +pub use craft_opc::{file_of, rels_path}; /// Resolve a relative target against a base directory into a part name. pub fn resolve(base: &str, target: &str) -> String { @@ -469,6 +434,27 @@ impl PackageOut { mod tests { use super::*; + #[test] + fn shared_names_preserve_relationship_wire_policy() { + for (part, dir, file, rels) in [ + ("", "", "", "_rels/.rels"), + ("/", "", "", "_rels/.rels"), + ("///ppt/slides/slide1.xml", "ppt/slides", "slide1.xml", "ppt/slides/_rels/slide1.xml.rels"), + ("ppt/", "ppt", "", "ppt/_rels/.rels"), + ("é/😀.xml", "é", "😀.xml", "é/_rels/😀.xml.rels"), + ] { + assert_eq!(dir_of(part), dir); + assert_eq!(file_of(part), file); + assert_eq!(rels_path(part), rels); + } + assert_eq!(percent_decode("a+b%20c%2Fd%23e"), "a+b c/d#e"); + assert_eq!(percent_decode("% %1 %zz %+1 %ff"), "% %1 %zz %+1 �"); + // Keep Deck's policy: strip the raw fragment first, then decode percent escapes once. + assert_eq!(resolve("ppt/slides", "../media/a%23b.png#ignored"), "ppt/media/a#b.png"); + assert_eq!(resolve("ppt/slides", "%252e%252e/a"), "ppt/slides/%2e%2e/a"); + assert_eq!(resolve("ppt/slides", "%2e%2e/%2e%2e/%2e%2e/a"), "a"); + } + #[test] fn resolve_keeps_encoded_hash_and_strips_fragment() { assert_eq!(resolve("ppt/slides", "../media/a%23b.png"), "ppt/media/a#b.png"); From d842a0cc2ae94dfabeb549110e8fd63aa769c3bf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:54:50 -0500 Subject: [PATCH 54/76] Delegate Base64 decoding while preserving command input guards --- Cargo.lock | 4 +- Cargo.toml | 2 +- crates/engine/src/cmd.rs | 91 ++++++++++++++++++++++++++++------------ 3 files changed, 68 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6b4a4acd7..17a5f4b1a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -856,7 +856,7 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" +source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db" [[package]] name = "craft-fonts-build" @@ -908,7 +908,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" +source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db" dependencies = [ "chrono", "craft-codepage", diff --git a/Cargo.toml b/Cargo.toml index bc6f15c9c..548ad1165 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,7 @@ vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # craft-media, craft-audio and craft-video share types and stay on one rev. -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db", version = "=0.1.0" } craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] } # H.264, HEVC, VP9 and AV1 decoders. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 628571edd..b97d42b4c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -612,43 +612,82 @@ pub fn base64_encode(data: &[u8]) -> String { pub fn base64_decode(s: &str) -> Option> { 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; + // Preserve the command transport's admission rules before the shared legacy decoder: + // padding ends the payload and one trailing symbol cannot encode a byte. + let (mut symbols_mod_four, mut padded) = (0u8, false); for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - b'=' => { - padded = true; - continue; + match c { + b'=' => padded = true, + b'\n' | b'\r' | b' ' => {} + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'-' | b'/' | b'_' if !padded => { + symbols_mod_four = (symbols_mod_four + 1) % 4; } - 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) + if symbols_mod_four == 1 { + return None; + } + craft_mime::base64_compat::decode(s).ok() } #[cfg(test)] mod tests { use super::*; + // Frozen pre-cutover implementation (Brandon Thomas, with Mex's padding/tail fixes). + fn previous_base64_decode(s: &str) -> Option> { + 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 From bb2c2254ee60761b2b4dab2053fe33d7190b6804 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:27:58 +0100 Subject: [PATCH 55/76] Native format: take the .deckcraft package layer from craft-deckcraft-format (#2170) * Native format: golden package bytes and load results before the move to craft-libs A deck that reaches every kind of member (stored and deflated media, linked media without bytes, stored and deflated chart parts, a NaN) is saved with a fixed generator. Its bytes, the presentation and media loaded from them, and the damage report for a copy missing two members are golden files written by the current code. `save_as` names the generator so the bytes don't change with the version. * Native format: the .deckcraft package layer comes from craft-deckcraft-format The mimetype and legacy type, sniffing, the presentation.json envelope, the NaN-safe writer (finite.rs, deleted), the null-number manifest reader, member names, the stored-or-deflated choice, bounded and budget-charged member reads and the format limits now come from craft-deckcraft-format (storytold/craft-libs#1748), pinned at its PR tip. The presentation mapping stays here: which media and chart parts become members, the load loop over them, repair and sanitising, and outline/RTF. The golden tests from the previous commit pass unchanged: the saved bytes, the loaded presentation and the damage report are the same. The crate no longer depends on serde, serde_json or thiserror; zip is a test dependency. Part of storytold/craft-libs#778. * ATTRIBUTION: the native format golden deck * Native format: pin craft-deckcraft-format to the craft-libs merge commit 254e9a40 (storytold/craft-libs#1748) --- ATTRIBUTION.md | 1 + Cargo.lock | 41 ++- Cargo.toml | 2 + crates/format/Cargo.toml | 5 +- crates/format/src/chart_parts.rs | 18 +- crates/format/src/finite.rs | 185 ------------ crates/format/src/golden_tests.rs | 118 ++++++++ crates/format/src/lib.rs | 267 +++--------------- crates/format/src/tests.rs | 14 +- crates/format/tests/golden/.gitattributes | 2 + .../format/tests/golden/damaged.loaded.json | 1 + crates/format/tests/golden/deck.deckcraft | Bin 0 -> 6334 bytes crates/format/tests/golden/deck.loaded.json | 1 + 13 files changed, 211 insertions(+), 444 deletions(-) delete mode 100644 crates/format/src/finite.rs create mode 100644 crates/format/src/golden_tests.rs create mode 100644 crates/format/tests/golden/.gitattributes create mode 100644 crates/format/tests/golden/damaged.loaded.json create mode 100644 crates/format/tests/golden/deck.deckcraft create mode 100644 crates/format/tests/golden/deck.loaded.json diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8382a760b..8e6b3b651 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -35,6 +35,7 @@ artwork. The ribbon and menu icons stay original drawings. | `crates/fonts/tests/fixtures/legacy-semibold.ttf` | DeckCraft contributors | a one-glyph Semibold face named like Segoe UI Semibold (its Windows family differs from the typographic one), built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests | | `crates/fonts/tests/fixtures/legacy-regular.ttf` | DeckCraft contributors | the same family's one-glyph Regular face, built by `make_legacy_font.py` (fontTools as the builder only) | CC0-1.0 | Font lookup by Windows family name tests | | `crates/render/tests/fixtures/make_colr_font.py` | DeckCraft contributors | this repository | MIT OR Apache-2.0 | Regenerates the COLR test font | +| `crates/format/tests/golden/deck.deckcraft` | DeckCraft contributors | a synthetic deck (placeholder bytes, no images or text from elsewhere) written by `crates/format/src/golden_tests.rs` with `DECKCRAFT_BLESS_GOLDEN=1` | CC0-1.0 | Native format golden bytes | | Lucide icon paths in `crates/engine/src/icon_data.rs` (Insert › Icons) | Lucide Contributors; Feather icons by Cole Bemis | https://github.com/lucide-icons/lucide/tree/440a1e1dfb1e712505308da46bead3c28b1f1398/icons (release 1.56.0, 2026-10-13) | ISC; MIT for the Feather-derived icons named in that commit's LICENSE | Stroke icons inserted as shapes | ## Bundled through dependencies diff --git a/Cargo.lock b/Cargo.lock index 2aef7c588..d36fab678 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,7 +222,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.52.0", "wl-clipboard-rs", "x11rb", ] @@ -858,6 +858,18 @@ name = "craft-codepage" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=63196e66f3033a6623eb629af95a104d26986725#63196e66f3033a6623eb629af95a104d26986725" +[[package]] +name = "craft-deckcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", + "zip 9.1.0", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1009,6 +1021,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=254e9a409b410dc93c0e06ff66cd1e767893ac32#254e9a409b410dc93c0e06ff66cd1e767893ac32" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.0", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1170,11 +1192,10 @@ dependencies = [ name = "deckcraft-format" version = "0.19.0" dependencies = [ + "craft-deckcraft-format", "craft-rtf", "deckcraft-model", - "serde", "serde_json", - "thiserror 2.0.21", "zip 3.0.0", ] @@ -1712,7 +1733,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3074,7 +3095,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -4102,7 +4123,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4159,7 +4180,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4830,10 +4851,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5784,7 +5805,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fd27300df..adc2d9414 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,8 @@ vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # craft-media, craft-audio and craft-video share types and stay on one rev. +# The .deckcraft package layer (identity, manifest, member names, bounded reads); crates/format maps the presentation onto it. +craft-deckcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "254e9a409b410dc93c0e06ff66cd1e767893ac32", version = "=0.1.0" } craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0" } craft-media = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "63196e66f3033a6623eb629af95a104d26986725", version = "=0.1.0", default-features = false, features = ["opus-decode"] } diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 2dc1a545c..d111e7778 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -9,9 +9,10 @@ description = "DeckCraft native file format (.deckcraft: zip of a JSON manifest workspace = true [dependencies] +craft-deckcraft-format = { workspace = true } craft-rtf = { workspace = true } deckcraft-model = { workspace = true } -serde = { workspace = true } + +[dev-dependencies] serde_json = { workspace = true } zip = { workspace = true } -thiserror = { workspace = true } diff --git a/crates/format/src/chart_parts.rs b/crates/format/src/chart_parts.rs index f57c08679..dcc6c81b9 100644 --- a/crates/format/src/chart_parts.rs +++ b/crates/format/src/chart_parts.rs @@ -1,14 +1,14 @@ //! Keep opaque chart payloads out of the JSON manifest and within the media load budget. use std::collections::HashSet; -use std::io::Cursor; use std::sync::Arc; +use craft_deckcraft_format::{MAX_ENTRY, Package, chart_part_entry, is_chart_part_entry}; + use deckcraft_model::chart::ChartPart; use deckcraft_model::{Master, Presentation, Shape, ShapeKind}; -use crate::{FormatError, MAX_ENTRY, Result, read_entry_max}; +use crate::{FormatError, Result}; -const PREFIX: &str = "chart-parts/"; type Payload = (String, String, Vec); pub(super) fn separate(p: &mut Presentation) -> Result> { @@ -16,7 +16,7 @@ pub(super) fn separate(p: &mut Presentation) -> Result> { visit_parts(p, |part| { // The native namespace is independent of the original OPC names, which may repeat // when charts from several decks are combined. No user-supplied path is extracted. - let entry = format!("{PREFIX}{}", payloads.len()); + let entry = chart_part_entry(payloads.len()); part.native_entry = Some(entry.clone()); payloads.push((entry, part.content_type.clone(), std::mem::take(&mut part.bytes))); Ok(()) @@ -26,7 +26,7 @@ pub(super) fn separate(p: &mut Presentation) -> Result> { pub(super) fn restore( p: &mut Presentation, - z: &mut zip::ZipArchive>, + z: &mut Package<'_>, left: &mut u64, mut items: usize, max_items: usize, @@ -40,21 +40,21 @@ pub(super) fn restore( items += 1; if let Some(entry) = part.native_entry.take() { // Accept only names produced by separate(), and inflate each member once. - let canonical = entry.strip_prefix(PREFIX).and_then(|s| s.parse::().ok()).is_some_and(|n| entry == format!("{PREFIX}{n}")); + let canonical = is_chart_part_entry(&entry); if !canonical || !seen.insert(entry.clone()) || !part.bytes.is_empty() { return Err(FormatError::Damaged("invalid or ambiguous chart part reference".into())); } - if z.index_for_name(&entry).is_none() { + if !z.contains(&entry) { // Missing members consume no inflation work and can be reported for recovery. damaged.push(format!("{entry}: missing chart part")); return Ok(()); } - if z.by_name(&entry).is_ok_and(|f| f.size() > *left) { + if z.declared_size(&entry).is_some_and(|size| size > *left) { return Err(FormatError::Damaged("embedded media and chart parts are larger than DeckCraft can open".into())); } // A CRC/decode error may already have inflated bytes. Stop on that first error // rather than letting later corrupt members reuse the unchanged byte budget. - let bytes = read_entry_max(z, &entry, (*left).min(MAX_ENTRY))?; + let bytes = z.read_max(&entry, (*left).min(MAX_ENTRY))?; *left -= bytes.len() as u64; part.bytes = bytes; } else { diff --git a/crates/format/src/finite.rs b/crates/format/src/finite.rs deleted file mode 100644 index 834108a33..000000000 --- a/crates/format/src/finite.rs +++ /dev/null @@ -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 Serialize for Finite<'_, T> { - fn serialize(&self, s: S) -> Result { - self.0.serialize(Wrap(s)) - } -} - -struct Wrap(S); - -macro_rules! pass { - ($($m:ident($t:ty)),* $(,)?) => { - $(fn $m(self, v: $t) -> Result { self.0.$m(v) })* - }; -} - -impl Serializer for Wrap { - type Ok = S::Ok; - type Error = S::Error; - type SerializeSeq = Wrap; - type SerializeTuple = Wrap; - type SerializeTupleStruct = Wrap; - type SerializeTupleVariant = Wrap; - type SerializeMap = Wrap; - type SerializeStruct = Wrap; - type SerializeStructVariant = Wrap; - - 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 { - self.0.serialize_f32(if v.is_finite() { v } else { 0.0 }) - } - fn serialize_f64(self, v: f64) -> Result { - self.0.serialize_f64(if v.is_finite() { v } else { 0.0 }) - } - fn serialize_none(self) -> Result { - self.0.serialize_none() - } - fn serialize_some(self, v: &T) -> Result { - self.0.serialize_some(&Finite(v)) - } - fn serialize_unit(self) -> Result { - self.0.serialize_unit() - } - fn serialize_unit_struct(self, name: &'static str) -> Result { - self.0.serialize_unit_struct(name) - } - fn serialize_unit_variant(self, name: &'static str, i: u32, variant: &'static str) -> Result { - self.0.serialize_unit_variant(name, i, variant) - } - fn serialize_newtype_struct(self, name: &'static str, v: &T) -> Result { - self.0.serialize_newtype_struct(name, &Finite(v)) - } - fn serialize_newtype_variant(self, name: &'static str, i: u32, variant: &'static str, v: &T) -> Result { - self.0.serialize_newtype_variant(name, i, variant, &Finite(v)) - } - fn serialize_seq(self, len: Option) -> Result { - self.0.serialize_seq(len).map(Wrap) - } - fn serialize_tuple(self, len: usize) -> Result { - self.0.serialize_tuple(len).map(Wrap) - } - fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result { - 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.0.serialize_tuple_variant(name, i, variant, len).map(Wrap) - } - fn serialize_map(self, len: Option) -> Result { - self.0.serialize_map(len).map(Wrap) - } - fn serialize_struct(self, name: &'static str, len: usize) -> Result { - 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.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 ser::$tr for Wrap { - type Ok = S::Ok; - type Error = S::Error; - fn $m(&mut self, v: &T) -> Result<(), S::Error> { - self.0.$m(&Finite(v)) - } - fn end(self) -> Result { - self.0.end() - } - } - }; -} -compound!(SerializeSeq, serialize_element); -compound!(SerializeTuple, serialize_element); -compound!(SerializeTupleStruct, serialize_field); -compound!(SerializeTupleVariant, serialize_field); - -impl ser::SerializeMap for Wrap { - type Ok = S::Ok; - type Error = S::Error; - fn serialize_key(&mut self, k: &T) -> Result<(), S::Error> { - self.0.serialize_key(&Finite(k)) - } - fn serialize_value(&mut self, v: &T) -> Result<(), S::Error> { - self.0.serialize_value(&Finite(v)) - } - fn end(self) -> Result { - self.0.end() - } -} - -macro_rules! fields { - ($tr:ident) => { - impl ser::$tr for Wrap { - type Ok = S::Ok; - type Error = S::Error; - fn serialize_field(&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 { - 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, - c: Vec<(f32, f64)>, - d: Option, - e: std::collections::BTreeMap, - } - 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}}"#); - } -} diff --git a/crates/format/src/golden_tests.rs b/crates/format/src/golden_tests.rs new file mode 100644 index 000000000..8cc241b12 --- /dev/null +++ b/crates/format/src/golden_tests.rs @@ -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"".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"".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::(); + 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()); +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 4125c2905..52cbe3ebd 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -5,158 +5,63 @@ #![forbid(unsafe_code)] mod chart_parts; -mod finite; pub mod rtf; #[cfg(test)] mod chart_parts_tests; +#[cfg(test)] +mod golden_tests; -use std::io::{Cursor, Read, Write}; use std::sync::Arc; use deckcraft_model::text::{Paragraph, TextBody}; use deckcraft_model::{LayoutType, Presentation, ShapeKind, defaults}; -pub const MIMETYPE: &str = "application/vnd.storyteller.deckcraft+zip"; -/// Files written before the SlideCraft → DeckCraft rename (`.slidecraft`) are still read. -pub const LEGACY_MIMETYPE: &str = concat!("application/vnd.storyteller.", "slide", "craft+zip"); -pub const EXTENSION: &str = "deckcraft"; -/// Format version written into the manifest. -pub const VERSION: u32 = 1; -/// Largest entry we will inflate (guards against zip bombs). -const MAX_ENTRY: u64 = 2 << 30; -/// All embedded media and chart sidecars together, inflated (#393). -const MAX_TOTAL_MEDIA: u64 = 4 << 30; -/// Media items and chart sidecar parts one file may list. -const MAX_MEDIA_ITEMS: usize = 100_000; -/// Largest `presentation.json` we will inflate. The manifest holds no media bytes, so it is far -/// smaller than a media entry may be; inflating and parsing one is what dominates memory. -const MAX_MANIFEST: u64 = 256 << 20; - -/// What one load may inflate. -#[derive(Clone, Copy)] -struct Budget { - total: u64, - items: usize, - manifest: u64, -} - -#[cfg(test)] -impl Budget { - /// A media budget with the default manifest limit. - fn media(total: u64, items: usize) -> Self { - Budget { total, items, manifest: MAX_MANIFEST } - } -} - -#[derive(Debug, thiserror::Error)] -pub enum FormatError { - #[error("not a DeckCraft file: {0}")] - NotOurs(String), - #[error("damaged file: {0}")] - Damaged(String), - #[error("write failed: {0}")] - Write(String), -} - -pub type Result = std::result::Result; - -#[derive(serde::Serialize, serde::Deserialize)] -struct Manifest { - format: String, - version: u32, - generator: String, - presentation: Presentation, -} +// The package itself (identity, manifest, member names, bounded reads) is shared. +pub use craft_deckcraft_format::{Budget, EXTENSION, FormatError, LEGACY_MIMETYPE, MIMETYPE, Result, VERSION, sniff}; +use craft_deckcraft_format::{Member, Package, media_entry}; /// Serialize a presentation. pub fn save(p: &Presentation) -> Result> { - let mut buf = Cursor::new(Vec::new()); - { - let mut z = zip::ZipWriter::new(&mut buf); - let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); - let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); - let w = |e: zip::result::ZipError| FormatError::Write(e.to_string()); - z.start_file("mimetype", stored).map_err(w)?; - z.write_all(MIMETYPE.as_bytes()).map_err(|e| FormatError::Write(e.to_string()))?; - let mut presentation = p.clone(); - let parts = chart_parts::separate(&mut presentation)?; - let m = - Manifest { format: "deckcraft".into(), version: VERSION, generator: format!("DeckCraft {}", env!("CARGO_PKG_VERSION")), presentation }; - let json = serde_json::to_vec(&finite::Finite(&m)).map_err(|e| FormatError::Write(e.to_string()))?; - z.start_file("presentation.json", deflate).map_err(w)?; - z.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?; - for item in &p.media { - if item.link.is_some() && item.data.is_empty() { - continue; - } - // Already-compressed media is stored, not deflated again. - let opts = if is_compressed(&item.content_type) { stored } else { deflate }; - z.start_file(format!("media/{}", item.id.0), opts).map_err(w)?; - z.write_all(&item.data).map_err(|e| FormatError::Write(e.to_string()))?; - } - for (name, content_type, bytes) in parts { - let opts = if is_compressed(&content_type) { stored } else { deflate }; - z.start_file(name, opts).map_err(w)?; - z.write_all(&bytes).map_err(|e| FormatError::Write(e.to_string()))?; - } - z.finish().map_err(w)?; - } - Ok(buf.into_inner()) + save_as(p, &format!("DeckCraft {}", env!("CARGO_PKG_VERSION"))) } -fn is_compressed(ct: &str) -> bool { - ct.starts_with("image/jpeg") - || ct.starts_with("image/png") - || ct.starts_with("video/") - || ct.starts_with("audio/mpeg") - || ct.starts_with("audio/mp4") - || ct.contains("zip") -} - -/// Does this look like a `.deckcraft` file? -pub fn sniff(bytes: &[u8]) -> bool { - bytes.starts_with(b"PK") && [MIMETYPE, LEGACY_MIMETYPE].iter().any(|m| bytes.windows(m.len()).take(200).any(|w| w == m.as_bytes())) +/// [`save`] naming `generator` in the manifest. +fn save_as(p: &Presentation, generator: &str) -> Result> { + let mut presentation = p.clone(); + let parts = chart_parts::separate(&mut presentation)?; + // Linked media saved without its bytes has no member. + let media: Vec<(String, &deckcraft_model::MediaItem)> = + p.media.iter().filter(|item| !(item.link.is_some() && item.data.is_empty())).map(|item| (media_entry(item.id.0), item)).collect(); + let members: Vec> = media + .iter() + .map(|(name, item)| Member { name, content_type: &item.content_type, bytes: &item.data }) + .chain(parts.iter().map(|(name, content_type, bytes)| Member { name, content_type, bytes })) + .collect(); + craft_deckcraft_format::write(&presentation, generator, &members) } +/// A member of a package a test built or rewrote with `zip`, within `max` bytes. #[cfg(test)] -fn read_entry(z: &mut zip::ZipArchive>, name: &str) -> Result> { - read_entry_max(z, name, MAX_ENTRY) -} - -/// Read one member, refusing it before inflating if it declares more than `max` bytes, and -/// stopping at `max` if it inflates further than it declared. -fn read_entry_max(z: &mut zip::ZipArchive>, name: &str, max: u64) -> Result> { - 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>, name: &str, left: &mut u64) -> Result> { - 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>, name: &str, max: u64, spent: &mut u64) -> Result> { +fn read_entry_max(z: &mut zip::ZipArchive>, name: &str, max: u64) -> Result> { + use std::io::Read; let f = z.by_name(name).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?; if f.size() > max { return Err(FormatError::Damaged(format!("{name} is too large"))); } - let mut out = Vec::with_capacity(f.size().min(64 << 20) as usize); - let mut f = f.take(max.saturating_add(1)); - let read = f.read_to_end(&mut out); - *spent = spent.saturating_add(out.len() as u64); - read.map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?; + let mut out = vec![]; + f.take(max.saturating_add(1)).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?; if out.len() as u64 > max { return Err(FormatError::Damaged(format!("{name} is too large"))); } Ok(out) } +#[cfg(test)] +fn read_entry(z: &mut zip::ZipArchive>, name: &str) -> Result> { + read_entry_max(z, name, craft_deckcraft_format::MAX_ENTRY) +} + /// Read a presentation. Missing media/chart parts are left empty; use [`load_checked`] to /// learn which. A damaged chart member refuses the file before further chart inflation. pub fn load(bytes: &[u8]) -> Result { @@ -167,19 +72,11 @@ pub fn load(bytes: &[u8]) -> Result { /// A chart member that is present but fails decoding, CRC or its entry limit refuses the file. /// Linked media saved without its bytes isn't damage. pub fn load_checked(bytes: &[u8]) -> Result<(Presentation, Vec)> { - 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)> { - let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| FormatError::NotOurs(e.to_string()))?; - if z.index_for_name("presentation.json").is_none() { - return Err(FormatError::NotOurs("no presentation.json".into())); - } - let json = read_entry_max(&mut z, "presentation.json", budget.manifest)?; - let m = parse_manifest(&json)?; - if m.format != "deckcraft" { - return Err(FormatError::NotOurs(m.format)); - } + let (m, mut z) = Package::open_manifest::(bytes, budget.manifest)?; let mut p = m.presentation; let mut damaged = vec![]; let items = p.media.len(); @@ -192,13 +89,13 @@ fn load_within(bytes: &[u8], budget: Budget) -> Result<(Presentation, Vec left) { + let name = media_entry(item.id.0); + let linked_only = item.link.is_some() && !z.contains(&name); + if z.declared_size(&name).is_some_and(|size| size > left) { return Err(FormatError::Damaged("embedded media is larger than DeckCraft can open".into())); } // A failed read is charged for what it inflated, so later members can't reuse that budget. - match read_entry_charged(&mut z, &name, &mut left) { + match z.read_charged(&name, &mut left) { Ok(data) => item.data = Arc::new(data), Err(_) if linked_only => {} Err(e) => damaged.push(e.to_string()), @@ -346,100 +243,6 @@ fn add_outline_slides(p: &mut Presentation, slides: OutlineSlides) -> usize { made } -/// Most `null`s standing in for numbers that [`parse_manifest`] patches in one file, and the -/// candidates it tries for each. -const MAX_NULL_FIXES: usize = 256; -const MAX_TRIES_PER_FIX: usize = 32; -/// Bytes [`parse_manifest`] may re-parse in all while patching, so a hostile file full of `null`s -/// can't keep it busy: past this the file is reported damaged. -const MAX_REPARSE_BYTES: usize = 256 * 1024 * 1024; - -/// Where a parse failed, comparable: later is progress. -fn failure(src: &[u8]) -> std::result::Result { - serde_json::from_slice::(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 { - // 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 = 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 { - 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 + '_ { - let end = end.min(src.len()); - (0..end.saturating_sub(3)).rev().filter(move |&i| { - src.get(i..i + 4) == Some(b"null") - && src[..i].iter().rev().find(|b| !b.is_ascii_whitespace()).is_some_and(|b| matches!(b, b':' | b'[' | b',')) - && src.get(i + 4).is_none_or(|b| !b.is_ascii_alphanumeric()) - }) -} - /// Largest coordinate or size kept, in points (about 350 m; PowerPoint's own limit is far smaller). const MAX_COORD: f64 = 1.0e6; diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index ccda612f0..8d963c302 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -1,4 +1,6 @@ use super::*; +use craft_deckcraft_format::{Manifest, parse_manifest}; +use std::io::{Cursor, Read, Write}; #[test] fn chart_sidecars_are_optional_for_older_native_files() { @@ -364,7 +366,7 @@ fn reflection_transform_survives_two_native_saves_and_absent_fields_stay_absent( assert_eq!(reopened.slides[0].shapes.last().and_then(|s| s.effects.as_ref()).and_then(|e| e.reflection.as_ref()), Some(&absent)); } -/// Files written before [`finite::Finite`] (plain serde_json: NaN as `null`) open too, +/// Files written before [`craft_deckcraft_format::Finite`] (plain serde_json: NaN as `null`) open too, /// including a `null` inside a tagged enum, where serde reports only the enclosing object. #[test] fn older_files_with_null_numbers_open() { @@ -387,7 +389,7 @@ fn older_files_with_null_numbers_open() { let m = Manifest { format: "deckcraft".into(), version: VERSION, generator: "old".into(), presentation: p }; let json = serde_json::to_vec(&m).unwrap(); assert!(json.windows(4).any(|w| w == b"null")); - let back = parse_manifest(&json).unwrap_or_else(|e| panic!("case {case}: {e}")); + let back = parse_manifest::(&json).unwrap_or_else(|e| panic!("case {case}: {e}")); assert_eq!(back.presentation.slides[0].shapes.len(), m.presentation.slides[0].shapes.len(), "case {case}"); } } @@ -419,14 +421,14 @@ fn a_bare_normautofit_body_round_trips() { #[test] fn other_damage_is_still_reported() { let ok = serde_json::to_vec(&serde_json::json!({"format": "deckcraft", "version": 1, "generator": "t", "presentation": {}})).unwrap(); - assert!(parse_manifest(&ok).is_ok()); + assert!(parse_manifest::(&ok).is_ok()); let bad = br#"{"format": null, "version": 1, "generator": "t", "presentation": {}}"#; - assert!(parse_manifest(bad).is_err()); + assert!(parse_manifest::(bad).is_err()); let truncated = &ok[..ok.len() - 3]; - assert!(parse_manifest(truncated).is_err()); + assert!(parse_manifest::(truncated).is_err()); // A null number on a later line (pretty-printed by another tool) is found too. let pretty = b"{\n \"format\": \"deckcraft\",\n \"version\": 1,\n \"generator\": \"t\",\n \"presentation\": {\"slides\": [{\"shapes\": [{\"xfrm\": {\"x\": null, \"y\": 1, \"w\": 2, \"h\": 3}}]}]}\n}"; - let m = parse_manifest(pretty).unwrap_or_else(|e| panic!("{e}")); + let m = parse_manifest::(pretty).unwrap_or_else(|e| panic!("{e}")); assert_eq!(m.presentation.slides[0].shapes[0].xfrm.unwrap().x, 0.0); } diff --git a/crates/format/tests/golden/.gitattributes b/crates/format/tests/golden/.gitattributes new file mode 100644 index 000000000..c5d2e24da --- /dev/null +++ b/crates/format/tests/golden/.gitattributes @@ -0,0 +1,2 @@ +# Golden files are compared byte for byte: no line-ending conversion on checkout. +* -text diff --git a/crates/format/tests/golden/damaged.loaded.json b/crates/format/tests/golden/damaged.loaded.json new file mode 100644 index 000000000..dbfc76039 --- /dev/null +++ b/crates/format/tests/golden/damaged.loaded.json @@ -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,""]]} diff --git a/crates/format/tests/golden/deck.deckcraft b/crates/format/tests/golden/deck.deckcraft new file mode 100644 index 0000000000000000000000000000000000000000..7e8174095a29b24127051ec1c1d39b58bdfb6f43 GIT binary patch literal 6334 zcmZ`-bzD?yw+5vLq`ReS=piJBh9Oiyy1N@m=@5jWL!^dAx}^kRXeoynB@_gtOH$zu z-*>)y?(yEc*Kh5;*ILiB-goacf6RV#H11>Iq5b<{M$<|20CAy$JI6t}tD~!}Pk@K5 zrH6-$qqU`vqq`fwpPLQP+sEB2z{l3b#nuaGV{7ef?PY1_!xQM}p@V8i_7|BM4MAz~ z^BFm+)fqY(F)HifW$SJ0=JT&UKqqf^w>{GduQl=1P;%^z1#UyupY}^8`Ddq!?N!yE zTV`YNRInAnBuLgGH2E>^Se7gLjd$hU`=sN$t_-F5HZ16=Or@#6I5g7pDAh1HiC9yH zd-;VAhE<2-xP_R|PwGO{R9=b<6Qto%3Q~&`2-yjy>Efzkt=EnB%0zl6!5`uqKxk~Z z4g0N>GGuO(SeXeI*ltHxE#UV>nIqHOsu!K0xNB?i4p0^RB{M;Pq_L3050%Px zZ3Q8!X#q=u)Gb=jeE!rruV#9jj2f|~p5Moi$i(MV8ywM6z?=8VEF0CVvXDY>lBnd3Y!_W#fuXa7WswlBmD<^HT0sDOb|6aDi6Tb1vlGZ;K>t0R1Iq8+-xV`L! zx!?ZQ_Ily_!gqy&P)0hsM_b5D5HIlPi|8z3!68vP)-N3V$ z(d!nebrWM-x7w4!zn5kuYF4Hoy^wPKvigx)YzAU)b$huS(LGj*bj>(-Xp%d?dCT0r zG&zC>y28py37;3DL(3iC=&g_Wjhj)g+oUH^(kRj^yd^c7RjEx*3m6eqVCsE8cMH%N z=4S|Q9?^?r<=yGwaZqb>knvRbpzGiI+UL~GVLHj(Dr; zx6OLwauC!lB4aOu5SNb#+7{iOYt~IWN{Z&)>P1GmjE|?XUZU&RsBUH!t3R8_g{NW* zOh@6TL%#M)Q5?IsiattSK31%AZbz3UzG&x;LZcj(wo!MaAufW#M52_W2%>wAtQ62m zxWv#F3;Gy&F=KOZ=AHa#Y#`;m)IY{uB{>N0ozh1T9o8azf(|p+O>S4T{BFXBE*(w? zPg_r~34`8TMpN~cs~sh6Y~~2$(%=bD46bMw^ z%M6*2qv~Wy{XS-^URt$FGFvG*r!6EA(?hWfdZ^EC`pYh@ z->yroz?Xk`CL5PD-%u+1%_RksVoz`ea456vHGh*>SS%PlBgK zj7>VN`yQ8?0==6T}>=C!vlhG)La*}9zO~ANcnics$1B!k2c|StbW_Q&iL&x*guv{&~nP} zyjx~MG8J30_X}|)qNL%5Zd)5qQVknNYuo(YvloO-2cy*amqDLre=n7ycjZ&RAHzD# zixx(jhD5B1Z(x*niYtB=wQmmGNK7MV@tL4IRm~u!tE-z7_k3o0&j@Y4&OAfLju}oc!#a-&X_wta>&m<{F+|EjkZE?rkaOg>^p{}2QG=PV zCaM_i^z7WPgr&Fs0y(Q(38Fu|i;k_w1hESEdY+A=344|Xk5ybAQfdJ z%mxO%w54`&NPKN5_9kFZYITvk%IQXK2Nd0zaquKbel2FQkEX-MvApoB5BTI&@f%k% z0wMgTYFMV-p%M#UrB0r1JclI4EbY2~q>L~XK}K}9z;RxIpV%A?6Mv(%p%lv+9S zd;B$aa`A6z4ouB_kW3lF|~?t?mQ*i(n*nfwzBe%G$Jv<|Q8hi37rHu3dm z&k!yu_+w=zvalr?yho%6YS2;FWd{Uw`pySrK3}Mjydry2p!vR%Q$wqhn_gn?jD$JB z)qO3hB7HM)Y%h#J}KeC3l{&9xK zq}@D(_Fz#}Ro_vPKD>o5Yi(A*rYg_}`0b!MFF}Azc$EXu^HQwtQ}cH4+ODz7B?fTT zrXwVPOeuCS0G)PPM7Q8a{izi|NpWDi`7OP0ZpCcW>_x=TZnsTyVW?}IiPM{@=i_Tf zK z|8Cy~mKMF^q-WP|pysV^NO(#(U!6wb>9?%RFf>+iS05X0G|SsXkK^T#3snyZ@FWnmV?cjT4~fv! zS{p8f26ev6fZx1;z#<$whMOO#_6p6); z@>!xQiyI8(#NmKlu&r^Jgi(PItzo3uSU}gAG~FXCahj5RJLp4M#TQ)wQStpsWv;c`#g@mT*>I3$x}x#Gtw%19YBa1ZVnj$@Nw^P-9|(G2^{#u+hg*;FT=!dKq8qN(^D7p2uM-~jmN z%jK(W@}&6HytHuUQ$zib<@CBOcbU2+dGZ7fg`)H@x{&PP+m4(=fsmb^!GzBM>5-RK zRiwL;`690^98bh6K0$odu$J2{^=6B>RMu+0N!5C`70p?1M=}TL&s8%Ju55K8(Vh5EtY$ow zS?@q%w6t6@6G?tERnaEs_T2)(%KI}`FRh-JPl%6KgSO{qm0Cx&_BdqlVhlf^$YzuV z&c@1X*1i#A{n7Y3=i0nKm*_1b4xkI${UcoUKJ2DXRrxP_M5al~lat z0fxIK(NtZnZJt&{A7rNn6MgD2CF|MdZ`H|-pLVylEPZQ1*Q2mKDq9F&dQ3@Qr>o>ffe^Qnd4j8kd3eqHWQq|6@ zJD+E3o9R!jX~<2+lxltDXfkuKstn@B<;q%~K>%+|r~$q;AvZHpKVSt^qKU$rmSx=z zW~c6Nq*hn9*Fhn5X`fG-t;Xw3=F@o;u;wF(lVV)O10WzV|q_!(cq~EKL#S%WK ze8Ik&Av$ju5WrV2Y4py_T?VIowQuCYr&Q2J!WYsf4C2}e2SQvXBV)KQQ;g~JoptNo08d65mt<~=Dudx>R3A|LVw2ygipi0VvS{9=E}F zx$U&pu-_w4+~JDvPc>~~fhOp9CNm@N&PV@TPtxIaE?Xya)NiaM>$8ho(ufJtNT8X| zQE>vLY1h^_C0M{7v=yXv-?YntSA~+_Xp9&d1zgUBM?VJvG42q9Q#a}|qPh(_gJ5!i zX_vEUm+KgK^8EpOz(cE@uRq6J0SspD4Pg=+Z{c|ecld{$faGK~;Fr$)wsk~=fGxh7 z*;hpWCkiU7Uw+nYqs;J_*aOLdgn&vLl`OgcMFx@W1I#!6YJFwQy*+fWO&6U9%@KbG_s+G_UEf#Yv?_yXRq!jB?w zAv@MI-wWl3LNsEqs;e0tYG{QCcr8M<`a%q{HD%3Y@}q3~0eyk(UD6+R8f+j6zK}ufFg}7gp}sINt#Zfx)Ovnj*7XKopR7bb?pzpG$&1#}8xFRA9h9ex0jvjr zo?{Xh-~2RqNyeTnYjH#t)Z-i9OIQiQ+B|x?__dgN<>BcxG~R`RAje@?5ttA&j;xFU zg<=upRFD)ilcFx9#mr5$F%Vki$QX!-4JsEtfFsUbn4uNm9<*rO;Wn=1eNxZ*S)Ln6wNMfd&Ny*#cS0a_n7GO1E|K1GiRJDp<{~%mQAD~QB{-< zTNF35E^d)Jj$Rf0>&C~tIC|g;5^%=Uuf)3&La(wBx9~4q(InX&4qP#_R-|s~ob_uU zBtyORUX_Sw_fC;IXbSVL8aU{JjXDD=9}rcYW~O)CkZ@Fy>T<2Uz(#+@%}DREoQHht z{2FnuNCii_%KnTqiXntVDpWXv9GtuiwLr9>E8<9lw}`>XM1fILEKv-IB+W(CP8gU^ zaqcMpDs5NkE{1{snIj53#n_r20b8-qV5{5?=T)g7znRs152V2k@Sp1plifyck@N1n zv^8DHhIKekAChw$VZ-W2fXH_=(~0<3d-@Mx4ncLfyTuVj0*?ll{emYP9JJCjN9k5ybI~)u(8;8Wjv*Q``J0!d1LWFTH&+hCCh*67J0G2KD?k zxsobmHdR+*CKk=W{C?qBe6}sY2*#AC|JAj(T~~onV2!0q5z*}JOLD>&kY5o;3hK@& zRmr*$ifF2NPD764FejDV`bnv8NA2zAYSw_o2JcbhGTx6m-TsQH;eZw{IP$aTrvlwJ z^te2Bh|Iojdmkb1Dw&g*2D*bcshkRXA{K-ugC+*IqR~o=c!<`%Y?>q7@#S8e(Y7d}Unao5mK=!wSa@)dUsb zQnPLhqrS3zj-^8sQ8J4J|5cgDM?zK@9)`SloZ@>GDOo(nVi_C0gQi)w&ad(DWgTry z-hS66__qoOgBtf^w(kaGDw}N2-?_>gZ#LGX{URDX06(|Zjy*cxL0c2sAJKe&ad1GZ zSW*@I6PHoD|2UPP&%BMWVh9f7oSiN8NfB|THjON~%v5VCKNn@yWYt{H6=l&ZFJ)sa z(L~wAyXmr#q44H-lo^U4cVTQ5JtK5FOTlB?WzOoanN}2$iamFQLOz^J_COt{5i!jp z$olJHu@rYV(Q*w8wB(0zpW*M0}rbA^zqX!Z%5z1ItsUM$9 zxv`5?!&TkjvR{;;`aS`4wC}#g1|t*8_Dbd5p1&Vx_#t>78vkV0#v^##%~6EFFl|Uo zWWCQ*P+6vH5ZNzlcsTqBlTw0~j*)T53S^l|pLIh(1tTswLu@V4q2EtVU#jZ;01JPp zz)RD}WPvWng}-`nbBlhb!u~Dlvf2=k;-l2pJI6-3tF4WrCBI<2j+P1m9?idS|CDXD zzC4uEKmj??|0hAHi3_OltYUa#gr`++l#`3AerBGZpMRc5Y;KHSeO^pRKwyd=g=lQz zQr84N=A49ZjnwN2J$^E*IsuvFL>K(I=OU-R>k`wVhW5`5UM<|t-KouY{`UrjQ4y6L zN`3w(c>g(d#~tX-2~ckBVCm(<=YcwT^9$TT(eK^==i^{`LHX=do6a60E{l8!3pZYke<&lmIOWd5ci{-6r#XkcR9m9bIw67{=epuCIz3-rxT4*&oF literal 0 HcmV?d00001 diff --git a/crates/format/tests/golden/deck.loaded.json b/crates/format/tests/golden/deck.loaded.json new file mode 100644 index 000000000..5fade90d4 --- /dev/null +++ b/crates/format/tests/golden/deck.loaded.json @@ -0,0 +1 @@ +{"damaged":[],"media":[[1,"89504e470d0a1a0a00000000"],[2,"3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e3c73766720786d6c6e733d22687474703a2f2f7777772e77332e6f72672f323030302f737667223e3c726563742077696474683d223422206865696768743d2234222f3e3c2f7376673e"],[3,"0000001866747970"],[4,""]],"presentation":{"customShows":[],"defaultTextStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":36.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":72.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":108.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":144.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":180.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":216.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":252.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":288.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"embeddedFonts":[],"firstSlideNumber":1,"handoutMaster":null,"headerFooter":{"date":false,"dateFormat":"","dateText":"","footer":false,"footerText":"","header":false,"hideOnTitle":false,"slideNumber":false},"masters":[{"background":{"color":{"base":{"kind":"scheme","slot":"bg1"}},"idx":1001,"kind":"ref"},"bodyStyle":{"levels":[{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":18.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":10.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":28.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":54.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":24.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":90.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":20.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":126.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":162.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":198.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":234.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":270.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":{"char":"•","kind":"char"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":"Arial","bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":-18.0,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":306.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":5.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"colorMap":[],"id":76,"layouts":[{"background":null,"id":12,"kind":"title","name":"Title Slide","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":7,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"ctrTitle","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":60.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":188.0,"w":720.0,"x":120.0,"y":88.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":8,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Subtitle 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"subTitle","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":24.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":130.0,"w":720.0,"x":120.0,"y":284.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":9,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":10,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":11,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":18,"kind":"titleAndContent","name":"Title and Content","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":13,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":14,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":343.0,"w":840.0,"x":60.0,"y":144.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":15,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":16,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":17,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":24,"kind":"sectionHeader","name":"Section Header","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":19,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":60.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":225.0,"w":830.0,"x":65.0,"y":135.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":20,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":82000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":24.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":118.0,"w":830.0,"x":65.0,"y":362.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":21,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":22,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":23,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":31,"kind":"twoContent","name":"Two Content","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":25,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":26,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":343.0,"w":412.0,"x":60.0,"y":144.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":27,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 3","ph":{"hasCustomPrompt":false,"idx":2,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":343.0,"w":412.0,"x":488.0,"y":144.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":28,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":29,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":30,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":40,"kind":"comparison","name":"Comparison","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":32,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":33,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":true,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":24.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":62.0,"w":412.0,"x":60.0,"y":133.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":34,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 3","ph":{"hasCustomPrompt":false,"idx":2,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":289.0,"w":412.0,"x":60.0,"y":198.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":35,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 4","ph":{"hasCustomPrompt":false,"idx":3,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":true,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":24.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":62.0,"w":412.0,"x":488.0,"y":133.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":36,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 5","ph":{"hasCustomPrompt":false,"idx":4,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":289.0,"w":412.0,"x":488.0,"y":198.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":37,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":38,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":39,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":45,"kind":"titleOnly","name":"Title Only","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":41,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":42,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":43,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":44,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":49,"kind":"blank","name":"Blank","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":46,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":47,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":48,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":56,"kind":"contentWithCaption","name":"Content with Caption","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":50,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":32.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":126.0,"w":322.0,"x":60.0,"y":36.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":51,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Content Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"obj","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":384.0,"w":488.0,"x":412.0,"y":78.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":52,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 3","ph":{"hasCustomPrompt":false,"idx":2,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":16.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":300.0,"w":322.0,"x":60.0,"y":162.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":53,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":54,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":55,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":63,"kind":"pictureWithCaption","name":"Picture with Caption","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":57,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"bottom","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":32.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":126.0,"w":322.0,"x":60.0,"y":36.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":58,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Picture Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"picture","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":null,"anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":384.0,"w":488.0,"x":412.0,"y":78.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":59,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 3","ph":{"hasCustomPrompt":false,"idx":2,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":null,"bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":0.0,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":null,"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":16.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":300.0,"w":322.0,"x":60.0,"y":162.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":60,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":61,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":62,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":69,"kind":"titleAndVerticalText","name":"Title and Vertical Text","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":64,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":65,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Vertical Text Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"body","size":null,"vertical":true},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":"eaVertical","vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":343.0,"w":840.0,"x":60.0,"y":144.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":66,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":67,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":68,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true},{"background":null,"id":75,"kind":"verticalTitleAndText","name":"Vertical Title and Text","preserve":true,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":70,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Vertical Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":true},"style":null,"text":{"body":{"anchor":null,"anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":"eaVertical","vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":458.0,"w":213.0,"x":687.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":71,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Vertical Text Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"body","size":null,"vertical":true},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":"eaVertical","vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":458.0,"w":612.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":72,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":73,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":74,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"showMasterShapes":true}],"name":"DeckCraft","otherStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":0.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":36.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":72.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":108.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":144.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":180.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":216.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":252.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}},{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":288.0,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mn-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":18.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"preserve":false,"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":2,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"title","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[{"level":0,"runs":[{"text":"Click to edit Master title style"}]}]},"textBox":false,"title":"","xfrm":{"h":104.0,"w":840.0,"x":60.0,"y":29.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":3,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Text Placeholder 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"body","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"top","anchorCtr":null,"autofit":{"font_scale":1.0,"kind":"shrink","line_reduction":0.0},"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[{"level":0,"runs":[{"text":"Click to edit Master text styles"}]}]},"textBox":false,"title":"","xfrm":{"h":343.0,"w":840.0,"x":60.0,"y":144.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":4,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Date Placeholder","ph":{"hasCustomPrompt":false,"idx":10,"kind":"date","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"left","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":60.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":5,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Footer Placeholder","ph":{"hasCustomPrompt":false,"idx":11,"kind":"footer","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"center","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":324.0,"x":318.0,"y":500.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":6,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Slide Number Placeholder","ph":{"hasCustomPrompt":false,"idx":12,"kind":"slideNum","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":"middle","anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"listStyle":{"levels":[{"para":{"align":"right","bullet":null,"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":null,"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":null,"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"},"mods":[{"op":"tint","val":75000}]},"kind":"solid"},"font":null,"fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":null,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":12.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]},"paragraphs":[{"level":0,"runs":[{"kind":{"field":"slidenum","kind":"field"},"text":"‹#›"}]}]},"textBox":false,"title":"","xfrm":{"h":28.0,"w":216.0,"x":684.0,"y":500.0}}],"theme":{"colors":{"colors":[{"a":255,"b":0,"g":0,"r":0},{"a":255,"b":255,"g":255,"r":255},{"a":255,"b":60,"g":43,"r":30},{"a":255,"b":231,"g":235,"r":237},{"a":255,"b":216,"g":111,"r":46},{"a":255,"b":29,"g":107,"r":242},{"a":255,"b":111,"g":163,"r":46},{"a":255,"b":216,"g":92,"r":138},{"a":255,"b":107,"g":63,"r":216},{"a":255,"b":28,"g":178,"r":227},{"a":255,"b":216,"g":111,"r":46},{"a":255,"b":166,"g":91,"r":122}],"name":"DeckCraft"},"fonts":{"major":{"cs":"","ea":"","latin":"Inter"},"minor":{"cs":"","ea":"","latin":"Inter"},"name":"DeckCraft"},"format":{"bgFills":[{"color":{"base":{"kind":"scheme","slot":"phClr"}},"kind":"solid"},{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"tint","val":95000},{"op":"satMod","val":170000}]},"kind":"solid"},{"kind":"gradient","rotateWithShape":true,"shape":{"angle":90.0,"kind":"linear","scaled":false},"stops":[{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":102000},{"op":"satMod","val":103000}]},"pos":0.0},{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":85000}]},"pos":1.0}]}],"effects":[{"bevel":null,"fillOverlay":null,"glow":null,"innerShadow":null,"outerShadow":null,"raw3d":null,"reflection":null,"softEdge":null},{"bevel":null,"fillOverlay":null,"glow":null,"innerShadow":null,"outerShadow":null,"raw3d":null,"reflection":null,"softEdge":null},{"bevel":null,"fillOverlay":null,"glow":null,"innerShadow":null,"outerShadow":{"align":"t","blur":6.0,"color":{"base":{"kind":"rgb","rgb":{"a":255,"b":0,"g":0,"r":0}},"mods":[{"op":"alpha","val":40000}]},"dir":90.0,"dist":3.0,"inner":false,"kx":0.0,"ky":0.0,"rotateWithShape":false,"sx":1.0,"sy":1.0},"raw3d":null,"reflection":null,"softEdge":null}],"fills":[{"color":{"base":{"kind":"scheme","slot":"phClr"}},"kind":"solid"},{"kind":"gradient","rotateWithShape":true,"shape":{"angle":90.0,"kind":"linear","scaled":false},"stops":[{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":110000},{"op":"satMod","val":103000}]},"pos":0.0},{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":92000}]},"pos":1.0}]},{"kind":"gradient","rotateWithShape":true,"shape":{"angle":90.0,"kind":"linear","scaled":false},"stops":[{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":105000},{"op":"satMod","val":103000}]},"pos":0.0},{"color":{"base":{"kind":"scheme","slot":"phClr"},"mods":[{"op":"lumMod","val":80000}]},"pos":1.0}]}],"lines":[{"align":null,"cap":null,"compound":null,"dash":null,"fill":{"color":{"base":{"kind":"scheme","slot":"phClr"}},"kind":"solid"},"head":null,"join":null,"miterLimit":null,"tail":null,"width":0.75},{"align":null,"cap":null,"compound":null,"dash":null,"fill":{"color":{"base":{"kind":"scheme","slot":"phClr"}},"kind":"solid"},"head":null,"join":null,"miterLimit":null,"tail":null,"width":1.0},{"align":null,"cap":null,"compound":null,"dash":null,"fill":{"color":{"base":{"kind":"scheme","slot":"phClr"}},"kind":"solid"},"head":null,"join":null,"miterLimit":null,"tail":null,"width":1.5}],"name":"DeckCraft"},"name":"DeckCraft"},"titleStyle":{"levels":[{"para":{"align":"left","bullet":{"kind":"none"},"bulletColor":null,"bulletColorFollowText":null,"bulletFont":null,"bulletFontFollowText":null,"bulletSize":null,"bulletSizeFollowText":null,"bulletSizePoints":null,"defaultTab":null,"eastAsianLineBreak":null,"fontAlign":null,"hangingPunct":null,"indent":null,"latinLineBreak":null,"lineSpacing":{"kind":"pct","v":0.9},"marginLeft":null,"marginRight":null,"rtl":null,"spaceAfter":null,"spaceBefore":{"kind":"pts","v":0.0},"tabs":null},"run":{"altLang":null,"baseline":null,"bold":null,"caps":null,"fill":{"color":{"base":{"kind":"scheme","slot":"tx1"}},"kind":"solid"},"font":"+mj-lt","fontCs":null,"fontEa":null,"fontSym":null,"glow":null,"highlight":null,"hover":null,"innerShadow":null,"italic":null,"kern":12.0,"lang":null,"link":null,"noProof":null,"normalizeHeight":null,"outline":null,"reflection":null,"shadow":null,"size":44.0,"softEdge":null,"spacing":null,"strike":null,"underline":null,"underlineColor":null}}]}}],"media":[{"contentType":"image/png","id":1,"link":null,"name":"image1.png"},{"contentType":"image/svg+xml","id":2,"link":null,"name":"drawing.svg"},{"contentType":"video/mp4","id":3,"link":"https://example.invalid/clip.mp4","name":"clip.mp4"},{"contentType":"image/png","id":4,"link":"file:///nowhere/linked.png","name":"linked.png"}],"nextId":261,"notesMaster":null,"notesSize":{"height":720.0,"width":540.0},"props":{"author":"","category":"","comments":"","company":"","created":"","keywords":"","lastModifiedBy":"","modified":"","revision":0,"subject":"","title":""},"sections":[],"show":{"customShow":null,"laserColor":{"a":255,"b":0,"g":0,"r":255},"loopUntilEsc":false,"penColor":{"a":255,"b":0,"g":0,"r":255},"range":null,"showMediaControls":true,"showType":"speaker","useTimings":true,"withoutAnimation":false,"withoutNarration":false},"slideSize":{"height":540.0,"width":960.0},"slides":[{"animations":[],"background":null,"comments":[],"hidden":false,"id":257,"layout":12,"name":"","notes":{"body":{"anchor":null,"anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"shapes":[{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":258,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Title 1","ph":{"hasCustomPrompt":false,"idx":0,"kind":"ctrTitle","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":null,"anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[{"level":0,"runs":[{"text":"Golden «deck» ✓"}]}]},"textBox":false,"title":"","xfrm":null},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":259,"kind":{"type":"shape"},"line":null,"locked":false,"name":"Subtitle 2","ph":{"hasCustomPrompt":false,"idx":1,"kind":"subTitle","size":null,"vertical":false},"style":null,"text":{"body":{"anchor":null,"anchorCtr":null,"autofit":null,"colSpacing":null,"columns":null,"compatLnSpc":null,"horzOverflow":null,"insetB":null,"insetL":null,"insetR":null,"insetT":null,"rot":null,"rtlCol":null,"spaceFirstLast":null,"upright":null,"vert":null,"vertOverflow":null,"warp":null,"wrap":null},"paragraphs":[]},"textBox":false,"title":"","xfrm":null},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":260,"kind":{"axisTitles":[null,null],"catReversed":false,"categories":["Q1","Q2","Q3","Q4"],"chartFill":null,"dataLabels":false,"gapWidth":2.19,"gridlines":true,"holeSize":0.5,"kept":{"parts":[{"bytes":[80,75,3,4,1,2,3],"contentType":"application/zip","name":"ppt/charts/part0"},{"bytes":[60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62,60,99,115,58,99,104,97,114,116,83,116,121,108,101,32,105,100,61,34,50,48,49,34,47,62],"contentType":"application/vnd.ms-office.chartstyle+xml","name":"ppt/charts/part1"}],"rels":[]},"kind":"bar","lang":null,"legend":"b","legendOverlay":false,"minorGridlines":false,"overlap":-0.27,"palette":"colorful1","plotFill":null,"series":[{"dataLabels":null,"fill":null,"kind":null,"line":null,"marker":null,"name":"Series 1","pointFills":[],"secondaryAxis":false,"sizes":[],"smooth":false,"values":[4.2,2.8,3.6,4.7],"xValues":[]},{"dataLabels":null,"fill":null,"kind":null,"line":null,"marker":null,"name":"Series 2","pointFills":[],"secondaryAxis":false,"sizes":[],"smooth":false,"values":[2.6,4.1,1.9,3.0],"xValues":[]},{"dataLabels":null,"fill":null,"kind":null,"line":null,"marker":null,"name":"Series 3","pointFills":[],"secondaryAxis":false,"sizes":[],"smooth":false,"values":[2.1,2.4,3.3,5.1],"xValues":[]}],"style":2,"textColor":null,"title":"Chart Title","type":"chart","varyColors":false,"y2Format":null,"y2Hidden":false,"y2Major":null,"y2Max":null,"y2Min":null,"yFormat":null,"yHidden":false,"yLogBase":null,"yMajor":null,"yMax":null,"yMin":null},"line":null,"locked":false,"name":"","ph":null,"style":null,"text":null,"textBox":false,"title":"","xfrm":{"h":200.0,"w":300.0,"x":10.0,"y":20.0}},{"click":null,"decorative":false,"descr":"","effects":null,"fill":null,"geom":{"kind":"preset","name":"rect"},"hidden":false,"hover":null,"id":261,"kind":{"type":"shape"},"line":null,"locked":false,"name":"","ph":null,"style":null,"text":null,"textBox":false,"title":"","xfrm":{"h":7.5,"w":0.0,"x":0.0,"y":5.0}}],"showMasterShapes":true,"transition":null}]}} From 97423d80fdc6945f8a542eca75caa99786250c75 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 06:46:59 +0100 Subject: [PATCH 56/76] test(engine): pin the standard Base64 alphabet in the encoder test The lenient decoder accepts both alphabets, so the round trip alone would not catch a switch to the URL-safe encoder. --- crates/engine/src/cmd.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 628571edd..f257d3282 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -656,6 +656,8 @@ mod tests { { 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 = (0..=255).cycle().take(513).collect(); for len in 0..=all.len() { let encoded = base64_encode(&all[..len]); From 9e975b0049a433e874e918a1e9bb4720600e7f01 Mon Sep 17 00:00:00 2001 From: scks1 <126534658+scks1@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:46:28 -0500 Subject: [PATCH 57/76] engine: arrange.align and arrange.distribute refuse values they do not name (#1974) * engine: arrange.align and arrange.distribute refuse values they do not name arrange.align took an `edge` it did not know as a no-op that still reported its shapes as edited, aligned left when `edge` was left out (the spec does not mark it optional), and read any `to` other than exactly "slide" as the selection. arrange.distribute distributed vertically for any `dir` starting with "v" and horizontally for any other, and also read any `to` other than "slide" as the selection. `edge` must now be left, center, right, top, middle or bottom, `to` slide or selection, and `dir` horizontal or vertical. Anything else, or a missing `edge`, is refused with the accepted values and nothing moves. A missing `to` or `dir` keeps its default. Test: align_and_distribute_refuse_values_they_do_not_name. * engine: arrange.align and arrange.distribute refuse a dir or to that is not a string `align_to` and `distribute` read `to` and `dir` through `str_param`, which returns None for a value that is present but not a string, the same as for a missing one. So `{"dir": 123}` distributed horizontally, and `{"edge": "left", "to": false}` aligned to each command's default reference, moving the selected shapes instead of failing. Both now match on `p.get(..).map(Value::as_str)`: a missing field keeps its default (horizontal for `dir`, each command's own rule for `to`), the named strings work as before, and anything else, null included, is refused with the accepted values. The new test `align_and_distribute_refuse_dir_and_to_that_are_not_strings` sends null, 123, false, {} and [] as `dir` to arrange.distribute and as `to` to both commands, in a fresh three-shape session each time, and checks the error, the revision and every shape's box. --- crates/engine/src/cmd/arrange.rs | 32 ++++++++++---- crates/engine/src/tests.rs | 76 ++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/arrange.rs b/crates/engine/src/cmd/arrange.rs index 2f633501c..854758e55 100644 --- a/crates/engine/src/cmd/arrange.rs +++ b/crates/engine/src/cmd/arrange.rs @@ -417,17 +417,28 @@ fn regroup(s: &mut Session, _p: &Value) -> Result { } } +/// `to` of arrange.align and arrange.distribute: `Some(true)` for the slide, `Some(false)` for the +/// selection, `None` when it is left out. Any other value, a non-string included, is refused. +fn align_to(cmd: &str, p: &Value) -> Result> { + match p.get("to").map(Value::as_str) { + None => Ok(None), + Some(Some("slide")) => Ok(Some(true)), + Some(Some("selection")) => Ok(Some(false)), + Some(_) => Err(bad(cmd, "`to` must be slide or selection")), + } +} + fn align(s: &mut Session, p: &Value) -> Result { - let edge = str_param(p, "edge").unwrap_or("left").to_string(); + let edge = match str_param(p, "edge") { + Some(e @ ("left" | "center" | "right" | "top" | "middle" | "bottom")) => e.to_string(), + _ => return Err(bad("arrange.align", "`edge` must be left, center, right, top, middle or bottom")), + }; + let to = align_to("arrange.align", p)?; let ids = targets(s, p)?; let st = s.doc()?; let size = st.doc.slide_size; let boxes: Vec<(ShapeId, Xfrm)> = ids.iter().filter_map(|id| st.shape(*id).map(|x| (*id, xfrm_of(&st.doc, &st.selection, x)))).collect(); - let to_slide = match str_param(p, "to") { - Some("slide") => true, - Some(_) => false, - None => boxes.len() < 2, - }; + let to_slide = to.unwrap_or(boxes.len() < 2); let reference = if to_slide { Rect::new(0.0, 0.0, size.width, size.height) } else { @@ -453,13 +464,18 @@ fn align(s: &mut Session, p: &Value) -> Result { } fn distribute(s: &mut Session, p: &Value) -> Result { - let horiz = !str_param(p, "dir").unwrap_or("horizontal").starts_with('v'); + let horiz = match p.get("dir").map(Value::as_str) { + None | Some(Some("horizontal")) => true, + Some(Some("vertical")) => false, + Some(_) => return Err(bad("arrange.distribute", "`dir` must be horizontal or vertical")), + }; + let to = align_to("arrange.distribute", p)?; let ids = targets(s, p)?; let st = s.doc()?; let size = st.doc.slide_size; let mut boxes: Vec<(ShapeId, Rect)> = ids.iter().filter_map(|id| st.shape(*id).map(|x| (*id, xfrm_of(&st.doc, &st.selection, x).bounds()))).collect(); - let to_slide = str_param(p, "to") == Some("slide") || boxes.len() < 3; + let to_slide = to == Some(true) || boxes.len() < 3; if boxes.is_empty() { return ok(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 21b67310a..66494ea22 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1184,6 +1184,82 @@ fn distribute_wide_middle_stays_in_selection_bounds() { assert!(xs.iter().all(|x| (*x - [0.0, 10.0, 110.0][xs.iter().position(|y| y == x).unwrap()]).abs() < 1e-6), "{xs:?}"); } +/// An `edge`, `dir` or `to` that the commands do not name, or no `edge` at all, is refused with +/// the accepted values. Before, such a call reported its shapes as edited and moved nothing, +/// aligned to the selection, or fell back to the left edge or to horizontal. +#[test] +fn align_and_distribute_refuse_values_they_do_not_name() { + let mut s = session(); + let mut ids = vec![]; + for (x, y) in [(10.0, 10.0), (200.0, 50.0), (500.0, 200.0)] { + ids.push(s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 40, 40]})).unwrap()["id"].as_u64().unwrap()); + } + s.execute("edit.select", &json!({"ids": ids})).unwrap(); + let before = s.doc().unwrap().revision; + let edges = "`edge` must be left, center, right, top, middle or bottom"; + let dirs = "`dir` must be horizontal or vertical"; + let tos = "`to` must be slide or selection"; + for (cmd, params, want) in [ + ("arrange.align", json!({"edge": "centre"}), edges), + ("arrange.align", json!({"edge": "Left"}), edges), + ("arrange.align", json!({"edge": "hcenter"}), edges), + ("arrange.align", json!({}), edges), + ("arrange.align", json!({"ids": [ids[0]], "edge": "left", "to": "Slide"}), tos), + ("arrange.distribute", json!({"dir": "Vertical"}), dirs), + ("arrange.distribute", json!({"dir": "columns"}), dirs), + ("arrange.distribute", json!({"dir": "v"}), dirs), + ("arrange.distribute", json!({"dir": "vertical", "to": "page"}), tos), + ] { + let err = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(err.contains(want), "{cmd} {params}: {err}"); + } + assert_eq!(s.doc().unwrap().revision, before, "a refused call leaves the slide as it was"); + let pos = |s: &mut Session, id: u64, k: &str| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"][k].as_f64().unwrap(); + s.execute("arrange.align", &json!({"ids": [ids[1]], "edge": "left", "to": "slide"})).unwrap(); + assert!(pos(&mut s, ids[1], "x").abs() < 1e-6); + // Within the selection's span, 10..240: 120 pt of shapes leaves two 55 pt gaps. + s.execute("arrange.distribute", &json!({"ids": ids, "dir": "vertical", "to": "selection"})).unwrap(); + assert!((pos(&mut s, ids[1], "y") - 105.0).abs() < 1e-6); +} + +/// A `dir` or `to` that is present but is not a string (null, a number, a bool, an object or an +/// array) is refused with the accepted values, and the shapes and the revision stay as they were. +/// Before, such a value counted as left out: `dir` meant horizontal and `to` each command's +/// default, so the call moved the selected shapes. +#[test] +fn align_and_distribute_refuse_dir_and_to_that_are_not_strings() { + let dirs = "`dir` must be horizontal or vertical"; + let tos = "`to` must be slide or selection"; + let mut failures = vec![]; + for v in [json!(null), json!(123), json!(false), json!({}), json!([])] { + for (cmd, params, want) in [ + ("arrange.distribute", json!({"dir": v.clone()}), dirs), + ("arrange.distribute", json!({"dir": "horizontal", "to": v.clone()}), tos), + ("arrange.align", json!({"edge": "left", "to": v.clone()}), tos), + ] { + let mut s = session(); + let mut ids = vec![]; + for (x, y) in [(10.0, 10.0), (200.0, 50.0), (500.0, 200.0)] { + ids.push(s.execute("shape.insert", &json!({"preset": "rect", "rect": [x, y, 40, 40]})).unwrap()["id"].as_u64().unwrap()); + } + s.execute("edit.select", &json!({"ids": ids})).unwrap(); + let boxes = |s: &mut Session| -> Vec { + ids.iter().map(|id| s.execute("shape.inspect", &json!({"id": id})).unwrap()["box"].clone()).collect() + }; + let (rev, before) = (s.doc().unwrap().revision, boxes(&mut s)); + match s.execute(cmd, ¶ms) { + Ok(_) => failures.push(format!("{cmd} {params}: accepted")), + Err(e) if !e.to_string().contains(want) => failures.push(format!("{cmd} {params}: {e}")), + Err(_) => {} + } + if s.doc().unwrap().revision != rev || boxes(&mut s) != before { + failures.push(format!("{cmd} {params}: moved the shapes")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + #[test] fn pointer_draw_move_resize() { let mut s = session(); From 596ec54b592dc6c3492c7e149b79684824ba508a Mon Sep 17 00:00:00 2001 From: Zinadin Zidan Date: Mon, 16 Nov 2026 15:22:24 +0600 Subject: [PATCH 58/76] Slide show: play a slide's animations again when the show advances to it (#2090) (#2126) ShowState remembers what was played on each visited slide, so a slide reached again by a link or by Back looks as it was left. Going forward used the same path: next() entered a visited slide at the step it was left at, so after Back and forward again its entrance effects did not play and the shapes were already in place. next() now forgets the slide's run before entering it, when it moves to the next slide and when a looping show comes round to the first one. The slide starts over: its automatic first step plays, an On Click build starts at its first step, and its triggered animations start over. Back, links, Go to slide and Return to Zoom are unchanged. --- ROADMAP.md | 4 ++- crates/anim/src/interact.rs | 3 +- crates/anim/src/show.rs | 15 +++++++-- crates/anim/src/tests.rs | 52 +++++++++++++++++++++++++++++++ crates/anim/src/tests_interact.rs | 17 ++++++++++ docs/slideshow-parity.md | 6 ++-- 6 files changed, 90 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a67c5e7ab..c1a9cbc39 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** trivial (slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** trivial (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -154,6 +154,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-14 | Slide show: a slide the show advances to again (click, →, Space, automatic advance or a loop) starts over, so its animations play again, as in PowerPoint. Back and links still show it as it was left (#2090) | | 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed | | 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Slide lists over 10,000 entries are explicitly refused before a partial load; exactly 10,000 remain supported. Synthetic 13-slide regression; does not establish the cause of #1910's field report. | | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | @@ -342,6 +343,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| +| 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged | | 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged | | 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged | | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | diff --git a/crates/anim/src/interact.rs b/crates/anim/src/interact.rs index e32d980e8..a66b241e7 100644 --- a/crates/anim/src/interact.rs +++ b/crates/anim/src/interact.rs @@ -9,7 +9,8 @@ //! - a shape with a link and a triggered animation follows the link at once. The animation's clock //! runs only while its slide is shown, so it goes on where it stopped when the show returns; //! - with "advance on click" off a click never leaves the slide, but it still plays animation steps; -//! - a slide the show returns to (link or arrow keys) looks as it was left. +//! - a slide the show returns to by a link or by going back looks as it was left; going forward +//! to a slide starts it over (#2090). use deckcraft_model::text::Action; use deckcraft_model::{Presentation, ShapeId}; diff --git a/crates/anim/src/show.rs b/crates/anim/src/show.rs index 15fb8ce9f..1320688a5 100644 --- a/crates/anim/src/show.rs +++ b/crates/anim/src/show.rs @@ -47,7 +47,8 @@ pub enum LinkJump { /// Where a slide show is. Besides the current position it remembers what was played on every slide /// the show has visited (main steps, triggered sequences), so a slide reached again by a link or -/// the arrow keys looks the way it was left, as in PowerPoint. +/// by going back looks the way it was left, as in PowerPoint. Going forward to a slide starts it +/// over, so its animations play again (#2090). #[derive(Clone, Debug, PartialEq, Default)] pub struct ShowState { /// Index into `presentation.slides`. @@ -226,6 +227,14 @@ impl ShowState { } } + /// Advance to slide `i`: it starts over, as if the show had not been there, so its + /// animations play again (#2090). Links and Back keep a slide as it was left. + fn enter_forward(&mut self, pres: &Presentation, i: usize) { + self.leave(pres); + self.runs.remove(&i); + self.enter(pres, i); + } + fn next_index(&self, pres: &Presentation) -> Option { let order = self.visit(pres); match order.iter().position(|&i| i == self.slide) { @@ -271,12 +280,12 @@ impl ShowState { } match self.next_index(pres) { Some(i) => { - self.enter(pres, i); + self.enter_forward(pres, i); ShowAction::Slide(i) } None if looping(pres) => match self.visit(pres).first() { Some(&i) => { - self.enter(pres, i); + self.enter_forward(pres, i); ShowAction::Slide(i) } None => { diff --git a/crates/anim/src/tests.rs b/crates/anim/src/tests.rs index 385520b6d..562004ef2 100644 --- a/crates/anim/src/tests.rs +++ b/crates/anim/src/tests.rs @@ -876,6 +876,8 @@ fn show_back_leaves_a_slide_whose_first_step_is_automatic() { // While the automatic step plays. assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}"); assert_eq!(s.next(&p), ShowAction::Slide(1)); + // Going forward again plays the automatic step again (#2090). + assert_eq!(s.step_done(&p), ShowAction::FinishStep(0), "{start:?}"); // Once it has played, the click step is undone first, then Back leaves the slide. assert_eq!(s.next(&p), ShowAction::PlayStep(1)); assert_eq!(s.step_done(&p), ShowAction::FinishStep(1)); @@ -885,6 +887,56 @@ fn show_back_leaves_a_slide_whose_first_step_is_automatic() { } } +#[test] +fn a_slide_entered_going_forward_again_plays_its_animations_again() { + // #2090: the show remembered slide 2 as fully built, so its entrance effects did not play the + // second time the show advanced to it. + for start in [AnimStart::WithPrevious, AnimStart::AfterPrevious] { + let mut p = pres(3); + Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A")]; + Arc::make_mut(&mut p.slides[1]).animations = vec![anim(1, AnimClass::Entrance, "fade", start)]; + let mut s = ShowState::new(&p); + assert_eq!(s.next(&p), ShowAction::Slide(1)); + assert_eq!(s.step_done(&p), ShowAction::FinishStep(0)); + assert_eq!(s.prev(&p), ShowAction::Slide(0), "{start:?}"); + assert_eq!(s.next(&p), ShowAction::Slide(1)); + assert_eq!((s.step, s.playing), (0, true), "{start:?}: the slide starts again"); + let a = ShowState::timeline(&p, 1).state(ShapeId(1), None, s.step, 0.0); + assert!(!a.visible || a.opacity < 0.01, "{start:?}: the shape has not come in yet"); + // Back from the next slide still shows it as it was left. + assert_eq!(s.step_done(&p), ShowAction::FinishStep(0)); + assert_eq!(s.next(&p), ShowAction::Slide(2)); + assert_eq!(s.prev(&p), ShowAction::Slide(1)); + assert_eq!((s.step, s.playing), (1, false), "{start:?}"); + } + // An On Click build left by a jump starts again when the show advances to the slide. + let mut p = pres(2); + Arc::make_mut(&mut p.slides[1]).shapes = vec![shape(1, "A")]; + Arc::make_mut(&mut p.slides[1]).animations = vec![anim(1, AnimClass::Entrance, "fade", AnimStart::OnClick)]; + let mut s = ShowState::new(&p); + assert_eq!(s.next(&p), ShowAction::Slide(1)); + assert_eq!(s.next(&p), ShowAction::PlayStep(0)); + assert_eq!(s.step_done(&p), ShowAction::FinishStep(0)); + assert_eq!(s.goto(&p, 0), ShowAction::Slide(0)); + assert_eq!(s.next(&p), ShowAction::Slide(1)); + assert_eq!((s.step, s.playing), (0, false)); +} + +#[test] +fn a_looping_show_plays_the_first_slide_again() { + // #2090: a kiosk or loop-until-Esc show comes round to the first slide going forward. + let mut p = pres(2); + p.show.loop_until_esc = true; + Arc::make_mut(&mut p.slides[0]).shapes = vec![shape(1, "A")]; + Arc::make_mut(&mut p.slides[0]).animations = vec![anim(1, AnimClass::Entrance, "fade", AnimStart::WithPrevious)]; + let mut s = ShowState::new(&p); + assert!(s.playing); + assert_eq!(s.step_done(&p), ShowAction::FinishStep(0)); + assert_eq!(s.next(&p), ShowAction::Slide(1)); + assert_eq!(s.next(&p), ShowAction::Slide(0)); + assert_eq!((s.step, s.playing), (0, true)); +} + #[test] fn show_auto_advance() { let mut p = pres(2); diff --git a/crates/anim/src/tests_interact.rs b/crates/anim/src/tests_interact.rs index 1d2810811..ab2a0b40b 100644 --- a/crates/anim/src/tests_interact.rs +++ b/crates/anim/src/tests_interact.rs @@ -325,6 +325,23 @@ fn a_slide_comes_back_the_way_it_was_left() { assert_eq!(s.step, ShowState::steps(&pres, 1)); } +#[test] +fn a_slide_entered_going_forward_again_starts_over() { + // #2090: the show advances to slide 2 a second time; its triggered animation is undone too. + let s1 = slide(1000, vec![], vec![], true); + let s2 = slide(1001, vec![shape(4)], vec![exit_on_click(4, 4, 0)], true); + let pres = Presentation { slides: vec![s1, s2], ..Default::default() }; + let mut r = Run::new(pres, vec![vec![], vec![hit(4, None)]]); + assert_eq!(r.show.next(&r.pres), ShowAction::Slide(1)); + assert_eq!(r.click(), Click::Animated); + assert!(!r.visible(ShapeId(4))); + assert_eq!(r.show.prev(&r.pres), ShowAction::Slide(0)); + assert_eq!(r.show.prev(&r.pres), ShowAction::None); + assert_eq!(r.show.next(&r.pres), ShowAction::Slide(1)); + assert!(r.visible(ShapeId(4)), "the shape is back"); + assert!(r.show.trigger_plays().is_empty()); +} + #[test] fn a_playing_main_step_is_finished_when_the_show_leaves() { let a = Animation { shape: ShapeId(1), class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 500, ..Default::default() }; diff --git a/docs/slideshow-parity.md b/docs/slideshow-parity.md index 08fff1b5f..96938c0c4 100644 --- a/docs/slideshow-parity.md +++ b/docs/slideshow-parity.md @@ -1,6 +1,6 @@ # Slide show and presenter view: parity with PowerPoint -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** minor (deleting slides removes them from custom shows; previous: minor, Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; previous: minor, deleting slides removes them from custom shows; previous: minor, Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) Presenting is the job PowerPoint is hired for. This doc covers the show window, presenter view, rehearsal and recording. Transition and animation playback are in @@ -23,7 +23,8 @@ ready** (estimated), **10–16 h** to parity. | Hidden slides skipped | yes | yes | | | Hyperlinks and action settings followed (slides, web, mail, End Show, Last Viewed) | yes | yes | Only `http(s)` and `mailto` open outside the show, by design (`safe_url`) | | A shape with a triggered animation plays it when clicked; shapes an animation has hidden cannot be clicked; a shape without an action on top of one with an action blocks it; the pointer is a hand over what can be clicked | yes | yes | Click boxes are bounding boxes; "play sound" actions (`ppaction://media`) do nothing yet | -| A slide the show returns to (link, arrow keys) looks as it was left; a triggered animation goes on where it stopped | yes | yes | A main-sequence step still playing when the show leaves is finished | +| A slide the show returns to by a link or Back looks as it was left; a triggered animation goes on where it stopped | yes | yes | A main-sequence step still playing when the show leaves is finished | +| A slide the show advances to again (click, →, Space, automatic advance, loop) starts over and plays its animations again | yes | yes | Its triggered animations start over too (#2090) | | "Advance on click" off: a click never leaves the slide (animation steps still play, keys still move on) | yes | yes | | | Hyperlinks and action settings followed (slides, web, mail, End Show, Last Viewed, Custom Show) | yes | yes | Only `http(s)` and `mailto` open outside the show, by design (`safe_url`). A Custom Show action plays that show | | Media playback with controls, play across slides, full-screen video, Play/Pause/Stop in the click sequence | yes | yes | WMA/WMV not decodable. Click sequence since #116. Slide Show ▸ Show Media Controls (on by default) hides the playback bar. Seeks and loops preserve new-generation video frames and end-of-stream; queue regression and repeated seeks across H.264/HEVC/VP9/AV1 in `crates/media` | @@ -96,4 +97,5 @@ Reading View in a window with navigation: present (checklist row done). | 2026-10-14 | minor | See All Slides (G) and click-to-zoom (Z) during the show. Presenter view opens that grid and sets black, white and zoom. Checklist breadth stays 66% | | 2026-10-24 | minor | Ctrl+wheel (Cmd+wheel on a Mac) zooms the show in and out around the pointer, up to 4×; the plain wheel still turns the page (#1286) | | 2026-10-23 | trivial | Presenter view draws the notes with their formatting (bullets, numbers, indents, bold/italic) instead of plain text (#1128) | +| 2026-11-14 | minor | A slide the show advances to again starts over, so its entrance effects play again; Back and links still show it as it was left (#2090) | | 2026-10-10 | major | Created: show, presenter view, rehearse and record, compared with PowerPoint 16.113's Slide Show tab and menu | From 5f58c3c2083dfa73110239c845424b66858edee1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:52:29 +0100 Subject: [PATCH 59/76] #792: read password-protected decks with craft-cfb and drop the local PNG encoder DeckCraft's pptx crate carried a copy of GridCraft's CFB directory walk to tell an encrypted package from other compound files. It now asks the shared craft-cfb (has_entry_named, same UTF-16 fallback for damaged directories, directory entries capped at 4096 as before). The placeholder for missing picture media keeps its exact bytes, written as a constant instead of through a hand-rolled CRC/Adler/PNG encoder. Part of storytold/craft-libs#778 and storytold/craft-libs#792. --- Cargo.lock | 6 +++ Cargo.toml | 2 + crates/pptx/Cargo.toml | 1 + crates/pptx/src/cfb.rs | 110 ++++++----------------------------------- crates/pptx/src/png.rs | 70 +++++++++----------------- 5 files changed, 47 insertions(+), 142 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 414a49d9d..f1bc8b16c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -853,6 +853,11 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" + [[package]] name = "craft-codepage" version = "0.1.0" @@ -1301,6 +1306,7 @@ dependencies = [ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ + "craft-cfb", "craft-opc", "craft-xml", "deckcraft-color", diff --git a/Cargo.toml b/Cargo.toml index 1d0a505ab..0dab1e523 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,8 @@ repository = "https://github.com/storytold/deckcraft" [workspace.dependencies] # OPC part-name primitives; relationship admission stays app-local. craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } +# Compound File Binary directory reads (password-protected deck detection). +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # XML writer primitives; parser admission and OOXML policy stay app-local. craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # internal diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index 419c39bad..7e66abf13 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] craft-opc.workspace = true craft-xml.workspace = true +craft-cfb.workspace = true deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/pptx/src/cfb.rs b/crates/pptx/src/cfb.rs index 3155d1923..f17662f25 100644 --- a/crates/pptx/src/cfb.rs +++ b/crates/pptx/src/cfb.rs @@ -1,103 +1,24 @@ -//! Just enough of the Compound File Binary (CFB/OLE2) container to tell a password-protected -//! presentation apart: PowerPoint wraps an encrypted `.pptx` in a CFB holding `EncryptionInfo` -//! and `EncryptedPackage` streams (ECMA-376 / [MS-OFFCRYPTO]) instead of a zip. Every read is -//! bounds-checked and every loop bounded. Copied from GridCraft's `crates/xlsx/src/cfb.rs`. - -/// The CFB signature at the start of the file. -const SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]; - -const END_OF_CHAIN: u32 = 0xFFFF_FFFE; -/// Sector ids at or above this are markers (free, end of chain, FAT/DIFAT sector), not sectors. -const MAX_REG_SECT: u32 = 0xFFFF_FFFA; -/// Directory sectors followed at most (4096 entries with 512-byte sectors). -const MAX_DIR_SECTORS: usize = 1024; -/// DIFAT sectors followed at most. -const MAX_DIFAT_SECTORS: usize = 1024; +//! Password-protected presentations. PowerPoint wraps an encrypted `.pptx` in a Compound File +//! Binary (CFB/OLE2) container holding `EncryptionInfo` and `EncryptedPackage` streams +//! (ECMA-376 / [MS-OFFCRYPTO]) instead of a zip. The container's directory is read by the shared +//! `craft-cfb` crate, which bounds every chain and falls back to a UTF-16 name search when a +//! damaged file's directory cannot be followed. /// Stream names that mark an encrypted (password-protected) OOXML package. const ENCRYPTED_STREAMS: [&str; 2] = ["EncryptedPackage", "EncryptionInfo"]; -fn u16_at(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(2)?)?; - Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) +/// Directory entries read at most: 1024 directory sectors of 512 bytes, as before the move to +/// `craft-cfb`, so a hostile directory chain stays cheap. +const MAX_DIR_ENTRIES: usize = 4096; + +fn limits() -> craft_cfb::Limits { + craft_cfb::Limits { max_dir_entries: MAX_DIR_ENTRIES, ..craft_cfb::Limits::default() } } -fn u32_at(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(4)?)?; - Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) -} - -/// Whether `bytes` is a compound file holding an encryption stream. Walks the directory through -/// the FAT; when the structure can't be followed (truncated or malformed), falls back to scanning -/// the bytes for the UTF-16LE stream names. +/// Whether `bytes` is a compound file holding an encryption stream. pub(crate) fn is_encrypted(bytes: &[u8]) -> bool { - if !bytes.starts_with(&SIGNATURE) { - return false; - } - match directory_names(bytes) { - Some(names) => names.iter().any(|n| ENCRYPTED_STREAMS.iter().any(|e| n.eq_ignore_ascii_case(e))), - None => ENCRYPTED_STREAMS.iter().any(|e| contains_utf16(bytes, e)), - } -} - -fn contains_utf16(hay: &[u8], needle: &str) -> bool { - let n: Vec = needle.encode_utf16().flat_map(u16::to_le_bytes).collect(); - !n.is_empty() && hay.windows(n.len()).any(|w| w == n.as_slice()) -} - -/// Names of every directory entry, or `None` when the directory can't be read. -fn directory_names(b: &[u8]) -> Option> { - if !b.starts_with(&SIGNATURE) { - return None; - } - let shift = u16_at(b, 30)?; - if shift != 9 && shift != 12 { - return None; - } - let size = 1usize << shift; - let per = size / 4; - let sector = |id: u32| -> Option<&[u8]> { - let start = (id as usize).checked_add(1)?.checked_mul(size)?; - b.get(start..start.checked_add(size)?) - }; - // The DIFAT: the FAT's sector ids, 109 in the header then chained DIFAT sectors. - let mut difat: Vec = (0..109).filter_map(|i| u32_at(b, 76 + i * 4)).filter(|&s| s < MAX_REG_SECT).collect(); - let mut next = u32_at(b, 68)?; - for _ in 0..MAX_DIFAT_SECTORS { - if next >= MAX_REG_SECT { - break; - } - let s = sector(next)?; - difat.extend((0..per - 1).filter_map(|i| u32_at(s, i * 4)).filter(|&x| x < MAX_REG_SECT)); - next = u32_at(s, (per - 1) * 4)?; - } - let fat_next = |id: u32| -> Option { - let idx = id as usize; - let fat_sector = *difat.get(idx / per)?; - u32_at(sector(fat_sector)?, (idx % per) * 4) - }; - let mut names = Vec::new(); - let mut id = u32_at(b, 48)?; - for _ in 0..MAX_DIR_SECTORS { - if id == END_OF_CHAIN { - return Some(names); - } - if id >= MAX_REG_SECT { - return None; - } - let s = sector(id)?; - for e in s.as_chunks::<128>().0 { - let len = usize::from(u16_at(e, 64)?); - if !(2..=64).contains(&len) { - continue; - } - let units: Vec = (0..(len - 2) / 2).filter_map(|i| u16_at(e, i * 2)).collect(); - names.push(String::from_utf16_lossy(&units)); - } - id = fat_next(id)?; - } - // A directory longer than the bound (or a cyclic chain): report what was read. - Some(names) + let limits = limits(); + ENCRYPTED_STREAMS.iter().any(|name| craft_cfb::has_entry_named(bytes, name, &limits)) } #[cfg(test)] @@ -105,6 +26,7 @@ mod tests { #![allow(clippy::unwrap_used)] use super::*; + use craft_cfb::{ENDOFCHAIN as END_OF_CHAIN, SIGNATURE}; /// A minimal valid compound file (512-byte sectors: FAT at sector 0, directory at sector 1) /// whose directory holds a root entry plus the given stream names. @@ -146,7 +68,7 @@ mod tests { #[test] fn reads_directory_names() { let b = build(&["EncryptionInfo", "EncryptedPackage"]); - assert_eq!(directory_names(&b), Some(vec!["Root Entry".into(), "EncryptionInfo".into(), "EncryptedPackage".into()])); + assert_eq!(craft_cfb::directory_names(&b, &limits()), Some(vec!["Root Entry".into(), "EncryptionInfo".into(), "EncryptedPackage".into()])); assert!(is_encrypted(&b)); // A PowerPoint 97-2003 .ppt is a compound file too, without the encryption streams. assert!(!is_encrypted(&build(&["PowerPoint Document", "Current User"]))); diff --git a/crates/pptx/src/png.rs b/crates/pptx/src/png.rs index 55b88f1d8..6f770bd29 100644 --- a/crates/pptx/src/png.rs +++ b/crates/pptx/src/png.rs @@ -1,59 +1,33 @@ -//! A minimal PNG encoder for the placeholder image written when a picture's media is missing. +//! The placeholder image written when a picture's media is missing: a 1×1 fully transparent RGBA +//! PNG, kept as its fixed bytes (signature, IHDR, one stored-deflate IDAT scanline, IEND) so the +//! app carries no PNG encoder of its own. -fn crc32(data: &[u8]) -> u32 { - let mut c = 0xFFFF_FFFFu32; - for b in data { - c ^= *b as u32; - for _ in 0..8 { - c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; - } - } - !c -} - -fn adler32(data: &[u8]) -> u32 { - let (mut a, mut b) = (1u32, 0u32); - for x in data { - a = (a + *x as u32) % 65521; - b = (b + a) % 65521; - } - (b << 16) | a -} - -fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { - out.extend_from_slice(&(data.len() as u32).to_be_bytes()); - let mut c = Vec::with_capacity(data.len() + 4); - c.extend_from_slice(kind); - c.extend_from_slice(data); - out.extend_from_slice(&c); - out.extend_from_slice(&crc32(&c).to_be_bytes()); -} +/// The PNG file, byte for byte what the former local encoder produced. +const TRANSPARENT_1X1: [u8; 73] = [ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x01, 0x05, 0x00, 0xFA, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x64, 0x78, 0x95, 0x38, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, + 0x82, +]; /// A 1×1 fully transparent RGBA PNG. pub fn transparent_1x1() -> Vec { - let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); - let mut ihdr = vec![]; - ihdr.extend_from_slice(&1u32.to_be_bytes()); - ihdr.extend_from_slice(&1u32.to_be_bytes()); - ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); - chunk(&mut out, b"IHDR", &ihdr); - // One scanline: filter byte + RGBA, stored (uncompressed) deflate block. - let raw = [0u8, 0, 0, 0, 0]; - let mut z = vec![0x78, 0x01, 0x01]; - z.extend_from_slice(&(raw.len() as u16).to_le_bytes()); - z.extend_from_slice(&(!(raw.len() as u16)).to_le_bytes()); - z.extend_from_slice(&raw); - z.extend_from_slice(&adler32(&raw).to_be_bytes()); - chunk(&mut out, b"IDAT", &z); - chunk(&mut out, b"IEND", &[]); - out + TRANSPARENT_1X1.to_vec() } #[cfg(test)] mod tests { + #![allow(clippy::unwrap_used)] + #[test] - fn crc_known() { - assert_eq!(super::crc32(b"IEND"), 0xAE42_6082); - assert!(super::transparent_1x1().starts_with(b"\x89PNG")); + fn placeholder_is_a_transparent_1x1_png() { + let png = super::transparent_1x1(); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + // IHDR: 1×1, 8-bit RGBA, no interlace. + assert_eq!(&png[12..16], b"IHDR"); + assert_eq!(&png[16..29], &[0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]); + assert!(png.ends_with(b"IEND\xAE\x42\x60\x82")); + // The stored scanline: filter byte 0, then one pixel with zero alpha. + assert_eq!(&png[49..54], &[0, 0, 0, 0, 0]); } } From f5f106d6940510d7f498dade3a31709d64cd91e1 Mon Sep 17 00:00:00 2001 From: Naseq Date: Mon, 16 Nov 2026 14:34:13 +0430 Subject: [PATCH 60/76] ROADMAP: fold the #2025 status into the current line; rows in date order (review) --- ROADMAP.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 5f7d8e479..d8d9c527e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,8 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-11 · **Change:** minor (empty notes slides are preserved through PPTX and native saves rather than dropped, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) -> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** trivial (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-14 · **Change:** minor (a slide the show advances to again plays its animations again, #2090; slide-list entries with missing relationships are reported as lost slides and open as repaired copies; the Opus decoder and the Ogg, MP4 and Matroska demuxers come from craft-libs; empty notes slides are kept through PPTX and native saves, #2025; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -155,8 +154,8 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| -| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips | | 2026-11-14 | Slide show: a slide the show advances to again (click, →, Space, automatic advance or a loop) starts over, so its animations play again, as in PowerPoint. Back and links still show it as it was left (#2090) | +| 2026-11-11 | PPTX: a slide whose notes slide has empty text retains its notesSlide part and relationship on save and reopen (#2025); empty notes slides survive native round trips | | 2026-11-11 | Media: the Opus decoder and the Ogg, MP4/MOV and Matroska demuxers are craft-audio and craft-media from craft-libs; DeckCraft's own copies and re-export crates are removed | | 2026-11-07 | PPTX slide-list entries with missing relationships are reported in lostSlides instead of silently omitted. The engine opens the partial deck as a repaired copy with no original save path. Slide lists over 10,000 entries are explicitly refused before a partial load; exactly 10,000 remain supported. Synthetic 13-slide regression; does not establish the cause of #1910's field report. | | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | @@ -345,8 +344,8 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| -| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged | | 2026-11-14 | trivial | Progress log: a slide the show advances to again plays its animations again (#2090); parity scores unchanged | +| 2026-11-11 | minor | Progress log: empty notes slides preserved on PPTX/native save (#2025); parity scores unchanged | | 2026-11-11 | trivial | Opus and container code moved to craft-libs crates; parity scores unchanged | | 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged | | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | From dea0af6cebd25af8959cd5d5a59450accb2b98d8 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:33:00 +0100 Subject: [PATCH 61/76] color: DrawingML colours come from craft-drawingml (craft-libs#778, #792) deckcraft-color re-exports craft_drawingml::color (Rgba, SchemeSlot, ColorScheme, ColorTransform, presets and transforms) and its own copy is deleted. The existing colour tests run unchanged against the shared module. ColorScheme literals use ColorScheme::new, since the shared scheme also keeps extra colours and tint rows. --- Cargo.lock | 27 +- Cargo.toml | 2 + crates/color/Cargo.toml | 2 +- crates/color/src/lib.rs | 758 +-------------------------------- crates/model/src/theme.rs | 4 +- crates/pptx/src/read/theme.rs | 2 +- crates/render/src/text_draw.rs | 2 +- 7 files changed, 36 insertions(+), 761 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f1bc8b16c..4afd5b8c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -880,6 +880,17 @@ dependencies = [ "zip 9.1.0", ] +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", + "kurbo", + "log", + "serde", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -942,7 +953,7 @@ name = "craft-opc" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10#ea24422ae9859dc5da398d0462bc87f8e02e0d10" dependencies = [ - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "log", "thiserror 2.0.21", @@ -1043,6 +1054,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b#44d83fa8f635333dcb3c231f87381387a1f5631b" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1188,7 +1209,7 @@ dependencies = [ name = "deckcraft-color" version = "0.19.0" dependencies = [ - "serde", + "craft-drawingml", ] [[package]] @@ -1308,7 +1329,7 @@ version = "0.19.0" dependencies = [ "craft-cfb", "craft-opc", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "deckcraft-color", "deckcraft-engine", "deckcraft-geom", diff --git a/Cargo.toml b/Cargo.toml index 0dab1e523..bcb704a2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,8 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9 craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # XML writer primitives; parser admission and OOXML policy stay app-local. craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } +# DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes. +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } deckcraft-color = { path = "crates/color" } diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 9d5a5521f..380ebab9e 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,4 +9,4 @@ description = "DeckCraft colour: RGB/HSL, theme colour slots, DrawingML-style co workspace = true [dependencies] -serde = { workspace = true } +craft-drawingml = { workspace = true } diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 3d42aca9a..0d10484e5 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -1,758 +1,10 @@ -//! DeckCraft colour: sRGB colours, theme colour slots and DrawingML-style colour transforms -//! (tint, shade, luminance modulation/offset, alpha…), so theme-relative colours resolve the way -//! presentation files expect. +//! DrawingML colours for DeckCraft: `Rgba`, scheme slots, colour schemes and colour transforms. +//! They live in craft-libs (`craft_drawingml::color`, craft-libs#778 and #792), shared with the +//! PPTX reader and writer; this crate re-exports them under the name the app uses. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -use serde::{Deserialize, Serialize}; - -/// An sRGB colour with straight alpha, components 0–255. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Rgba { - pub r: u8, - pub g: u8, - pub b: u8, - pub a: u8, -} - -impl Default for Rgba { - fn default() -> Self { - Rgba::BLACK - } -} - -impl Rgba { - pub const BLACK: Rgba = Rgba::rgb(0, 0, 0); - pub const WHITE: Rgba = Rgba::rgb(255, 255, 255); - pub const TRANSPARENT: Rgba = Rgba { r: 0, g: 0, b: 0, a: 0 }; - - pub const fn rgb(r: u8, g: u8, b: u8) -> Self { - Rgba { r, g, b, a: 255 } - } - pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self { - Rgba { r, g, b, a } - } - /// `RRGGBB` or `#RRGGBB` (also `RRGGBBAA`). - pub fn from_hex(s: &str) -> Option { - let s = s.trim(); - let s = s.strip_prefix('#').unwrap_or(s); - if !s.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); - match s.len() { - 6 => Some(Rgba::rgb(byte(0)?, byte(2)?, byte(4)?)), - 8 => Some(Rgba::rgba(byte(0)?, byte(2)?, byte(4)?, byte(6)?)), - 3 => { - let n = |i: usize| s.get(i..i + 1).and_then(|h| u8::from_str_radix(h, 16).ok()).map(|v| v * 17); - Some(Rgba::rgb(n(0)?, n(1)?, n(2)?)) - } - _ => None, - } - } - /// `RRGGBB` uppercase (no alpha). - pub fn hex(&self) -> String { - format!("{:02X}{:02X}{:02X}", self.r, self.g, self.b) - } - pub fn with_alpha(self, a: u8) -> Self { - Rgba { a, ..self } - } - pub fn to_f32(self) -> [f32; 4] { - [self.r as f32 / 255.0, self.g as f32 / 255.0, self.b as f32 / 255.0, self.a as f32 / 255.0] - } - pub fn from_f64(r: f64, g: f64, b: f64, a: f64) -> Self { - let c = |v: f64| if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } else { 0 }; - Rgba { r: c(r), g: c(g), b: c(b), a: c(a) } - } - /// Relative luminance (WCAG), 0–1. - pub fn luminance(self) -> f64 { - let lin = |c: u8| { - let v = c as f64 / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * lin(self.r) + 0.7152 * lin(self.g) + 0.0722 * lin(self.b) - } - /// WCAG contrast ratio between two colours (1–21). - pub fn contrast(self, other: Rgba) -> f64 { - let (a, b) = (self.luminance(), other.luminance()); - let (hi, lo) = if a > b { (a, b) } else { (b, a) }; - (hi + 0.05) / (lo + 0.05) - } - pub fn to_hsl(self) -> (f64, f64, f64) { - let r = self.r as f64 / 255.0; - let g = self.g as f64 / 255.0; - let b = self.b as f64 / 255.0; - let max = r.max(g).max(b); - let min = r.min(g).min(b); - let l = (max + min) / 2.0; - if (max - min).abs() < 1e-12 { - return (0.0, 0.0, l); - } - let d = max - min; - let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; - let h = if (max - r).abs() < 1e-12 { - (g - b) / d + if g < b { 6.0 } else { 0.0 } - } else if (max - g).abs() < 1e-12 { - (b - r) / d + 2.0 - } else { - (r - g) / d + 4.0 - }; - (h * 60.0, s, l) - } - pub fn from_hsl(h: f64, s: f64, l: f64, a: u8) -> Self { - let h = ((h % 360.0) + 360.0) % 360.0 / 360.0; - let s = s.clamp(0.0, 1.0); - let l = l.clamp(0.0, 1.0); - if s == 0.0 { - return Rgba::from_f64(l, l, l, a as f64 / 255.0); - } - let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; - let p = 2.0 * l - q; - let f = |t: f64| { - let t = if t < 0.0 { - t + 1.0 - } else if t > 1.0 { - t - 1.0 - } else { - t - }; - if t < 1.0 / 6.0 { - p + (q - p) * 6.0 * t - } else if t < 0.5 { - q - } else if t < 2.0 / 3.0 { - p + (q - p) * (2.0 / 3.0 - t) * 6.0 - } else { - p - } - }; - Rgba::from_f64(f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0), a as f64 / 255.0) - } - /// Linear interpolation (straight alpha). - pub fn lerp(self, o: Rgba, t: f64) -> Rgba { - let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; - let m = |a: u8, b: u8| (a as f64 + (b as f64 - a as f64) * t).round().clamp(0.0, 255.0) as u8; - Rgba { r: m(self.r, o.r), g: m(self.g, o.g), b: m(self.b, o.b), a: m(self.a, o.a) } - } -} - -/// The twelve theme colour slots, plus the mapped aliases (`bg1`, `tx1`…) and `phClr` (the -/// placeholder colour a style matrix entry is applied with). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum SchemeSlot { - Dk1, - Lt1, - Dk2, - Lt2, - Accent1, - Accent2, - Accent3, - Accent4, - Accent5, - Accent6, - Hlink, - FolHlink, - Bg1, - Tx1, - Bg2, - Tx2, - PhClr, -} - -impl SchemeSlot { - pub const THEME: [SchemeSlot; 12] = [ - SchemeSlot::Dk1, - SchemeSlot::Lt1, - SchemeSlot::Dk2, - SchemeSlot::Lt2, - SchemeSlot::Accent1, - SchemeSlot::Accent2, - SchemeSlot::Accent3, - SchemeSlot::Accent4, - SchemeSlot::Accent5, - SchemeSlot::Accent6, - SchemeSlot::Hlink, - SchemeSlot::FolHlink, - ]; - pub fn xml_name(self) -> &'static str { - match self { - SchemeSlot::Dk1 => "dk1", - SchemeSlot::Lt1 => "lt1", - SchemeSlot::Dk2 => "dk2", - SchemeSlot::Lt2 => "lt2", - SchemeSlot::Accent1 => "accent1", - SchemeSlot::Accent2 => "accent2", - SchemeSlot::Accent3 => "accent3", - SchemeSlot::Accent4 => "accent4", - SchemeSlot::Accent5 => "accent5", - SchemeSlot::Accent6 => "accent6", - SchemeSlot::Hlink => "hlink", - SchemeSlot::FolHlink => "folHlink", - SchemeSlot::Bg1 => "bg1", - SchemeSlot::Tx1 => "tx1", - SchemeSlot::Bg2 => "bg2", - SchemeSlot::Tx2 => "tx2", - SchemeSlot::PhClr => "phClr", - } - } - pub fn from_xml(s: &str) -> Option { - Some(match s { - "dk1" => SchemeSlot::Dk1, - "lt1" => SchemeSlot::Lt1, - "dk2" => SchemeSlot::Dk2, - "lt2" => SchemeSlot::Lt2, - "accent1" => SchemeSlot::Accent1, - "accent2" => SchemeSlot::Accent2, - "accent3" => SchemeSlot::Accent3, - "accent4" => SchemeSlot::Accent4, - "accent5" => SchemeSlot::Accent5, - "accent6" => SchemeSlot::Accent6, - "hlink" => SchemeSlot::Hlink, - "folHlink" => SchemeSlot::FolHlink, - "bg1" => SchemeSlot::Bg1, - "tx1" => SchemeSlot::Tx1, - "bg2" => SchemeSlot::Bg2, - "tx2" => SchemeSlot::Tx2, - "phClr" => SchemeSlot::PhClr, - _ => return None, - }) - } - pub fn label(self) -> &'static str { - match self { - SchemeSlot::Dk1 | SchemeSlot::Tx1 => "Text/Background - Dark 1", - SchemeSlot::Lt1 | SchemeSlot::Bg1 => "Text/Background - Light 1", - SchemeSlot::Dk2 | SchemeSlot::Tx2 => "Text/Background - Dark 2", - SchemeSlot::Lt2 | SchemeSlot::Bg2 => "Text/Background - Light 2", - SchemeSlot::Accent1 => "Accent 1", - SchemeSlot::Accent2 => "Accent 2", - SchemeSlot::Accent3 => "Accent 3", - SchemeSlot::Accent4 => "Accent 4", - SchemeSlot::Accent5 => "Accent 5", - SchemeSlot::Accent6 => "Accent 6", - SchemeSlot::Hlink => "Hyperlink", - SchemeSlot::FolHlink => "Followed Hyperlink", - SchemeSlot::PhClr => "Placeholder colour", - } - } -} - -/// A colour scheme: the twelve theme colours. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ColorScheme { - pub name: String, - pub colors: [Rgba; 12], -} - -impl ColorScheme { - pub fn get(&self, slot: SchemeSlot) -> Rgba { - let i = match slot { - SchemeSlot::Dk1 | SchemeSlot::Tx1 => 0, - SchemeSlot::Lt1 | SchemeSlot::Bg1 => 1, - SchemeSlot::Dk2 | SchemeSlot::Tx2 => 2, - SchemeSlot::Lt2 | SchemeSlot::Bg2 => 3, - SchemeSlot::Accent1 => 4, - SchemeSlot::Accent2 => 5, - SchemeSlot::Accent3 => 6, - SchemeSlot::Accent4 => 7, - SchemeSlot::Accent5 => 8, - SchemeSlot::Accent6 => 9, - SchemeSlot::Hlink => 10, - SchemeSlot::FolHlink => 11, - SchemeSlot::PhClr => 4, - }; - self.colors.get(i).copied().unwrap_or(Rgba::BLACK) - } - pub fn set(&mut self, slot: SchemeSlot, c: Rgba) { - if let Some(i) = SchemeSlot::THEME.iter().position(|s| *s == slot) - && let Some(v) = self.colors.get_mut(i) - { - *v = c; - } - } -} - -/// One colour transform, in file units (percentages ×1000, angles ×60000), applied in order. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", tag = "op", content = "val")] -pub enum ColorTransform { - Tint(i32), - Shade(i32), - LumMod(i32), - LumOff(i32), - SatMod(i32), - SatOff(i32), - HueMod(i32), - HueOff(i32), - Alpha(i32), - AlphaMod(i32), - AlphaOff(i32), - Comp, - Inv, - Gray, - RedMod(i32), - GreenMod(i32), - BlueMod(i32), -} - -impl ColorTransform { - pub fn xml_name(&self) -> &'static str { - match self { - ColorTransform::Tint(_) => "tint", - ColorTransform::Shade(_) => "shade", - ColorTransform::LumMod(_) => "lumMod", - ColorTransform::LumOff(_) => "lumOff", - ColorTransform::SatMod(_) => "satMod", - ColorTransform::SatOff(_) => "satOff", - ColorTransform::HueMod(_) => "hueMod", - ColorTransform::HueOff(_) => "hueOff", - ColorTransform::Alpha(_) => "alpha", - ColorTransform::AlphaMod(_) => "alphaMod", - ColorTransform::AlphaOff(_) => "alphaOff", - ColorTransform::Comp => "comp", - ColorTransform::Inv => "inv", - ColorTransform::Gray => "gray", - ColorTransform::RedMod(_) => "redMod", - ColorTransform::GreenMod(_) => "greenMod", - ColorTransform::BlueMod(_) => "blueMod", - } - } - pub fn value(&self) -> Option { - match *self { - ColorTransform::Tint(v) - | ColorTransform::Shade(v) - | ColorTransform::LumMod(v) - | ColorTransform::LumOff(v) - | ColorTransform::SatMod(v) - | ColorTransform::SatOff(v) - | ColorTransform::HueMod(v) - | ColorTransform::HueOff(v) - | ColorTransform::Alpha(v) - | ColorTransform::AlphaMod(v) - | ColorTransform::AlphaOff(v) - | ColorTransform::RedMod(v) - | ColorTransform::GreenMod(v) - | ColorTransform::BlueMod(v) => Some(v), - _ => None, - } - } - pub fn from_xml(name: &str, val: Option) -> Option { - let v = val.unwrap_or(0); - Some(match name { - "tint" => ColorTransform::Tint(v), - "shade" => ColorTransform::Shade(v), - "lumMod" => ColorTransform::LumMod(v), - "lumOff" => ColorTransform::LumOff(v), - "satMod" => ColorTransform::SatMod(v), - "satOff" => ColorTransform::SatOff(v), - "hueMod" => ColorTransform::HueMod(v), - "hueOff" => ColorTransform::HueOff(v), - "alpha" => ColorTransform::Alpha(v), - "alphaMod" => ColorTransform::AlphaMod(v), - "alphaOff" => ColorTransform::AlphaOff(v), - "comp" => ColorTransform::Comp, - "inv" => ColorTransform::Inv, - "gray" => ColorTransform::Gray, - "redMod" => ColorTransform::RedMod(v), - "greenMod" => ColorTransform::GreenMod(v), - "blueMod" => ColorTransform::BlueMod(v), - _ => return None, - }) - } -} - -/// Apply transforms to a base colour. -pub fn apply(base: Rgba, transforms: &[ColorTransform]) -> Rgba { - let mut c = base; - for t in transforms { - c = apply_one(c, *t); - } - c -} - -fn pct(v: i32) -> f64 { - v as f64 / 100_000.0 -} - -fn apply_one(c: Rgba, t: ColorTransform) -> Rgba { - match t { - // tint: towards white by (1 - value); shade: towards black by (1 - value). Office applies - // these in linear light, which keeps mid-tones from washing out. - ColorTransform::Tint(v) => { - let k = pct(v).clamp(0.0, 1.0); - map_linear(c, |x| x * k + (1.0 - k)) - } - ColorTransform::Shade(v) => { - let k = pct(v).clamp(0.0, 1.0); - map_linear(c, |x| x * k) - } - ColorTransform::LumMod(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h, s, l * pct(v), c.a) - } - ColorTransform::LumOff(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h, s, l + pct(v), c.a) - } - ColorTransform::SatMod(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h, s * pct(v), l, c.a) - } - ColorTransform::SatOff(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h, s + pct(v), l, c.a) - } - ColorTransform::HueMod(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h * pct(v), s, l, c.a) - } - ColorTransform::HueOff(v) => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h + v as f64 / 60_000.0, s, l, c.a) - } - ColorTransform::Alpha(v) => c.with_alpha((pct(v).clamp(0.0, 1.0) * 255.0).round() as u8), - ColorTransform::AlphaMod(v) => c.with_alpha((c.a as f64 * pct(v)).round().clamp(0.0, 255.0) as u8), - ColorTransform::AlphaOff(v) => c.with_alpha((c.a as f64 + pct(v) * 255.0).round().clamp(0.0, 255.0) as u8), - ColorTransform::Comp => { - let (h, s, l) = c.to_hsl(); - Rgba::from_hsl(h + 180.0, s, l, c.a) - } - ColorTransform::Inv => Rgba { r: 255 - c.r, g: 255 - c.g, b: 255 - c.b, a: c.a }, - ColorTransform::Gray => { - let y = (0.299 * c.r as f64 + 0.587 * c.g as f64 + 0.114 * c.b as f64).round().clamp(0.0, 255.0) as u8; - Rgba { r: y, g: y, b: y, a: c.a } - } - ColorTransform::RedMod(v) => Rgba { r: (c.r as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c }, - ColorTransform::GreenMod(v) => Rgba { g: (c.g as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c }, - ColorTransform::BlueMod(v) => Rgba { b: (c.b as f64 * pct(v)).round().clamp(0.0, 255.0) as u8, ..c }, - } -} - -fn to_lin(v: u8) -> f64 { - let v = v as f64 / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} -fn from_lin(v: f64) -> f64 { - let v = v.clamp(0.0, 1.0); - if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } -} -fn map_linear(c: Rgba, f: impl Fn(f64) -> f64) -> Rgba { - Rgba::from_f64(from_lin(f(to_lin(c.r))), from_lin(f(to_lin(c.g))), from_lin(f(to_lin(c.b))), c.a as f64 / 255.0) -} - -/// The colour-picker grid shown under each theme colour: lighter 80/60/40%, darker 25/50% -/// (for dark colours: lighter 90/75/50/25/10%). -pub fn theme_variants(c: Rgba) -> [(Vec, &'static str); 5] { - let (_, _, l) = c.to_hsl(); - if l < 0.2 { - [ - (vec![ColorTransform::LumMod(10000), ColorTransform::LumOff(90000)], "Lighter 90%"), - (vec![ColorTransform::LumMod(25000), ColorTransform::LumOff(75000)], "Lighter 75%"), - (vec![ColorTransform::LumMod(50000), ColorTransform::LumOff(50000)], "Lighter 50%"), - (vec![ColorTransform::LumMod(75000), ColorTransform::LumOff(25000)], "Lighter 25%"), - (vec![ColorTransform::LumMod(90000), ColorTransform::LumOff(10000)], "Lighter 10%"), - ] - } else if l > 0.8 { - [ - (vec![ColorTransform::LumMod(95000)], "Darker 5%"), - (vec![ColorTransform::LumMod(85000)], "Darker 15%"), - (vec![ColorTransform::LumMod(75000)], "Darker 25%"), - (vec![ColorTransform::LumMod(65000)], "Darker 35%"), - (vec![ColorTransform::LumMod(50000)], "Darker 50%"), - ] - } else { - [ - (vec![ColorTransform::LumMod(20000), ColorTransform::LumOff(80000)], "Lighter 80%"), - (vec![ColorTransform::LumMod(40000), ColorTransform::LumOff(60000)], "Lighter 60%"), - (vec![ColorTransform::LumMod(60000), ColorTransform::LumOff(40000)], "Lighter 40%"), - (vec![ColorTransform::LumMod(75000)], "Darker 25%"), - (vec![ColorTransform::LumMod(50000)], "Darker 50%"), - ] - } -} - -/// Standard colours row of the colour picker. -pub const STANDARD_COLORS: [(Rgba, &str); 10] = [ - (Rgba::rgb(0xC0, 0x00, 0x00), "Dark Red"), - (Rgba::rgb(0xFF, 0x00, 0x00), "Red"), - (Rgba::rgb(0xFF, 0xC0, 0x00), "Orange"), - (Rgba::rgb(0xFF, 0xFF, 0x00), "Yellow"), - (Rgba::rgb(0x92, 0xD0, 0x50), "Light Green"), - (Rgba::rgb(0x00, 0xB0, 0x50), "Green"), - (Rgba::rgb(0x00, 0xB0, 0xF0), "Light Blue"), - (Rgba::rgb(0x00, 0x70, 0xC0), "Blue"), - (Rgba::rgb(0x00, 0x20, 0x60), "Dark Blue"), - (Rgba::rgb(0x70, 0x30, 0xA0), "Purple"), -]; - -/// A few CSS-like preset colour names (`prstClr`). -pub fn preset(name: &str) -> Option { - let c = match name { - "black" => (0, 0, 0), - "white" => (255, 255, 255), - "red" => (255, 0, 0), - "green" => (0, 128, 0), - "lime" => (0, 255, 0), - "blue" => (0, 0, 255), - "yellow" => (255, 255, 0), - "cyan" | "aqua" => (0, 255, 255), - "magenta" | "fuchsia" => (255, 0, 255), - "gray" | "grey" => (128, 128, 128), - "silver" => (192, 192, 192), - "maroon" => (128, 0, 0), - "navy" => (0, 0, 128), - "olive" => (128, 128, 0), - "purple" => (128, 0, 128), - "teal" => (0, 128, 128), - "orange" => (255, 165, 0), - "pink" => (255, 192, 203), - "brown" => (165, 42, 42), - "gold" => (255, 215, 0), - "ltGray" | "lightGray" => (211, 211, 211), - "dkGray" | "darkGray" => (169, 169, 169), - _ => return None, - }; - Some(Rgba::rgb(c.0, c.1, c.2)) -} - -/// Every preset colour name a file may write (`ST_PresetColorVal`, with the later editions' aliases). -pub const PRESET_NAMES: [&str; 190] = [ - "aliceBlue", - "antiqueWhite", - "aqua", - "aquamarine", - "azure", - "beige", - "bisque", - "black", - "blanchedAlmond", - "blue", - "blueViolet", - "brown", - "burlyWood", - "cadetBlue", - "chartreuse", - "chocolate", - "coral", - "cornflowerBlue", - "cornsilk", - "crimson", - "cyan", - "darkBlue", - "darkCyan", - "darkGoldenrod", - "darkGray", - "darkGrey", - "darkGreen", - "darkKhaki", - "darkMagenta", - "darkOliveGreen", - "darkOrange", - "darkOrchid", - "darkRed", - "darkSalmon", - "darkSeaGreen", - "darkSlateBlue", - "darkSlateGray", - "darkSlateGrey", - "darkTurquoise", - "darkViolet", - "dkBlue", - "dkCyan", - "dkGoldenrod", - "dkGray", - "dkGrey", - "dkGreen", - "dkKhaki", - "dkMagenta", - "dkOliveGreen", - "dkOrange", - "dkOrchid", - "dkRed", - "dkSalmon", - "dkSeaGreen", - "dkSlateBlue", - "dkSlateGray", - "dkSlateGrey", - "dkTurquoise", - "dkViolet", - "deepPink", - "deepSkyBlue", - "dimGray", - "dimGrey", - "dodgerBlue", - "firebrick", - "floralWhite", - "forestGreen", - "fuchsia", - "gainsboro", - "ghostWhite", - "gold", - "goldenrod", - "gray", - "grey", - "green", - "greenYellow", - "honeydew", - "hotPink", - "indianRed", - "indigo", - "ivory", - "khaki", - "lavender", - "lavenderBlush", - "lawnGreen", - "lemonChiffon", - "lightBlue", - "lightCoral", - "lightCyan", - "lightGoldenrodYellow", - "lightGray", - "lightGrey", - "lightGreen", - "lightPink", - "lightSalmon", - "lightSeaGreen", - "lightSkyBlue", - "lightSlateGray", - "lightSlateGrey", - "lightSteelBlue", - "lightYellow", - "ltBlue", - "ltCoral", - "ltCyan", - "ltGoldenrodYellow", - "ltGray", - "ltGrey", - "ltGreen", - "ltPink", - "ltSalmon", - "ltSeaGreen", - "ltSkyBlue", - "ltSlateGray", - "ltSlateGrey", - "ltSteelBlue", - "ltYellow", - "lime", - "limeGreen", - "linen", - "magenta", - "maroon", - "medAquamarine", - "medBlue", - "medOrchid", - "medPurple", - "medSeaGreen", - "medSlateBlue", - "medSpringGreen", - "medTurquoise", - "medVioletRed", - "mediumAquamarine", - "mediumBlue", - "mediumOrchid", - "mediumPurple", - "mediumSeaGreen", - "mediumSlateBlue", - "mediumSpringGreen", - "mediumTurquoise", - "mediumVioletRed", - "midnightBlue", - "mintCream", - "mistyRose", - "moccasin", - "navajoWhite", - "navy", - "oldLace", - "olive", - "oliveDrab", - "orange", - "orangeRed", - "orchid", - "paleGoldenrod", - "paleGreen", - "paleTurquoise", - "paleVioletRed", - "papayaWhip", - "peachPuff", - "peru", - "pink", - "plum", - "powderBlue", - "purple", - "red", - "rosyBrown", - "royalBlue", - "saddleBrown", - "salmon", - "sandyBrown", - "seaGreen", - "seaShell", - "sienna", - "silver", - "skyBlue", - "slateBlue", - "slateGray", - "slateGrey", - "snow", - "springGreen", - "steelBlue", - "tan", - "teal", - "thistle", - "tomato", - "turquoise", - "violet", - "wheat", - "white", - "whiteSmoke", - "yellow", - "yellowGreen", -]; - -/// Every system colour name a file may write (`ST_SystemColorVal`). -pub const SYSTEM_NAMES: [&str; 30] = [ - "scrollBar", - "background", - "activeCaption", - "inactiveCaption", - "menu", - "window", - "windowFrame", - "menuText", - "windowText", - "captionText", - "activeBorder", - "inactiveBorder", - "appWorkspace", - "highlight", - "highlightText", - "btnFace", - "btnShadow", - "grayText", - "btnText", - "inactiveCaptionText", - "btnHighlight", - "3dDkShadow", - "3dLight", - "infoText", - "infoBk", - "hotLight", - "gradientActiveCaption", - "gradientInactiveCaption", - "menuHighlight", - "menuBar", -]; - -/// Whether `name` is a preset colour name a file may write. -pub fn is_preset_name(name: &str) -> bool { - PRESET_NAMES.contains(&name) -} - -/// Whether `name` is a system colour name a file may write. -pub fn is_system_name(name: &str) -> bool { - SYSTEM_NAMES.contains(&name) -} +pub use craft_drawingml::color::*; #[cfg(test)] mod tests { @@ -820,7 +72,7 @@ mod tests { #[test] fn scheme_slots() { - let mut s = ColorScheme { name: "t".into(), colors: [Rgba::BLACK; 12] }; + let mut s = ColorScheme::new("t", [Rgba::BLACK; 12]); s.set(SchemeSlot::Accent3, Rgba::WHITE); assert_eq!(s.get(SchemeSlot::Accent3), Rgba::WHITE); assert_eq!(s.get(SchemeSlot::Tx1), Rgba::BLACK); diff --git a/crates/model/src/theme.rs b/crates/model/src/theme.rs index 5087f3ea4..d0f76b186 100644 --- a/crates/model/src/theme.rs +++ b/crates/model/src/theme.rs @@ -69,7 +69,7 @@ impl Default for Theme { fn default() -> Self { builtin_themes().into_iter().next().unwrap_or_else(|| Theme { name: "DeckCraft".into(), - colors: ColorScheme { name: "DeckCraft".into(), colors: [Rgba::BLACK; 12] }, + colors: ColorScheme::new("DeckCraft", [Rgba::BLACK; 12]), fonts: FontScheme::default(), format: FormatScheme::default(), raw_extra: None, @@ -97,7 +97,7 @@ fn hex(s: &str) -> Rgba { } fn scheme(name: &str, c: [&str; 12]) -> ColorScheme { - ColorScheme { name: name.into(), colors: c.map(hex) } + ColorScheme::new(name, c.map(hex)) } fn ph() -> ColorRef { diff --git a/crates/pptx/src/read/theme.rs b/crates/pptx/src/read/theme.rs index 77a381597..d5ca8df84 100644 --- a/crates/pptx/src/read/theme.rs +++ b/crates/pptx/src/read/theme.rs @@ -28,7 +28,7 @@ pub fn read_theme(imp: &mut Imp, part: &Part, root: &El) -> Theme { let mut t = Theme { name: root.attr("name").unwrap_or("Theme").to_string(), ..Default::default() }; let Some(te) = root.child("themeElements") else { return t }; if let Some(cs) = te.child("clrScheme") { - let mut scheme = ColorScheme { name: cs.attr("name").unwrap_or("").to_string(), colors: t.colors.colors }; + let mut scheme = ColorScheme::new(cs.attr("name").unwrap_or("").to_string(), t.colors.colors); for slot in SchemeSlot::THEME { if let Some(c) = cs.child(slot.xml_name()).and_then(dml::color) { let rgb = match c.base { diff --git a/crates/render/src/text_draw.rs b/crates/render/src/text_draw.rs index d9788a4a9..9470a76de 100644 --- a/crates/render/src/text_draw.rs +++ b/crates/render/src/text_draw.rs @@ -155,7 +155,7 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, }; let li = lines_of.line_at(run.para, *y); if !grads.iter().any(|(i, _)| *i == li) { - let scheme = deckcraft_color::ColorScheme { name: String::new(), colors: [Rgba::BLACK; 12] }; + let scheme = deckcraft_color::ColorScheme::new(String::new(), [Rgba::BLACK; 12]); let stops = g.stops.iter().map(|s| (s.pos, s.color.resolve(&scheme, None))).collect(); let bounds = l.lines.get(li).and_then(line_bounds).unwrap_or(tr); grads.push((li, paint::gradient(&g.shape, stops, bounds, run.alpha * ps.opacity))); From 7e1d6925ece28f901adae3583e2fc9c64edff0fd Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:45:15 +0100 Subject: [PATCH 62/76] geom: placement, preset and warp geometry come from craft-drawingml (craft-libs#778, #792) deckcraft-geom re-exports craft_drawingml's Xfrm, EMU units, group_child_affine, preset and warp, and deletes its copies (preset/, warp.rs). The shared versions add Xfrm::from_affine, preset text rectangles, separate bentConnector4/5 and curvedConnector4/5 outlines with their own default adjustments, and smoother follow-path warps. App-only geometry (Unit, morph, squircle, hit testing, snapping) stays. --- Cargo.lock | 1 + crates/geom/Cargo.toml | 1 + crates/geom/src/lib.rs | 98 +-- crates/geom/src/preset.rs | 24 - crates/geom/src/preset/build.rs | 1204 ----------------------------- crates/geom/src/preset/builder.rs | 344 --------- crates/geom/src/preset/catalog.rs | 391 ---------- crates/geom/src/preset/extra.rs | 799 ------------------- crates/geom/src/preset/shapes.rs | 375 --------- crates/geom/src/preset/tests.rs | 420 ---------- crates/geom/src/warp.rs | 1023 ------------------------ crates/geom/src/warp/tests.rs | 338 -------- 12 files changed, 5 insertions(+), 5013 deletions(-) delete mode 100644 crates/geom/src/preset.rs delete mode 100644 crates/geom/src/preset/build.rs delete mode 100644 crates/geom/src/preset/builder.rs delete mode 100644 crates/geom/src/preset/catalog.rs delete mode 100644 crates/geom/src/preset/extra.rs delete mode 100644 crates/geom/src/preset/shapes.rs delete mode 100644 crates/geom/src/preset/tests.rs delete mode 100644 crates/geom/src/warp.rs delete mode 100644 crates/geom/src/warp/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 4afd5b8c4..56e5fbf5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1266,6 +1266,7 @@ dependencies = [ name = "deckcraft-geom" version = "0.19.0" dependencies = [ + "craft-drawingml", "kurbo", "serde", ] diff --git a/crates/geom/Cargo.toml b/crates/geom/Cargo.toml index b648d9e87..f0e6d13f6 100644 --- a/crates/geom/Cargo.toml +++ b/crates/geom/Cargo.toml @@ -9,5 +9,6 @@ description = "DeckCraft geometry: units (EMU/pt), transforms, preset shape gene workspace = true [dependencies] +craft-drawingml = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index a08bed987..5a302f24f 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -7,39 +7,14 @@ #![forbid(unsafe_code)] pub mod morph; -pub mod preset; pub mod squircle; -pub mod warp; pub use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as KurboShape, Size, Vec2}; +// Placement, units and preset and warp geometry are DrawingML's, shared in craft-libs +// (`craft_drawingml`, craft-libs#778 and #792). +pub use craft_drawingml::{EMU_PER_CM, EMU_PER_IN, EMU_PER_PT, Xfrm, emu_to_pt, group_child_affine, preset, pt_to_emu, warp}; use serde::{Deserialize, Serialize}; -/// EMU per point. -pub const EMU_PER_PT: f64 = 12_700.0; -/// EMU per inch. -pub const EMU_PER_IN: f64 = 914_400.0; -/// EMU per centimetre. -pub const EMU_PER_CM: f64 = 360_000.0; - -pub fn emu_to_pt(emu: i64) -> f64 { - emu as f64 / EMU_PER_PT -} - -/// Points to EMU, rounded. Non-finite input becomes 0; huge values saturate. -pub fn pt_to_emu(pt: f64) -> i64 { - if !pt.is_finite() { - return 0; - } - let v = (pt * EMU_PER_PT).round(); - if v >= i64::MAX as f64 { - i64::MAX - } else if v <= i64::MIN as f64 { - i64::MIN - } else { - v as i64 - } -} - /// Display units for measurements (inches on US English systems, centimetres elsewhere). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -101,73 +76,6 @@ fn split_number(t: &str) -> Option<(f64, &str)> { Some((n, t.get(end..).unwrap_or(""))) } -/// A shape's placement on its slide (or in its group's child space): offset, extent, rotation -/// (degrees clockwise) and flips. Rotation and flips are about the centre. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -pub struct Xfrm { - pub x: f64, - pub y: f64, - pub w: f64, - pub h: f64, - #[serde(skip_serializing_if = "is_zero")] - pub rot: f64, - #[serde(skip_serializing_if = "std::ops::Not::not")] - pub flip_h: bool, - #[serde(skip_serializing_if = "std::ops::Not::not")] - pub flip_v: bool, -} - -fn is_zero(v: &f64) -> bool { - *v == 0.0 -} - -impl Xfrm { - pub fn new(x: f64, y: f64, w: f64, h: f64) -> Self { - Xfrm { x, y, w, h, ..Default::default() } - } - pub fn rect(&self) -> Rect { - Rect::new(self.x, self.y, self.x + self.w, self.y + self.h) - } - pub fn center(&self) -> Point { - Point::new(self.x + self.w / 2.0, self.y + self.h / 2.0) - } - /// Local shape space (0..w, 0..h) → parent space, applying flips and rotation about the centre. - pub fn affine(&self) -> Affine { - let c = Vec2::new(self.w / 2.0, self.h / 2.0); - let sx = if self.flip_h { -1.0 } else { 1.0 }; - let sy = if self.flip_v { -1.0 } else { 1.0 }; - Affine::translate(Vec2::new(self.x, self.y) + c) - * Affine::rotate(self.rot.to_radians()) - * Affine::scale_non_uniform(sx, sy) - * Affine::translate(-c) - } - /// Axis-aligned bounds of the rotated box in parent space. - pub fn bounds(&self) -> Rect { - let a = self.affine(); - let pts = [Point::new(0.0, 0.0), Point::new(self.w, 0.0), Point::new(self.w, self.h), Point::new(0.0, self.h)].map(|p| a * p); - let mut r = Rect::from_points(pts[0], pts[1]); - r = r.union_pt(pts[2]).union_pt(pts[3]); - r - } - /// True when no dimension is NaN/inf. - pub fn is_finite(&self) -> bool { - [self.x, self.y, self.w, self.h, self.rot].iter().all(|v| v.is_finite()) - } - /// Rotation normalised to 0..360. - pub fn rot_norm(&self) -> f64 { - let r = self.rot.rem_euclid(360.0); - if r >= 360.0 { 0.0 } else { r } - } -} - -/// Maps a group's child coordinate space (`ch_off`, `ch_ext`) onto the group's own box. -pub fn group_child_affine(group: &Xfrm, ch: Rect) -> Affine { - let sx = if ch.width().abs() > 1e-9 { group.w / ch.width() } else { 1.0 }; - let sy = if ch.height().abs() > 1e-9 { group.h / ch.height() } else { 1.0 }; - group.affine() * Affine::scale_non_uniform(sx, sy) * Affine::translate(-ch.origin().to_vec2()) -} - /// Distance from `p` to the segment `a`–`b`. pub fn dist_to_segment(p: Point, a: Point, b: Point) -> f64 { let ab = b - a; diff --git a/crates/geom/src/preset.rs b/crates/geom/src/preset.rs deleted file mode 100644 index 3e3b5af5a..000000000 --- a/crates/geom/src/preset.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Preset shape geometry. -//! -//! Each preset is identified by its Office Open XML name (`rect`, `roundRect`, `rightArrow`…) so -//! files round-trip, but every outline here is our own construction in Rust: we re-derive the shapes -//! from what they look like and from the meaning of their adjust values, not from any reference -//! geometry table. Adjust values use the file convention: ratios in 1/100 000 of the shorter side (or -//! of the width/height), angles in 1/60 000 degree. - -use kurbo::{Arc, BezPath, Point, Rect, Vec2}; -use serde::{Deserialize, Serialize}; - -mod build; -mod builder; -mod catalog; -mod shapes; - -pub use build::build; -use builder::{Corner, Dir, Pb, corner_rect, fill, fill_eo, fill_only, mid_sites, orient, shade, simple, stroke_only, vis}; -pub use catalog::{CATALOG, Category, FillMode, Geometry, Handle, PresetInfo, SubPath, info, is_line_like, mitred_by_default}; - -mod extra; - -#[cfg(test)] -mod tests; diff --git a/crates/geom/src/preset/build.rs b/crates/geom/src/preset/build.rs deleted file mode 100644 index 95b833efd..000000000 --- a/crates/geom/src/preset/build.rs +++ /dev/null @@ -1,1204 +0,0 @@ -use super::builder::{ - Corner, Dir, Pb, arrow, corner_rect, double_arrow, ellipse_sites, fill, fill_eo, fill_only, len_thick, mid_sites, orient, polygon_regular, shade, - simple, spec_pts, star, star_text_rect, stroke_only, tip_handle, vis, -}; -use super::catalog::{FillMode, Geometry, Handle, info}; -use super::shapes::{action_button, cloud, math, ribbon, scroll, wedge_rect}; -use super::{Arc, BezPath, Point, Rect, Vec2, extra}; - -/// Size and adjust values shared by every preset-shape builder. -struct Ctx<'a> { - name: &'a str, - w: f64, - h: f64, - adj: &'a [f64], - defaults: &'a [f64], -} - -impl Ctx<'_> { - /// Adjust value `i`: the caller's value, else the preset default, else 0 (non-finite values become 0). - fn a(&self, i: usize) -> f64 { - let v = self.adj.get(i).copied().or_else(|| self.defaults.get(i).copied()).unwrap_or(0.0); - if v.is_finite() { v } else { 0.0 } - } -} - -/// Builds the geometry for preset `name` at size `w`×`h` with adjust values `adj` (missing -/// values use the preset's defaults). Unknown names return `None`; the caller falls back to `rect`. -pub fn build(name: &str, w: f64, h: f64, adj: &[f64]) -> Option { - if !(w.is_finite() && h.is_finite()) { - return None; - } - let defaults = info(name).map(|i| i.defaults).unwrap_or(&[]); - let c = Ctx { name, w: w.max(0.0), h: h.max(0.0), adj, defaults }; - rect_and_triangle_shapes(&c) - .or_else(|| polygon_and_symbol_shapes(&c)) - .or_else(|| bracket_and_arrow_shapes(&c)) - .or_else(|| flowchart_and_star_shapes(&c)) - .or_else(|| callout_wave_and_connector_shapes(&c)) - .or_else(|| extra::build(name, c.w, c.h, &|i| c.a(i))) -} - -fn rect_and_triangle_shapes(c: &Ctx) -> Option { - let name = c.name; - let w = c.w; - let h = c.h; - let ss = c.w.min(c.h); - let full = Rect::new(0.0, 0.0, c.w, c.h); - let a = |i: usize| c.a(i); - let mut b = Pb::new(); - let g = match c.name { - "rect" | "textBox" | "flowChartProcess" => simple(corner_rect(w, h, [Corner::Square; 4]), full, w, h), - "actionButtonBlank" - | "actionButtonBackPrevious" - | "actionButtonForwardNext" - | "actionButtonBeginning" - | "actionButtonEnd" - | "actionButtonHome" - | "actionButtonInformation" - | "actionButtonReturn" - | "actionButtonMovie" - | "actionButtonDocument" - | "actionButtonSound" - | "actionButtonHelp" => action_button(name, w, h), - "roundRect" => { - let v = a(0).clamp(0.0, 50000.0); - let r = ss * v / 100000.0; - let mut g = simple(corner_rect(w, h, [Corner::Round(r); 4]), full.inset(-r * 0.29289), w, h); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "flowChartAlternateProcess" => simple(corner_rect(w, h, [Corner::Round(ss / 6.0); 4]), full.inset(-ss / 6.0 * 0.29289), w, h), - "snip1Rect" => { - let v = a(0).clamp(0.0, 50000.0); - let d = ss * v / 100000.0; - let mut g = simple( - corner_rect(w, h, [Corner::Square, Corner::Snip(d), Corner::Square, Corner::Square]), - Rect::new(0.0, d / 2.0, w - d / 2.0, h), - w, - h, - ); - g.handles.push(Handle::new(0, Point::new(w, 0.0), Vec2::new(-ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "snip2SameRect" => { - let (d1, d2) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple(corner_rect(w, h, [Corner::Snip(d1), Corner::Snip(d1), Corner::Snip(d2), Corner::Snip(d2)]), full.inset(-d1.max(d2) / 2.0), w, h) - } - "snip2DiagRect" => { - let (d1, d2) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple(corner_rect(w, h, [Corner::Snip(d1), Corner::Snip(d2), Corner::Snip(d1), Corner::Snip(d2)]), full.inset(-d1.max(d2) / 2.0), w, h) - } - "snipRoundRect" => { - let (r, d) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple(corner_rect(w, h, [Corner::Round(r), Corner::Snip(d), Corner::Square, Corner::Square]), full.inset(-r.max(d) / 2.0), w, h) - } - "round1Rect" => { - let r = ss * a(0).clamp(0.0, 50000.0) / 1e5; - simple(corner_rect(w, h, [Corner::Square, Corner::Round(r), Corner::Square, Corner::Square]), full.inset(-r * 0.29289), w, h) - } - "round2SameRect" => { - let (r1, r2) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple( - corner_rect(w, h, [Corner::Round(r1), Corner::Round(r1), Corner::Round(r2), Corner::Round(r2)]), - full.inset(-r1.max(r2) * 0.29289), - w, - h, - ) - } - "round2DiagRect" => { - let (r1, r2) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple( - corner_rect(w, h, [Corner::Round(r1), Corner::Round(r2), Corner::Round(r1), Corner::Round(r2)]), - full.inset(-r1.max(r2) * 0.29289), - w, - h, - ) - } - "ellipse" | "flowChartConnector" => { - let mut g = - simple(b.ellipse(w / 2.0, h / 2.0, w / 2.0, h / 2.0).take(), Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), w, h); - g.sites = ellipse_sites(w, h); - g - } - "triangle" | "flowChartExtract" => { - let v = if name == "triangle" { a(0).clamp(0.0, 100000.0) } else { 50000.0 }; - let ax = w * v / 100000.0; - let mut g = simple(b.poly(&[(0.0, h), (ax, 0.0), (w, h)]).take(), Rect::new(ax / 2.0, h / 2.0, (ax + w) / 2.0, h), w, h); - g.sites = vec![ - Point::new(ax, 0.0), - Point::new(ax / 2.0, h / 2.0), - Point::new(0.0, h), - Point::new(w / 2.0, h), - Point::new(w, h), - Point::new((ax + w) / 2.0, h / 2.0), - ]; - if name == "triangle" { - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(w / 100000.0, 0.0), v, 0.0, 100000.0)); - } - g - } - "flowChartMerge" => simple(b.poly(&[(0.0, 0.0), (w, 0.0), (w / 2.0, h)]).take(), Rect::new(w / 4.0, 0.0, w * 0.75, h / 2.0), w, h), - "rtTriangle" => { - simple(b.poly(&[(0.0, 0.0), (0.0, h), (w, h)]).take(), Rect::new(w / 12.0, h * 7.0 / 12.0, w * 7.0 / 12.0, h * 11.0 / 12.0), w, h) - } - "parallelogram" | "flowChartInputOutput" => { - let v = if name == "parallelogram" { a(0).clamp(0.0, 100000.0 * w / ss.max(1e-9)) } else { 20000.0 * w / ss.max(1e-9) }; - let off = ss * v / 100000.0; - let mut g = simple( - b.poly(&[(0.0, h), (off, 0.0), (w, 0.0), (w - off, h)]).take(), - Rect::new(off / 2.0 + off * 0.2, h * 0.08, w - off / 2.0 - off * 0.2, h * 0.92), - w, - h, - ); - if name == "parallelogram" { - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 100000.0 * w / ss.max(1e-9))); - } - g - } - "trapezoid" => { - let v = a(0).clamp(0.0, 50000.0 * w / ss.max(1e-9)); - let off = ss * v / 100000.0; - let mut g = - simple(b.poly(&[(0.0, h), (off, 0.0), (w - off, 0.0), (w, h)]).take(), Rect::new(off * 0.66, h * 0.2, w - off * 0.66, h), w, h); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0 * w / ss.max(1e-9))); - g - } - "flowChartManualOperation" => { - simple(b.poly(&[(0.0, 0.0), (w, 0.0), (w * 0.8, h), (w * 0.2, h)]).take(), Rect::new(w * 0.2, 0.0, w * 0.8, h), w, h) - } - "diamond" | "flowChartDecision" => simple( - b.poly(&[(w / 2.0, 0.0), (w, h / 2.0), (w / 2.0, h), (0.0, h / 2.0)]).take(), - Rect::new(w / 4.0, h / 4.0, w * 0.75, h * 0.75), - w, - h, - ), - "flowChartSort" => { - let d = b.poly(&[(w / 2.0, 0.0), (w, h / 2.0), (w / 2.0, h), (0.0, h / 2.0)]).take(); - let line = Pb::new().m(0.0, h / 2.0).l(w, h / 2.0).take(); - Geometry { - paths: vec![fill(d), stroke_only(line)], - text_rect: Rect::new(w / 4.0, h / 4.0, w * 0.75, h * 0.75), - handles: vec![], - sites: mid_sites(w, h), - } - } - _ => return None, - }; - Some(g) -} - -fn polygon_and_symbol_shapes(c: &Ctx) -> Option { - let name = c.name; - let w = c.w; - let h = c.h; - let ss = c.w.min(c.h); - let full = Rect::new(0.0, 0.0, c.w, c.h); - let a = |i: usize| c.a(i); - let mut b = Pb::new(); - let g = match c.name { - "pentagon" => simple(b.poly(&polygon_regular(5, w, h, -90.0)).take(), Rect::new(w * 0.2, h * 0.27, w * 0.8, h * 0.9), w, h), - "heptagon" => simple(b.poly(&polygon_regular(7, w, h, -90.0)).take(), Rect::new(w * 0.16, h * 0.2, w * 0.84, h * 0.86), w, h), - "decagon" => simple(b.poly(&polygon_regular(10, w, h, 0.0)).take(), Rect::new(w * 0.1, h * 0.17, w * 0.9, h * 0.83), w, h), - "dodecagon" => simple(b.poly(&polygon_regular(12, w, h, 15.0)).take(), Rect::new(w * 0.13, h * 0.13, w * 0.87, h * 0.87), w, h), - "hexagon" | "flowChartPreparation" => { - let v = if name == "hexagon" { a(0).clamp(0.0, 50000.0 * w / ss.max(1e-9)) } else { 20000.0 * w / ss.max(1e-9) }; - let off = ss * v / 100000.0; - let mut g = simple( - b.poly(&[(0.0, h / 2.0), (off, 0.0), (w - off, 0.0), (w, h / 2.0), (w - off, h), (off, h)]).take(), - Rect::new(off * 0.6, h * 0.14, w - off * 0.6, h * 0.86), - w, - h, - ); - if name == "hexagon" { - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0 * w / ss.max(1e-9))); - } - g - } - "octagon" => { - let v = a(0).clamp(0.0, 50000.0); - let d = ss * v / 100000.0; - let mut g = simple( - b.poly(&[(d, 0.0), (w - d, 0.0), (w, d), (w, h - d), (w - d, h), (d, h), (0.0, h - d), (0.0, d)]).take(), - full.inset(-d / 2.0), - w, - h, - ); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "plus" => { - let v = a(0).clamp(0.0, 50000.0); - let d = ss * v / 100000.0; - let mut g = simple( - b.poly(&[ - (d, 0.0), - (w - d, 0.0), - (w - d, d), - (w, d), - (w, h - d), - (w - d, h - d), - (w - d, h), - (d, h), - (d, h - d), - (0.0, h - d), - (0.0, d), - (d, d), - ]) - .take(), - Rect::new(0.0, d, w, h - d), - w, - h, - ); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "frame" => { - let v = a(0).clamp(0.0, 50000.0); - let t = ss * v / 100000.0; - b.poly(&[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)]); - b.poly(&[(t, t), (w - t, t), (w - t, h - t), (t, h - t)]); - let mut g = Geometry { paths: vec![fill_eo(b.take())], text_rect: full.inset(-t), handles: vec![], sites: mid_sites(w, h) }; - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "halfFrame" => { - let (t1, t2) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5); - simple(b.poly(&[(0.0, 0.0), (w, 0.0), (w - t1, t1), (t2, t1), (t2, h - t2), (0.0, h)]).take(), full, w, h) - } - "corner" => { - let (t1, t2) = (ss * a(0).clamp(0.0, 100000.0) / 1e5, ss * a(1).clamp(0.0, 100000.0) / 1e5); - simple(b.poly(&[(0.0, 0.0), (t2, 0.0), (t2, h - t1), (w, h - t1), (w, h), (0.0, h)]).take(), Rect::new(0.0, h - t1, w, h), w, h) - } - "diagStripe" => { - let k = a(0).clamp(0.0, 100000.0) / 1e5; - simple(b.poly(&[(0.0, h * k), (w * k, 0.0), (w, 0.0), (0.0, h)]).take(), Rect::new(0.0, 0.0, w / 2.0, h / 2.0), w, h) - } - "plaque" => { - let v = a(0).clamp(0.0, 50000.0); - let r = ss * v / 100000.0; - b.m(0.0, r) - .arc(r, r, 90.0, -90.0) - .l(w - r, 0.0) - .arc(r, r, 180.0, -90.0) - .l(w, h - r) - .arc(r, r, 270.0, -90.0) - .l(r, h) - .arc(r, r, 0.0, -90.0) - .z(); - let mut g = simple(b.take(), full.inset(-r * 0.7), w, h); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "can" | "flowChartMagneticDisk" => { - // The disk's ends are a third of its height (ECMA-376: ellipses of radius h/6). - let v = if name == "can" { a(0).clamp(0.0, 50000.0 * h / ss.max(1e-9)) } else { 100000.0 / 3.0 * h / ss.max(1e-9) }; - let eh = ss * v / 100000.0; - let r = eh / 2.0; - let body = Pb::new().m(0.0, r).l(0.0, h - r).arc(w / 2.0, r, 180.0, -180.0).l(w, r).arc(w / 2.0, r, 0.0, -180.0).z().take(); - let top = Pb::new().ellipse(w / 2.0, r, w / 2.0, r).take(); - let mut g = Geometry { - paths: vec![fill(body), shade(top, if name == "can" { FillMode::Lighten } else { FillMode::Norm })], - text_rect: Rect::new(0.0, eh, w, h - r), - handles: vec![], - sites: mid_sites(w, h), - }; - if name == "can" { - g.handles.push(Handle::new(0, Point::new(w / 2.0, 0.0), Vec2::new(0.0, ss / 100000.0), v, 0.0, 50000.0 * h / ss.max(1e-9))); - } - g - } - "flowChartMagneticDrum" => { - // ECMA-376: end ellipses of radius w/6 across. - let r = w / 6.0; - let body = Pb::new().m(r, 0.0).l(w - r, 0.0).arc(r, h / 2.0, 270.0, 180.0).l(r, h).arc(r, h / 2.0, 90.0, 180.0).z().take(); - let side = Pb::new().m(w - r, 0.0).arc(r, h / 2.0, 270.0, -180.0).take(); - Geometry { - paths: vec![fill(body), stroke_only(side)], - text_rect: Rect::new(r, 0.0, w - 2.0 * r, h), - handles: vec![], - sites: mid_sites(w, h), - } - } - "cube" => { - let v = a(0).clamp(0.0, 100000.0); - let d = ss * v / 100000.0; - let front = Pb::new().poly(&[(0.0, d), (w - d, d), (w - d, h), (0.0, h)]).take(); - let top = Pb::new().poly(&[(0.0, d), (d, 0.0), (w, 0.0), (w - d, d)]).take(); - let side = Pb::new().poly(&[(w - d, d), (w, 0.0), (w, h - d), (w - d, h)]).take(); - let mut g = Geometry { - paths: vec![fill(front), shade(top, FillMode::LightenLess), shade(side, FillMode::DarkenLess)], - text_rect: Rect::new(0.0, d, w - d, h), - handles: vec![], - sites: mid_sites(w, h), - }; - g.handles.push(Handle::new(0, Point::new(0.0, 0.0), Vec2::new(0.0, ss / 100000.0), v, 0.0, 100000.0)); - g - } - "bevel" => { - let v = a(0).clamp(0.0, 50000.0); - let d = ss * v / 100000.0; - let inner = Pb::new().poly(&[(d, d), (w - d, d), (w - d, h - d), (d, h - d)]).take(); - let top = Pb::new().poly(&[(0.0, 0.0), (w, 0.0), (w - d, d), (d, d)]).take(); - let left = Pb::new().poly(&[(0.0, 0.0), (d, d), (d, h - d), (0.0, h)]).take(); - let right = Pb::new().poly(&[(w, 0.0), (w, h), (w - d, h - d), (w - d, d)]).take(); - let bottom = Pb::new().poly(&[(0.0, h), (d, h - d), (w - d, h - d), (w, h)]).take(); - let mut g = Geometry { - paths: vec![ - fill(inner), - shade(top, FillMode::LightenLess), - shade(left, FillMode::Lighten), - shade(right, FillMode::DarkenLess), - shade(bottom, FillMode::Darken), - ], - text_rect: full.inset(-d), - handles: vec![], - sites: mid_sites(w, h), - }; - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "donut" => { - let v = a(0).clamp(0.0, 50000.0); - let t = ss * v / 100000.0; - b.ellipse(w / 2.0, h / 2.0, w / 2.0, h / 2.0); - b.ellipse(w / 2.0, h / 2.0, (w / 2.0 - t).max(0.0), (h / 2.0 - t).max(0.0)); - let mut g = Geometry { - paths: vec![fill_eo(b.take())], - text_rect: Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), - handles: vec![], - sites: ellipse_sites(w, h), - }; - g.handles.push(Handle::new(0, Point::new(0.0, h / 2.0), Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)); - g - } - "noSmoking" => { - let v = a(0).clamp(0.0, 50000.0); - let t = ss * v / 100000.0; - let (rx, ry) = ((w / 2.0 - t).max(0.0), (h / 2.0 - t).max(0.0)); - b.ellipse(w / 2.0, h / 2.0, w / 2.0, h / 2.0); - b.ellipse(w / 2.0, h / 2.0, rx, ry); - let ring = b.take(); - let th = (h).atan2(w); - let dir = Vec2::new(th.cos(), th.sin()); - let r = if rx > 0.0 && ry > 0.0 { rx * ry / ((ry * th.cos()).powi(2) + (rx * th.sin()).powi(2)).sqrt() } else { 0.0 }; - let perp = Vec2::new(-dir.y, dir.x) * (t / 2.0); - let c = Point::new(w / 2.0, h / 2.0); - let p = [c - dir * r - perp, c + dir * r - perp, c + dir * r + perp, c - dir * r + perp]; - let bar = Pb::new().poly(&p.map(|q| (q.x, q.y))).take(); - Geometry { - paths: vec![fill_eo(ring), fill(bar)], - text_rect: Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), - handles: vec![Handle::new(0, Point::new(0.0, h / 2.0), Vec2::new(ss / 100000.0, 0.0), v, 0.0, 50000.0)], - sites: ellipse_sites(w, h), - } - } - "blockArc" => { - let st = a(0) / 60000.0; - let en = a(1) / 60000.0; - let t = ss * a(2).clamp(0.0, 50000.0) / 100000.0; - let mut sw = en - st; - if sw <= 0.0 { - sw += 360.0; - } - let (rx, ry) = (w / 2.0, h / 2.0); - let (irx, iry) = ((rx - t).max(0.0), (ry - t).max(0.0)); - let s0 = vis(st, rx, ry); - let e0 = vis(st + sw, rx, ry); - let mut sweep = e0 - s0; - if sweep <= 0.0 { - sweep += 360.0; - } - let si = vis(st + sw, irx, iry); - let ei = vis(st, irx, iry); - let mut isweep = ei - si; - if isweep >= 0.0 { - isweep -= 360.0; - } - let p0 = Point::new(w / 2.0 + rx * s0.to_radians().cos(), h / 2.0 + ry * s0.to_radians().sin()); - b.m(p0.x, p0.y).arc(rx, ry, s0, sweep); - let pi = Point::new(w / 2.0 + irx * si.to_radians().cos(), h / 2.0 + iry * si.to_radians().sin()); - b.l(pi.x, pi.y).arc(irx, iry, si, isweep).z(); - let mut g = simple(b.take(), full, w, h); - let c = Point::new(rx, ry); - g.handles.push(Handle::angle(0, c, rx - t / 2.0, ry - t / 2.0, a(0))); - // Thickness: slides inward from the outer edge along the end angle's ray. - let pe = Point::new(rx + rx * e0.to_radians().cos(), ry + ry * e0.to_radians().sin()); - let u = (c - pe).normalize(); - let u = if u.x.is_finite() && u.y.is_finite() { u } else { Vec2::ZERO }; - g.handles.push(Handle::new(2, pe, u * (ss / 100000.0), a(2).clamp(0.0, 50000.0), 0.0, 50000.0)); - g - } - "pie" | "chord" | "arc" => { - let (rx, ry) = (w / 2.0, h / 2.0); - let s = vis(a(0) / 60000.0, rx, ry); - let e = vis(a(1) / 60000.0, rx, ry); - let mut sw = e - s; - if sw <= 0.0 { - sw += 360.0; - } - let p0 = Point::new(rx + rx * s.to_radians().cos(), ry + ry * s.to_radians().sin()); - b.m(p0.x, p0.y).arc(rx, ry, s, sw); - let text = Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355); - let mut g = match name { - "pie" => { - b.l(rx, ry).z(); - simple(b.take(), text, w, h) - } - "chord" => { - b.z(); - simple(b.take(), text, w, h) - } - _ => { - let open = b.take(); - let mut f = BezPath::from_vec(open.elements().to_vec()); - f.line_to(Point::new(rx, ry)); - f.close_path(); - Geometry { paths: vec![fill_only(f), stroke_only(open)], text_rect: text, handles: vec![], sites: mid_sites(w, h) } - } - }; - let c = Point::new(rx, ry); - g.handles.push(Handle::angle(0, c, rx, ry, a(0))); - g.handles.push(Handle::angle(1, c, rx, ry, a(1))); - g - } - "teardrop" => { - let k = a(0).clamp(0.0, 200000.0) / 100000.0; - let tip = (w / 2.0 + w / 2.0 * k, h / 2.0 - h / 2.0 * k); - b.m(0.0, h / 2.0).arc(w / 2.0, h / 2.0, 180.0, 90.0); - b.q(w / 2.0 + w / 4.0 * k, 0.0, tip.0, tip.1).q(w, h / 2.0 - h / 4.0 * k, w, h / 2.0); - b.arc(w / 2.0, h / 2.0, 0.0, 180.0).z(); - simple(b.take(), Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), w, h) - } - "foldedCorner" => { - let v = a(0).clamp(0.0, 50000.0); - let d = ss * v / 100000.0; - let body = Pb::new().poly(&[(0.0, 0.0), (w, 0.0), (w, h - d), (w - d, h), (0.0, h)]).take(); - let fold = Pb::new().m(w - d, h).l(w - d + d * 0.2, h - d + d * 0.2).l(w, h - d).z().take(); - Geometry { - paths: vec![fill(body), shade(fold, FillMode::DarkenLess)], - text_rect: Rect::new(0.0, 0.0, w, h - d), - handles: vec![], - sites: mid_sites(w, h), - } - } - "smileyFace" => { - let k = a(0).clamp(-4653.0, 4653.0) / 100000.0; - let face = Pb::new().ellipse(w / 2.0, h / 2.0, w / 2.0, h / 2.0).take(); - let mut eyes = Pb::new(); - eyes.ellipse(w * 0.35, h * 0.37, w * 0.05, h * 0.05); - eyes.ellipse(w * 0.65, h * 0.37, w * 0.05, h * 0.05); - let ys = h * (0.72 - k); - let smile = Pb::new().m(w * 0.22, ys).q(w / 2.0, ys + h * k * 4.0 + h * 0.0, w * 0.78, ys).take(); - Geometry { - paths: vec![fill(face), shade(eyes.take(), FillMode::DarkenLess), stroke_only(smile)], - text_rect: Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), - handles: vec![], - sites: ellipse_sites(w, h), - } - } - "heart" => { - // ECMA-376 heart: two cubic curves from the notch at the top to the point. - let (dx1, dx2) = (w * 49.0 / 48.0, w * 10.0 / 48.0); - let y1 = -h / 3.0; - b.m(w / 2.0, h / 4.0) - .c(w / 2.0 + dx2, y1, w / 2.0 + dx1, h / 4.0, w / 2.0, h) - .c(w / 2.0 - dx1, h / 4.0, w / 2.0 - dx2, y1, w / 2.0, h / 4.0) - .z(); - simple(b.take(), Rect::new(w * 0.2, h * 0.25, w * 0.8, h * 0.7), w, h) - } - "lightningBolt" => { - // ECMA-376 lightningBolt, in 21600ths of the box. - let pts = spec_pts( - &[ - (8472, 0), - (12860, 6080), - (11050, 6797), - (16577, 12007), - (14767, 12877), - (21600, 21600), - (10012, 14915), - (12222, 13987), - (5022, 9705), - (7602, 8382), - (0, 3890), - ], - w, - h, - ); - simple(b.poly(&pts).take(), Rect::new(w * 8757.0 / 21600.0, h * 7637.0 / 21600.0, w * 13917.0 / 21600.0, h * 12963.0 / 21600.0), w, h) - } - "sun" => { - // ECMA-376 sun: eight triangular rays (their bases at fixed fractions of the core's - // margin) around a circle of radius 50% - adj. - let a = a(0).clamp(12500.0, 46875.0); - let g0 = 50000.0 - a; - let (g1, g2) = (g0 * 30274.0 / 32768.0, g0 * 12540.0 / 32768.0); - let (g10, g11) = ((50000.0 - g1) * 0.75, (50000.0 - g2) * 0.75); - let (g12, g13, g14) = (g10 + 3662.0, g11 + 3662.0, g11 + 12500.0); - let (g15, g16, g17, g18) = (100000.0 - g10, 100000.0 - g12, 100000.0 - g13, 100000.0 - g14); - let x = |g: f64| w * g / 100000.0; - let y = |g: f64| h * g / 100000.0; - let (ox1, oy1, ox2, oy2) = (w * 18436.0 / 21600.0, h * 3163.0 / 21600.0, w * 3163.0 / 21600.0, h * 18436.0 / 21600.0); - let (hc, vc) = (w / 2.0, h / 2.0); - b.poly(&[(w, vc), (x(g15), y(g18)), (x(g15), y(g14))]); - b.poly(&[(ox1, oy1), (x(g16), y(g13)), (x(g17), y(g12))]); - b.poly(&[(hc, 0.0), (x(g18), y(g10)), (x(g14), y(g10))]); - b.poly(&[(ox2, oy1), (x(g13), y(g12)), (x(g12), y(g13))]); - b.poly(&[(0.0, vc), (x(g10), y(g14)), (x(g10), y(g18))]); - b.poly(&[(ox2, oy2), (x(g12), y(g17)), (x(g13), y(g16))]); - b.poly(&[(hc, h), (x(g14), y(g15)), (x(g18), y(g15))]); - b.poly(&[(ox1, oy2), (x(g17), y(g16)), (x(g16), y(g17))]); - b.ellipse(hc, vc, x(g0), y(g0)); - let g7 = g0 * 23170.0 / 32768.0; - let mut g = simple(b.take(), Rect::new(x(50000.0 - g7), y(50000.0 - g7), x(50000.0 + g7), y(50000.0 + g7)), w, h); - g.handles.push(Handle::new(0, Point::new(0.0, vc), Vec2::new(w / 100000.0, 0.0), a, 12500.0, 46875.0)); - g - } - "moon" => { - // ECMA-376 moon: the outer edge is the left half of an ellipse w × h/2 centred on the - // right edge; the inner edge an arc through the corners and (adj · w, middle) of a - // larger ellipse (rx = g18, ry = dy1) whose centre lies right of that point. - let k = a(0).clamp(0.0, 87500.0) / 100000.0; - let ssf = ss.max(1e-9); - let g0 = ss * k; - let g1 = (ss - g0).max(1e-9); - let g2 = g0 * g0 / g1; - let g3 = ss * ss / g1; - let g5 = 2.0 * g3 - g2; - let g6 = g5 - g0; - let dy1 = (g5 / 2.0 - g0) * (h / 2.0) / ssf; - let (g0w, g6w) = (g0 * w / ssf, g6 * w / ssf); - let rx = (g6w - g0w) / 2.0; - let cx = g0w + rx; - b.m(w, 0.0).arc(w, h / 2.0, 270.0, -180.0); - if rx > 1e-9 && dy1 > 1e-9 { - // From the bottom-right corner back up to the top-right through (g0w, h/2). - let t0 = ((h / 2.0) / dy1).clamp(-1.0, 1.0).atan2((w - cx) / rx); - let t1 = (-(h / 2.0) / dy1).clamp(-1.0, 1.0).atan2((w - cx) / rx) + std::f64::consts::TAU; - let arc = Arc::new(Point::new(cx, h / 2.0), Vec2::new(rx, dy1), t0, t1 - t0, 0.0); - arc.to_cubic_beziers(0.05, |p1, p2, p| { - b.p.curve_to(p1, p2, p); - }); - } - b.z(); - let g12 = g0 * 9598.0 / 32768.0; - let g13 = ss - g12; - let dy4 = (ss * ss - g13 * g13).max(0.0).sqrt() * (h / 2.0) / ssf; - simple(b.take(), Rect::new(g12 * w / ssf, h / 2.0 - dy4, g0w, h / 2.0 + dy4), w, h) - } - _ => return None, - }; - Some(g) -} - -fn bracket_and_arrow_shapes(c: &Ctx) -> Option { - let name = c.name; - let w = c.w; - let h = c.h; - let ss = c.w.min(c.h); - let full = Rect::new(0.0, 0.0, c.w, c.h); - let a = |i: usize| c.a(i); - let mut b = Pb::new(); - let g = match c.name { - "cloud" | "cloudCallout" => cloud(name, w, h, a(0), a(1)), - "bracketPair" => { - let r = ss * a(0).clamp(0.0, 50000.0) / 1e5; - let mut l = Pb::new(); - l.m(r, h).arc(r, r, 90.0, 90.0).l(0.0, r).arc(r, r, 180.0, 90.0); - l.m(w - r, 0.0).arc(r, r, 270.0, 90.0).l(w, h - r).arc(r, r, 0.0, 90.0); - let f = corner_rect(w, h, [Corner::Round(r); 4]); - Geometry { - paths: vec![fill_only(f), stroke_only(l.take())], - text_rect: full.inset(-r * 0.29289), - handles: vec![], - sites: mid_sites(w, h), - } - } - "bracePair" => { - let r = ss * a(0).clamp(0.0, 25000.0) / 1e5; - let mut l = Pb::new(); - l.m(2.0 * r, h).arc(r, r, 90.0, 90.0).l(r, h / 2.0 + r).arc(r, r, 0.0, -90.0).arc(r, r, 90.0, -90.0).l(r, r).arc(r, r, 180.0, 90.0); - l.m(w - 2.0 * r, 0.0) - .arc(r, r, 270.0, 90.0) - .l(w - r, h / 2.0 - r) - .arc(r, r, 180.0, -90.0) - .arc(r, r, 270.0, -90.0) - .l(w - r, h - r) - .arc(r, r, 0.0, 90.0); - let f = corner_rect(w, h, [Corner::Round(r); 4]); - Geometry { paths: vec![fill_only(f), stroke_only(l.take())], text_rect: full.inset(-r * 1.2), handles: vec![], sites: mid_sites(w, h) } - } - "leftBracket" | "rightBracket" => { - let r = (ss * a(0).clamp(0.0, 50000.0 * h / ss.max(1e-9)) / 1e5).min(h / 2.0); - let mut l = Pb::new(); - l.m(w, h).arc(w, r, 90.0, 90.0).l(0.0, r).arc(w, r, 180.0, 90.0); - let mut path = l.take(); - if name == "rightBracket" { - path.apply_affine(kurbo::Affine::new([-1.0, 0.0, 0.0, 1.0, w, 0.0])); - } - // Filled (when the shape has a fill) out to the straight side, as PowerPoint does. - let mut area = path.clone(); - area.close_path(); - Geometry { paths: vec![fill_only(area), stroke_only(path)], text_rect: full, handles: vec![], sites: mid_sites(w, h) } - } - "leftBrace" | "rightBrace" => { - let r = (ss * a(0).clamp(0.0, 25000.0 * h / ss.max(1e-9)) / 1e5).min(h / 4.0); - let my = h * a(1).clamp(0.0, 100000.0) / 1e5; - let hw = w / 2.0; - let mut l = Pb::new(); - l.m(w, h).arc(hw, r, 90.0, 90.0).l(hw, my + r).arc(hw, r, 0.0, -90.0).arc(hw, r, 90.0, -90.0).l(hw, r).arc(hw, r, 180.0, 90.0); - let mut path = l.take(); - if name == "rightBrace" { - path.apply_affine(kurbo::Affine::new([-1.0, 0.0, 0.0, 1.0, w, 0.0])); - } - // Filled (when the shape has a fill) out to the straight side, as PowerPoint does. - let mut area = path.clone(); - area.close_path(); - Geometry { paths: vec![fill_only(area), stroke_only(path)], text_rect: full, handles: vec![], sites: mid_sites(w, h) } - } - "rightArrow" => arrow(Dir::Right, w, h, a(0), a(1)), - "leftArrow" => arrow(Dir::Left, w, h, a(0), a(1)), - "upArrow" => arrow(Dir::Up, w, h, a(0), a(1)), - "downArrow" => arrow(Dir::Down, w, h, a(0), a(1)), - "leftRightArrow" => double_arrow(false, w, h, a(0), a(1)), - "upDownArrow" => double_arrow(true, w, h, a(0), a(1)), - "notchedRightArrow" | "stripedRightArrow" => { - let mut g = arrow(Dir::Right, w, h, a(0), a(1)); - let k = a(0).clamp(0.0, 100000.0) / 1e5; - let (y1, y2) = (h / 2.0 - h * k / 2.0, h / 2.0 + h * k / 2.0); - let dx = (ss * a(1).max(0.0) / 1e5).min(w); - if name == "notchedRightArrow" { - // x1 = dy1 · dx2 / hd2 in presetShapeDefinitions, with dy1 = h·k/2: the notch's - // edges run parallel to the head's - let n = dx * k; - let pts = [(0.0, y1), (w - dx, y1), (w - dx, 0.0), (w, h / 2.0), (w - dx, h), (w - dx, y2), (0.0, y2), (n, h / 2.0)]; - g.paths = vec![fill(Pb::new().poly(&pts).take())]; - } else { - let s = ss / 32.0; - let start = 5.0 * s; - let pts = [(start, y1), (w - dx, y1), (w - dx, 0.0), (w, h / 2.0), (w - dx, h), (w - dx, y2), (start, y2)]; - let mut stripes = Pb::new(); - stripes.poly(&[(0.0, y1), (s, y1), (s, y2), (0.0, y2)]); - stripes.poly(&[(2.0 * s, y1), (4.0 * s, y1), (4.0 * s, y2), (2.0 * s, y2)]); - g.paths = vec![fill(stripes.take()), fill(Pb::new().poly(&pts).take())]; - } - g - } - "homePlate" | "chevron" => { - let v = a(0).clamp(0.0, 100000.0 * w / ss.max(1e-9)); - let d = (ss * v / 1e5).min(w); - let pts: Vec<(f64, f64)> = if name == "homePlate" { - vec![(0.0, 0.0), (w - d, 0.0), (w, h / 2.0), (w - d, h), (0.0, h)] - } else { - vec![(0.0, 0.0), (w - d, 0.0), (w, h / 2.0), (w - d, h), (0.0, h), (d, h / 2.0)] - }; - // Text rectangles as presetShapeDefinitions give them: homePlate's runs to halfway - // along the point; chevron's lies between the notch and the point's base (x1..x2) - // and covers the whole width once those meet or cross (`?: dx x1 l`). - let text = if name == "homePlate" { - Rect::new(0.0, 0.0, w - d / 2.0, h) - } else if w - d > d { - Rect::new(d, 0.0, w - d, h) - } else { - Rect::new(0.0, 0.0, w, h) - }; - let mut g = simple(b.poly(&pts).take(), text, w, h); - g.handles.push(Handle::new(0, Point::new(w, 0.0), Vec2::new(-ss / 1e5, 0.0), v, 0.0, 100000.0 * w / ss.max(1e-9))); - g - } - "quadArrow" => { - let (t, hw, hl) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5, ss * a(2).clamp(0.0, 50000.0) / 1e5); - let (cx, cy) = (w / 2.0, h / 2.0); - let (t2, hw2) = (t / 2.0, hw); - let pts = [ - (0.0, cy), - (hl, cy - hw2), - (hl, cy - t2), - (cx - t2, cy - t2), - (cx - t2, hl), - (cx - hw2, hl), - (cx, 0.0), - (cx + hw2, hl), - (cx + t2, hl), - (cx + t2, cy - t2), - (w - hl, cy - t2), - (w - hl, cy - hw2), - (w, cy), - (w - hl, cy + hw2), - (w - hl, cy + t2), - (cx + t2, cy + t2), - (cx + t2, h - hl), - (cx + hw2, h - hl), - (cx, h), - (cx - hw2, h - hl), - (cx - t2, h - hl), - (cx - t2, cy + t2), - (hl, cy + t2), - (hl, cy + hw2), - ]; - simple(b.poly(&pts).take(), Rect::new(cx - t2, cy - t2, cx + t2, cy + t2), w, h) - } - "leftRightUpArrow" => { - let (t, hw, hl) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5, ss * a(2).clamp(0.0, 50000.0) / 1e5); - let cx = w / 2.0; - let by = h - hw; // horizontal shaft centre - let pts = [ - (0.0, by), - (hl, by - hw), - (hl, by - t / 2.0), - (cx - t / 2.0, by - t / 2.0), - (cx - t / 2.0, hl), - (cx - hw, hl), - (cx, 0.0), - (cx + hw, hl), - (cx + t / 2.0, hl), - (cx + t / 2.0, by - t / 2.0), - (w - hl, by - t / 2.0), - (w - hl, by - hw), - (w, by), - (w - hl, h), - (w - hl, by + t / 2.0), - (hl, by + t / 2.0), - (hl, h), - ]; - simple(b.poly(&pts).take(), Rect::new(hl, by - t / 2.0, w - hl, by + t / 2.0), w, h) - } - "leftUpArrow" | "bentUpArrow" => { - let (t, hw, hl) = (ss * a(0).clamp(0.0, 50000.0) / 1e5, ss * a(1).clamp(0.0, 50000.0) / 1e5, ss * a(2).clamp(0.0, 50000.0) / 1e5); - let pts: Vec<(f64, f64)> = if name == "leftUpArrow" { - let cx = w - hw; - let cy = h - hw; - vec![ - (0.0, cy), - (hl, cy - hw), - (hl, cy - t / 2.0), - (cx - t / 2.0, cy - t / 2.0), - (cx - t / 2.0, hl), - (cx - hw, hl), - (cx, 0.0), - (w, hl), - (cx + t / 2.0, hl), - (cx + t / 2.0, cy + t / 2.0), - (hl, cy + t / 2.0), - (hl, h), - ] - } else { - let cx = w - hw; - vec![ - (0.0, h - t), - (cx - t / 2.0, h - t), - (cx - t / 2.0, hl), - (cx - hw, hl), - (cx, 0.0), - (w, hl), - (cx + t / 2.0, hl), - (cx + t / 2.0, h), - (0.0, h), - ] - }; - simple(b.poly(&pts).take(), full, w, h) - } - "bentArrow" => { - let (t, hw, hl, r) = ( - ss * a(0).clamp(0.0, 50000.0) / 1e5, - ss * a(1).clamp(0.0, 50000.0) / 1e5, - ss * a(2).clamp(0.0, 50000.0) / 1e5, - ss * a(3).clamp(0.0, 100000.0) / 1e5, - ); - let cy = hw; // head centre line - let ro = r.max(t); - let ri = (ro - t).max(0.0); - b.m(0.0, h) - .l(0.0, cy - t / 2.0 + ro) - .arc(ro, ro, 180.0, 90.0) - .l(w - hl, cy - t / 2.0) - .l(w - hl, 0.0) - .l(w, cy) - .l(w - hl, 2.0 * hw) - .l(w - hl, cy + t / 2.0); - b.l(t + ri, cy + t / 2.0); - if ri > 0.0 { - b.arc(ri, ri, 270.0, -90.0); - } - b.l(t, h).z(); - simple(b.take(), full, w, h) - } - "uturnArrow" => { - let (t, hw, hl, r) = ( - ss * a(0).clamp(0.0, 25000.0) / 1e5, - ss * a(1).clamp(0.0, 25000.0) / 1e5, - ss * a(2).clamp(0.0, 25000.0) / 1e5, - ss * a(3).clamp(0.0, 100000.0) / 1e5, - ); - let hy = (h * a(4).clamp(0.0, 100000.0) / 1e5).max(hl + t); - let ax = w - hw; // arrow shaft centre x - let ro = r.max(t).min((ax + t / 2.0) / 2.0); - let ri = (ro - t).max(0.0); - b.m(0.0, h).l(0.0, ro).arc(ro, ro, 180.0, 90.0).l(ax + t / 2.0 - ro, 0.0).arc(ro, ro, 270.0, 90.0); - b.l(ax + t / 2.0, hy - hl).l(w, hy - hl).l(ax, hy).l(ax - hw, hy - hl).l(ax - t / 2.0, hy - hl).l(ax - t / 2.0, ro); - if ri > 0.0 { - b.arc(ri, ri, 0.0, -90.0); - } - b.l(t + ri, t); - if ri > 0.0 { - b.arc(ri, ri, 270.0, -90.0); - } - b.l(t, h).z(); - simple(b.take(), full, w, h) - } - "rightArrowCallout" | "leftArrowCallout" | "upArrowCallout" | "downArrowCallout" => { - let d = match name { - "rightArrowCallout" => Dir::Right, - "leftArrowCallout" => Dir::Left, - "upArrowCallout" => Dir::Up, - _ => Dir::Down, - }; - let (l, t) = len_thick(d, w, h); - let ss2 = l.min(t); - let shaft = ss2 * a(0).clamp(0.0, 100000.0) / 1e5; - let head = ss2 * a(1).clamp(0.0, 100000.0) / 1e5; - let hl = ss2 * a(2).clamp(0.0, 100000.0) / 1e5; - let boxl = (l * a(3).clamp(0.0, 100000.0) / 1e5).min(l - hl); - let c = t / 2.0; - let pts = [ - (0.0, 0.0), - (boxl, 0.0), - (boxl, c - shaft / 2.0), - (l - hl, c - shaft / 2.0), - (l - hl, c - head), - (l, c), - (l - hl, c + head), - (l - hl, c + shaft / 2.0), - (boxl, c + shaft / 2.0), - (boxl, t), - (0.0, t), - ]; - let pts = orient(d, w, h, &pts); - let tr = orient(d, w, h, &[(0.0, 0.0), (boxl, t)]); - simple(b.poly(&pts).take(), Rect::from_points(Point::new(tr[0].0, tr[0].1), Point::new(tr[1].0, tr[1].1)).abs(), w, h) - } - "mathPlus" | "mathMinus" | "mathEqual" | "mathDivide" | "mathMultiply" | "mathNotEqual" => math(name, w, h, a(0), a(1), a(2)), - _ => return None, - }; - Some(g) -} - -fn flowchart_and_star_shapes(c: &Ctx) -> Option { - let name = c.name; - let w = c.w; - let h = c.h; - let ss = c.w.min(c.h); - let full = Rect::new(0.0, 0.0, c.w, c.h); - let a = |i: usize| c.a(i); - let mut b = Pb::new(); - let g = match c.name { - "flowChartPredefinedProcess" => { - let r = Pb::new().poly(&[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)]).take(); - let mut l = Pb::new(); - l.m(w / 8.0, 0.0).l(w / 8.0, h).m(w * 7.0 / 8.0, 0.0).l(w * 7.0 / 8.0, h); - Geometry { - paths: vec![fill(r), stroke_only(l.take())], - text_rect: Rect::new(w / 8.0, 0.0, w * 7.0 / 8.0, h), - handles: vec![], - sites: mid_sites(w, h), - } - } - "flowChartInternalStorage" => { - let r = Pb::new().poly(&[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)]).take(); - let mut l = Pb::new(); - l.m(w / 8.0, 0.0).l(w / 8.0, h).m(0.0, h / 8.0).l(w, h / 8.0); - Geometry { - paths: vec![fill(r), stroke_only(l.take())], - text_rect: Rect::new(w / 8.0, h / 8.0, w, h), - handles: vec![], - sites: mid_sites(w, h), - } - } - "flowChartDocument" => { - let u = |x: f64, y: f64| (w * x / 21600.0, h * y / 21600.0); - let (p1, p2, p3, p4) = (u(21600.0, 17322.0), u(10800.0, 17322.0), u(10800.0, 23922.0), u(0.0, 20172.0)); - b.m(0.0, 0.0).l(w, 0.0).l(p1.0, p1.1).c(p2.0, p2.1, p3.0, p3.1, p4.0, p4.1).z(); - simple(b.take(), Rect::new(0.0, 0.0, w, h * 17322.0 / 21600.0), w, h) - } - "flowChartMultidocument" => { - // ECMA-376 multidocument (21600ths): two back pages peeking out above and right of - // the front one; the back pages' edges are outlined only where they show. - let x = |v: f64| w * v / 21600.0; - let y = |v: f64| h * v / 21600.0; - let front = |b: &mut Pb| { - b.m(0.0, y(20782.0)) - .c(x(9298.0), y(23542.0), x(9298.0), y(18022.0), x(18595.0), y(18022.0)) - .l(x(18595.0), y(3675.0)) - .l(0.0, y(3675.0)) - .z(); - }; - let mid = |b: &mut Pb| { - b.m(x(1532.0), y(3675.0)).l(x(1532.0), y(1815.0)).l(x(20000.0), y(1815.0)).l(x(20000.0), y(16252.0)); - b.c(x(19298.0), y(16252.0), x(18595.0), y(16352.0), x(18595.0), y(16352.0)); - }; - let back = |b: &mut Pb| { - b.m(x(2972.0), y(1815.0)).l(x(2972.0), 0.0).l(w, 0.0).l(w, y(14392.0)); - b.c(x(20800.0), y(14392.0), x(20000.0), y(14467.0), x(20000.0), y(14467.0)); - }; - let mut area = Pb::new(); - front(&mut area); - mid(&mut area); - area.l(x(18595.0), y(3675.0)).z(); - back(&mut area); - area.l(x(20000.0), y(1815.0)).z(); - let mut outline = Pb::new(); - outline.m(0.0, y(3675.0)).l(x(18595.0), y(3675.0)).l(x(18595.0), y(18022.0)); - outline.c(x(9298.0), y(18022.0), x(9298.0), y(23542.0), 0.0, y(20782.0)).z(); - mid(&mut outline); - back(&mut outline); - Geometry { - paths: vec![fill_only(area.take()), stroke_only(outline.take())], - text_rect: Rect::new(0.0, y(3675.0), x(18595.0), y(17322.0)), - handles: vec![], - sites: mid_sites(w, h), - } - } - "flowChartTerminator" => { - let rx = (w * 0.16).min(w / 2.0); - b.m(rx, 0.0).l(w - rx, 0.0).arc(rx, h / 2.0, 270.0, 180.0).l(rx, h).arc(rx, h / 2.0, 90.0, 180.0).z(); - simple(b.take(), Rect::new(rx * 0.3, h * 0.15, w - rx * 0.3, h * 0.85), w, h) - } - "flowChartManualInput" => simple(b.poly(&[(0.0, h / 5.0), (w, 0.0), (w, h), (0.0, h)]).take(), Rect::new(0.0, h / 5.0, w, h), w, h), - "flowChartOffpageConnector" => { - simple(b.poly(&[(0.0, 0.0), (w, 0.0), (w, h * 0.8), (w / 2.0, h), (0.0, h * 0.8)]).take(), Rect::new(0.0, 0.0, w, h * 0.8), w, h) - } - "flowChartPunchedCard" => { - simple(b.poly(&[(w * 0.2, 0.0), (w, 0.0), (w, h), (0.0, h), (0.0, h * 0.2)]).take(), Rect::new(0.0, h * 0.2, w, h), w, h) - } - "flowChartPunchedTape" => { - // ECMA-376: each long edge is two half-ellipses a quarter of the width wide and a - // tenth of the height deep, one bulging in and one out. - let (rx, ry) = (w / 4.0, h / 10.0); - b.m(0.0, ry).arc(rx, ry, 180.0, -180.0).arc(rx, ry, 180.0, 180.0).l(w, h - ry).arc(rx, ry, 0.0, -180.0).arc(rx, ry, 0.0, 180.0).z(); - simple(b.take(), Rect::new(0.0, h / 5.0, w, h * 0.8), w, h) - } - "flowChartSummingJunction" | "flowChartOr" => { - let e = Pb::new().ellipse(w / 2.0, h / 2.0, w / 2.0, h / 2.0).take(); - let mut l = Pb::new(); - if name == "flowChartOr" { - l.m(w / 2.0, 0.0).l(w / 2.0, h).m(0.0, h / 2.0).l(w, h / 2.0); - } else { - let (dx, dy) = (w / 2.0 * std::f64::consts::FRAC_1_SQRT_2, h / 2.0 * std::f64::consts::FRAC_1_SQRT_2); - l.m(w / 2.0 - dx, h / 2.0 - dy).l(w / 2.0 + dx, h / 2.0 + dy).m(w / 2.0 + dx, h / 2.0 - dy).l(w / 2.0 - dx, h / 2.0 + dy); - } - Geometry { - paths: vec![fill(e), stroke_only(l.take())], - text_rect: Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), - handles: vec![], - sites: ellipse_sites(w, h), - } - } - "flowChartCollate" => simple(b.poly(&[(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]).take(), Rect::new(w / 4.0, h / 4.0, w * 0.75, h * 0.75), w, h), - "flowChartOnlineStorage" => { - let rx = w / 6.0; - b.m(rx, 0.0).l(w, 0.0).arc(rx, h / 2.0, 270.0, -180.0).l(rx, h).arc(rx, h / 2.0, 90.0, 180.0).z(); - simple(b.take(), Rect::new(rx, 0.0, w - rx, h), w, h) - } - "flowChartDelay" => { - b.m(0.0, 0.0).l(w / 2.0, 0.0).arc(w / 2.0, h / 2.0, 270.0, 180.0).l(0.0, h).z(); - simple(b.take(), Rect::new(0.0, h * 0.15, w * 0.85, h * 0.85), w, h) - } - "flowChartMagneticTape" => { - b.m(w / 2.0, h).arc(w / 2.0, h / 2.0, 90.0, 90.0).arc(w / 2.0, h / 2.0, 180.0, 90.0).arc(w / 2.0, h / 2.0, 270.0, 90.0).arc( - w / 2.0, - h / 2.0, - 0.0, - 45.0, - ); - let p = b.cur; - b.l(w, p.y).l(w, h).z(); - simple(b.take(), Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), w, h) - } - "flowChartDisplay" => { - let rx = w / 6.0; - b.m(0.0, h / 2.0).l(rx, 0.0).l(w - rx, 0.0).arc(rx, h / 2.0, 270.0, 180.0).l(rx, h).z(); - simple(b.take(), Rect::new(rx, 0.0, w - rx, h), w, h) - } - "star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => { - let n: usize = name.trim_start_matches("star").parse().unwrap_or(5); - let v = a(0).clamp(0.0, 50000.0); - let inner = v / 50000.0; - let text = star_text_rect(n, w, h, inner).unwrap_or_else(|| full.inset(-ss * (0.5 - inner * 0.5) * 0.5)); - let mut g = simple(b.poly(&star(n, w, h, inner)).take(), text, w, h); - g.handles.push(Handle::new(0, Point::new(w / 2.0, h / 2.0), Vec2::new(0.0, -h / 2.0 / 50000.0), v, 0.0, 50000.0)); - g - } - "irregularSeal1" => { - // ECMA-376 irregularSeal1 ("Explosion: 8 Points"), in 21600ths of the box. - let pts = spec_pts( - &[ - (10800, 5800), - (14522, 0), - (14155, 5325), - (18380, 4457), - (16702, 7315), - (21097, 8137), - (17607, 10475), - (21600, 13290), - (16837, 12942), - (18145, 18095), - (14020, 14457), - (13247, 19737), - (10532, 14935), - (8485, 21600), - (7715, 15627), - (4762, 17617), - (5667, 13937), - (135, 14587), - (3722, 11775), - (0, 8615), - (4627, 7617), - (370, 2295), - (7312, 6320), - (8352, 2295), - ], - w, - h, - ); - simple(b.poly(&pts).take(), Rect::new(w * 4627.0 / 21600.0, h * 6320.0 / 21600.0, w * 16702.0 / 21600.0, h * 13937.0 / 21600.0), w, h) - } - "irregularSeal2" => { - // ECMA-376 irregularSeal2 ("Explosion: 14 Points"), in 21600ths of the box. - let pts = spec_pts( - &[ - (11462, 4342), - (14790, 0), - (14525, 5777), - (18007, 3172), - (16380, 6532), - (21600, 6645), - (16985, 9402), - (18270, 11290), - (16380, 12310), - (18877, 15632), - (14640, 14350), - (14942, 17370), - (12180, 15935), - (11612, 18842), - (9872, 17370), - (8700, 19712), - (7527, 18125), - (4917, 21600), - (4805, 18240), - (1285, 17825), - (3330, 15370), - (0, 12877), - (3935, 11592), - (1172, 8270), - (5372, 7817), - (4502, 3625), - (8550, 6382), - (9722, 1887), - ], - w, - h, - ); - simple(b.poly(&pts).take(), Rect::new(w * 5372.0 / 21600.0, h * 6382.0 / 21600.0, w * 14640.0 / 21600.0, h * 15935.0 / 21600.0), w, h) - } - _ => return None, - }; - Some(g) -} - -fn callout_wave_and_connector_shapes(c: &Ctx) -> Option { - let name = c.name; - let w = c.w; - let h = c.h; - let ss = c.w.min(c.h); - let full = Rect::new(0.0, 0.0, c.w, c.h); - let a = |i: usize| c.a(i); - let mut b = Pb::new(); - let g = match c.name { - "ribbon" | "ribbon2" => ribbon(name == "ribbon2", w, h, a(0), a(1)), - "verticalScroll" | "horizontalScroll" => scroll(name == "verticalScroll", w, h, a(0)), - "wave" | "doubleWave" => { - // ECMA-376 wave / doubleWave: the top and bottom edges are cubic waves (one or two - // periods) of amplitude adj1, shifted sideways by adj2. - let a1 = a(0).clamp(0.0, if name == "wave" { 20000.0 } else { 12500.0 }); - let a2 = a(1).clamp(-10000.0, 10000.0); - let y1 = h * a1 / 100000.0; - let dy2 = y1 * 10.0 / 3.0; - let (y2, y3, y4) = (y1 - dy2, y1 + dy2, h - y1); - let (y5, y6) = (y4 - dy2, y4 + dy2); - let of2 = w * a2 / 50000.0; - let dx2 = of2.min(0.0); - let dxr = of2.max(0.0); - let (x2, xr, xl, x10) = (-dx2, w - dxr, dxr, w + dx2); - let text_y = h * a1 / 50000.0; - if name == "wave" { - let dx3 = (dx2 + xr) / 3.0; - let (x3, x7) = (x2 + dx3, xl + dx3); - let (x4, x8) = ((x3 + xr) / 2.0, (x7 + x10) / 2.0); - b.m(x2, y1).c(x3, y2, x4, y3, xr, y1).l(x10, y4).c(x8, y6, x7, y5, xl, y4).z(); - } else { - let (dx3, dx4) = ((dx2 + xr) / 6.0, (dx2 + xr) / 3.0); - let (x3, x4, x5) = (x2 + dx3, x2 + dx4, (x2 + xr) / 2.0); - let x6 = x5 + dx3; - let x7 = (x6 + xr) / 2.0; - let (x10b, x11, x12) = (xl + dx3, xl + dx4, (xl + x10) / 2.0); - let x13 = x12 + dx3; - let x14 = (x13 + x10) / 2.0; - b.m(x2, y1).c(x3, y2, x4, y3, x5, y1).c(x6, y2, x7, y3, xr, y1).l(x10, y4); - b.c(x14, y6, x13, y5, x12, y4).c(x11, y6, x10b, y5, xl, y4).z(); - } - simple(b.take(), Rect::new(x2.max(xl), text_y, xr.min(x10), h - text_y), w, h) - } - "wedgeRectCallout" | "wedgeRoundRectCallout" => { - let r = if name == "wedgeRoundRectCallout" { ss * a(2).clamp(0.0, 50000.0) / 1e5 } else { 0.0 }; - wedge_rect(w, h, a(0), a(1), r) - } - "wedgeEllipseCallout" => { - let tip = Point::new(w / 2.0 + w * a(0) / 1e5, h / 2.0 + h * a(1) / 1e5); - let ang = (tip.y - h / 2.0).atan2(tip.x - w / 2.0).to_degrees(); - let s = vis(ang + 10.0, w / 2.0, h / 2.0); - let p0 = Point::new(w / 2.0 + w / 2.0 * s.to_radians().cos(), h / 2.0 + h / 2.0 * s.to_radians().sin()); - let e = vis(ang - 10.0, w / 2.0, h / 2.0); - let mut sw = e - s; - if sw <= 0.0 { - sw += 360.0; - } - b.m(p0.x, p0.y).arc(w / 2.0, h / 2.0, s, sw).l(tip.x, tip.y).z(); - let mut g = simple(b.take(), Rect::new(w * 0.14645, h * 0.14645, w * 0.85355, h * 0.85355), w, h); - g.handles.push(Handle::new(0, Point::new(w / 2.0, h / 2.0), Vec2::new(w / 1e5, 0.0), a(0), -1e6, 1e6)); - g.handles.push(Handle::new(1, Point::new(w / 2.0, h / 2.0), Vec2::new(0.0, h / 1e5), a(1), -1e6, 1e6)); - g.handles.retain(|_| false); - g.handles.push(tip_handle(w, h, tip)); - g - } - "borderCallout1" => { - let r = Pb::new().poly(&[(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)]).take(); - let p1 = (w * a(1) / 1e5, h * a(0) / 1e5); - let p2 = (w * a(3) / 1e5, h * a(2) / 1e5); - let l = Pb::new().m(p1.0, p1.1).l(p2.0, p2.1).take(); - Geometry { paths: vec![fill(r), stroke_only(l)], text_rect: full, handles: vec![], sites: mid_sites(w, h) } - } - "line" | "straightConnector1" => { - let l = Pb::new().m(0.0, 0.0).l(w, h).take(); - Geometry { paths: vec![stroke_only(l)], text_rect: full, handles: vec![], sites: vec![Point::ZERO, Point::new(w, h)] } - } - "bentConnector2" => { - let l = Pb::new().m(0.0, 0.0).l(w, 0.0).l(w, h).take(); - Geometry { paths: vec![stroke_only(l)], text_rect: full, handles: vec![], sites: vec![Point::ZERO, Point::new(w, h)] } - } - "bentConnector3" | "bentConnector4" | "bentConnector5" => { - let x = w * a(0) / 1e5; - let l = Pb::new().m(0.0, 0.0).l(x, 0.0).l(x, h).l(w, h).take(); - let mut g = Geometry { paths: vec![stroke_only(l)], text_rect: full, handles: vec![], sites: vec![Point::ZERO, Point::new(w, h)] }; - g.handles.push(Handle::new(0, Point::new(0.0, h / 2.0), Vec2::new(w / 1e5, 0.0), a(0), -1e6, 1e6)); - g - } - "curvedConnector2" | "curvedConnector3" | "curvedConnector4" | "curvedConnector5" => { - let x = w * if name == "curvedConnector2" { 100000.0 } else { a(0) } / 1e5; - let l = Pb::new().m(0.0, 0.0).c(x / 2.0, 0.0, x, h / 4.0, x, h / 2.0).c(x, h * 0.75, (x + w) / 2.0, h, w, h).take(); - Geometry { paths: vec![stroke_only(l)], text_rect: full, handles: vec![], sites: vec![Point::ZERO, Point::new(w, h)] } - } - _ => return None, - }; - Some(g) -} diff --git a/crates/geom/src/preset/builder.rs b/crates/geom/src/preset/builder.rs deleted file mode 100644 index 701d15242..000000000 --- a/crates/geom/src/preset/builder.rs +++ /dev/null @@ -1,344 +0,0 @@ -use super::catalog::{FillMode, Geometry, Handle, SubPath}; -use super::{Arc, BezPath, Point, Rect, Vec2}; - -// ---------- path builder ---------- - -pub(super) struct Pb { - pub(super) p: BezPath, - pub(super) cur: Point, -} - -impl Pb { - pub(super) fn new() -> Self { - Pb { p: BezPath::new(), cur: Point::ZERO } - } - pub(super) fn m(&mut self, x: f64, y: f64) -> &mut Self { - self.cur = Point::new(x, y); - self.p.move_to(self.cur); - self - } - pub(super) fn l(&mut self, x: f64, y: f64) -> &mut Self { - self.cur = Point::new(x, y); - self.p.line_to(self.cur); - self - } - pub(super) fn c(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x: f64, y: f64) -> &mut Self { - self.cur = Point::new(x, y); - self.p.curve_to(Point::new(x1, y1), Point::new(x2, y2), self.cur); - self - } - pub(super) fn q(&mut self, x1: f64, y1: f64, x: f64, y: f64) -> &mut Self { - self.cur = Point::new(x, y); - self.p.quad_to(Point::new(x1, y1), self.cur); - self - } - /// Elliptic arc continuing from the current point, which lies on the ellipse at parametric - /// angle `st` (degrees); sweeps `sw` degrees (positive = clockwise on screen). - pub(super) fn arc(&mut self, wr: f64, hr: f64, st: f64, sw: f64) -> &mut Self { - let (s, e) = (st.to_radians(), (st + sw).to_radians()); - let c = Point::new(self.cur.x - wr * s.cos(), self.cur.y - hr * s.sin()); - let a = Arc::new(c, Vec2::new(wr.abs(), hr.abs()), s, e - s, 0.0); - a.to_cubic_beziers(0.05, |p1, p2, p| { - self.p.curve_to(p1, p2, p); - }); - self.cur = Point::new(c.x + wr * e.cos(), c.y + hr * e.sin()); - self - } - /// A DrawingML `arcTo`: angles are where the ray from the ellipse's centre at that angle - /// meets it (not the ellipse's parameter), so elliptical arcs start and end where the - /// standard's shapes expect. - pub(super) fn arc_spec(&mut self, wr: f64, hr: f64, st: f64, sw: f64) -> &mut Self { - let par = |a: f64| { - let a = a.to_radians(); - (wr * a.sin()).atan2(hr * a.cos()) - }; - let t0 = par(st); - let mut d = par(st + sw) - t0; - let tau = std::f64::consts::TAU; - if sw.abs() >= 360.0 { - d = tau.copysign(sw); - } else { - while sw > 0.0 && d < 0.0 { - d += tau; - } - while sw < 0.0 && d > 0.0 { - d -= tau; - } - } - self.arc(wr, hr, t0.to_degrees(), d.to_degrees()) - } - pub(super) fn z(&mut self) -> &mut Self { - self.p.close_path(); - self - } - pub(super) fn poly(&mut self, pts: &[(f64, f64)]) -> &mut Self { - for (i, (x, y)) in pts.iter().enumerate() { - if i == 0 { - self.m(*x, *y); - } else { - self.l(*x, *y); - } - } - self.z() - } - pub(super) fn ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64) -> &mut Self { - self.m(cx + rx, cy); - self.arc(rx, ry, 0.0, 360.0); - self.z() - } - pub(super) fn take(&mut self) -> BezPath { - std::mem::take(&mut self.p) - } -} - -pub(super) fn fill(p: BezPath) -> SubPath { - SubPath { path: p, fill: FillMode::Norm, stroke: true, even_odd: false } -} - -pub(super) fn fill_eo(p: BezPath) -> SubPath { - SubPath { path: p, fill: FillMode::Norm, stroke: true, even_odd: true } -} - -pub(super) fn shade(p: BezPath, m: FillMode) -> SubPath { - SubPath { path: p, fill: m, stroke: true, even_odd: false } -} - -pub(super) fn stroke_only(p: BezPath) -> SubPath { - SubPath { path: p, fill: FillMode::None, stroke: true, even_odd: false } -} - -pub(super) fn fill_only(p: BezPath) -> SubPath { - SubPath { path: p, fill: FillMode::Norm, stroke: false, even_odd: false } -} - -/// Parametric angle on an rx×ry ellipse for a visual angle `deg` (file angles are visual). -pub(super) fn vis(deg: f64, rx: f64, ry: f64) -> f64 { - let t = deg.to_radians(); - (rx * t.sin()).atan2(ry * t.cos()).to_degrees() -} - -pub(super) fn polygon_regular(n: usize, w: f64, h: f64, phase: f64) -> Vec<(f64, f64)> { - let pts: Vec<(f64, f64)> = (0..n) - .map(|i| { - let a = (phase + 360.0 * i as f64 / n as f64).to_radians(); - (a.cos(), a.sin()) - }) - .collect(); - normalize(&pts, w, h) -} - -/// Scale `pts` so their bounding box fills 0..w × 0..h. -fn normalize(pts: &[(f64, f64)], w: f64, h: f64) -> Vec<(f64, f64)> { - let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); - for (x, y) in pts { - x0 = x0.min(*x); - y0 = y0.min(*y); - x1 = x1.max(*x); - y1 = y1.max(*y); - } - let sx = if x1 - x0 > 1e-12 { w / (x1 - x0) } else { 0.0 }; - let sy = if y1 - y0 > 1e-12 { h / (y1 - y0) } else { 0.0 }; - pts.iter().map(|(x, y)| ((x - x0) * sx, (y - y0) * sy)).collect() -} - -/// An n-pointed star as ECMA-376 draws it: points on an ellipse around (hc, vc · vf) with radii -/// half the box stretched by the preset's `hf` / `vf` (so a five-pointed star fills its box and -/// looks regular in a square), the inner corners `inner` of the way out. -pub(super) fn star(n: usize, w: f64, h: f64, inner: f64) -> Vec<(f64, f64)> { - let (hf, vf) = match n { - 5 => (1.05146, 1.10557), - 6 => (1.15470, 1.0), - 7 => (1.02572, 1.05210), - 10 => (1.05146, 1.0), - _ => (1.0, 1.0), - }; - let (rx, ry, cy) = (w / 2.0 * hf, h / 2.0 * vf, h / 2.0 * vf); - let mut pts = Vec::with_capacity(n * 2); - for i in 0..n * 2 { - let a = (-90.0 + 180.0 * i as f64 / n as f64).to_radians(); - let r = if i % 2 == 0 { 1.0 } else { inner }; - pts.push((w / 2.0 + r * rx * a.cos(), cy + r * ry * a.sin())); - } - pts -} - -/// The text rectangle ECMA-376's presetShapeDefinitions give a star (`inner` is the adjust value -/// over 50000), where known: star4's is the square inside its inner points, star5's spans the -/// inner pentagon from its upper side points to its bottom inner point. -pub(super) fn star_text_rect(n: usize, w: f64, h: f64, inner: f64) -> Option { - let (hc, vc) = (w / 2.0, h / 2.0); - match n { - 4 => { - let (dx, dy) = (hc * inner * 45f64.to_radians().cos(), vc * inner * 45f64.to_radians().sin()); - Some(Rect::new(hc - dx, vc - dy, hc + dx, vc + dy)) - } - 5 => { - let (swd2, shd2, svc) = (hc * 1.05146, vc * 1.10557, vc * 1.10557); - let (iwd2, ihd2) = (swd2 * inner, shd2 * inner); - let sdx1 = iwd2 * 18f64.to_radians().cos(); - let sdy1 = ihd2 * 54f64.to_radians().sin(); - Some(Rect::new(hc - sdx1, svc - sdy1, hc + sdx1, svc + ihd2)) - } - _ => None, - } -} - -#[derive(Clone, Copy)] -pub(super) enum Corner { - Square, - Round(f64), - Snip(f64), -} - -/// A rectangle with each corner (TL, TR, BR, BL) square, rounded or snipped. -pub(super) fn corner_rect(w: f64, h: f64, c: [Corner; 4]) -> BezPath { - let mut b = Pb::new(); - let size = |k: Corner| match k { - Corner::Square => 0.0, - Corner::Round(r) | Corner::Snip(r) => r.max(0.0), - }; - let s0 = size(c[0]); - b.m(s0, 0.0); - // top edge → TR - let s1 = size(c[1]); - b.l(w - s1, 0.0); - match c[1] { - Corner::Round(r) if r > 0.0 => { - b.arc(r, r, 270.0, 90.0); - } - Corner::Snip(_) => { - b.l(w, s1); - } - _ => {} - } - let s2 = size(c[2]); - b.l(w, h - s2); - match c[2] { - Corner::Round(r) if r > 0.0 => { - b.arc(r, r, 0.0, 90.0); - } - Corner::Snip(_) => { - b.l(w - s2, h); - } - _ => {} - } - let s3 = size(c[3]); - b.l(s3, h); - match c[3] { - Corner::Round(r) if r > 0.0 => { - b.arc(r, r, 90.0, 90.0); - } - Corner::Snip(_) => { - b.l(0.0, h - s3); - } - _ => {} - } - b.l(0.0, s0); - match c[0] { - Corner::Round(r) if r > 0.0 => { - b.arc(r, r, 180.0, 90.0); - } - Corner::Snip(_) => { - b.l(s0, 0.0); - } - _ => {} - } - b.z(); - b.take() -} - -pub(super) fn mid_sites(w: f64, h: f64) -> Vec { - vec![Point::new(w / 2.0, 0.0), Point::new(0.0, h / 2.0), Point::new(w / 2.0, h), Point::new(w, h / 2.0)] -} - -/// Orientation for single-axis arrows built along +x. -#[derive(Clone, Copy)] -pub(super) enum Dir { - Right, - Left, - Up, - Down, -} - -/// Map canonical (u along the arrow's length L, v across thickness T) to shape space. -pub(super) fn orient(d: Dir, w: f64, h: f64, pts: &[(f64, f64)]) -> Vec<(f64, f64)> { - pts.iter() - .map(|&(u, v)| match d { - Dir::Right => (u, v), - Dir::Left => (w - u, v), - Dir::Up => (v, h - u), - Dir::Down => (v, u), - }) - .collect() -} - -pub(super) fn len_thick(d: Dir, w: f64, h: f64) -> (f64, f64) { - match d { - Dir::Right | Dir::Left => (w, h), - Dir::Up | Dir::Down => (h, w), - } -} - -pub(super) fn arrow(d: Dir, w: f64, h: f64, a1: f64, a2: f64) -> Geometry { - let (l, t) = len_thick(d, w, h); - let ss = l.min(t); - let a1 = a1.clamp(0.0, 100000.0) / 100000.0; - let dx = (ss * a2.clamp(0.0, 100000.0 * l / ss.max(1e-9)) / 100000.0).min(l); - let y1 = t / 2.0 - t * a1 / 2.0; - let y2 = t / 2.0 + t * a1 / 2.0; - let pts = [(0.0, y1), (l - dx, y1), (l - dx, 0.0), (l, t / 2.0), (l - dx, t), (l - dx, y2), (0.0, y2)]; - let pts = orient(d, w, h, &pts); - let tr = orient(d, w, h, &[(0.0, y1), (l - dx + dx * (y1 / (t / 2.0).max(1e-9)), y2)]); - let mut text = Rect::from_points(tr[0], tr[1]); - text = text.abs(); - let mut g = Geometry { paths: vec![fill(Pb::new().poly(&pts).take())], text_rect: text, handles: vec![], sites: mid_sites(w, h) }; - // handle 0: shaft thickness on the head base; handle 1: head length. - let o = orient(d, w, h, &[(l - dx, t / 2.0), (l, t / 2.0)]); - let (o0, o1) = (Point::new(o[0].0, o[0].1), Point::new(o[1].0, o[1].1)); - let across = match d { - Dir::Right | Dir::Left => Vec2::new(0.0, -t / 2.0 / 100000.0), - Dir::Up | Dir::Down => Vec2::new(-t / 2.0 / 100000.0, 0.0), - }; - let along = (o0 - o1) * (ss / 100000.0 / dx.max(1e-9)); - g.handles.push(Handle::new(0, o0, across, a1 * 100000.0, 0.0, 100000.0)); - if dx > 1e-9 { - g.handles.push(Handle::new(1, o1, along, a2, 0.0, 100000.0 * l / ss.max(1e-9))); - } - g -} - -pub(super) fn double_arrow(vertical: bool, w: f64, h: f64, a1: f64, a2: f64) -> Geometry { - let (l, t) = if vertical { (h, w) } else { (w, h) }; - let ss = l.min(t); - let a1 = a1.clamp(0.0, 100000.0) / 100000.0; - let dx = (ss * a2.max(0.0) / 100000.0).min(l / 2.0); - let y1 = t / 2.0 - t * a1 / 2.0; - let y2 = t / 2.0 + t * a1 / 2.0; - let pts = [(0.0, t / 2.0), (dx, 0.0), (dx, y1), (l - dx, y1), (l - dx, 0.0), (l, t / 2.0), (l - dx, t), (l - dx, y2), (dx, y2), (dx, t)]; - let pts = orient(if vertical { Dir::Down } else { Dir::Right }, w, h, &pts); - let r = if vertical { Rect::new(y1, dx, y2, h - dx) } else { Rect::new(dx, y1, w - dx, y2) }; - Geometry { paths: vec![fill(Pb::new().poly(&pts).take())], text_rect: r, handles: vec![], sites: mid_sites(w, h) } -} - -/// Points given in 21600ths of the box (as ECMA-376 defines many fixed shapes), scaled to it. -pub(super) fn spec_pts(pts: &[(i32, i32)], w: f64, h: f64) -> Vec<(f64, f64)> { - pts.iter().map(|(x, y)| (w * *x as f64 / 21600.0, h * *y as f64 / 21600.0)).collect() -} - -pub(super) fn simple(path: BezPath, text: Rect, w: f64, h: f64) -> Geometry { - Geometry { paths: vec![fill(path)], text_rect: text, handles: vec![], sites: mid_sites(w, h) } -} - -pub(super) fn ellipse_sites(w: f64, h: f64) -> Vec { - (0..8) - .map(|i| { - let a = (-90.0 - 45.0 * i as f64).to_radians(); - Point::new(w / 2.0 + w / 2.0 * a.cos(), h / 2.0 + h / 2.0 * a.sin()) - }) - .collect() -} - -pub(super) fn tip_handle(w: f64, h: f64, tip: Point) -> Handle { - // A free 2-D handle is represented as index 0 with zero direction; callers move both values. - Handle { index: 0, pos: tip, origin: Point::new(w / 2.0, h / 2.0), dir: Vec2::new(w / 1e5, h / 1e5), min: -1e6, max: 1e6, angle: false } -} diff --git a/crates/geom/src/preset/catalog.rs b/crates/geom/src/preset/catalog.rs deleted file mode 100644 index ca090f94d..000000000 --- a/crates/geom/src/preset/catalog.rs +++ /dev/null @@ -1,391 +0,0 @@ -use super::builder::vis; -use super::{BezPath, Deserialize, Point, Rect, Serialize, Vec2}; - -/// How a sub-path is filled. `Lighten`/`Darken` variants shade the shape's fill (3-D looking faces). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum FillMode { - Norm, - None, - Lighten, - LightenLess, - Darken, - DarkenLess, -} - -#[derive(Clone, Debug)] -pub struct SubPath { - pub path: BezPath, - pub fill: FillMode, - pub stroke: bool, - /// Even-odd fill (holes in donuts and frames). - pub even_odd: bool, -} - -/// A draggable adjust handle (the yellow dot). `pos = origin + dir * value`; dragging projects -/// the pointer onto `dir`. An `angle` handle instead measures the pointer's angle about `origin` -/// (1/60 000 degree, y down, 0° at +x). -#[derive(Clone, Debug, PartialEq)] -pub struct Handle { - pub index: usize, - pub pos: Point, - pub origin: Point, - pub dir: Vec2, - pub min: f64, - pub max: f64, - pub angle: bool, -} - -impl Handle { - pub(super) fn new(index: usize, origin: Point, dir: Vec2, value: f64, min: f64, max: f64) -> Self { - Handle { index, pos: origin + dir * value, origin, dir, min, max, angle: false } - } - /// An angle handle on the `rx`×`ry` ellipse around `center` at visual angle `value`. - pub(super) fn angle(index: usize, center: Point, rx: f64, ry: f64, value: f64) -> Self { - let t = vis(value / 60000.0, rx, ry).to_radians(); - let pos = Point::new(center.x + rx * t.cos(), center.y + ry * t.sin()); - Handle { index, pos, origin: center, dir: Vec2::ZERO, min: 0.0, max: 21600000.0, angle: true } - } - /// The adjust value for a pointer at `p` (shape-local space). - pub fn value_at(&self, p: Point) -> f64 { - if self.angle { - let d = p - self.origin; - if !(d.x.is_finite() && d.y.is_finite()) || d.hypot() < 1e-9 { - return self.min; - } - let v = (d.y.atan2(d.x).to_degrees().rem_euclid(360.0) * 60000.0).round(); - return if v >= self.max { self.min } else { v }; - } - let l2 = self.dir.hypot2(); - if l2 < 1e-18 { - return self.min; - } - let v = (p - self.origin).dot(self.dir) / l2; - if !v.is_finite() { - return self.min; - } - v.clamp(self.min.min(self.max), self.max.max(self.min)).round() - } -} - -#[derive(Clone, Debug)] -pub struct Geometry { - pub paths: Vec, - /// Where text goes, in shape-local space. - pub text_rect: Rect, - pub handles: Vec, - /// Connector glue points, shape-local. - pub sites: Vec, -} - -impl Geometry { - /// The union outline used for hit testing and selection (all filled or stroked sub-paths). - pub fn outline(&self) -> BezPath { - let mut p = BezPath::new(); - for s in &self.paths { - p.extend(s.path.iter()); - } - p - } - /// Whether nothing is filled (lines, connectors, arcs, brackets). - pub fn is_open(&self) -> bool { - self.paths.iter().all(|s| s.fill == FillMode::None) - } -} - -/// Gallery category, as in the Shapes menu. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum Category { - Lines, - Rectangles, - BasicShapes, - BlockArrows, - EquationShapes, - Flowchart, - StarsAndBanners, - Callouts, - ActionButtons, -} - -impl Category { - pub const ALL: [Category; 9] = [ - Category::Lines, - Category::Rectangles, - Category::BasicShapes, - Category::BlockArrows, - Category::EquationShapes, - Category::Flowchart, - Category::StarsAndBanners, - Category::Callouts, - Category::ActionButtons, - ]; - pub fn label(self) -> &'static str { - match self { - Category::Lines => "Lines", - Category::Rectangles => "Rectangles", - Category::BasicShapes => "Basic Shapes", - Category::BlockArrows => "Block Arrows", - Category::EquationShapes => "Equation Shapes", - Category::Flowchart => "Flowchart", - Category::StarsAndBanners => "Stars and Banners", - Category::Callouts => "Callouts", - Category::ActionButtons => "Action Buttons", - } - } -} - -pub struct PresetInfo { - pub name: &'static str, - pub label: &'static str, - pub category: Category, - /// Default adjust values. - pub defaults: &'static [f64], -} - -macro_rules! p { - ($n:literal, $l:literal, $c:ident, [$($d:expr),*]) => { - PresetInfo { name: $n, label: $l, category: Category::$c, defaults: &[$($d as f64),*] } - }; -} - -/// Every preset we generate, in gallery order. -pub static CATALOG: &[PresetInfo] = &[ - p!("line", "Line", Lines, []), - p!("straightConnector1", "Arrow", Lines, []), - p!("bentConnector3", "Connector: Elbow", Lines, [50000]), - p!("curvedConnector3", "Connector: Curved", Lines, [50000]), - p!("bentConnector2", "Connector: Elbow (one bend)", Lines, []), - p!("lineInv", "Line: Rising", Lines, []), - p!("rect", "Rectangle", Rectangles, []), - p!("roundRect", "Rectangle: Rounded Corners", Rectangles, [16667]), - p!("snip1Rect", "Rectangle: Single Corner Snipped", Rectangles, [16667]), - p!("snip2SameRect", "Rectangle: Top Corners Snipped", Rectangles, [16667, 0]), - p!("snip2DiagRect", "Rectangle: Diagonal Corners Snipped", Rectangles, [0, 16667]), - p!("snipRoundRect", "Rectangle: Top Corners One Rounded and One Snipped", Rectangles, [16667, 16667]), - p!("round1Rect", "Rectangle: Single Corner Rounded", Rectangles, [16667]), - p!("round2SameRect", "Rectangle: Top Corners Rounded", Rectangles, [16667, 0]), - p!("round2DiagRect", "Rectangle: Diagonal Corners Rounded", Rectangles, [16667, 0]), - p!("textBox", "Text Box", BasicShapes, []), - p!("ellipse", "Oval", BasicShapes, []), - p!("triangle", "Isosceles Triangle", BasicShapes, [50000]), - p!("rtTriangle", "Right Triangle", BasicShapes, []), - p!("parallelogram", "Parallelogram", BasicShapes, [25000]), - p!("trapezoid", "Trapezoid", BasicShapes, [25000]), - p!("nonIsoscelesTrapezoid", "Trapezoid: Uneven Sides", BasicShapes, [25000, 25000]), - p!("diamond", "Diamond", BasicShapes, []), - p!("pentagon", "Regular Pentagon", BasicShapes, []), - p!("hexagon", "Hexagon", BasicShapes, [25000]), - p!("heptagon", "Heptagon", BasicShapes, []), - p!("octagon", "Octagon", BasicShapes, [29289]), - p!("decagon", "Decagon", BasicShapes, []), - p!("dodecagon", "Dodecagon", BasicShapes, []), - p!("pie", "Partial Circle", BasicShapes, [0, 16200000]), - p!("pieWedge", "Quarter Wedge", BasicShapes, []), - p!("chord", "Chord", BasicShapes, [2700000, 16200000]), - p!("teardrop", "Teardrop", BasicShapes, [100000]), - p!("frame", "Frame", BasicShapes, [12500]), - p!("cornerTabs", "Corner Tabs: Triangles", BasicShapes, []), - p!("squareTabs", "Corner Tabs: Squares", BasicShapes, []), - p!("plaqueTabs", "Corner Tabs: Quarter Circles", BasicShapes, []), - p!("halfFrame", "Half Frame", BasicShapes, [33333, 33333]), - p!("corner", "L-Shape", BasicShapes, [50000, 50000]), - p!("diagStripe", "Diagonal Stripe", BasicShapes, [50000]), - p!("plus", "Cross", BasicShapes, [25000]), - p!("plaque", "Plaque", BasicShapes, [16667]), - p!("can", "Cylinder", BasicShapes, [25000]), - p!("cube", "Cube", BasicShapes, [25000]), - p!("bevel", "Bevel", BasicShapes, [12500]), - p!("donut", "Donut", BasicShapes, [25000]), - p!("noSmoking", "\"Not Allowed\" Symbol", BasicShapes, [18750]), - p!("blockArc", "Block Arc", BasicShapes, [10800000, 0, 25000]), - p!("foldedCorner", "Folded Corner", BasicShapes, [16667]), - p!("smileyFace", "Smiley Face", BasicShapes, [4653]), - p!("heart", "Heart", BasicShapes, []), - p!("lightningBolt", "Lightning Bolt", BasicShapes, []), - p!("sun", "Sun", BasicShapes, [25000]), - p!("moon", "Moon", BasicShapes, [50000]), - p!("cloud", "Cloud", BasicShapes, []), - p!("gear6", "Gear: 6 Teeth", BasicShapes, [15000, 3526]), - p!("gear9", "Gear: 9 Teeth", BasicShapes, [10000, 1763]), - p!("funnel", "Funnel", BasicShapes, []), - p!("arc", "Arc", BasicShapes, [16200000, 0]), - p!("bracketPair", "Double Bracket", BasicShapes, [16667]), - p!("bracePair", "Double Brace", BasicShapes, [8333]), - p!("leftBracket", "Left Bracket", BasicShapes, [8333]), - p!("rightBracket", "Right Bracket", BasicShapes, [8333]), - p!("leftBrace", "Left Brace", BasicShapes, [8333, 50000]), - p!("rightBrace", "Right Brace", BasicShapes, [8333, 50000]), - p!("chartX", "Chart Marker: Cross Lines", BasicShapes, []), - p!("chartStar", "Chart Marker: Star Lines", BasicShapes, []), - p!("chartPlus", "Chart Marker: Plus Lines", BasicShapes, []), - p!("rightArrow", "Arrow: Right", BlockArrows, [50000, 50000]), - p!("leftArrow", "Arrow: Left", BlockArrows, [50000, 50000]), - p!("upArrow", "Arrow: Up", BlockArrows, [50000, 50000]), - p!("downArrow", "Arrow: Down", BlockArrows, [50000, 50000]), - p!("leftRightArrow", "Arrow: Left-Right", BlockArrows, [50000, 50000]), - p!("upDownArrow", "Arrow: Up-Down", BlockArrows, [50000, 50000]), - p!("quadArrow", "Arrow: Quad", BlockArrows, [22500, 22500, 22500]), - p!("leftRightUpArrow", "Arrow: Left-Right-Up", BlockArrows, [25000, 25000, 25000]), - p!("bentArrow", "Arrow: Bent", BlockArrows, [25000, 25000, 25000, 43750]), - p!("uturnArrow", "Arrow: U-Turn", BlockArrows, [25000, 25000, 25000, 43750, 75000]), - p!("curvedRightArrow", "Arrow: Curved Right", BlockArrows, [25000, 50000, 25000]), - p!("curvedLeftArrow", "Arrow: Curved Left", BlockArrows, [25000, 50000, 25000]), - p!("curvedUpArrow", "Arrow: Curved Up", BlockArrows, [25000, 50000, 25000]), - p!("curvedDownArrow", "Arrow: Curved Down", BlockArrows, [25000, 50000, 25000]), - p!("leftUpArrow", "Arrow: Left-Up", BlockArrows, [25000, 25000, 25000]), - p!("bentUpArrow", "Arrow: Bent-Up", BlockArrows, [25000, 25000, 25000]), - p!("stripedRightArrow", "Arrow: Striped Right", BlockArrows, [50000, 50000]), - p!("notchedRightArrow", "Arrow: Notched Right", BlockArrows, [50000, 50000]), - p!("homePlate", "Arrow: Pentagon", BlockArrows, [50000]), - p!("chevron", "Arrow: Chevron", BlockArrows, [50000]), - p!("circularArrow", "Arrow: Circular", BlockArrows, [12500, 1142319, 20457681, 10800000, 12500]), - p!("leftCircularArrow", "Arrow: Circular Counter-clockwise", BlockArrows, [12500, -1142319, 1142319, 10800000, 12500]), - p!("leftRightCircularArrow", "Arrow: Circular Two-headed", BlockArrows, [12500, 1142319, 20457681, 11942319, 12500]), - p!("swooshArrow", "Arrow: Swoosh", BlockArrows, [25000, 16667]), - p!("rightArrowCallout", "Callout: Right Arrow", BlockArrows, [25000, 25000, 25000, 64977]), - p!("downArrowCallout", "Callout: Down Arrow", BlockArrows, [25000, 25000, 25000, 64977]), - p!("leftArrowCallout", "Callout: Left Arrow", BlockArrows, [25000, 25000, 25000, 64977]), - p!("upArrowCallout", "Callout: Up Arrow", BlockArrows, [25000, 25000, 25000, 64977]), - p!("leftRightArrowCallout", "Callout: Left-Right Arrow", BlockArrows, [25000, 25000, 25000, 48123]), - p!("upDownArrowCallout", "Callout: Up-Down Arrow", BlockArrows, [25000, 25000, 25000, 48123]), - p!("quadArrowCallout", "Callout: Quad Arrow", BlockArrows, [18515, 18515, 18515, 48123]), - p!("mathPlus", "Plus Sign", EquationShapes, [23520]), - p!("mathMinus", "Minus Sign", EquationShapes, [23520]), - p!("mathMultiply", "Multiplication Sign", EquationShapes, [23520]), - p!("mathDivide", "Division Sign", EquationShapes, [23520, 5880, 11760]), - p!("mathEqual", "Equals", EquationShapes, [23520, 11760]), - p!("mathNotEqual", "Not Equal", EquationShapes, [23520, 6600000, 11760]), - p!("flowChartProcess", "Flowchart: Process", Flowchart, []), - p!("flowChartAlternateProcess", "Flowchart: Alternate Process", Flowchart, []), - p!("flowChartDecision", "Flowchart: Decision", Flowchart, []), - p!("flowChartInputOutput", "Flowchart: Data", Flowchart, []), - p!("flowChartPredefinedProcess", "Flowchart: Predefined Process", Flowchart, []), - p!("flowChartInternalStorage", "Flowchart: Internal Storage", Flowchart, []), - p!("flowChartDocument", "Flowchart: Document", Flowchart, []), - p!("flowChartMultidocument", "Flowchart: Multidocument", Flowchart, []), - p!("flowChartTerminator", "Flowchart: Terminator", Flowchart, []), - p!("flowChartPreparation", "Flowchart: Preparation", Flowchart, []), - p!("flowChartManualInput", "Flowchart: Manual Input", Flowchart, []), - p!("flowChartManualOperation", "Flowchart: Manual Operation", Flowchart, []), - p!("flowChartConnector", "Flowchart: Connector", Flowchart, []), - p!("flowChartOffpageConnector", "Flowchart: Off-page Connector", Flowchart, []), - p!("flowChartPunchedCard", "Flowchart: Card", Flowchart, []), - p!("flowChartPunchedTape", "Flowchart: Punched Tape", Flowchart, []), - p!("flowChartSummingJunction", "Flowchart: Summing Junction", Flowchart, []), - p!("flowChartOr", "Flowchart: Or", Flowchart, []), - p!("flowChartCollate", "Flowchart: Collate", Flowchart, []), - p!("flowChartSort", "Flowchart: Sort", Flowchart, []), - p!("flowChartExtract", "Flowchart: Extract", Flowchart, []), - p!("flowChartMerge", "Flowchart: Merge", Flowchart, []), - p!("flowChartOnlineStorage", "Flowchart: Stored Data", Flowchart, []), - p!("flowChartDelay", "Flowchart: Delay", Flowchart, []), - p!("flowChartMagneticTape", "Flowchart: Sequential Access Storage", Flowchart, []), - p!("flowChartMagneticDisk", "Flowchart: Magnetic Disk", Flowchart, []), - p!("flowChartMagneticDrum", "Flowchart: Direct Access Storage", Flowchart, []), - p!("flowChartDisplay", "Flowchart: Display", Flowchart, []), - p!("flowChartOfflineStorage", "Flowchart: Offline Storage", Flowchart, []), - p!("irregularSeal1", "Explosion: 8 Points", StarsAndBanners, []), - p!("irregularSeal2", "Explosion: 14 Points", StarsAndBanners, []), - p!("star4", "Star: 4 Points", StarsAndBanners, [12500]), - p!("star5", "Star: 5 Points", StarsAndBanners, [19098]), - p!("star6", "Star: 6 Points", StarsAndBanners, [28868]), - p!("star7", "Star: 7 Points", StarsAndBanners, [34601]), - p!("star8", "Star: 8 Points", StarsAndBanners, [37500]), - p!("star10", "Star: 10 Points", StarsAndBanners, [42533]), - p!("star12", "Star: 12 Points", StarsAndBanners, [37500]), - p!("star16", "Star: 16 Points", StarsAndBanners, [37500]), - p!("star24", "Star: 24 Points", StarsAndBanners, [37500]), - p!("star32", "Star: 32 Points", StarsAndBanners, [37500]), - p!("ribbon2", "Ribbon: Tilted Up", StarsAndBanners, [16667, 50000]), - p!("ribbon", "Ribbon: Tilted Down", StarsAndBanners, [16667, 50000]), - p!("ellipseRibbon2", "Ribbon: Curved and Tilted Up", StarsAndBanners, [25000, 50000, 12500]), - p!("ellipseRibbon", "Ribbon: Curved and Tilted Down", StarsAndBanners, [25000, 50000, 12500]), - p!("leftRightRibbon", "Ribbon: Left-Right Fold", StarsAndBanners, [50000, 50000, 16667]), - p!("verticalScroll", "Scroll: Vertical", StarsAndBanners, [12500]), - p!("horizontalScroll", "Scroll: Horizontal", StarsAndBanners, [12500]), - p!("wave", "Wave", StarsAndBanners, [12500, 0]), - p!("doubleWave", "Double Wave", StarsAndBanners, [6250, 0]), - p!("wedgeRectCallout", "Speech Bubble: Rectangle", Callouts, [-20833, 62500]), - p!("wedgeRoundRectCallout", "Speech Bubble: Rectangle with Corners Rounded", Callouts, [-20833, 62500, 16667]), - p!("wedgeEllipseCallout", "Speech Bubble: Oval", Callouts, [-20833, 62500]), - p!("cloudCallout", "Thought Bubble: Cloud", Callouts, [-20833, 62500]), - p!("borderCallout1", "Callout: Line", Callouts, [18750, -8333, 112500, -38333]), - p!("borderCallout2", "Callout: Bent Line", Callouts, [18750, -8333, 18750, -16667, 112500, -46667]), - p!("borderCallout3", "Callout: Double Bent Line", Callouts, [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333]), - p!("accentCallout1", "Callout: Line with Accent Bar", Callouts, [18750, -8333, 112500, -38333]), - p!("accentCallout2", "Callout: Bent Line with Accent Bar", Callouts, [18750, -8333, 18750, -16667, 112500, -46667]), - p!("accentCallout3", "Callout: Double Bent Line with Accent Bar", Callouts, [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333]), - p!("callout1", "Callout: Line with No Border", Callouts, [18750, -8333, 112500, -38333]), - p!("callout2", "Callout: Bent Line with No Border", Callouts, [18750, -8333, 18750, -16667, 112500, -46667]), - p!("callout3", "Callout: Double Bent Line with No Border", Callouts, [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333]), - p!("accentBorderCallout1", "Callout: Line with Border and Accent Bar", Callouts, [18750, -8333, 112500, -38333]), - p!("accentBorderCallout2", "Callout: Bent Line with Border and Accent Bar", Callouts, [18750, -8333, 18750, -16667, 112500, -46667]), - p!( - "accentBorderCallout3", - "Callout: Double Bent Line with Border and Accent Bar", - Callouts, - [18750, -8333, 18750, -16667, 100000, -16667, 112963, -8333] - ), - p!("actionButtonBackPrevious", "Action Button: Go Back or Previous", ActionButtons, []), - p!("actionButtonForwardNext", "Action Button: Go Forward or Next", ActionButtons, []), - p!("actionButtonBeginning", "Action Button: Go to Beginning", ActionButtons, []), - p!("actionButtonEnd", "Action Button: Go to End", ActionButtons, []), - p!("actionButtonHome", "Action Button: Go Home", ActionButtons, []), - p!("actionButtonInformation", "Action Button: Get Information", ActionButtons, []), - p!("actionButtonReturn", "Action Button: Go Back", ActionButtons, []), - p!("actionButtonMovie", "Action Button: Video", ActionButtons, []), - p!("actionButtonDocument", "Action Button: Document", ActionButtons, []), - p!("actionButtonSound", "Action Button: Sound", ActionButtons, []), - p!("actionButtonHelp", "Action Button: Help", ActionButtons, []), - p!("actionButtonBlank", "Action Button: Custom", ActionButtons, []), -]; - -pub fn info(name: &str) -> Option<&'static PresetInfo> { - CATALOG.iter().find(|p| p.name == name) -} - -/// Whether PowerPoint joins this preset's outline with sharp (miter) corners when the line names -/// no join (it rounds them otherwise). Observed per preset on its export: the plus, the right, -/// up and down block arrows (not the left one), chevrons, stars from five points up, the -/// equation shapes, curved ribbons and the action buttons are mitred. -pub fn mitred_by_default(name: &str) -> bool { - matches!( - name, - "plus" - | "rightArrow" - | "upArrow" - | "downArrow" - | "upDownArrow" - | "leftUpArrow" - | "bentUpArrow" - | "stripedRightArrow" - | "notchedRightArrow" - | "chevron" - | "leftArrowCallout" - | "leftRightArrowCallout" - | "upDownArrowCallout" - | "quadArrowCallout" - | "mathPlus" - | "mathMinus" - | "mathMultiply" - | "mathEqual" - | "mathNotEqual" - | "star5" - | "star6" - | "star8" - | "star10" - | "star12" - | "star16" - | "star24" - | "star32" - | "ellipseRibbon" - | "ellipseRibbon2" - ) || name.starts_with("actionButton") -} - -pub fn is_line_like(name: &str) -> bool { - matches!(name, "line" | "straightConnector1" | "bentConnector2" | "bentConnector3" | "curvedConnector3" | "arc") - || name.starts_with("bentConnector") - || name.starts_with("curvedConnector") -} diff --git a/crates/geom/src/preset/extra.rs b/crates/geom/src/preset/extra.rs deleted file mode 100644 index 8c61e5f11..000000000 --- a/crates/geom/src/preset/extra.rs +++ /dev/null @@ -1,799 +0,0 @@ -//! More preset outlines: line callouts, arrow callouts, curved and circular arrows, curved -//! ribbons, gears, tabs and chart markers. Like the rest of `preset`, every outline is our own -//! construction, fitted to how the shapes look and to what their adjust values mean. - -use super::{ - Corner, Dir, FillMode, Geometry, Handle, Pb, Point, Rect, Vec2, corner_rect, fill, fill_eo, fill_only, mid_sites, orient, shade, simple, - stroke_only, vis, -}; - -/// Builds the presets this module knows; `None` for any other name. -pub(super) fn build(name: &str, w: f64, h: f64, a: &dyn Fn(usize) -> f64) -> Option { - let ss = w.min(h); - let full = Rect::new(0.0, 0.0, w, h); - let mut b = Pb::new(); - let g = match name { - "lineInv" => { - let l = b.m(0.0, h).l(w, 0.0).take(); - Geometry { paths: vec![stroke_only(l)], text_rect: full, handles: vec![], sites: vec![Point::new(0.0, h), Point::new(w, 0.0)] } - } - "nonIsoscelesTrapezoid" => { - let max = 50000.0 * w / ss.max(1e-9); - let (v1, v2) = (a(0).clamp(0.0, max), a(1).clamp(0.0, max)); - let (d1, d2) = (ss * v1 / 1e5, ss * v2 / 1e5); - let mut g = simple(b.poly(&[(0.0, h), (d1, 0.0), (w - d2, 0.0), (w, h)]).take(), Rect::new(d1 * 0.66, h * 0.2, w - d2 * 0.66, h), w, h); - g.handles.push(Handle::new(0, Point::ZERO, Vec2::new(ss / 1e5, 0.0), v1, 0.0, max)); - g.handles.push(Handle::new(1, Point::new(w, 0.0), Vec2::new(-ss / 1e5, 0.0), v2, 0.0, max)); - g - } - "pieWedge" => { - b.m(0.0, h).arc(w, h, 180.0, 90.0).l(w, h).z(); - simple(b.take(), Rect::new(w * 0.29289, h * 0.29289, w, h), w, h) - } - "flowChartOfflineStorage" => { - let tri = b.poly(&[(0.0, 0.0), (w, 0.0), (w / 2.0, h)]).take(); - let bar = Pb::new().m(w * 0.4, h * 0.8).l(w * 0.6, h * 0.8).take(); - Geometry { - paths: vec![fill(tri), stroke_only(bar)], - text_rect: Rect::new(w / 4.0, 0.0, w * 0.75, h * 0.8), - handles: vec![], - sites: vec![Point::new(w / 2.0, 0.0), Point::new(w / 4.0, h / 2.0), Point::new(w / 2.0, h), Point::new(w * 0.75, h / 2.0)], - } - } - "chartX" | "chartStar" | "chartPlus" => { - let body = corner_rect(w, h, [Corner::Square; 4]); - let mut l = Pb::new(); - if name != "chartPlus" { - l.m(0.0, 0.0).l(w, h).m(0.0, h).l(w, 0.0); - } - if name != "chartX" { - l.m(w / 2.0, 0.0).l(w / 2.0, h); - } - if name == "chartPlus" { - l.m(0.0, h / 2.0).l(w, h / 2.0); - } - Geometry { paths: vec![fill_only(body), stroke_only(l.take())], text_rect: full, handles: vec![], sites: mid_sites(w, h) } - } - "cornerTabs" | "squareTabs" | "plaqueTabs" => { - // Each tab's size is a twentieth of the diagonal. - let d = (w.hypot(h) / 20.0).min(w / 2.0).min(h / 2.0); - match name { - "cornerTabs" => { - b.poly(&[(0.0, 0.0), (d, 0.0), (0.0, d)]); - b.poly(&[(w - d, 0.0), (w, 0.0), (w, d)]); - b.poly(&[(w, h - d), (w, h), (w - d, h)]); - b.poly(&[(0.0, h - d), (d, h), (0.0, h)]); - } - "squareTabs" => { - b.poly(&[(0.0, 0.0), (d, 0.0), (d, d), (0.0, d)]); - b.poly(&[(w - d, 0.0), (w, 0.0), (w, d), (w - d, d)]); - b.poly(&[(w - d, h - d), (w, h - d), (w, h), (w - d, h)]); - b.poly(&[(0.0, h - d), (d, h - d), (d, h), (0.0, h)]); - } - _ => { - if d > 0.0 { - b.m(0.0, 0.0).l(d, 0.0).arc(d, d, 0.0, 90.0).z(); - b.m(w, 0.0).l(w, d).arc(d, d, 90.0, 90.0).z(); - b.m(w, h).l(w - d, h).arc(d, d, 180.0, 90.0).z(); - b.m(0.0, h).l(0.0, h - d).arc(d, d, 270.0, 90.0).z(); - } else { - b.m(0.0, 0.0).z(); - } - } - } - Geometry { paths: vec![fill(b.take())], text_rect: full.inset(-d), handles: vec![], sites: mid_sites(w, h) } - } - "callout1" - | "callout2" - | "callout3" - | "accentCallout1" - | "accentCallout2" - | "accentCallout3" - | "borderCallout2" - | "borderCallout3" - | "accentBorderCallout1" - | "accentBorderCallout2" - | "accentBorderCallout3" => { - let n = match name.chars().last() { - Some('2') => 2, - Some('3') => 3, - _ => 1, - }; - line_callout(w, h, a, n + 1, name.starts_with("accent"), name.contains("order")) - } - "leftRightArrowCallout" | "upDownArrowCallout" => { - let vertical = name == "upDownArrowCallout"; - let (l, t) = if vertical { (h, w) } else { (w, h) }; - let ss = l.min(t); - let head = (ss * a(1).max(0.0) / 1e5).min(t / 2.0); - let shaft = (ss * a(0).max(0.0) / 1e5).min(head * 2.0); - let hl = (ss * a(2).max(0.0) / 1e5).min(l / 2.0); - let boxl = (l * a(3).max(0.0) / 1e5).min(l - 2.0 * hl); - let (c, b0, b1) = (t / 2.0, (l - boxl) / 2.0, (l + boxl) / 2.0); - let pts = [ - (0.0, c), - (hl, c - head), - (hl, c - shaft / 2.0), - (b0, c - shaft / 2.0), - (b0, 0.0), - (b1, 0.0), - (b1, c - shaft / 2.0), - (l - hl, c - shaft / 2.0), - (l - hl, c - head), - (l, c), - (l - hl, c + head), - (l - hl, c + shaft / 2.0), - (b1, c + shaft / 2.0), - (b1, t), - (b0, t), - (b0, c + shaft / 2.0), - (hl, c + shaft / 2.0), - (hl, c + head), - ]; - let d = if vertical { Dir::Down } else { Dir::Right }; - let pts = orient(d, w, h, &pts); - let tr = orient(d, w, h, &[(b0, 0.0), (b1, t)]); - simple(b.poly(&pts).take(), Rect::from_points(Point::new(tr[0].0, tr[0].1), Point::new(tr[1].0, tr[1].1)).abs(), w, h) - } - "quadArrowCallout" => { - let head = (ss * a(1).max(0.0) / 1e5).min(ss / 2.0); - let shaft = (ss * a(0).max(0.0) / 1e5).min(head * 2.0); - let hl = (ss * a(2).max(0.0) / 1e5).min(ss / 2.0); - let k = a(3).clamp(0.0, 100000.0) / 1e5; - let (bw, bh) = ((w * k).min(w - 2.0 * hl).max(shaft), (h * k).min(h - 2.0 * hl).max(shaft)); - let (cx, cy) = (w / 2.0, h / 2.0); - let (bx0, bx1, by0, by1) = (cx - bw / 2.0, cx + bw / 2.0, cy - bh / 2.0, cy + bh / 2.0); - let (s2, hd) = (shaft / 2.0, head); - let pts = [ - (0.0, cy), - (hl, cy - hd), - (hl, cy - s2), - (bx0, cy - s2), - (bx0, by0), - (cx - s2, by0), - (cx - s2, hl), - (cx - hd, hl), - (cx, 0.0), - (cx + hd, hl), - (cx + s2, hl), - (cx + s2, by0), - (bx1, by0), - (bx1, cy - s2), - (w - hl, cy - s2), - (w - hl, cy - hd), - (w, cy), - (w - hl, cy + hd), - (w - hl, cy + s2), - (bx1, cy + s2), - (bx1, by1), - (cx + s2, by1), - (cx + s2, h - hl), - (cx + hd, h - hl), - (cx, h), - (cx - hd, h - hl), - (cx - s2, h - hl), - (cx - s2, by1), - (bx0, by1), - (bx0, cy + s2), - (hl, cy + s2), - (hl, cy + hd), - ]; - simple(b.poly(&pts).take(), Rect::new(bx0, by0, bx1, by1), w, h) - } - "curvedRightArrow" | "curvedLeftArrow" | "curvedUpArrow" | "curvedDownArrow" => curved_arrow(name, w, h, a(0), a(1), a(2)), - "swooshArrow" => swoosh(w, h, a(0), a(1)), - "ellipseRibbon" | "ellipseRibbon2" => ellipse_ribbon(name == "ellipseRibbon2", w, h, a(0), a(1), a(2)), - "leftRightRibbon" => left_right_ribbon(w, h, a(0), a(1), a(2)), - "gear6" | "gear9" => gear(if name == "gear6" { 6 } else { 9 }, w, h, a(0), a(1)), - "funnel" => funnel(w, h), - "circularArrow" | "leftCircularArrow" | "leftRightCircularArrow" => circular_arrow(name, w, h, [a(0), a(1), a(2), a(3), a(4)]), - _ => return None, - }; - Some(g) -} - -/// An ellipse-centred frame for the circular arrows: the band's middle runs on the ellipse -/// `(rx, ry)`, its edges `th/2` either side. -struct Ring { - c: Point, - rx: f64, - ry: f64, - th: f64, - hw: f64, -} - -impl Ring { - /// The point at visual angle `deg` on the ellipse grown by `d`. - fn at(&self, deg: f64, d: f64) -> Point { - let (ax, ay) = ((self.rx + d).max(0.0), (self.ry + d).max(0.0)); - let t = vis(deg, ax, ay).to_radians(); - Point::new(self.c.x + ax * t.cos(), self.c.y + ay * t.sin()) - } - /// Parametric angle (degrees) of `p` on the ellipse grown by `d`. - fn param(&self, p: Point, d: f64) -> f64 { - let (ax, ay) = ((self.rx + d).max(1e-9), (self.ry + d).max(1e-9)); - ((p.y - self.c.y) / ay).atan2((p.x - self.c.x) / ax).to_degrees() - } - /// Where the line `b + s·u` meets the ellipse grown by `d`, taking the crossing nearest `b` - /// on the side `sign` (+1 outwards, −1 inwards). - fn cross(&self, b: Point, u: Vec2, d: f64, sign: f64) -> Point { - let (ax, ay) = ((self.rx + d).max(1e-9), (self.ry + d).max(1e-9)); - let (px, py) = ((b.x - self.c.x) / ax, (b.y - self.c.y) / ay); - let (ux, uy) = (u.x / ax, u.y / ay); - let qa = ux * ux + uy * uy; - let qb = 2.0 * (px * ux + py * uy); - let qc = px * px + py * py - 1.0; - let disc = qb * qb - 4.0 * qa * qc; - if qa < 1e-18 || disc < 0.0 { - // The line misses (a long head on a thin ring): the edge then carries on from the - // base centre itself, as the reference does. - return b; - } - let r = disc.sqrt(); - let (s0, s1) = ((-qb - r) / (2.0 * qa), (-qb + r) / (2.0 * qa)); - let s = if sign > 0.0 { - if s0 >= 0.0 { s0 } else { s1 } - } else if s1 <= 0.0 { - s1 - } else { - s0 - }; - b + u * s - } - /// An arrow head whose base centre sits on the middle ellipse at `base` degrees and whose tip - /// sits there at `base + sweep`. The base runs along the line from the centre to the tip. - /// Returns (band outer edge, outer wing, tip, inner wing, band inner edge). - fn head(&self, base: f64, sweep: f64) -> [Point; 5] { - let b = self.at(base, 0.0); - let tip = self.at(base + sweep, 0.0); - let d = tip - self.c; - let u = if d.hypot() > 1e-12 { d / d.hypot() } else { Vec2::new(1.0, 0.0) }; - let half = self.th / 2.0; - [self.cross(b, u, half, 1.0), b + u * self.hw, tip, b - u * self.hw, self.cross(b, u, -half, -1.0)] - } -} - -/// Sweep (degrees) from `a` to `b` turning one way: positive when `dir > 0`. -fn turn(a: f64, b: f64, dir: f64) -> f64 { - if dir > 0.0 { (b - a).rem_euclid(360.0) } else { -(a - b).rem_euclid(360.0) } -} - -/// The circular arrows: a band along an ellipse with one head (`circularArrow` clockwise, -/// `leftCircularArrow` anticlockwise) or a head at each end (`leftRightCircularArrow`). -/// Adjusts: band thickness, head sweep (degrees), end angle, start angle, head half-width. -fn circular_arrow(name: &str, w: f64, h: f64, a: [f64; 5]) -> Geometry { - let ss = w.min(h); - if ss <= 0.0 { - return simple(corner_rect(w, h, [Corner::Square; 4]), Rect::new(0.0, 0.0, w, h), w, h); - } - let a5 = a[4].clamp(0.0, 25000.0); - let hw = ss * a5 / 1e5; - let th = ss * a[0].clamp(0.0, 2.0 * a5) / 1e5; - let ring = Ring { c: Point::new(w / 2.0, h / 2.0), rx: (w / 2.0 - hw).max(th / 2.0), ry: (h / 2.0 - hw).max(th / 2.0), th, hw }; - let deg = |v: f64| (v / 60000.0) % 360.0; - let (sweep, end, start) = (deg(a[1]), deg(a[2]), deg(a[3])); - let half = th / 2.0; - let mut b = Pb::new(); - // Arcs of the ellipse grown by `d`, drawn on from the current point (which is on it except in - // the degenerate case above, where the arc shifts with it like the reference's). - let edge_arc = |b: &mut Pb, from: Point, to: Point, d: f64, dir: f64| { - let (ax, ay) = ((ring.rx + d).max(0.0), (ring.ry + d).max(0.0)); - let (s, e) = (ring.param(from, d), ring.param(to, d)); - b.arc(ax, ay, s, turn(s, e, dir)); - }; - let outer_arc = |b: &mut Pb, from: Point, to: Point, dir: f64| edge_arc(b, from, to, half, dir); - let inner_arc = |b: &mut Pb, from: Point, to: Point, dir: f64| edge_arc(b, from, to, -half, dir); - if name == "leftRightCircularArrow" { - let hs = ring.head(start, -sweep); - let he = ring.head(end, sweep); - b.m(hs[0].x, hs[0].y); - outer_arc(&mut b, hs[0], he[0], 1.0); - b.l(he[1].x, he[1].y).l(he[2].x, he[2].y).l(he[3].x, he[3].y).l(he[4].x, he[4].y); - inner_arc(&mut b, he[4], hs[4], -1.0); - b.l(hs[3].x, hs[3].y).l(hs[2].x, hs[2].y).l(hs[1].x, hs[1].y).z(); - } else { - let dir = if name == "circularArrow" { 1.0 } else { -1.0 }; - let he = ring.head(end, sweep); - let (o0, i0) = (ring.at(start, half), ring.at(start, -half)); - b.m(o0.x, o0.y); - outer_arc(&mut b, o0, he[0], dir); - b.l(he[1].x, he[1].y).l(he[2].x, he[2].y).l(he[3].x, he[3].y).l(he[4].x, he[4].y); - inner_arc(&mut b, he[4], i0, -dir); - b.z(); - } - simple(b.take(), Rect::new(0.0, 0.0, w, h), w, h) -} - -/// A funnel: an elliptical rim (with an open mouth) across the top quarter, and straight sides -/// down to a small rounded spout. The side lines leave the rim and meet the spout at fixed -/// angles, fitted to the reference look. -fn funnel(w: f64, h: f64) -> Geometry { - const RIM: f64 = 173.0; // where the left side leaves the rim, degrees on the rim ellipse - const SPOUT: f64 = 163.4; // where it meets the spout, degrees on the spout ellipse - let ss = w.min(h); - let (cx, rim_y) = (w / 2.0, h / 4.0); - let (sx, sy) = (w / 8.0, h / 15.0); - let spout_y = h - sy; - let at = |rx: f64, ry: f64, cy: f64, deg: f64| { - let t = deg.to_radians(); - Point::new(cx + rx * t.cos(), cy + ry * t.sin()) - }; - let p0 = at(cx, rim_y, rim_y, RIM); - let p1 = at(sx, sy, spout_y, 180.0 - SPOUT); - let mut b = Pb::new(); - b.m(p0.x, p0.y).arc(cx, rim_y, RIM, 540.0 - 2.0 * RIM); - b.l(p1.x, p1.y).arc(sx, sy, 180.0 - SPOUT, 2.0 * SPOUT - 180.0).z(); - let d = ss / 20.0; - b.ellipse(cx, rim_y, (cx - d).max(0.0), (rim_y - d).max(0.0)); - Geometry { paths: vec![fill_eo(b.take())], text_rect: Rect::new(w / 4.0, h / 2.0, w * 0.75, h - sy), handles: vec![], sites: mid_sites(w, h) } -} - -/// A gear: an elliptical body with `n` teeth, the first pointing straight up. Each tooth leaves -/// the body at two points an equal angle either side of its centre, and its tip corners sit a -/// tooth height further out along the body's normal and a flank lean further in. -fn gear(n: usize, w: f64, h: f64, a0: f64, a1: f64) -> Geometry { - let ss = w.min(h); - let th = ss * a0.clamp(0.0, 20000.0) / 1e5; // tooth height - let lean_max = if n == 6 { 5380.0 } else { 2730.0 }; - let l = ss * a1.clamp(0.0, a0.clamp(0.0, 20000.0).min(lean_max)) / 1e5; // flank lean - let (cx, cy) = (w / 2.0, h / 2.0); - let (rx, ry) = ((cx - th).max(0.0), (cy - th).max(0.0)); - let r = (ss / 2.0 - th).max(1e-9); - let half = ((th + l) / 2.0 / r).atan(); - let step = std::f64::consts::TAU / n as f64; - let on_body = |t: f64| Point::new(cx + rx * t.cos(), cy + ry * t.sin()); - let mut b = Pb::new(); - for k in 0..n { - let t = -std::f64::consts::FRAC_PI_2 + step * k as f64; - // The tooth stands along the body's normal at its centre. - let nrm = Vec2::new(t.cos() * ry, t.sin() * rx); - let u = if nrm.hypot() > 1e-12 { nrm / nrm.hypot() } else { Vec2::new(t.cos(), t.sin()) }; - let v = Vec2::new(-u.y, u.x); - let (r0, r1) = (on_body(t - half), on_body(t + half)); - let (c0, c1) = (r0 + u * th + v * l, r1 + u * th - v * l); - if k == 0 { - b.m(r0.x, r0.y); - } else { - b.arc(rx, ry, (t - step + half).to_degrees(), (step - 2.0 * half).to_degrees()); - } - b.l(c0.x, c0.y).l(c1.x, c1.y).l(r1.x, r1.y); - } - let t_last = -std::f64::consts::FRAC_PI_2 + step * (n - 1) as f64; - b.arc(rx, ry, (t_last + half).to_degrees(), (step - 2.0 * half).to_degrees()).z(); - let k = std::f64::consts::FRAC_1_SQRT_2; - let text = Rect::new(cx - rx * k, cy - ry * k, cx + rx * k, cy + ry * k); - simple(b.take(), text, w, h) -} - -/// Two arrows on a band that steps down in the middle: the left arrow sits high, the right one low, -/// and the band rolls over between them in a shaded half-ellipse curl. -fn left_right_ribbon(w: f64, h: f64, a0: f64, a1: f64, a2: f64) -> Geometry { - let ss = w.min(h); - let sh = h * a2.clamp(0.0, 33333.0) / 1e5; // step between the two halves - let bt = (h * a0.max(0.0) / 1e5).min(h - sh); // band thickness - let cx = w / 2.0; - let (rx, ry) = (w / 32.0, (sh / 4.0).min(w / 24.0)); - let hb = (ss * a1.max(0.0) / 1e5).min(cx - rx); // head length - let yc = (h - sh) / 2.0; - let (lt, lb) = (yc - bt / 2.0, yc + bt / 2.0); - let (rt, rb) = (lt + sh, lb + sh); - // The left half: filled as a closed outline, stroked only where it can show. - let mut edge = Pb::new(); - edge.m(cx - rx, lb).l(hb, lb).l(hb, h - sh).l(0.0, yc).l(hb, 0.0).l(hb, lt).l(cx, lt); - edge.arc(rx, ry, 270.0, 180.0).arc(rx, ry, 270.0, -90.0); - let edge = edge.take(); - let mut left = Pb::new(); - left.m(0.0, yc).l(hb, 0.0).l(hb, lt).l(cx, lt).arc(rx, ry, 270.0, 180.0).arc(rx, ry, 270.0, -180.0); - left.l(cx, lb.max(lt + 4.0 * ry)).l(hb, lb).l(hb, h - sh).z(); - let left = left.take(); - let mut curl = Pb::new(); - curl.m(cx + rx, lt + ry).l(cx + rx, rt).l(cx, lt + 4.0 * ry).arc(rx, ry, 90.0, 180.0).arc(rx, ry, 90.0, -90.0).z(); - let mut right = Pb::new(); - right.m(w, yc + sh).l(w - hb, h).l(w - hb, rb).l(cx, rb).arc(rx, ry, 90.0, 90.0).l(cx - rx, rt - ry).arc(rx, ry, 180.0, -90.0); - right.l(w - hb, rt).l(w - hb, sh).z(); - Geometry { - paths: vec![fill_only(left), stroke_only(edge), shade(curl.take(), FillMode::DarkenLess), fill(right.take())], - text_rect: Rect::new(hb.min(cx - rx), rt, (w - hb).max(cx + rx), lb.max(rt)), - handles: vec![], - sites: vec![Point::new(0.0, yc), Point::new(cx, rt), Point::new(w, yc + sh), Point::new(cx, lb)], - } -} - -/// Adds a piece of the parabola `y = y0 + d·(1 − ((x − w/2)/(w/2))²)` from the current point (at -/// `xa`) to `xb`, as one quadratic curve. -fn sag(b: &mut Pb, w: f64, d: f64, y0: f64, xa: f64, xb: f64) { - let hw = (w / 2.0).max(1e-9); - let f = |x: f64| y0 + d * (1.0 - ((x - hw) / hw).powi(2)); - let slope = -2.0 * d * (xa - hw) / (hw * hw); - b.q((xa + xb) / 2.0, f(xa) + slope * (xb - xa) / 2.0, xb, f(xb)); -} - -/// A ribbon whose edges sag along one parabola: a front band in the middle and two notched ends -/// behind it, joined by shaded folds. Built sagging downwards; `up` mirrors it vertically. -fn ellipse_ribbon(up: bool, w: f64, h: f64, a0: f64, a1: f64, a2: f64) -> Geometry { - let th = h * a0.clamp(0.0, 100000.0) / 1e5; // band drop at the centre - // Sag of every edge: never more than the drop, never so little that the band would rise - // above the ends by more than half their height. - let d = (h * a2.max(0.0) / 1e5).max(th - (h - th) / 2.0).clamp(0.0, th); - let bw = w * a1.clamp(25000.0, 75000.0) / 1e5; - let (x0, x1) = ((w - bw) / 2.0, (w + bw) / 2.0); - let ear = w / 8.0; - let (xf, xg) = (x0 + ear, x1 - ear); - let e = h - th; // band height - let off = th - d; // band top below the ends' top - let t = |x: f64| { - let hw = (w / 2.0).max(1e-9); - d * (1.0 - ((x - hw) / hw).powi(2)) - }; - let mut ends = Pb::new(); - ends.m(0.0, 0.0); - sag(&mut ends, w, d, 0.0, 0.0, xf); - ends.l(xf, t(xf) + off).l(x0, t(x0) + off).l(x0, t(x0) + e); - sag(&mut ends, w, d, e, x0, 0.0); - ends.l(ear, t(ear) + e / 2.0).z(); - ends.m(w, 0.0).l(w - ear, t(w - ear) + e / 2.0).l(w, e); - sag(&mut ends, w, d, e, w, x1); - ends.l(x1, t(x1) + off).l(xg, t(xg) + off).l(xg, t(xg)); - sag(&mut ends, w, d, 0.0, xg, w); - ends.z(); - let mut folds = Pb::new(); - folds.poly(&[(x0, t(x0) + off), (xf, t(xf)), (xf, t(xf) + off)]); - folds.poly(&[(x1, t(x1) + off), (xg, t(xg)), (xg, t(xg) + off)]); - let mut band = Pb::new(); - band.m(x0, t(x0) + off); - sag(&mut band, w, d, off, x0, x1); - band.l(x1, t(x1) + off + e); - sag(&mut band, w, d, off + e, x1, x0); - band.z(); - let mut paths = vec![fill(ends.take()), shade(folds.take(), FillMode::DarkenLess), fill(band.take())]; - let mut text = Rect::new(x0, th, x1, t(x0) + off + e); - if up { - let m = kurbo::Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, h]); - for p in &mut paths { - p.path.apply_affine(m); - } - text = m.transform_rect_bbox(text); - } - Geometry { paths, text_rect: text, handles: vec![], sites: mid_sites(w, h) } -} - -/// A sweeping arrow rising from the bottom-left corner. The band's two edges are quadratic curves -/// from the corner; the head's base leans slightly forward and reaches one eighth of the shorter -/// side above and below the band. The tilt and the tip's lift were fitted to the reference look. -fn swoosh(w: f64, h: f64, a0: f64, a1: f64) -> Geometry { - const TILT: f64 = 0.1126; // tan of the head base's lean from vertical - const LIFT: f64 = 0.051; // tip height above the band's centre, per unit of height - let ss = w.min(h); - let e = ss / 8.0; - let th = (h * a0.max(0.0) / 1e5).min((h - 2.0 * e).max(0.0)); - // The head is at least long enough to keep its leaning base inside the frame. - let hl = (ss * a1.max(0.0) / 1e5).max((e + th) * TILT).min((w - e * TILT).max(0.0)); - let qx = w - hl; - let mut b = Pb::new(); - b.m(0.0, h) - .q(w / 6.0, h / 3.0, qx, e) - .l(qx - e * TILT, 0.0) - .l(w, (e + th / 2.0 - LIFT * h).clamp(0.0, 2.0 * e + th)) - .l((qx + (e + th) * TILT).min(w), 2.0 * e + th) - .l((qx + th * TILT).min(w), e + th) - .q(w / 4.0, (th + h / 12.0 + e).min(h), 0.0, h) - .z(); - simple(b.take(), Rect::new(0.0, 0.0, w, h), w, h) -} - -/// A band that sweeps around half an ellipse and ends in an arrow head. Built pointing right -/// (`curvedRightArrow`) in a `cw`×`ch` frame, then turned for the other directions. -/// -/// Both halves of the band hang off one ellipse touching the far side: its centre sits on the -/// head side's edge, its horizontal radius is the full length, and the band has a constant -/// vertical thickness. The back half (shaded) starts flat against the head side; the front half -/// runs to the head, centred on the band where it ends. -fn curved_arrow(name: &str, w: f64, h: f64, a0: f64, a1: f64, a2: f64) -> Geometry { - let along_x = matches!(name, "curvedRightArrow" | "curvedLeftArrow"); - let (cw, ch) = if along_x { (w, h) } else { (h, w) }; - let ss = cw.min(ch); - let head = (ss * a1.max(0.0) / 1e5).min(ch / 2.0); - let th = (ss * a0.max(0.0) / 1e5).min(head); - let hl = (ss * a2.max(0.0) / 1e5).min(cw); - let hh = head / 2.0; - // The band's centre line, carried on to the head side, ends at the tip, which sits half a - // head width above the bottom. - let r = ((ch - hh - th / 2.0) / 2.0).max(0.0); - // Parametric angle where the front band reaches the head base. - let te = if cw > 0.0 { (-(hl / cw)).clamp(-1.0, 1.0).acos().to_degrees() } else { 90.0 }; - let mut back = Pb::new(); - back.m(cw, 0.0).arc(cw, r, 270.0, -90.0).l(0.0, r + th).arc(cw, r, 180.0, 90.0).z(); - let mut front = Pb::new(); - front.m(0.0, r).arc(cw, r, 180.0, te - 180.0); - let yb = front.cur.y; - let yc = yb + th / 2.0; - front.l(cw - hl, yc - hh).l(cw, 2.0 * r + th / 2.0).l(cw - hl, yc + hh).l(cw - hl, yb + th).arc(cw, r, te, 180.0 - te).z(); - let m = match name { - "curvedLeftArrow" => kurbo::Affine::new([-1.0, 0.0, 0.0, 1.0, w, 0.0]), - "curvedUpArrow" => kurbo::Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, h]), - "curvedDownArrow" => kurbo::Affine::new([0.0, 1.0, 1.0, 0.0, 0.0, 0.0]), - _ => kurbo::Affine::IDENTITY, - }; - let (mut back, mut front) = (back.take(), front.take()); - back.apply_affine(m); - front.apply_affine(m); - Geometry { - paths: vec![shade(back, FillMode::DarkenLess), fill(front)], - text_rect: Rect::new(0.0, 0.0, w, h), - handles: vec![], - sites: mid_sites(w, h), - } -} - -/// A rectangle with a callout leader through `pts` points (`(y, x)` adjust pairs in 1/100 000 of -/// the height and width), optionally with an accent bar at the first point's x and a border. -fn line_callout(w: f64, h: f64, a: &dyn Fn(usize) -> f64, pts: usize, accent: bool, border: bool) -> Geometry { - let body = corner_rect(w, h, [Corner::Square; 4]); - // Leaders may reach well outside the box, but not without bound. - let pt = |i: usize| (w * a(2 * i + 1).clamp(-1e7, 1e7) / 1e5, h * a(2 * i).clamp(-1e7, 1e7) / 1e5); - let mut l = Pb::new(); - let (x0, y0) = pt(0); - l.m(x0, y0); - for i in 1..pts { - let (x, y) = pt(i); - l.l(x, y); - } - let mut paths = vec![if border { fill(body) } else { fill_only(body) }]; - if accent { - paths.push(stroke_only(Pb::new().m(x0, 0.0).l(x0, h).take())); - } - paths.push(stroke_only(l.take())); - Geometry { paths, text_rect: Rect::new(0.0, 0.0, w, h), handles: vec![], sites: mid_sites(w, h) } -} - -#[cfg(test)] -mod tests { - use super::super::{CATALOG, FillMode, build, info}; - use kurbo::{BezPath, PathEl, Point, Shape}; - - const NEW: [&str; 38] = [ - "lineInv", - "nonIsoscelesTrapezoid", - "pieWedge", - "leftRightArrowCallout", - "upDownArrowCallout", - "quadArrowCallout", - "circularArrow", - "leftCircularArrow", - "leftRightCircularArrow", - "curvedRightArrow", - "curvedLeftArrow", - "curvedUpArrow", - "curvedDownArrow", - "swooshArrow", - "callout1", - "callout2", - "callout3", - "accentCallout1", - "accentCallout2", - "accentCallout3", - "borderCallout2", - "borderCallout3", - "accentBorderCallout1", - "accentBorderCallout2", - "accentBorderCallout3", - "ellipseRibbon", - "ellipseRibbon2", - "leftRightRibbon", - "flowChartOfflineStorage", - "gear6", - "gear9", - "funnel", - "cornerTabs", - "squareTabs", - "plaqueTabs", - "chartX", - "chartStar", - "chartPlus", - ]; - - fn outline(name: &str, w: f64, h: f64, adj: &[f64]) -> BezPath { - build(name, w, h, adj).map(|g| g.outline()).unwrap_or_default() - } - - /// Distance from `p` to the nearest point of the (flattened) outline. - fn dist(path: &BezPath, p: Point) -> f64 { - let mut best = f64::MAX; - let mut prev = Point::ZERO; - let mut start = Point::ZERO; - kurbo::flatten(path.iter(), 0.01, |el| { - let (a, b) = match el { - PathEl::MoveTo(q) => { - prev = q; - start = q; - return; - } - PathEl::LineTo(q) => (prev, q), - PathEl::ClosePath => (prev, start), - _ => return, - }; - let d = b - a; - let t = if d.hypot2() > 0.0 { ((p - a).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 }; - best = best.min((a + d * t - p).hypot()); - prev = b; - }); - best - } - - /// Asserts every point lies within 1pt of the outline. - fn on(name: &str, w: f64, h: f64, adj: &[f64], pts: &[(f64, f64)]) { - let path = outline(name, w, h, adj); - for &(x, y) in pts { - let d = dist(&path, Point::new(x, y)); - assert!(d < 1.0, "{name} {w}x{h} {adj:?}: ({x}, {y}) is {d:.2} from the outline"); - } - } - - #[test] - fn new_presets_are_in_the_catalog() { - for n in NEW { - let i = info(n).unwrap_or_else(|| panic!("{n} missing from the catalog")); - assert!(!i.label.is_empty()); - } - assert!(CATALOG.len() >= 183); - } - - #[test] - fn new_presets_build_within_bounds_at_many_sizes_and_adjusts() { - let sizes = [(480.0, 300.0), (300.0, 300.0), (200.0, 460.0), (100.0, 460.0), (1.0, 1.0), (0.0, 0.0), (0.0, 50.0), (60.0, 0.0)]; - let adjusts: [&[f64]; 8] = [ - &[], - &[0.0; 8], - &[100000.0; 8], - &[-50000.0; 8], - &[1e12, -1e12, 1e12, -1e12, 1e12, -1e12, 1e12, -1e12], - &[f64::MAX, f64::MIN, f64::MAX, f64::MIN, f64::MAX, f64::MIN, f64::MAX, f64::MIN], - &[f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::NAN, 5.0, 6.0, 7.0, 8.0], - &[30000.0, 60000.0, 20000.0, 9000000.0, 20000.0, 40000.0, 120000.0, -30000.0], - ]; - for n in NEW { - // Line callouts' leaders may reach anywhere, by design. - let callout = n.contains("allout") && !n.contains("Arrow"); - for (w, h) in sizes { - for adj in adjusts { - let g = build(n, w, h, adj).unwrap_or_else(|| panic!("{n} did not build")); - assert!(!g.paths.is_empty(), "{n} has no paths"); - for s in &g.paths { - let bb = s.path.bounding_box(); - assert!(bb.x0.is_finite() && bb.y0.is_finite() && bb.x1.is_finite() && bb.y1.is_finite(), "{n} {w}x{h} {adj:?}: {bb:?}"); - if !callout { - // Circular arrows with a head longer than their ring can hold carry the - // inner edge on from the head, as the reference does, so may spill. - let spill = if n.contains("ircular") { 0.5 } else { 0.01 }; - let tol = 0.5 + w.max(h) * spill; - assert!( - bb.x0 >= -tol && bb.y0 >= -tol && bb.x1 <= w + tol && bb.y1 <= h + tol, - "{n} {w}x{h} {adj:?} out of bounds: {bb:?}" - ); - } - } - let t = g.text_rect; - assert!(t.x0.is_finite() && t.y0.is_finite() && t.x1.is_finite() && t.y1.is_finite(), "{n} text rect {t:?}"); - } - } - let g = build(n, 480.0, 300.0, &[]).unwrap_or_else(|| panic!("{n}")); - assert!(g.outline().elements().len() >= 2, "{n} default outline is empty"); - } - } - - // The spot checks below are outline points measured on reference renders. - - #[test] - fn simple_new_presets_match_reference_points() { - on("lineInv", 480.0, 300.0, &[], &[(0.0, 300.0), (480.0, 0.0)]); - on("nonIsoscelesTrapezoid", 480.0, 300.0, &[], &[(75.0, 0.0), (405.0, 0.0), (0.0, 300.0)]); - on("nonIsoscelesTrapezoid", 200.0, 460.0, &[80000.0, 20000.0], &[(100.0, 0.0), (160.0, 0.0)]); - on("pieWedge", 480.0, 300.0, &[], &[(64.3, 150.0), (0.0, 300.0), (480.0, 0.0)]); - on("flowChartOfflineStorage", 480.0, 300.0, &[], &[(240.0, 300.0), (192.0, 240.0), (288.0, 240.0)]); - on("squareTabs", 480.0, 300.0, &[], &[(28.3, 28.3), (451.7, 271.7)]); - on("cornerTabs", 480.0, 300.0, &[], &[(23.3, 5.0)]); - on("plaqueTabs", 480.0, 300.0, &[], &[(27.85, 5.0)]); - on("chartStar", 480.0, 300.0, &[], &[(240.0, 0.0), (240.0, 300.0), (48.0, 30.0)]); - on("chartPlus", 480.0, 300.0, &[], &[(0.0, 150.0), (240.0, 0.0)]); - // Chart markers and plain callouts leave the box unstroked. - for n in ["chartX", "callout1", "accentCallout2"] { - let g = build(n, 100.0, 100.0, &[]).unwrap_or_else(|| panic!("{n}")); - assert!(!g.paths[0].stroke, "{n}"); - } - } - - #[test] - fn line_callouts_follow_their_adjusts() { - on("callout3", 480.0, 300.0, &[], &[(-40.0, 56.25), (-80.0, 56.25), (-80.0, 300.0), (-40.0, 338.9)]); - let adj = [50000.0, 110000.0, 20000.0, 120000.0, -20000.0, 80000.0, 30000.0, 40000.0]; - let g = build("accentBorderCallout3", 480.0, 300.0, &adj).unwrap_or_else(|| panic!("accentBorderCallout3")); - assert_eq!(g.paths.len(), 3); - assert!(g.paths[0].stroke); - let accent = g.paths[1].path.bounding_box(); - assert!((accent.x0 - 528.0).abs() < 1e-6 && accent.y0 == 0.0 && accent.y1 == 300.0, "{accent:?}"); - on("accentBorderCallout3", 480.0, 300.0, &adj, &[(576.0, 60.0), (384.0, -60.0), (192.0, 90.0)]); - } - - #[test] - fn arrow_callouts_match_reference_points() { - on("leftRightArrowCallout", 480.0, 300.0, &[], &[(0.0, 150.0), (75.0, 75.0), (124.5, 0.0), (355.5, 300.0), (480.0, 150.0)]); - on("leftRightArrowCallout", 200.0, 460.0, &[], &[(50.0, 180.0), (52.0, 0.0), (148.0, 460.0)]); - on("upDownArrowCallout", 480.0, 300.0, &[], &[(240.0, 0.0), (0.0, 77.8), (480.0, 222.2), (240.0, 300.0)]); - on("quadArrowCallout", 480.0, 300.0, &[], &[(0.0, 150.0), (124.5, 77.8), (240.0, 0.0), (480.0, 150.0), (240.0, 300.0)]); - } - - #[test] - fn curved_arrows_match_reference_points() { - on( - "curvedRightArrow", - 480.0, - 300.0, - &[], - &[(480.0, 0.0), (480.0, 75.0), (480.0, 225.0), (405.0, 149.0), (405.0, 299.0), (100.0, 151.5), (300.0, 6.7)], - ); - on("curvedRightArrow", 200.0, 460.0, &[30000.0, 60000.0, 40000.0], &[(200.0, 400.0), (120.0, 324.5), (120.0, 443.5), (200.0, 60.0)]); - // The band never outgrows the head; the head never outgrows half the frame. - on("curvedRightArrow", 200.0, 460.0, &[60000.0, 30000.0, 80000.0], &[(200.0, 60.0)]); - on("curvedLeftArrow", 480.0, 300.0, &[], &[(0.0, 225.0), (0.0, 0.0)]); - on("curvedUpArrow", 480.0, 300.0, &[], &[(405.0, 0.0), (0.0, 0.0), (75.0, 0.0)]); - on("curvedDownArrow", 480.0, 300.0, &[], &[(405.0, 300.0), (0.0, 300.0)]); - let g = build("curvedRightArrow", 480.0, 300.0, &[]).unwrap_or_else(|| panic!("curvedRightArrow")); - assert_eq!(g.paths[0].fill, FillMode::DarkenLess); - } - - #[test] - fn swoosh_matches_reference_points() { - on("swooshArrow", 480.0, 300.0, &[], &[(0.0, 300.0), (425.8, 0.0), (480.0, 59.7), (442.8, 150.0), (202.0, 105.5), (202.0, 159.0)]); - on("swooshArrow", 480.0, 300.0, &[40000.0, 16667.0], &[(480.0, 82.2), (447.8, 195.0)]); - on("swooshArrow", 200.0, 460.0, &[], &[(163.9, 0.0), (200.0, 59.4)]); - } - - #[test] - fn ribbons_match_reference_points() { - on( - "ellipseRibbon", - 480.0, - 300.0, - &[], - &[(0.0, 0.0), (120.0, 28.1), (60.0, 128.9), (240.0, 300.0), (120.0, 66.1), (180.0, 72.2), (180.0, 35.2)], - ); - on("ellipseRibbon", 480.0, 300.0, &[30000.0, 60000.0, 20000.0], &[(120.0, 45.0), (240.0, 300.0), (96.0, 68.4)]); - on("ellipseRibbon", 480.0, 300.0, &[80000.0, 20000.0, 60000.0], &[(240.0, 240.0), (1.0, 61.75)]); - on("ellipseRibbon2", 480.0, 300.0, &[], &[(0.0, 300.0), (240.0, 0.0)]); - on( - "leftRightRibbon", - 480.0, - 300.0, - &[], - &[(0.0, 125.0), (150.0, 0.0), (150.0, 50.0), (255.0, 62.5), (225.0, 87.5), (480.0, 175.0), (330.0, 300.0)], - ); - on("leftRightRibbon", 480.0, 300.0, &[90000.0, 10000.0, 60000.0], &[(0.0, 100.0), (480.0, 200.0), (240.0, 300.0)]); - } - - #[test] - fn gears_and_funnel_match_reference_points() { - // Square gear6: body radius 105, top tooth tip 3.5 inside the frame, tip half-width ~16.3. - on("gear6", 300.0, 300.0, &[], &[(150.0, 3.5), (133.7, 3.5), (166.3, 3.5), (45.0, 150.0)]); - on("gear9", 300.0, 300.0, &[], &[(150.0, 1.0), (30.0, 150.0)]); - on("gear6", 480.0, 300.0, &[], &[(240.0, 3.5), (201.0, 3.5)]); - on("funnel", 480.0, 300.0, &[], &[(240.0, 0.0), (0.0, 75.0), (240.0, 15.0), (15.0, 75.0), (240.0, 300.0), (60.5, 150.0)]); - let g = build("funnel", 480.0, 300.0, &[]).unwrap_or_else(|| panic!("funnel")); - assert!(g.paths[0].even_odd); - } - - #[test] - fn circular_arrows_match_reference_points() { - on("circularArrow", 300.0, 300.0, &[], &[(19.0, 150.0), (56.5, 150.0), (150.0, 19.0), (262.4, 150.0), (218.6, 113.4), (293.6, 113.4)]); - on( - "circularArrow", - 300.0, - 300.0, - &[20000.0, 1800000.0, 18000000.0, 5400000.0, 20000.0], - &[(150.0, 270.0), (150.0, 210.0), (247.0, 42.1), (143.0, 102.1), (227.9, 105.0)], - ); - on("leftCircularArrow", 300.0, 300.0, &[], &[(37.6, 150.0), (262.4, 150.0), (150.0, 281.0)]); - on("leftRightCircularArrow", 300.0, 300.0, &[], &[(262.4, 150.0), (37.6, 150.0), (150.0, 19.0)]); - // The band never grows past twice the head's half-width. - on("circularArrow", 300.0, 300.0, &[25000.0, 1142319.0, 20457681.0, 10800000.0, 5000.0], &[(0.0, 150.0), (30.0, 150.0)]); - } -} diff --git a/crates/geom/src/preset/shapes.rs b/crates/geom/src/preset/shapes.rs deleted file mode 100644 index 156475435..000000000 --- a/crates/geom/src/preset/shapes.rs +++ /dev/null @@ -1,375 +0,0 @@ -use super::builder::{Corner, Pb, corner_rect, fill, mid_sites, shade, simple, stroke_only, tip_handle}; -use super::catalog::{FillMode, Geometry}; -use super::{Point, Rect}; - -pub(super) fn wedge_rect(w: f64, h: f64, a0: f64, a1: f64, r: f64) -> Geometry { - let tip = Point::new(w / 2.0 + w * a0 / 1e5, h / 2.0 + h * a1 / 1e5); - let inside = tip.x > 0.0 && tip.x < w && tip.y > 0.0 && tip.y < h; - let (dx, dy) = ((tip.x - w / 2.0) / w.max(1e-9), (tip.y - h / 2.0) / h.max(1e-9)); - let mut b = Pb::new(); - let r = r.min(w / 2.0).min(h / 2.0); - // Walk clockwise from the top-left; insert the wedge on the edge facing the tip. - let horiz = dx.abs() > dy.abs(); - // The wedge's base: 2..5 twelfths of the edge on the tip's side of the centre when it is - // before it, 7..10 twelfths when after (presetShapeDefinitions' xg1/xg2, yg1/yg2). - let (bx0, bx1) = if tip.x < w / 2.0 { (w * 2.0 / 12.0, w * 5.0 / 12.0) } else { (w * 7.0 / 12.0, w * 10.0 / 12.0) }; - let (by0, by1) = if tip.y < h / 2.0 { (h * 2.0 / 12.0, h * 5.0 / 12.0) } else { (h * 7.0 / 12.0, h * 10.0 / 12.0) }; - b.m(r, 0.0); - if !inside && !horiz && dy < 0.0 { - b.l(bx0, 0.0).l(tip.x, tip.y).l(bx1, 0.0); - } - b.l(w - r, 0.0); - if r > 0.0 { - b.arc(r, r, 270.0, 90.0); - } - if !inside && horiz && dx > 0.0 { - b.l(w, by0).l(tip.x, tip.y).l(w, by1); - } - b.l(w, h - r); - if r > 0.0 { - b.arc(r, r, 0.0, 90.0); - } - if !inside && !horiz && dy > 0.0 { - b.l(bx1, h).l(tip.x, tip.y).l(bx0, h); - } - b.l(r, h); - if r > 0.0 { - b.arc(r, r, 90.0, 90.0); - } - if !inside && horiz && dx < 0.0 { - b.l(0.0, by1).l(tip.x, tip.y).l(0.0, by0); - } - b.l(0.0, r); - if r > 0.0 { - b.arc(r, r, 180.0, 90.0); - } - b.z(); - let mut g = simple(b.take(), Rect::new(0.0, 0.0, w, h).inset(-r * 0.29289), w, h); - g.handles.push(tip_handle(w, h, tip)); - g -} - -/// ECMA-376 cloud outline arcs (radii in 43200ths of the box, angles in 60000ths of a degree, -/// as DrawingML `arcTo` takes them), from the start point (3900, 14370). -const CLOUD_ARCS: [(f64, f64, f64, f64); 11] = [ - (6753.0, 9190.0, -11429249.0, 7426832.0), - (5333.0, 7267.0, -8646143.0, 5396714.0), - (4365.0, 5945.0, -8748475.0, 5983381.0), - (4857.0, 6595.0, -7859164.0, 7034504.0), - (5333.0, 7273.0, -4722533.0, 6541615.0), - (6775.0, 9220.0, -2776035.0, 7816140.0), - (5785.0, 7867.0, 37501.0, 6842000.0), - (6752.0, 9215.0, 1347096.0, 6910353.0), - (7720.0, 10543.0, 3974558.0, 4542661.0), - (4360.0, 5918.0, -16496525.0, 8804134.0), - (4345.0, 5945.0, -14809710.0, 9151131.0), -]; - -/// The cloud's creases: short arcs inside the outline, each from its own start point. -const CLOUD_CREASES: [(f64, f64, f64, f64, f64, f64); 11] = [ - (4693.0, 26177.0, 4345.0, 5945.0, 5204520.0, 1585770.0), - (6928.0, 34899.0, 4360.0, 5918.0, 4416628.0, 686848.0), - (16478.0, 39090.0, 6752.0, 9215.0, 8257449.0, 844866.0), - (28827.0, 34751.0, 6752.0, 9215.0, 387196.0, 959901.0), - (34129.0, 22954.0, 5785.0, 7867.0, -4217541.0, 4255042.0), - (41798.0, 15354.0, 5333.0, 7273.0, 1819082.0, 1665090.0), - (38324.0, 5426.0, 4857.0, 6595.0, -824660.0, 891534.0), - (29078.0, 3952.0, 4857.0, 6595.0, -8950887.0, 1091722.0), - (22141.0, 4720.0, 4365.0, 5945.0, -9809656.0, 1061181.0), - (14000.0, 5192.0, 6753.0, 9190.0, -4002417.0, 739161.0), - (4127.0, 15789.0, 6753.0, 9190.0, 9459261.0, 711490.0), -]; - -pub(super) fn cloud(name: &str, w: f64, h: f64, a0: f64, a1: f64) -> Geometry { - // Drawn in the path's own 43200-unit square, then stretched to the box (as DrawingML lays out - // a path with its own w and h), so the arcs keep their shape's proportions at any aspect. - let to_box = kurbo::Affine::scale_non_uniform(w / 43200.0, h / 43200.0); - let deg = |v: f64| v / 60000.0; - let mut b = Pb::new(); - b.m(3900.0, 14370.0); - for (wr, hr, st, sw) in CLOUD_ARCS { - b.arc_spec(wr, hr, deg(st), deg(sw)); - } - b.z(); - let mut creases = Pb::new(); - for (x, y, wr, hr, st, sw) in CLOUD_CREASES { - creases.m(x, y).arc_spec(wr, hr, deg(st), deg(sw)); - } - let mut outline = b.take(); - outline.apply_affine(to_box); - let mut paths = vec![fill(outline)]; - if name == "cloud" { - let mut c = creases.take(); - c.apply_affine(to_box); - paths.push(stroke_only(c)); - } - let text_rect = Rect::new(w * 2977.0 / 21600.0, h * 3262.0 / 21600.0, w * 17087.0 / 21600.0, h * 17337.0 / 21600.0); - let mut handles = vec![]; - if name == "cloudCallout" { - let tip = Point::new(w / 2.0 + w * a0 / 1e5, h / 2.0 + h * a1 / 1e5); - let c = Point::new(w / 2.0, h / 2.0); - let mut bubbles = Pb::new(); - for (k, r) in [(0.55, 0.06), (0.75, 0.045), (0.95, 0.03)] { - let p = c + (tip - c) * k; - if !(p.x > w * 0.1 && p.x < w * 0.9 && p.y > h * 0.1 && p.y < h * 0.9) || k > 0.9 { - bubbles.ellipse(p.x, p.y, w * r, h * r); - } - } - paths.push(fill(bubbles.take())); - handles.push(tip_handle(w, h, tip)); - } - Geometry { paths, text_rect, handles, sites: mid_sites(w, h) } -} - -/// The equation shapes, by ECMA-376's formulas (checked against PowerPoint's outlines at several -/// sizes and adjust values). Their bars span 73.49% of the width; the plus and multiply bars are -/// `adj1` of the shorter side thick, the others' `adj1` of the height. -pub(super) fn math(name: &str, w: f64, h: f64, a0: f64, a1: f64, a2: f64) -> Geometry { - let pin = |lo: f64, v: f64, hi: f64| v.max(lo).min(hi.max(lo)); - let ss = w.min(h); - let (hc, vc) = (w / 2.0, h / 2.0); - let dx1 = w * 73490.0 / 200000.0; - let (x1, x2) = (hc - dx1, hc + dx1); - let mut b = Pb::new(); - let text = match name { - "mathPlus" => { - let a = pin(0.0, a0, 73490.0); - let dy1 = h * 73490.0 / 200000.0; - let dx2 = ss * a / 200000.0; - let (y1, y2, y3, y4) = (vc - dy1, vc - dx2, vc + dx2, vc + dy1); - let (xa, xb) = (hc - dx2, hc + dx2); - b.poly(&[(x1, y2), (xa, y2), (xa, y1), (xb, y1), (xb, y2), (x2, y2), (x2, y3), (xb, y3), (xb, y4), (xa, y4), (xa, y3), (x1, y3)]); - Rect::new(x1, y2, x2, y3) - } - "mathMinus" => { - let dy1 = h * pin(0.0, a0, 100000.0) / 200000.0; - b.poly(&[(x1, vc - dy1), (x2, vc - dy1), (x2, vc + dy1), (x1, vc + dy1)]); - Rect::new(x1, vc - dy1, x2, vc + dy1) - } - "mathEqual" => { - let a = pin(0.0, a0, 36745.0); - let g = pin(0.0, a1, 100000.0 - 2.0 * a); - let (dy1, dy2) = (h * a / 100000.0, h * g / 200000.0); - let (y2, y3) = (vc - dy2, vc + dy2); - let (y1, y4) = (y2 - dy1, y3 + dy1); - b.poly(&[(x1, y1), (x2, y1), (x2, y2), (x1, y2)]); - b.poly(&[(x1, y3), (x2, y3), (x2, y4), (x1, y4)]); - Rect::new(x1, y1, x2, y4) - } - "mathNotEqual" => { - let a = pin(0.0, a0, 50000.0); - let cr_ang = pin(4200000.0, a1, 6600000.0); - let g = pin(0.0, a2, 100000.0 - 2.0 * a); - let (dy1, dy2) = (h * a / 100000.0, h * g / 200000.0); - let hd2 = (h / 2.0).max(1e-9); - let (y2, y3) = (vc - dy2, vc + dy2); - let (y1, y4) = (y2 - dy1, y3 + dy1); - let cadj2 = cr_ang - 5400000.0; - let xadj2 = hd2 * (cadj2 / 60000.0).to_radians().tan(); - let len = xadj2.hypot(hd2); - let bhw = len * dy1 / hd2; - let x7 = hc + xadj2 - bhw / 2.0; - let at = |y: f64| x7 - xadj2 * y / hd2; - let (x6, x5, x4, x3) = (at(y1), at(y2), at(y3), at(y4)); - let rx7 = x7 + bhw; - let dx7 = dy1 * hd2 / len; - let dy3 = dy1 * xadj2 / len; - let (rx, lx, ry, ly) = if cadj2 > 0.0 { (x7 + dx7, x7, dy3, 0.0) } else { (rx7, rx7 - dx7, 0.0, -dy3) }; - b.poly(&[ - (x1, y1), - (x6, y1), - (lx, ly), - (rx, ry), - (x6 + bhw, y1), - (x2, y1), - (x2, y2), - (x5 + bhw, y2), - (x4 + bhw, y3), - (x2, y3), - (x2, y4), - (x3 + bhw, y4), - (w - lx, h - ly), - (w - rx, h - ry), - (x3, y4), - (x1, y4), - (x1, y3), - (x4, y3), - (x5, y2), - (x1, y2), - ]); - Rect::new(x1, y1, x2, y4) - } - "mathDivide" => { - let a = pin(1000.0, a0, 36745.0); - let max3 = ((73490.0 - a) / 4.0).min(36745.0 * w / h.max(1e-9)); - let r3 = pin(1000.0, a2, max3); - let g = pin(0.0, a1, 73490.0 - 4.0 * r3 - a); - let dy1 = h * a / 200000.0; - let yg = h * g / 100000.0; - let rad = h * r3 / 100000.0; - let (y3, y4) = (vc - dy1, vc + dy1); - let y2 = y3 - (yg + rad); - let y1 = y2 - rad; - b.ellipse(hc, y1 + rad, rad, rad); - b.ellipse(hc, h - y1 - rad, rad, rad); - b.poly(&[(x1, y3), (x2, y3), (x2, y4), (x1, y4)]); - Rect::new(x1, y3, x2, y4) - } - _ => { - // mathMultiply: an X whose arms run along the box's diagonals. - let th = ss * pin(0.0, a0, 51965.0) / 100000.0; - let ang = h.atan2(w); - let (sa, ca, ta) = (ang.sin(), ang.cos(), ang.tan().max(1e-9)); - let lm = w.hypot(h) * (1.0 - 51965.0 / 100000.0); - let (xm, ym) = (ca * lm / 2.0, sa * lm / 2.0); - let (dxam, dyam) = (sa * th / 2.0, ca * th / 2.0); - let (xa, ya, xb, yb) = (xm - dxam, ym + dyam, xm + dxam, ym - dyam); - let yc = (hc - xb) * ta + yb; - let (xd, xe) = (w - xb, w - xa); - let xfe = (vc - ya) / ta; - let (xf, xl) = (xe - xfe, xa + xfe); - let (yg, yh, yi) = (h - ya, h - yb, h - yc); - b.poly(&[(xa, ya), (xb, yb), (hc, yc), (xd, yb), (xe, ya), (xf, vc), (xe, yg), (xd, yh), (hc, yi), (xb, yh), (xa, yg), (xl, vc)]); - Rect::new(xa, yb, xe, yh) - } - }; - Geometry { paths: vec![fill(b.take())], text_rect: text, handles: vec![], sites: mid_sites(w, h) } -} - -pub(super) fn ribbon(up: bool, w: f64, h: f64, a0: f64, a1: f64) -> Geometry { - let fold = h * a0.clamp(0.0, 33333.0) / 1e5; - let cw = w * a1.clamp(25000.0, 75000.0) / 1e5; // centre band width - let x0 = (w - cw) / 2.0; - let x1 = w - x0; - let ear = w / 8.0; - let (top, bot) = (0.0, h); - let mut b = Pb::new(); - let mut shade_p = Pb::new(); - if up { - // centre band sits high; ends hang low. - b.poly(&[(x0, top), (x1, top), (x1, bot - fold), (x0, bot - fold)]); - let mut ends = Pb::new(); - ends.poly(&[(0.0, fold), (x0 + ear * 0.5, fold), (x0 + ear * 0.5, bot), (0.0, bot), (ear, (fold + bot) / 2.0)]); - ends.poly(&[(w, fold), (x1 - ear * 0.5, fold), (x1 - ear * 0.5, bot), (w, bot), (w - ear, (fold + bot) / 2.0)]); - shade_p.poly(&[(x0, bot - fold), (x0 + ear * 0.5, bot - fold), (x0 + ear * 0.5, bot)]); - shade_p.poly(&[(x1, bot - fold), (x1 - ear * 0.5, bot - fold), (x1 - ear * 0.5, bot)]); - let text = Rect::new(x0, top, x1, bot - fold); - return Geometry { - paths: vec![fill(ends.take()), shade(shade_p.take(), FillMode::DarkenLess), fill(b.take())], - text_rect: text, - handles: vec![], - sites: mid_sites(w, h), - }; - } - b.poly(&[(x0, top + fold), (x1, top + fold), (x1, bot), (x0, bot)]); - let mut ends = Pb::new(); - ends.poly(&[(0.0, top), (x0 + ear * 0.5, top), (x0 + ear * 0.5, bot - fold), (0.0, bot - fold), (ear, (bot - fold) / 2.0)]); - ends.poly(&[(w, top), (x1 - ear * 0.5, top), (x1 - ear * 0.5, bot - fold), (w, bot - fold), (w - ear, (bot - fold) / 2.0)]); - shade_p.poly(&[(x0, top + fold), (x0 + ear * 0.5, top + fold), (x0 + ear * 0.5, top)]); - shade_p.poly(&[(x1, top + fold), (x1 - ear * 0.5, top + fold), (x1 - ear * 0.5, top)]); - let text = Rect::new(x0, top + fold, x1, bot); - Geometry { - paths: vec![fill(ends.take()), shade(shade_p.take(), FillMode::DarkenLess), fill(b.take())], - text_rect: text, - handles: vec![], - sites: mid_sites(w, h), - } -} - -pub(super) fn scroll(vertical: bool, w: f64, h: f64, a0: f64) -> Geometry { - let ss = w.min(h); - let r = ss * a0.clamp(0.0, 25000.0) / 1e5 / 2.0; - let mut b = Pb::new(); - let mut curl = Pb::new(); - if vertical { - b.poly(&[(r, r * 2.0), (w - r, r * 2.0), (w - r, h - r), (r, h - r)]); - b.ellipse(w / 2.0, r, w / 2.0 - r * 0.0, r); - curl.ellipse(r, h - r, r, r); - curl.ellipse(w - r * 2.0, r, r * 0.5, r * 0.5); - let text = Rect::new(r, r * 2.0, w - r, h - r); - return Geometry { - paths: vec![fill(b.take()), shade(curl.take(), FillMode::DarkenLess)], - text_rect: text, - handles: vec![], - sites: mid_sites(w, h), - }; - } - b.poly(&[(r * 2.0, r), (w - r, r), (w - r, h - r), (r * 2.0, h - r)]); - b.ellipse(r, h / 2.0, r, h / 2.0); - curl.ellipse(w - r, r, r, r); - curl.ellipse(r, h - r * 2.0, r * 0.5, r * 0.5); - let text = Rect::new(r * 2.0, r, w - r, h - r); - Geometry { paths: vec![fill(b.take()), shade(curl.take(), FillMode::DarkenLess)], text_rect: text, handles: vec![], sites: mid_sites(w, h) } -} - -pub(super) fn action_button(name: &str, w: f64, h: f64) -> Geometry { - let body = corner_rect(w, h, [Corner::Square; 4]); - let ss = w.min(h); - let (cx, cy) = (w / 2.0, h / 2.0); - let s = ss * 0.3; - let mut g = Pb::new(); - match name { - "actionButtonBackPrevious" => { - g.poly(&[(cx + s, cy - s), (cx + s, cy + s), (cx - s, cy)]); - } - "actionButtonForwardNext" => { - g.poly(&[(cx - s, cy - s), (cx - s, cy + s), (cx + s, cy)]); - } - "actionButtonBeginning" => { - g.poly(&[(cx + s, cy - s), (cx + s, cy + s), (cx - s * 0.6, cy)]); - g.poly(&[(cx - s, cy - s), (cx - s * 0.7, cy - s), (cx - s * 0.7, cy + s), (cx - s, cy + s)]); - } - "actionButtonEnd" => { - g.poly(&[(cx - s, cy - s), (cx - s, cy + s), (cx + s * 0.6, cy)]); - g.poly(&[(cx + s * 0.7, cy - s), (cx + s, cy - s), (cx + s, cy + s), (cx + s * 0.7, cy + s)]); - } - "actionButtonHome" => { - g.poly(&[ - (cx, cy - s), - (cx + s, cy), - (cx + s * 0.7, cy), - (cx + s * 0.7, cy + s), - (cx - s * 0.7, cy + s), - (cx - s * 0.7, cy), - (cx - s, cy), - ]); - } - "actionButtonInformation" | "actionButtonHelp" => { - g.ellipse(cx, cy, s, s); - } - "actionButtonReturn" => { - g.m(cx + s, cy - s * 0.6).l(cx + s, cy + s * 0.2).q(cx + s, cy + s * 0.8, cx + s * 0.4, cy + s * 0.8).l(cx - s * 0.5, cy + s * 0.8); - g.l(cx - s * 0.5, cy + s * 0.4) - .l(cx - s, cy + s * 0.9) - .l(cx - s * 0.5, cy + s * 1.4) - .l(cx - s * 0.5, cy + s) - .l(cx + s * 0.6, cy + s) - .l(cx + s * 0.6, cy - s * 0.6) - .z(); - } - "actionButtonMovie" => { - g.poly(&[(cx - s, cy - s * 0.6), (cx + s * 0.4, cy - s * 0.6), (cx + s * 0.4, cy + s * 0.6), (cx - s, cy + s * 0.6)]); - g.poly(&[(cx + s * 0.4, cy), (cx + s, cy - s * 0.5), (cx + s, cy + s * 0.5)]); - } - "actionButtonDocument" => { - g.poly(&[(cx - s * 0.7, cy - s), (cx + s * 0.3, cy - s), (cx + s * 0.7, cy - s * 0.6), (cx + s * 0.7, cy + s), (cx - s * 0.7, cy + s)]); - } - "actionButtonSound" => { - g.poly(&[ - (cx - s, cy - s * 0.35), - (cx - s * 0.5, cy - s * 0.35), - (cx, cy - s), - (cx, cy + s), - (cx - s * 0.5, cy + s * 0.35), - (cx - s, cy + s * 0.35), - ]); - } - _ => {} - } - Geometry { - paths: vec![fill(body), shade(g.take(), FillMode::DarkenLess)], - text_rect: Rect::new(0.0, 0.0, w, h), - handles: vec![], - sites: mid_sites(w, h), - } -} diff --git a/crates/geom/src/preset/tests.rs b/crates/geom/src/preset/tests.rs deleted file mode 100644 index dc18dcdb5..000000000 --- a/crates/geom/src/preset/tests.rs +++ /dev/null @@ -1,420 +0,0 @@ -use super::*; -use kurbo::Shape; - -#[test] -fn every_catalog_preset_builds_within_bounds() { - for p in CATALOG { - for (w, h) in [(200.0, 100.0), (100.0, 200.0), (50.0, 50.0), (0.0, 0.0), (1.0, 300.0)] { - let g = build(p.name, w, h, &[]).unwrap_or_else(|| panic!("{} did not build", p.name)); - assert!(!g.paths.is_empty(), "{} has no paths", p.name); - for s in &g.paths { - let bb = s.path.bounding_box(); - if w > 0.0 && h > 0.0 && !p.name.contains("Connector") && !p.name.contains("allout") { - let tol = w.max(h) * 0.35 + 1.0; - assert!(bb.x0 >= -tol && bb.y0 >= -tol && bb.x1 <= w + tol && bb.y1 <= h + tol, "{} {w}x{h} out of bounds: {bb:?}", p.name); - } - assert!(bb.x0.is_finite() && bb.y1.is_finite(), "{} produced non-finite geometry", p.name); - } - assert!(g.text_rect.x0.is_finite() && g.text_rect.y1.is_finite(), "{}", p.name); - } - } -} - -#[test] -fn hostile_adjust_values_never_panic() { - for p in CATALOG { - for v in [f64::NAN, f64::INFINITY, -1e12, 1e12, -1.0, 0.0] { - let adj = vec![v; 6]; - let g = build(p.name, 120.0, 80.0, &adj); - assert!(g.is_some(), "{}", p.name); - } - } - assert!(build("rect", f64::NAN, 10.0, &[]).is_none()); - assert!(build("noSuchShape", 10.0, 10.0, &[]).is_none()); -} - -#[test] -fn catalog_names_are_unique() { - let mut names: Vec<&str> = CATALOG.iter().map(|p| p.name).collect(); - names.sort_unstable(); - let n = names.len(); - names.dedup(); - assert_eq!(n, names.len()); - assert!(n >= 140, "catalog has {n} presets"); -} - -#[test] -fn round_rect_handle_maps_back() { - let g = build("roundRect", 200.0, 100.0, &[16667.0]).unwrap(); - let h = g.handles.first().unwrap(); - assert!((h.value_at(h.pos) - 16667.0).abs() <= 1.0); - assert_eq!(h.value_at(Point::new(-50.0, 0.0)), 0.0); - assert_eq!(h.value_at(Point::new(500.0, 0.0)), 50000.0); -} - -#[test] -fn partial_circle_angle_handles_map_back() { - // Start 0° sits at the right of the ellipse, end 270° at its top. - for name in ["pie", "chord", "arc"] { - let g = build(name, 200.0, 100.0, &[0.0, 16200000.0]).unwrap(); - assert_eq!(g.handles.iter().map(|h| h.index).collect::>(), vec![0, 1], "{name}"); - let (s, e) = (&g.handles[0], &g.handles[1]); - assert!((s.pos - Point::new(200.0, 50.0)).hypot() < 1e-6, "{name} {:?}", s.pos); - assert!((e.pos - Point::new(100.0, 0.0)).hypot() < 1e-6, "{name} {:?}", e.pos); - assert_eq!(s.value_at(s.pos), 0.0, "{name}"); - assert_eq!(e.value_at(e.pos), 16200000.0, "{name}"); - // Dragging to the bottom of the ellipse gives 90°. - assert_eq!(s.value_at(Point::new(100.0, 100.0)), 5400000.0, "{name}"); - // Off-axis angles on a non-square ellipse: the visual 45° ray meets the 200×100 - // ellipse at offset (√2000, √2000) from the centre. - let k = 2000f64.sqrt(); - let g = build(name, 200.0, 100.0, &[2700000.0, 8100000.0]).unwrap(); - let (s, e) = (&g.handles[0], &g.handles[1]); - assert!((s.pos - Point::new(100.0 + k, 50.0 + k)).hypot() < 1e-6, "{name} {:?}", s.pos); - assert!((e.pos - Point::new(100.0 - k, 50.0 + k)).hypot() < 1e-6, "{name} {:?}", e.pos); - for (deg, h) in [(45.0, s), (135.0, e)] { - let on = ((h.pos.x - 100.0) / 100.0).powi(2) + ((h.pos.y - 50.0) / 50.0).powi(2); - assert!((on - 1.0).abs() < 1e-9, "{name} {deg}° off ellipse: {:?}", h.pos); - assert!((h.value_at(h.pos) - deg * 60000.0).abs() <= 1.0, "{name} {deg}°: {}", h.value_at(h.pos)); - } - } - for deg in [45.0, 135.0, 200.0, 315.0] { - let g = build("blockArc", 200.0, 100.0, &[deg * 60000.0, 0.0, 25000.0]).unwrap(); - let start = g.handles.iter().find(|h| h.index == 0).unwrap(); - // Thickness 25 → the handle runs on the 87.5×37.5 mid-ring ellipse. - let on = ((start.pos.x - 100.0) / 87.5).powi(2) + ((start.pos.y - 50.0) / 37.5).powi(2); - assert!((on - 1.0).abs() < 1e-9, "blockArc {deg}° off ring: {:?}", start.pos); - let d = start.pos - Point::new(100.0, 50.0); - assert!((d.y.atan2(d.x).to_degrees().rem_euclid(360.0) - deg).abs() < 1e-6, "blockArc {deg}°: {:?}", start.pos); - assert!((start.value_at(start.pos) - deg * 60000.0).abs() <= 1.0, "blockArc {deg}°"); - } - let g = build("blockArc", 200.0, 100.0, &[10800000.0, 0.0, 25000.0]).unwrap(); - let start = g.handles.iter().find(|h| h.index == 0).unwrap(); - assert_eq!(start.value_at(start.pos), 10800000.0); - let thick = g.handles.iter().find(|h| h.index == 2).unwrap(); - assert!((thick.value_at(thick.pos) - 25000.0).abs() <= 1.0); -} - -#[test] -fn presets_with_adjust_values_expose_handles() { - // Presets whose adjust values have no handle of their own yet. - const NO_HANDLES: &[&str] = &[ - "curvedConnector3", - "snip2SameRect", - "snip2DiagRect", - "snipRoundRect", - "round1Rect", - "round2SameRect", - "round2DiagRect", - "teardrop", - "halfFrame", - "corner", - "diagStripe", - "foldedCorner", - "smileyFace", - "moon", - "gear6", - "gear9", - "bracketPair", - "bracePair", - "leftBracket", - "rightBracket", - "leftBrace", - "rightBrace", - "leftRightArrow", - "upDownArrow", - "quadArrow", - "leftRightUpArrow", - "bentArrow", - "uturnArrow", - "curvedRightArrow", - "curvedLeftArrow", - "curvedUpArrow", - "curvedDownArrow", - "leftUpArrow", - "bentUpArrow", - "circularArrow", - "leftCircularArrow", - "leftRightCircularArrow", - "swooshArrow", - "rightArrowCallout", - "downArrowCallout", - "leftArrowCallout", - "upArrowCallout", - "leftRightArrowCallout", - "upDownArrowCallout", - "quadArrowCallout", - "mathPlus", - "mathMinus", - "mathMultiply", - "mathDivide", - "mathEqual", - "mathNotEqual", - "ribbon2", - "ribbon", - "ellipseRibbon2", - "ellipseRibbon", - "leftRightRibbon", - "verticalScroll", - "horizontalScroll", - "wave", - "doubleWave", - "borderCallout1", - "borderCallout2", - "borderCallout3", - "accentCallout1", - "accentCallout2", - "accentCallout3", - "callout1", - "callout2", - "callout3", - "accentBorderCallout1", - "accentBorderCallout2", - "accentBorderCallout3", - ]; - for p in CATALOG { - if p.defaults.is_empty() || NO_HANDLES.contains(&p.name) { - continue; - } - let g = build(p.name, 200.0, 100.0, &[]).unwrap(); - assert!(!g.handles.is_empty(), "{} has adjust values but no handles", p.name); - } -} - -#[test] -fn rect_area_and_ellipse_area() { - let g = build("rect", 100.0, 50.0, &[]).unwrap(); - assert!((g.paths[0].path.area().abs() - 5000.0).abs() < 1e-6); - let e = build("ellipse", 100.0, 50.0, &[]).unwrap(); - let expect = std::f64::consts::PI * 50.0 * 25.0; - assert!((e.paths[0].path.area().abs() - expect).abs() / expect < 0.01); -} - -#[test] -fn lines_are_open() { - assert!(build("line", 10.0, 10.0, &[]).unwrap().is_open()); - assert!(!build("rect", 10.0, 10.0, &[]).unwrap().is_open()); -} - -fn on_path(g: &Geometry, p: Point, tol: f64) -> bool { - use kurbo::ParamCurveNearest; - g.paths.iter().any(|sp| sp.path.segments().any(|seg| seg.nearest(p, 1e-6).distance_sq <= tol * tol)) -} - -#[test] -fn fixed_shapes_follow_the_standards_coordinates() { - // Points of ECMA-376's definitions (in 21600ths), checked on a 216 × 108 box. - let (w, h) = (216.0, 108.0); - let at = |x: f64, y: f64| Point::new(w * x / 21600.0, h * y / 21600.0); - let g = build("lightningBolt", w, h, &[]).unwrap(); - for (x, y) in [(8472.0, 0.0), (16577.0, 12007.0), (21600.0, 21600.0), (0.0, 3890.0)] { - assert!(on_path(&g, at(x, y), 1e-6), "lightningBolt ({x}, {y})"); - } - let g = build("irregularSeal1", w, h, &[]).unwrap(); - assert!(on_path(&g, at(14522.0, 0.0), 1e-6) && on_path(&g, at(8485.0, 21600.0), 1e-6)); - let g = build("irregularSeal2", w, h, &[]).unwrap(); - assert!(on_path(&g, at(14790.0, 0.0), 1e-6) && on_path(&g, at(4917.0, 21600.0), 1e-6)); - // The heart's point is the middle of the bottom edge, its notch a quarter down. - let g = build("heart", w, h, &[]).unwrap(); - assert!(on_path(&g, Point::new(w / 2.0, h), 1e-6) && on_path(&g, Point::new(w / 2.0, h / 4.0), 1e-6)); - let g = build("flowChartDocument", w, h, &[]).unwrap(); - assert!(on_path(&g, at(21600.0, 17322.0), 1e-6) && on_path(&g, at(0.0, 20172.0), 1e-6)); - // Punched tape: the top edge dips to a fifth of the height a quarter of the way along. - let g = build("flowChartPunchedTape", w, h, &[]).unwrap(); - assert!(on_path(&g, Point::new(w / 4.0, h / 5.0), 1e-3) && on_path(&g, Point::new(w * 0.75, 0.0), 1e-3)); - let g = build("flowChartMultidocument", w, h, &[]).unwrap(); - assert!(on_path(&g, at(2972.0, 0.0), 1e-6) && on_path(&g, at(18595.0, 18022.0), 1e-6)); -} - -#[test] -fn notched_arrow_notch_parallels_the_head() { - // presetShapeDefinitions: the notch's point is at x1 = dy1 · dx2 / hd2, so its edges run - // parallel to the head's (25 on a 200 × 100 arrow at the default adjusts). - for (w, h, adj, x1) in [(200.0, 100.0, [50000.0, 50000.0], 25.0), (300.0, 120.0, [80000.0, 30000.0], 28.8)] { - let g = build("notchedRightArrow", w, h, &adj).unwrap(); - let notch = g.paths[0].path.elements().iter().find_map(|e| match e { - kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) if (p.y - h / 2.0).abs() < 1e-9 && p.x < w / 2.0 => Some(*p), - _ => None, - }); - assert!(notch.is_some_and(|p| (p.x - x1).abs() < 1e-6), "{w}x{h} {adj:?}: notch at {notch:?}, want x = {x1}"); - } -} - -#[test] -fn equation_shapes_match_powerpoints_outlines() { - // Corners read off PowerPoint's own outlines of the presets at their default adjusts. - let g = build("mathMultiply", 216.0, 216.0, &[]).unwrap(); - for (x, y) in [(0.32333, 0.15702), (0.5, 0.33369), (0.84298, 0.32333), (0.66631, 0.5), (0.33369, 0.5)] { - assert!(on_path(&g, Point::new(216.0 * x, 216.0 * y), 0.01), "multiply ({x}, {y})"); - } - let g = build("mathEqual", 300.0, 120.0, &[]).unwrap(); - for (x, y) in [(0.13255, 0.5588), (0.86745, 0.794), (0.13255, 0.206), (0.86745, 0.4412)] { - assert!(on_path(&g, Point::new(300.0 * x, 120.0 * y), 0.01), "equal ({x}, {y})"); - } - let g = build("mathPlus", 216.0, 216.0, &[]).unwrap(); - assert!(on_path(&g, Point::new(216.0 * 0.3824, 216.0 * 0.13255), 0.01) && on_path(&g, Point::new(216.0 * 0.86745, 216.0 * 0.6176), 0.01)); - // A tall "not equal": its slash, leaning at the default 110° from top to bottom, reaches - // past the box's sides exactly as far as PowerPoint's (-22.242 to 122.242). - let g = build("mathNotEqual", 100.0, 260.0, &[]).unwrap(); - use kurbo::Shape as _; - let bb = g.paths[0].path.bounding_box(); - assert!((bb.x0 + 22.242).abs() < 0.01 && (bb.x1 - 122.242).abs() < 0.01 && bb.y0.abs() < 1e-6 && (bb.y1 - 260.0).abs() < 1e-6, "{bb:?}"); -} - -#[test] -fn sun_and_waves_match_powerpoints_outlines() { - // Points read off PowerPoint's outlines of the presets (216 pt square, default adjusts). - let k = 216.0; - let g = build("sun", k, k, &[]).unwrap(); - for (x, y) in [(0.85352, 0.14644), (0.76161, 0.33987), (0.66013, 0.23839), (0.42825, 0.79823), (0.20177, 0.57175), (0.75, 0.5), (0.5, 0.25)] { - assert!(on_path(&g, Point::new(k * x, k * y), 0.02), "sun ({x}, {y})"); - } - let g = build("wave", k, k, &[]).unwrap(); - for (x, y) in [(0.21875, 0.00484), (1.0, 0.125), (1.0, 0.875), (0.0, 0.875)] { - assert!(on_path(&g, Point::new(k * x, k * y), 0.05), "wave ({x}, {y})"); - } - // Shifted: a wave of 300 × 120 with adj (20000, 8000) starts 0.16 of the width in. - let g = build("wave", 300.0, 120.0, &[20000.0, 8000.0]).unwrap(); - for (x, y) in [(0.18375, 0.00774), (0.84, 0.2), (1.0, 0.8), (0.16, 0.8)] { - assert!(on_path(&g, Point::new(300.0 * x, 120.0 * y), 0.05), "shifted wave ({x}, {y})"); - } -} - -#[test] -fn star_text_rectangles_follow_the_standard() { - // star5 at its default 19098 in a 144 pt square: the inner pentagon, about 0.38 of the - // width (PowerPoint wraps "Shape 3" at 18 pt there), from y ≈ 55 to ≈ 110. - let g = build("star5", 144.0, 144.0, &[]).unwrap(); - let t = g.text_rect; - assert!((t.width() - 55.0).abs() < 1.0, "{t:?}"); - assert!((t.y0 - 55.0).abs() < 1.0 && (t.y1 - 110.0).abs() < 1.0, "{t:?}"); - // star4 at 12500: the square through its inner points' 45° corners. - let g = build("star4", 144.0, 144.0, &[]).unwrap(); - assert!((g.text_rect.width() - 72.0 * 0.25 * 2f64.sqrt()).abs() < 0.5, "{:?}", g.text_rect); -} - -#[test] -fn stars_are_stretched_like_the_standards() { - // star5 in a 216 pt square: top point at the top middle, side points at 18 degrees on an - // ellipse 5.146% wider and 10.557% taller, centred 10.557% below the middle; its bottom - // points reach the box's bottom edge. - let k = 216.0; - let g = build("star5", k, k, &[]).unwrap(); - let (rx, ry, cy) = (k / 2.0 * 1.05146, k / 2.0 * 1.10557, k / 2.0 * 1.10557); - let a = 18f64.to_radians(); - assert!(on_path(&g, Point::new(k / 2.0, 0.0), 1e-6)); - assert!(on_path(&g, Point::new(k / 2.0 + rx * a.cos(), cy - ry * a.sin()), 1e-6)); - use kurbo::Shape as _; - let bb = g.paths[0].path.bounding_box(); - assert!((bb.x0).abs() < 0.5 && (bb.x1 - k).abs() < 0.5 && (bb.y1 - k).abs() < 0.5, "{bb:?}"); - // star6 is 15.47% wider than its box's half-width allows (its points touch the sides). - let g = build("star6", k, k, &[]).unwrap(); - let bb = g.paths[0].path.bounding_box(); - assert!((bb.x0).abs() < 0.5 && (bb.x1 - k).abs() < 0.5, "{bb:?}"); -} - -#[test] -fn moon_disk_and_drum_match_powerpoints_outlines() { - let k = 216.0; - // Moon, default: the inner edge runs through (0.5, 0.5) and (0.625, 0.2266) of the box. - let g = build("moon", k, k, &[]).unwrap(); - for (x, y) in [(0.5, 0.5), (0.626, 0.2266), (0.0, 0.5), (1.0, 0.0)] { - assert!(on_path(&g, Point::new(k * x, k * y), 0.5), "moon ({x}, {y})"); - } - // 300 × 120 at 30%: its inner edge reaches 30% of the width in. - let g = build("moon", 300.0, 120.0, &[30000.0]).unwrap(); - assert!(on_path(&g, Point::new(90.0, 60.0), 0.5)); - // Magnetic disk ends are ellipses h/6 high, drum ends w/6 across. - let g = build("flowChartMagneticDisk", k, k, &[]).unwrap(); - assert!(on_path(&g, Point::new(k, k / 6.0), 0.01) && on_path(&g, Point::new(k / 2.0, k / 3.0), 0.5)); - let g = build("flowChartMagneticDrum", k, k, &[]).unwrap(); - assert!(on_path(&g, Point::new(k / 6.0, 0.0), 0.01) && on_path(&g, Point::new(0.0, k / 2.0), 0.01)); -} - -#[test] -fn the_cloud_fills_its_box_at_any_aspect_and_has_creases() { - use kurbo::Shape as _; - for (w, h) in [(200.0, 200.0), (300.0, 100.0), (60.0, 180.0)] { - let g = build("cloud", w, h, &[]).unwrap(); - let bb = g.paths[0].path.bounding_box(); - assert!(bb.x0.abs() < w * 0.02 && (bb.x1 - w).abs() < w * 0.02, "{w}×{h}: {bb:?}"); - assert!(bb.y0.abs() < h * 0.02 && (bb.y1 - h).abs() < h * 0.02, "{w}×{h}: {bb:?}"); - assert_eq!(g.paths.len(), 2, "outline and creases"); - assert!(g.paths[1].stroke && g.paths[1].fill == FillMode::None); - } -} - -#[test] -fn spec_arcs_take_angles_as_directions_from_the_centre() { - // A DrawingML arc of a 2:1 ellipse from 45° to 90°: 45° is the direction (1, 1) from the - // centre, which on that ellipse is the point (r/√5)·(2, 1)… scaled so it lies on it. - let mut b = Pb::new(); - b.m(0.0, 0.0).arc_spec(200.0, 100.0, 45.0, 45.0); - let p = b.take(); - let end = p.elements().last().and_then(|e| match e { - kurbo::PathEl::CurveTo(_, _, q) => Some(*q), - _ => None, - }); - // Centre: the start sits at direction 45°, i.e. at (k, k) from it with (k/200)² + (k/100)² = 1. - let k = 1.0 / (1.0f64 / 40000.0 + 1.0 / 10000.0).sqrt(); - let c = Point::new(-k, -k); - let q = end.unwrap(); - assert!((q.x - c.x).abs() < 1e-6 && (q.y - (c.y + 100.0)).abs() < 1e-6, "{q:?} vs centre {c:?}"); -} - -#[test] -fn brackets_and_braces_fill_out_to_their_straight_side() { - // PowerPoint fills a bracket or brace (when it has a fill) between its curve and the - // straight side it opens to; only the curve is outlined. - for name in ["leftBracket", "rightBracket", "leftBrace", "rightBrace"] { - let g = build(name, 40.0, 100.0, &[]).unwrap(); - let filled: Vec<_> = g.paths.iter().filter(|p| p.fill != FillMode::None).collect(); - assert_eq!(filled.len(), 1, "{name}"); - assert!(!filled[0].stroke, "{name}: the filled area is not outlined"); - let area = filled[0].path.area().abs(); - assert!(area > 40.0 * 100.0 * 0.4 && area < 40.0 * 100.0, "{name}: {area}"); - assert!(g.paths.iter().any(|p| p.stroke && p.fill == FillMode::None), "{name}: the curve is outlined"); - } -} - -/// The end points of a path's move/line elements, in order. -fn vertices(p: &BezPath) -> Vec { - p.elements() - .iter() - .filter_map(|e| match e { - kurbo::PathEl::MoveTo(q) | kurbo::PathEl::LineTo(q) => Some(*q), - _ => None, - }) - .collect() -} - -#[test] -fn wedge_callout_mirrors_with_its_tip() { - // A tip below and right of the centre draws the mirror image of the same tip on the left; - // the same for a tip right of the centre, above or below it. presetShapeDefinitions puts - // the wedge's base at 2..5 twelfths of the edge on the near side of the centre and at - // 7..10 twelfths on the far side. - let (w, h) = (240.0, 120.0); - // Sorted and deduplicated: the outline closes on the corner it starts from, which the - // mirror moves to the opposite corner. - let sorted = |mut v: Vec| { - v.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); - v.dedup_by(|a, b| (*a - *b).hypot() < 1e-9); - v - }; - for (right, left, flip_x) in [([10000.0, 80000.0], [-10000.0, 80000.0], true), ([80000.0, 10000.0], [80000.0, -10000.0], false)] { - let a = vertices(&build("wedgeRectCallout", w, h, &right).unwrap().paths[0].path); - let b = vertices(&build("wedgeRectCallout", w, h, &left).unwrap().paths[0].path); - let b: Vec = b.iter().map(|p| if flip_x { Point::new(w - p.x, p.y) } else { Point::new(p.x, h - p.y) }).collect(); - let (a, b) = (sorted(a), sorted(b)); - assert_eq!(a.len(), b.len(), "{right:?}: {a:?} vs mirrored {left:?}: {b:?}"); - for (p, q) in a.iter().zip(&b) { - assert!((*p - *q).hypot() < 1e-6, "{right:?}: {a:?}\n is not the mirror of {left:?}: {b:?}"); - } - } - // The bottom wedge of a tip right of the centre leaves the edge at 7/12 and 10/12 of the width. - let a = vertices(&build("wedgeRectCallout", w, h, &[10000.0, 80000.0]).unwrap().paths[0].path); - for x in [w * 7.0 / 12.0, w * 10.0 / 12.0] { - assert!(a.iter().any(|p| (p.x - x).abs() < 1e-6 && (p.y - h).abs() < 1e-6), "no wedge corner at ({x}, {h}): {a:?}"); - } -} diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs deleted file mode 100644 index 81376d7d7..000000000 --- a/crates/geom/src/warp.rs +++ /dev/null @@ -1,1023 +0,0 @@ -//! WordArt text warps (DrawingML `a:bodyPr/a:prstTxWarp`). -//! -//! A warp preset is a list of bands laid over the shape's text rectangle (insets are ignored). -//! Text lines are shared out over the bands in order (the first ⌈n/k⌉ lines to the first band -//! and so on). A band either -//! - stretches its lines between a top and a bottom guide ([`Band::Fill`]): the ink box of the -//! band's lines fills the band vertically (a band whose ink is shorter than the tallest band's -//! keeps the same scale, centred), and horizontally the text is scaled so that the -//! widest band is filled along the mean length of its guides (one scale for the whole text), or -//! - sets its lines at their natural size along one guide ([`Band::Follow`], arches and circles): -//! glyphs keep their size, are placed by arc length (aligned as in the paragraph, the whole -//! guide being the line's width: insets don't count) and stand on -//! the guide's left normal; lines further from the guide stack outwards. Lines that are longer -//! than the guide are shrunk to fit. -//! -//! Positions along a guide are by arc length; a fill band maps the same fraction of its top and -//! bottom guide's length and interpolates between them. The guide curves were derived from -//! observation: synthetic decks of `I` bars were drawn with PowerPoint and every curve fitted to -//! the measured bar ends (most fit within a point on a 420 × 200 pt box). -use kurbo::{Arc, BezPath, PathEl, Point, Rect, Vec2}; - -/// Flattening tolerance for guides, in points. -const TOL: f64 = 0.02; - -/// A guide curve flattened to a polyline with cumulative arc lengths. -#[derive(Clone, Debug, Default)] -pub struct Guide { - pts: Vec, - cum: Vec, - closed: bool, -} - -impl Guide { - fn from_points(raw: impl IntoIterator, closed: bool) -> Guide { - let mut pts: Vec = Vec::new(); - let mut cum: Vec = Vec::new(); - for p in raw { - if !(p.x.is_finite() && p.y.is_finite()) { - continue; - } - match pts.last() { - Some(q) => { - let d = (p - *q).hypot(); - if d > 1e-9 { - cum.push(cum.last().copied().unwrap_or(0.0) + d); - pts.push(p); - } - } - None => { - pts.push(p); - cum.push(0.0); - } - } - if pts.len() > 100_000 { - break; - } - } - Guide { pts, cum, closed } - } - - /// A guide through `path` (any curves), flattened. - pub fn from_path(path: &BezPath, closed: bool) -> Guide { - let mut pts = Vec::new(); - kurbo::flatten(path.iter(), TOL, |el| match el { - PathEl::MoveTo(p) | PathEl::LineTo(p) => pts.push(p), - _ => {} - }); - Guide::from_points(pts, closed) - } - - /// Total arc length. - pub fn length(&self) -> f64 { - self.cum.last().copied().unwrap_or(0.0) - } - - /// Whether the guide is a closed loop (positions past its end wrap around). - pub fn is_closed(&self) -> bool { - self.closed - } - - /// Point and unit tangent at arc length `s`. Open guides continue along their end tangents - /// past either end; closed guides wrap. - pub fn at(&self, s: f64) -> (Point, Vec2) { - let len = self.length(); - let (Some(&first), Some(&last)) = (self.pts.first(), self.pts.last()) else { - return (Point::ZERO, Vec2::new(1.0, 0.0)); - }; - if self.pts.len() < 2 || len <= 1e-9 { - return (first, Vec2::new(1.0, 0.0)); - } - let s = if s.is_finite() { s } else { 0.0 }; - let s = if self.closed { s.rem_euclid(len) } else { s }; - let seg = |i: usize| -> (Point, Point, f64) { - let a = self.pts.get(i).copied().unwrap_or(first); - let b = self.pts.get(i + 1).copied().unwrap_or(last); - (a, b, self.cum.get(i).copied().unwrap_or(0.0)) - }; - let n = self.pts.len(); - let i = if s <= 0.0 { - 0 - } else if s >= len { - n - 2 - } else { - self.cum.partition_point(|c| *c <= s).saturating_sub(1).min(n - 2) - }; - let (a, b, c0) = seg(i); - let d = b - a; - let l = d.hypot(); - let t = if l > 1e-12 { d / l } else { Vec2::new(1.0, 0.0) }; - (a + t * (s - c0), t) - } - - /// The parallel curve `d` points away on the left of the direction of travel (above a - /// guide running left to right). - pub fn offset(&self, d: f64) -> Guide { - let n = self.pts.len(); - if n < 2 || !d.is_finite() || d == 0.0 { - return self.clone(); - } - let unit = |i: usize| -> Vec2 { - let (a, b) = (self.pts.get(i).copied().unwrap_or(Point::ZERO), self.pts.get(i + 1).copied().unwrap_or(Point::ZERO)); - let v = b - a; - let l = v.hypot(); - if l > 1e-12 { v / l } else { Vec2::ZERO } - }; - let pts = (0..n).map(|i| { - let before = if i > 0 { - unit(i - 1) - } else if self.closed { - unit(n - 2) - } else { - Vec2::ZERO - }; - let after = if i + 1 < n { - unit(i) - } else if self.closed { - unit(0) - } else { - Vec2::ZERO - }; - let t = before + after; - let l = t.hypot(); - let t = if l > 1e-12 { t / l } else { Vec2::new(1.0, 0.0) }; - self.pts.get(i).copied().unwrap_or(Point::ZERO) + Vec2::new(t.y, -t.x) * d - }); - Guide::from_points(pts.collect::>(), self.closed) - } - - /// The point at fraction `t` of the length. - pub fn at_frac(&self, t: f64) -> Point { - self.at(t * self.length()).0 - } -} - -/// Which line of a follow band sits on its guide. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LineAnchor { - /// The last line; earlier lines stack outwards (arch up, circle). - Last, - /// The first line; later lines stack below it (arch down). - First, - /// The middle of the band's lines. - Middle, -} - -#[derive(Clone, Debug)] -pub enum Band { - /// Text stretched between two guides. - Fill { top: Guide, bottom: Guide }, - /// Text at its natural size along a guide. - Follow { path: Guide, anchor: LineAnchor }, -} - -impl Band { - /// The length text is measured against: the mean of a fill band's guides. - pub fn length(&self) -> f64 { - match self { - Band::Fill { top, bottom } => (top.length() + bottom.length()) / 2.0, - Band::Follow { path, .. } => path.length(), - } - } -} - -/// A resolved warp: its bands in shape-local points. -#[derive(Clone, Debug)] -pub struct Warp { - pub bands: Vec, -} - -/// Presets whose text follows a guide at its natural size (no wrapping). -pub fn is_follow(name: &str) -> bool { - matches!(name, "textArchUp" | "textArchDown" | "textCircle" | "textButton") -} - -/// Default adjust values of a warp preset (`adj`, or `adj1`, `adj2`); empty for unknown presets. -pub fn adjust_defaults(name: &str) -> &'static [f64] { - match name { - "textPlain" => &[50_000.0], - "textStop" => &[25_000.0], - "textTriangle" | "textTriangleInverted" => &[50_000.0], - "textChevron" => &[25_000.0], - "textChevronInverted" => &[75_000.0], - "textRingInside" | "textRingOutside" => &[60_000.0], - "textArchUp" | "textCircle" | "textButton" => &[10_800_000.0], - "textArchDown" => &[0.0], - "textArchUpPour" | "textCirclePour" | "textButtonPour" => &[10_800_000.0, 50_000.0], - "textArchDownPour" => &[0.0, 25_000.0], - "textCurveUp" | "textCurveDown" => &[45_977.0], - "textCanUp" => &[85_000.0], - "textCanDown" => &[14_286.0], - "textWave1" | "textWave2" => &[12_500.0, 0.0], - "textDoubleWave1" | "textWave4" => &[6_250.0, 0.0], - "textInflate" | "textDeflate" => &[18_750.0], - "textInflateBottom" => &[60_000.0], - "textDeflateBottom" | "textDeflateTop" => &[50_000.0], - "textInflateTop" => &[40_000.0], - "textDeflateInflate" => &[35_000.0], - "textDeflateInflateDeflate" => &[25_000.0], - "textFadeRight" | "textFadeLeft" | "textFadeUp" | "textFadeDown" => &[33_333.0], - "textSlantUp" => &[55_556.0], - "textSlantDown" => &[44_444.0], - "textCascadeUp" | "textCascadeDown" => &[44_444.0], - _ => &[], - } -} - -/// Number of adjust values a warp preset takes. -pub fn adjust_count(name: &str) -> usize { - adjust_defaults(name).len() -} - -/// Whether `name` is a warp preset DeckCraft draws. -pub fn is_supported(name: &str) -> bool { - !adjust_defaults(name).is_empty() -} - -/// One DrawingML text-warp preset, in gallery order. -pub struct Preset { - /// `prstTxWarp` value, e.g. `textArchUp`. - pub id: &'static str, - /// Name shown on the Transform gallery tile. - pub label: &'static str, -} - -/// The 40 presets DeckCraft draws, Follow Path first, then Warp. -pub const CATALOG: &[Preset] = &[ - Preset { id: "textArchUp", label: "Arch Up" }, - Preset { id: "textArchDown", label: "Arch Down" }, - Preset { id: "textCircle", label: "Circle" }, - Preset { id: "textButton", label: "Button" }, - Preset { id: "textPlain", label: "Plain" }, - Preset { id: "textStop", label: "Stop" }, - Preset { id: "textTriangle", label: "Triangle" }, - Preset { id: "textTriangleInverted", label: "Inverted Triangle" }, - Preset { id: "textChevron", label: "Chevron" }, - Preset { id: "textChevronInverted", label: "Inverted Chevron" }, - Preset { id: "textRingInside", label: "Ring Inside" }, - Preset { id: "textRingOutside", label: "Ring Outside" }, - Preset { id: "textArchUpPour", label: "Arch Up Pour" }, - Preset { id: "textArchDownPour", label: "Arch Down Pour" }, - Preset { id: "textCirclePour", label: "Circle Pour" }, - Preset { id: "textButtonPour", label: "Button Pour" }, - Preset { id: "textCurveUp", label: "Curve Up" }, - Preset { id: "textCurveDown", label: "Curve Down" }, - Preset { id: "textCanUp", label: "Can Up" }, - Preset { id: "textCanDown", label: "Can Down" }, - Preset { id: "textWave1", label: "Wave 1" }, - Preset { id: "textWave2", label: "Wave 2" }, - Preset { id: "textDoubleWave1", label: "Double Wave 1" }, - Preset { id: "textWave4", label: "Wave 4" }, - Preset { id: "textInflate", label: "Inflate" }, - Preset { id: "textDeflate", label: "Deflate" }, - Preset { id: "textInflateBottom", label: "Inflate Bottom" }, - Preset { id: "textDeflateBottom", label: "Deflate Bottom" }, - Preset { id: "textInflateTop", label: "Inflate Top" }, - Preset { id: "textDeflateTop", label: "Deflate Top" }, - Preset { id: "textDeflateInflate", label: "Deflate Inflate" }, - Preset { id: "textDeflateInflateDeflate", label: "Deflate Inflate Deflate" }, - Preset { id: "textFadeRight", label: "Fade Right" }, - Preset { id: "textFadeLeft", label: "Fade Left" }, - Preset { id: "textFadeUp", label: "Fade Up" }, - Preset { id: "textFadeDown", label: "Fade Down" }, - Preset { id: "textSlantUp", label: "Slant Up" }, - Preset { id: "textSlantDown", label: "Slant Down" }, - Preset { id: "textCascadeUp", label: "Cascade Up" }, - Preset { id: "textCascadeDown", label: "Cascade Down" }, -]; - -/// A yellow adjust handle for one warp guide value. `pos` is in the same space as `rect` -/// (shape-local points). Dragging projects the pointer onto the handle's axis, or around the -/// text rectangle's centre for an angle. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct WarpHandle { - pub index: usize, - pub pos: Point, - kind: HandleKind, -} - -#[derive(Clone, Copy, Debug, PartialEq)] -enum HandleKind { - /// `pos = origin + dir * raw`. `value_at` projects onto that line and clamps. - Line { origin: Point, dir: Vec2, min: f64, max: f64 }, - /// Angle about `center` (y down, 0° at +x). `invert` is arch-down, whose guide angle is `180° − adj`. - Angle { center: Point, invert: bool }, -} - -impl WarpHandle { - /// The raw guide value (`adj` / `adjN`) for a pointer at `p`. - pub fn value_at(&self, p: Point) -> f64 { - match self.kind { - HandleKind::Line { origin, dir, min, max } => { - let l2 = dir.hypot2(); - if l2 < 1e-18 || !(p.x.is_finite() && p.y.is_finite()) { - return min; - } - let v = (p - origin).dot(dir) / l2; - if !v.is_finite() { - return min; - } - let (lo, hi) = (min.min(max), max.max(min)); - v.clamp(lo, hi).round() - } - HandleKind::Angle { center, invert } => { - let d = p - center; - if !(d.x.is_finite() && d.y.is_finite()) || d.hypot() < 1e-9 { - return 0.0; - } - let mut deg = d.y.atan2(d.x).to_degrees(); - if invert { - deg = 180.0 - deg; - } - (deg.rem_euclid(360.0) * 60_000.0).round() - } - } - } -} - -fn stored_raw(adj: &[f64], defaults: &[f64], i: usize) -> f64 { - adj.get(i).copied().filter(|v| v.is_finite()).or_else(|| defaults.get(i).copied()).unwrap_or(0.0) -} - -fn unit(rect: Rect, u: f64, v: f64) -> Point { - Point::new(rect.x0 + u * rect.width(), rect.y0 + v * rect.height()) -} - -/// A fraction handle: unit position `(x, sign * frac)`, raw = frac × 100 000, clamped to `lo..=hi`. -fn frac_handle(rect: Rect, index: usize, x: f64, frac: f64, lo: f64, hi: f64, sign: f64) -> WarpHandle { - let frac = frac.clamp(lo, hi); - WarpHandle { - index, - pos: unit(rect, x, sign * frac), - kind: HandleKind::Line { - origin: unit(rect, x, 0.0), - dir: Vec2::new(0.0, sign * rect.height() / 100_000.0), - min: lo * 100_000.0, - max: hi * 100_000.0, - }, - } -} - -/// A fraction handle that slides horizontally: unit `(frac, y)`. -fn frac_x_handle(rect: Rect, index: usize, y: f64, frac: f64, lo: f64, hi: f64) -> WarpHandle { - let frac = frac.clamp(lo, hi); - WarpHandle { - index, - pos: unit(rect, frac, y), - kind: HandleKind::Line { - origin: unit(rect, 0.0, y), - dir: Vec2::new(rect.width() / 100_000.0, 0.0), - min: lo * 100_000.0, - max: hi * 100_000.0, - }, - } -} - -/// Angle handle, inset from the ellipse so it doesn't sit on a resize handle. -fn angle_handle(rect: Rect, index: usize, deg: f64, invert: bool) -> WarpHandle { - let geom = if invert { 180.0 - deg } else { deg }; - let rad = geom.to_radians(); - let c = rect.center(); - WarpHandle { - index, - pos: Point::new(c.x + rect.width() * 0.36 * rad.cos(), c.y + rect.height() * 0.36 * rad.sin()), - kind: HandleKind::Angle { center: c, invert }, - } -} - -/// Inner-ellipse radius (pour presets): the handle sits on the downward point of that ellipse. -fn radius_handle(rect: Rect, r: f64) -> WarpHandle { - let r = r.clamp(0.0, 0.99); - WarpHandle { - index: 1, - pos: unit(rect, 0.5, 0.5 + 0.5 * r), - kind: HandleKind::Line { origin: unit(rect, 0.5, 0.5), dir: Vec2::new(0.0, 0.5 * rect.height() / 100_000.0), min: 0.0, max: 99_000.0 }, - } -} - -/// Wave phase: slides sideways around the middle of the lower half. -fn shift_handle(rect: Rect, s: f64) -> WarpHandle { - let s = s.clamp(-0.1, 0.1); - WarpHandle { - index: 1, - pos: unit(rect, 0.5 + s, 0.78), - kind: HandleKind::Line { origin: unit(rect, 0.5, 0.78), dir: Vec2::new(rect.width() / 100_000.0, 0.0), min: -10_000.0, max: 10_000.0 }, - } -} - -/// Yellow handles for warp `name` over text rectangle `rect`. Empty when `name` isn't a drawn -/// preset or `rect` isn't a usable box. Missing adjust values take the preset defaults. -pub fn handles(name: &str, adj: &[f64], rect: Rect) -> Vec { - if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) { - return Vec::new(); - } - let rect = Rect::new(rect.x0.min(rect.x1), rect.y0.min(rect.y1), rect.x0.max(rect.x1), rect.y0.max(rect.y1)); - if rect.width() < 1e-3 || rect.height() < 1e-3 { - return Vec::new(); - } - let defaults = adjust_defaults(name); - if defaults.is_empty() { - return Vec::new(); - } - let raw = |i| stored_raw(adj, defaults, i); - let frac = |i| raw(i) / 100_000.0; - let deg = |i| (raw(i) / 60_000.0).rem_euclid(360.0); - let y = |out: &mut Vec, x, lo, hi, sign| out.push(frac_handle(rect, 0, x, frac(0), lo, hi, sign)); - let xh = |out: &mut Vec, yy, lo, hi| out.push(frac_x_handle(rect, 0, yy, frac(0), lo, hi)); - let mut out = Vec::with_capacity(defaults.len()); - match name { - "textPlain" => xh(&mut out, 0.28, 0.3, 0.7), - "textStop" => y(&mut out, 0.5, 0.14286, 0.5, 1.0), - "textTriangle" | "textTriangleInverted" => y(&mut out, 0.18, 0.0, 1.0, 1.0), - "textChevron" => y(&mut out, 0.18, 0.0, 0.5, 1.0), - "textChevronInverted" => y(&mut out, 0.18, 0.5, 1.0, 1.0), - "textFadeRight" => y(&mut out, 0.82, 0.0, 0.49999, 1.0), - "textFadeLeft" => y(&mut out, 0.18, 0.0, 0.49999, 1.0), - "textFadeUp" => xh(&mut out, 0.22, 0.0, 0.49999), - "textFadeDown" => xh(&mut out, 0.78, 0.0, 0.49999), - "textSlantUp" => y(&mut out, 0.18, 0.44444, 1.0, 1.0), - "textSlantDown" => y(&mut out, 0.18, 0.0, 0.55556, 1.0), - "textCascadeUp" => y(&mut out, 0.82, 0.0, 1.0, 1.0), - "textCascadeDown" => y(&mut out, 0.18, 0.0, 1.0, 1.0), - "textInflate" => y(&mut out, 0.62, 0.0, 0.2, -1.0), - "textDeflate" => y(&mut out, 0.62, 0.0, 0.375, 1.0), - "textInflateBottom" => y(&mut out, 0.62, 0.6, 1.0, 1.0), - "textDeflateBottom" => y(&mut out, 0.62, 0.0625, 1.0, 1.0), - "textInflateTop" => y(&mut out, 0.62, 0.0, 0.5, 1.0), - "textDeflateTop" => y(&mut out, 0.62, 0.0, 0.9375, 1.0), - "textDeflateInflate" => y(&mut out, 0.5, 0.05, 0.95, 1.0), - "textDeflateInflateDeflate" => y(&mut out, 0.5, 0.01, 1.0 / 3.0, 1.0), - "textCurveUp" | "textCurveDown" => y(&mut out, 0.18, 0.0, 0.56818, 1.0), - "textCanUp" => y(&mut out, 0.62, 0.5, 1.0, 1.0), - "textCanDown" => y(&mut out, 0.62, 0.0, 0.5, 1.0), - "textRingInside" | "textRingOutside" => y(&mut out, 0.5, 0.5, 0.99, 1.0), - "textArchUp" | "textCircle" | "textButton" => out.push(angle_handle(rect, 0, deg(0), false)), - "textArchDown" => out.push(angle_handle(rect, 0, deg(0), true)), - "textArchUpPour" | "textCirclePour" | "textButtonPour" => { - out.push(angle_handle(rect, 0, deg(0), false)); - out.push(radius_handle(rect, frac(1))); - } - "textArchDownPour" => { - out.push(angle_handle(rect, 0, deg(0), true)); - out.push(radius_handle(rect, frac(1))); - } - "textWave1" | "textWave2" => { - y(&mut out, 0.32, 0.0, 0.2, 1.0); - out.push(shift_handle(rect, frac(1))); - } - "textDoubleWave1" | "textWave4" => { - y(&mut out, 0.32, 0.0, 0.125, 1.0); - out.push(shift_handle(rect, frac(1))); - } - _ => return Vec::new(), - } - out -} - -/// Segments of a guide in unit coordinates (x, y in 0..1 over the text rectangle). -#[derive(Clone, Copy, Debug)] -enum Seg { - M(f64, f64), - L(f64, f64), - Q(f64, f64, f64, f64), - C(f64, f64, f64, f64, f64, f64), - /// Elliptical arc: centre, radii, start and sweep in degrees (y down: positive = clockwise). - A(f64, f64, f64, f64, f64, f64), -} - -enum Spec { - Fill(Vec, Vec), - Follow(Vec, LineAnchor), -} - -struct Adj<'a> { - raw: &'a [f64], - defaults: &'static [f64], -} - -impl Adj<'_> { - fn raw(&self, i: usize) -> f64 { - self.raw.get(i).copied().filter(|v| v.is_finite()).or_else(|| self.defaults.get(i).copied()).unwrap_or(0.0) - } - /// Adjust `i` as a fraction (1/100 000), pinned to `lo..=hi` (fractions). - fn frac(&self, i: usize, lo: f64, hi: f64) -> f64 { - (self.raw(i) / 100_000.0).clamp(lo, hi) - } - /// Adjust `i` as an angle in degrees (1/60 000), in 0..360. - fn angle(&self, i: usize) -> f64 { - (self.raw(i) / 60_000.0).rem_euclid(360.0) - } -} - -fn line(pts: &[(f64, f64)]) -> Vec { - pts.iter().enumerate().map(|(i, &(x, y))| if i == 0 { Seg::M(x, y) } else { Seg::L(x, y) }).collect() -} - -/// Quadratic from (0, y0) through control (0.5, c) to (1, y0). -fn quad(y0: f64, c: f64) -> Vec { - vec![Seg::M(0.0, y0), Seg::Q(0.5, c, 1.0, y0)] -} - -/// A sweep in (0, 360]: zero means a full turn. -fn turn(deg: f64) -> f64 { - let d = deg.rem_euclid(360.0); - if d < 1e-9 { 360.0 } else { d } -} - -/// Arc of the ellipse inscribed in the rectangle, scaled by `s` about its centre. -fn ellipse(s: f64, start: f64, sweep: f64) -> Vec { - vec![Seg::A(0.5, 0.5, 0.5 * s, 0.5 * s, start, sweep)] -} - -/// The arch-up arc for adjust angle `a`: symmetric about the top (270°), clockwise. -fn arch_up(a: f64) -> (f64, f64) { - (a, turn(2.0 * (270.0 - a))) -} - -/// The arch-down arc for adjust angle `a`: symmetric about the bottom (90°), counter-clockwise. -fn arch_down(a: f64) -> (f64, f64) { - (180.0 - a, -turn(180.0 - 2.0 * a)) -} - -/// The circle arc for adjust angle `a`: from `a` clockwise, symmetric about 0°. -fn circle(a: f64) -> (f64, f64) { - (a, turn(2.0 * (360.0 - a))) -} - -/// One cubic wave period from x0 to x1 at height y: up first when `k` > 0 (y decreases). -fn wave(out: &mut Vec, x0: f64, x1: f64, y: f64, k: f64) { - let l = x1 - x0; - out.push(Seg::C(x0 + l / 3.0, y - k, x0 + 2.0 * l / 3.0, y + k, x1, y)); -} - -/// Wave guides: `periods` cubic waves over the width, shifted apart by `shift` (fraction). -fn waves(a: f64, shift: f64, periods: usize, up_first: bool) -> Spec { - let d = 2.0 * shift; - let (top_x, bot_x) = if d >= 0.0 { ((0.0, 1.0 - d), (d, 1.0)) } else { ((-d, 1.0), (0.0, 1.0 + d)) }; - let k = if up_first { a * 10.0 / 3.0 } else { -a * 10.0 / 3.0 }; - let guide = |(x0, x1): (f64, f64), y: f64| { - let mut v = vec![Seg::M(x0, y)]; - let n = periods.max(1) as f64; - for i in 0..periods.max(1) { - let f = i as f64; - wave(&mut v, x0 + (x1 - x0) * f / n, x0 + (x1 - x0) * (f + 1.0) / n, y, k); - } - v - }; - Spec::Fill(guide(top_x, a), guide(bot_x, 1.0 - a)) -} - -fn spec(name: &str, a: &Adj) -> Option> { - use Seg::*; - let fill = |t: Vec, b: Vec| vec![Spec::Fill(t, b)]; - let top = || line(&[(0.0, 0.0), (1.0, 0.0)]); - let bottom = || line(&[(0.0, 1.0), (1.0, 1.0)]); - Some(match name { - "textPlain" => { - let d = 2.0 * (a.frac(0, 0.3, 0.7) - 0.5); - if d < 0.0 { - fill(line(&[(-d, 0.0), (1.0, 0.0)]), line(&[(0.0, 1.0), (1.0 + d, 1.0)])) - } else { - fill(line(&[(0.0, 0.0), (1.0 - d, 0.0)]), line(&[(d, 1.0), (1.0, 1.0)])) - } - } - "textStop" => { - let y = a.frac(0, 0.14286, 0.5); - let t = 1.0 / 3.0; - fill(line(&[(0.0, y), (t, 0.0), (1.0 - t, 0.0), (1.0, y)]), line(&[(0.0, 1.0 - y), (t, 1.0), (1.0 - t, 1.0), (1.0, 1.0 - y)])) - } - "textTriangle" => { - let y = a.frac(0, 0.0, 1.0); - fill(line(&[(0.0, y), (0.5, 0.0), (1.0, y)]), bottom()) - } - "textTriangleInverted" => { - let y = a.frac(0, 0.0, 1.0); - fill(top(), line(&[(0.0, y), (0.5, 1.0), (1.0, y)])) - } - "textChevron" => { - let y = a.frac(0, 0.0, 0.5); - fill(line(&[(0.0, y), (0.5, 0.0), (1.0, y)]), line(&[(0.0, 1.0), (0.5, 1.0 - y), (1.0, 1.0)])) - } - "textChevronInverted" => { - let y = a.frac(0, 0.5, 1.0); - fill(line(&[(0.0, 0.0), (0.5, 1.0 - y), (1.0, 0.0)]), line(&[(0.0, y), (0.5, 1.0), (1.0, y)])) - } - "textFadeRight" => { - let y = a.frac(0, 0.0, 0.49999); - fill(line(&[(0.0, 0.0), (1.0, y)]), line(&[(0.0, 1.0), (1.0, 1.0 - y)])) - } - "textFadeLeft" => { - let y = a.frac(0, 0.0, 0.49999); - fill(line(&[(0.0, y), (1.0, 0.0)]), line(&[(0.0, 1.0 - y), (1.0, 1.0)])) - } - "textFadeUp" => { - let x = a.frac(0, 0.0, 0.49999); - fill(line(&[(x, 0.0), (1.0 - x, 0.0)]), bottom()) - } - "textFadeDown" => { - let x = a.frac(0, 0.0, 0.49999); - fill(top(), line(&[(x, 1.0), (1.0 - x, 1.0)])) - } - "textSlantUp" => { - let y = a.frac(0, 0.44444, 1.0); - fill(line(&[(0.0, y), (1.0, 0.0)]), line(&[(0.0, 1.0), (1.0, 1.0 - y)])) - } - "textSlantDown" => { - let y = a.frac(0, 0.0, 0.55556); - fill(line(&[(0.0, 0.0), (1.0, 1.0 - y)]), line(&[(0.0, y), (1.0, 1.0)])) - } - "textCascadeUp" => { - let y = a.frac(0, 0.0, 1.0); - fill(line(&[(0.0, (1.0 - y) / 4.0), (1.0, 0.0)]), line(&[(0.0, 1.0), (1.0, y)])) - } - "textCascadeDown" => { - let y = a.frac(0, 0.0, 1.0); - fill(line(&[(0.0, 0.0), (1.0, (1.0 - y) / 4.0)]), line(&[(0.0, y), (1.0, 1.0)])) - } - "textInflate" => { - let y = a.frac(0, 0.0, 0.2); - fill(quad(y, -y), quad(1.0 - y, 1.0 + y)) - } - "textDeflate" => { - let y = a.frac(0, 0.0, 0.375); - fill(quad(0.0, 2.0 * y), quad(1.0, 1.0 - 2.0 * y)) - } - "textInflateBottom" => { - let y = a.frac(0, 0.6, 1.0); - fill(top(), quad(y, 1.0)) - } - "textDeflateBottom" => { - let y = a.frac(0, 0.0625, 1.0); - fill(top(), quad(1.0, 2.0 * y - 1.0)) - } - "textInflateTop" => { - let y = a.frac(0, 0.0, 0.5); - fill(quad(y, 0.0), bottom()) - } - "textDeflateTop" => { - let y = a.frac(0, 0.0, 0.9375); - fill(quad(0.0, 2.0 * y), bottom()) - } - "textDeflateInflate" => { - // The bands are split by a curve from mid-height up to `y`, with a gap of a tenth of - // a band's height. - let y = a.frac(0, 0.05, 0.95); - let g = 0.05; - vec![Spec::Fill(top(), quad(0.5 - g, 2.0 * y - 0.5 - g)), Spec::Fill(quad(0.5 + g, 2.0 * y - 0.5 + g), bottom())] - } - "textDeflateInflateDeflate" => { - let y = a.frac(0, 0.01, 1.0 / 3.0); - let g = 1.0 / 30.0; - let (t1, t2) = (1.0 / 3.0, 2.0 / 3.0); - let (c1, c2) = (2.0 * y - t1, 2.0 * (1.0 - y) - t2); - vec![ - Spec::Fill(top(), quad(t1 - g, c1 - g)), - Spec::Fill(quad(t1 + g, c1 + g), quad(t2 - g, c2 - g)), - Spec::Fill(quad(t2 + g, c2 + g), bottom()), - ] - } - "textCurveUp" | "textCurveDown" => { - let y = a.frac(0, 0.0, 0.56818); - let b = vec![M(0.0, 1.0 - 3.0 * y / 8.0), C(1.0 / 3.0, 1.0 + y / 8.0, 2.0 / 3.0, 1.0 + y / 8.0, 1.0, 1.0 - 3.0 * y / 8.0)]; - let t = if name == "textCurveUp" { - vec![M(0.0, y), C(1.0 / 3.0, 1.25 * y, 2.0 / 3.0, 0.75 * y, 1.0, 0.0)] - } else { - vec![M(0.0, 0.0), C(1.0 / 3.0, 0.75 * y, 2.0 / 3.0, 1.25 * y, 1.0, y)] - }; - fill(t, b) - } - "textCanUp" => { - let r = 1.0 - a.frac(0, 0.5, 1.0); - fill(vec![A(0.5, r, 0.5, r, 180.0, 180.0)], vec![A(0.5, 1.0, 0.5, r, 180.0, 180.0)]) - } - "textCanDown" => { - let r = a.frac(0, 0.0, 0.5); - fill(vec![A(0.5, 0.0, 0.5, r, 180.0, -180.0)], vec![A(0.5, 1.0 - r, 0.5, r, 180.0, -180.0)]) - } - "textRingInside" | "textRingOutside" => { - let h = a.frac(0, 0.5, 0.99); - let sweep = if name == "textRingInside" { 360.0 } else { -360.0 }; - fill(vec![A(0.5, h / 2.0, 0.5, h / 2.0, 180.0, sweep)], vec![A(0.5, 1.0 - h / 2.0, 0.5, h / 2.0, 180.0, sweep)]) - } - "textWave1" => vec![waves(a.frac(0, 0.0, 0.2), a.frac(1, -0.1, 0.1), 1, true)], - "textWave2" => vec![waves(a.frac(0, 0.0, 0.2), a.frac(1, -0.1, 0.1), 1, false)], - "textDoubleWave1" => vec![waves(a.frac(0, 0.0, 0.125), a.frac(1, -0.1, 0.1), 2, true)], - "textWave4" => vec![waves(a.frac(0, 0.0, 0.125), a.frac(1, -0.1, 0.1), 2, false)], - "textArchUp" => { - let (s, w) = arch_up(a.angle(0)); - vec![Spec::Follow(ellipse(1.0, s, w), LineAnchor::Last)] - } - "textArchDown" => { - let (s, w) = arch_down(a.angle(0)); - vec![Spec::Follow(ellipse(1.0, s, w), LineAnchor::First)] - } - "textCircle" => { - let (s, w) = circle(a.angle(0)); - vec![Spec::Follow(ellipse(1.0, s, w), LineAnchor::Last)] - } - "textButton" => { - let t = a.angle(0); - let (s, w) = arch_up(t); - let half = 0.5 * t.to_radians().cos().abs(); - vec![ - Spec::Follow(ellipse(1.0, s, w), LineAnchor::Last), - Spec::Follow(line(&[(0.5 - half, 0.5), (0.5 + half, 0.5)]), LineAnchor::Middle), - Spec::Follow(ellipse(1.0, 360.0 - s, -w), LineAnchor::First), - ] - } - "textArchUpPour" => { - let (s, w) = arch_up(a.angle(0)); - let r = a.frac(1, 0.0, 0.99); - fill(ellipse(1.0, s, w), ellipse(r, s, w)) - } - "textArchDownPour" => { - let (s, w) = arch_down(a.angle(0)); - let r = a.frac(1, 0.0, 0.99); - fill(ellipse(r, s, w), ellipse(1.0, s, w)) - } - "textCirclePour" => { - let (s, w) = circle(a.angle(0)); - let r = a.frac(1, 0.0, 0.99); - fill(ellipse(1.0, s, w), ellipse(r, s, w)) - } - "textButtonPour" => { - let (s, w) = arch_up(a.angle(0)); - let r = a.frac(1, 0.0, 0.99); - // The middle band runs between chords of the inner ellipse halfway to its top and - // bottom. - let (dy, half) = (0.25 * r, 0.25 * r * 3f64.sqrt()); - vec![ - Spec::Fill(ellipse(1.0, s, w), ellipse(r, s, w)), - Spec::Fill(line(&[(0.5 - half, 0.5 - dy), (0.5 + half, 0.5 - dy)]), line(&[(0.5 - half, 0.5 + dy), (0.5 + half, 0.5 + dy)])), - Spec::Fill(ellipse(r, 360.0 - s, -w), ellipse(1.0, 360.0 - s, -w)), - ] - } - _ => return None, - }) -} - -/// Build a guide from unit-space segments mapped onto `r`. -fn guide(segs: &[Seg], r: Rect) -> Guide { - let mut p = BezPath::new(); - let mut started = false; - let mut closed = false; - for s in segs { - match *s { - Seg::M(x, y) => { - p.move_to((x, y)); - started = true; - } - Seg::L(x, y) => { - if started { - p.line_to((x, y)) - } else { - p.move_to((x, y)) - } - started = true; - } - Seg::Q(cx, cy, x, y) => { - if started { - p.quad_to((cx, cy), (x, y)); - } - } - Seg::C(x1, y1, x2, y2, x, y) => { - if started { - p.curve_to((x1, y1), (x2, y2), (x, y)); - } - } - Seg::A(cx, cy, rx, ry, start, sweep) => { - let arc = Arc::new((cx, cy), (rx.max(0.0), ry.max(0.0)), start.to_radians(), sweep.to_radians(), 0.0); - let s0 = Point::new(cx + rx * start.to_radians().cos(), cy + ry * start.to_radians().sin()); - if started { - p.line_to(s0); - } else { - p.move_to(s0); - } - started = true; - for el in arc.append_iter(1e-5) { - p.push(el); - } - closed = sweep.abs() >= 359.999; - } - } - } - let m = kurbo::Affine::new([r.width(), 0.0, 0.0, r.height(), r.x0, r.y0]); - p.apply_affine(m); - Guide::from_path(&p, closed) -} - -/// The warp `name` with adjust values `adj` (raw guide values; missing ones take the defaults) -/// over text rectangle `rect`. `None` for unknown presets, `textNoShape` or a non-finite rect. -pub fn warp(name: &str, adj: &[f64], rect: Rect) -> Option { - if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) { - return None; - } - let r = Rect::new(rect.x0.min(rect.x1), rect.y0.min(rect.y1), rect.x0.max(rect.x1), rect.y0.max(rect.y1)); - let a = Adj { raw: adj, defaults: adjust_defaults(name) }; - let specs = spec(name, &a)?; - let bands = specs - .into_iter() - .map(|s| match s { - Spec::Fill(t, b) => Band::Fill { top: guide(&t, r), bottom: guide(&b, r) }, - Spec::Follow(p, anchor) => Band::Follow { path: guide(&p, r), anchor }, - }) - .collect(); - Some(Warp { bands }) -} - -/// The band line `line` of `lines` goes to when there are `bands` bands: the first ⌈n/k⌉ lines -/// share the first band, and so on. -pub fn band_of_line(line: usize, lines: usize, bands: usize) -> usize { - if bands <= 1 || lines == 0 { - return 0; - } - // Band b holds lines ceil(b·n/k) .. ceil((b+1)·n/k). - (0..bands).rev().find(|&b| (b * lines).div_ceil(bands) <= line).unwrap_or(0) -} - -/// One laid-out line as the warp sees it (layout coordinates, points). -#[derive(Clone, Copy, Debug)] -pub struct WarpLine { - /// Ink box of the line's glyphs; `None` for a line without ink. - pub ink: Option, - /// Advance extent of the line (left, right). - pub extent: (f64, f64), - /// Reference height for follow bands: the y that sits on the guide. - pub ref_y: f64, -} - -#[derive(Clone, Copy, Debug)] -enum LineMap { - Fill { - band: usize, - cx: f64, - k: f64, - len: f64, - y0: f64, - y1: f64, - }, - /// `guide`: the line's own parallel guide in [`Mapper::offsets`], if it is off the band's. - Follow { - band: usize, - guide: Option, - e0: f64, - s0: f64, - k: f64, - ref_y: f64, - }, -} - -/// Maps points of laid-out lines onto a warp. -#[derive(Clone, Debug)] -pub struct Mapper<'a> { - warp: &'a Warp, - lines: Vec, - offsets: Vec, - zoom: f64, -} - -impl Warp { - /// Plan the mapping of `lines`, laid out in the inner text box `inner` (the line's place in - /// it gives its alignment along follow guides; the insets themselves don't shorten a guide). - pub fn mapper(&self, lines: &[WarpLine], inner: Rect) -> Mapper<'_> { - let nb = self.bands.len().max(1); - let n = lines.len(); - let band_of: Vec = (0..n).map(|i| band_of_line(i, n, nb).min(nb - 1)).collect(); - // Ink of the whole text, for the shared horizontal centre and scale of fill bands. - let ink_all = lines.iter().filter_map(|l| l.ink).reduce(|a, b| a.union(b)); - let cx = ink_all.map(|r| r.center().x).unwrap_or(0.0); - let mut k_fill = f64::INFINITY; - let mut zoom: f64 = 1.0; - let mut band_y: Vec> = vec![None; nb]; - for (i, l) in lines.iter().enumerate() { - let Some(r) = l.ink else { continue }; - let b = band_of.get(i).copied().unwrap_or(0); - if let Some(slot) = band_y.get_mut(b) { - *slot = Some(match *slot { - Some((y0, y1)) => (y0.min(r.y0), y1.max(r.y1)), - None => (r.y0, r.y1), - }); - } - } - // Every fill band maps a box as tall as the tallest band's ink, centred on its own ink, so - // a band with fewer lines keeps them at the same size, centred between its guides. - let tallest = band_y.iter().flatten().map(|(y0, y1)| y1 - y0).fold(0.0, f64::max); - let band_y: Vec> = - band_y.iter().map(|r| r.map(|(y0, y1)| ((y0 + y1 - tallest) / 2.0, (y0 + y1 + tallest) / 2.0))).collect(); - for (b, band) in self.bands.iter().enumerate() { - if let Band::Fill { top, bottom } = band { - let half = lines - .iter() - .enumerate() - .filter(|(i, _)| band_of.get(*i) == Some(&b)) - .filter_map(|(_, l)| l.ink) - .map(|r| (r.x0 - cx).abs().max((r.x1 - cx).abs())) - .fold(0.0, f64::max); - if half > 1e-9 { - k_fill = k_fill.min(band.length() / (2.0 * half)); - } - if let Some(Some((y0, y1))) = band_y.get(b) { - let thick = [0.0, 0.25, 0.5, 0.75, 1.0].iter().map(|&u| (top.at_frac(u) - bottom.at_frac(u)).hypot()).fold(0.0, f64::max); - if y1 - y0 > 1e-9 { - zoom = zoom.max(thick / (y1 - y0)); - } - } - } - } - if !k_fill.is_finite() { - k_fill = 1.0; - } - zoom = zoom.max(k_fill); - // Per band, measured once: its widest line and its first and last lines' baselines. - let mut stats: Vec> = vec![None; nb]; - for (l, &b) in lines.iter().zip(&band_of) { - let w = l.extent.1 - l.extent.0; - if let Some(slot) = stats.get_mut(b) { - match slot { - Some((widest, _, last)) => { - *widest = widest.max(w); - *last = l.ref_y; - } - None => *slot = Some((0.0f64.max(w), l.ref_y, l.ref_y)), - } - } - } - let mut maps = Vec::with_capacity(n); - let mut offsets = Vec::new(); - for (i, l) in lines.iter().enumerate() { - let b = band_of.get(i).copied().unwrap_or(0); - let band = stats.get(b).copied().flatten(); - match self.bands.get(b) { - Some(Band::Fill { .. }) | None => { - let (y0, y1) = band_y.get(b).copied().flatten().unwrap_or((0.0, 1.0)); - let len = self.bands.get(b).map(Band::length).unwrap_or(0.0); - maps.push(LineMap::Fill { band: b, cx, k: k_fill, len, y0, y1 }); - } - Some(Band::Follow { path, anchor }) => { - let len = path.length(); - let widest = band.map_or(0.0, |s| s.0); - let k = if widest > len && widest > 1e-9 { len / widest } else { 1.0 }; - let ref_y = match anchor { - LineAnchor::Last => band.map(|s| s.2), - LineAnchor::First => band.map(|s| s.1), - LineAnchor::Middle => band.map(|s| (s.1 + s.2) / 2.0), - } - .unwrap_or(l.ref_y); - // Lines off the guide run on a parallel curve at their natural length. - let d = (ref_y - l.ref_y) * k; - let (guide, len) = if d.abs() > 1e-6 && d.is_finite() && offsets.len() < 4096 { - let g = path.offset(d); - let len = g.length(); - offsets.push(g); - (Some(offsets.len() - 1), len) - } else { - (None, len) - }; - let (e0, e1) = l.extent; - let w = (e1 - e0).max(0.0) * k; - let (gl, gr) = ((e0 - inner.x0).max(0.0), (inner.x1 - e1).max(0.0)); - let f = if gl + gr > 1e-9 { gl / (gl + gr) } else { 0.5 }; - let s0 = f * (len - w); - maps.push(LineMap::Follow { band: b, guide, e0, s0, k, ref_y: l.ref_y }); - } - } - } - Mapper { warp: self, lines: maps, offsets, zoom: if zoom.is_finite() { zoom.clamp(1.0, 1.0e4) } else { 1.0 } } - } -} - -impl Mapper<'_> { - /// How much the warp magnifies text at most (for flattening tolerances), ≥ 1. - pub fn zoom(&self) -> f64 { - self.zoom - } - - /// Map point `p` of line `line` (layout coordinates) onto the warp. - pub fn map(&self, line: usize, p: Point) -> Point { - let out = match self.lines.get(line) { - Some(&LineMap::Fill { band, cx, k, len, y0, y1 }) => { - let Some(Band::Fill { top, bottom }) = self.warp.bands.get(band) else { return p }; - let u = if len > 1e-9 { 0.5 + (p.x - cx) * k / len } else { 0.5 }; - let v = if y1 - y0 > 1e-9 { (p.y - y0) / (y1 - y0) } else { 0.5 }; - let (t, b) = (top.at_frac(u), bottom.at_frac(u)); - t.lerp(b, v) - } - Some(&LineMap::Follow { band, guide, e0, s0, k, ref_y }) => { - let path = match (guide.and_then(|g| self.offsets.get(g)), self.warp.bands.get(band)) { - (Some(g), _) => g, - (None, Some(Band::Follow { path, .. })) => path, - _ => return p, - }; - let s = s0 + (p.x - e0) * k; - let d = (ref_y - p.y) * k; - let (q, t) = path.at(s); - q + Vec2::new(t.y, -t.x) * d - } - None => p, - }; - if out.x.is_finite() && out.y.is_finite() { out } else { p } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/geom/src/warp/tests.rs b/crates/geom/src/warp/tests.rs deleted file mode 100644 index c4aa1bbd0..000000000 --- a/crates/geom/src/warp/tests.rs +++ /dev/null @@ -1,338 +0,0 @@ -use super::{ - Band, BezPath, CATALOG, Guide, Point, Rect, WarpLine, adjust_count, adjust_defaults, band_of_line, handles, is_follow, is_supported, warp, -}; - -const W: f64 = 420.0; -const H: f64 = 200.0; - -fn rect() -> Rect { - Rect::new(0.0, 0.0, W, H) -} - -/// One line whose ink box is `ink`. -fn one_line(ink: Rect) -> Vec { - vec![WarpLine { ink: Some(ink), extent: (ink.x0, ink.x1), ref_y: ink.y1 }] -} - -/// Where the unit-square point (u, v) of a single line's ink box lands, in unit coordinates. -fn land(name: &str, adj: &[f64], u: f64, v: f64) -> (f64, f64) { - let w = warp(name, adj, rect()).unwrap(); - let ink = Rect::new(100.0, 50.0, 300.0, 90.0); - let lines = one_line(ink); - let m = w.mapper(&lines, rect().inset(-5.0)); - let p = m.map(0, Point::new(ink.x0 + u * ink.width(), ink.y0 + v * ink.height())); - (p.x / W, p.y / H) -} - -fn close(a: (f64, f64), b: (f64, f64), tol: f64) -> bool { - (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol -} - -#[track_caller] -fn corners(name: &str, adj: &[f64], tl: (f64, f64), tr: (f64, f64), bl: (f64, f64), br: (f64, f64)) { - for ((u, v), want) in [((0.0, 0.0), tl), ((1.0, 0.0), tr), ((0.0, 1.0), bl), ((1.0, 1.0), br)] { - let got = land(name, adj, u, v); - assert!(close(got, want, 0.004), "{name} corner ({u},{v}): got {got:?}, want {want:?}"); - } -} - -#[test] -fn catalog_is_the_forty_drawn_presets() { - assert_eq!(CATALOG.len(), 40); - let mut seen = std::collections::BTreeSet::new(); - for p in CATALOG { - assert!(seen.insert(p.id), "duplicate {}", p.id); - assert!(!p.label.is_empty(), "{}", p.id); - assert!(is_supported(p.id), "{}", p.id); - assert_eq!(is_follow(p.id), matches!(p.id, "textArchUp" | "textArchDown" | "textCircle" | "textButton"), "{}", p.id); - } -} - -#[test] -fn every_preset_builds_finite_guides() { - for p in CATALOG { - let name = p.id; - assert!(is_supported(name), "{name}"); - let w = warp(name, &[], rect()).unwrap_or_else(|| panic!("{name}")); - assert!(!w.bands.is_empty(), "{name}"); - for b in &w.bands { - let l = b.length(); - assert!(l.is_finite() && l > 10.0, "{name}: band length {l}"); - } - assert_eq!(adjust_count(name), adjust_defaults(name).len()); - } - assert!(warp("textNoShape", &[], rect()).is_none()); - assert!(warp("bogus", &[], rect()).is_none()); - assert!(!is_supported("textNoShape")); -} - -#[test] -fn straight_presets_put_the_ink_corners_on_their_guides() { - corners("textPlain", &[], (0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)); - // A smaller adjust shears the text: the top edge starts 40 % in, the bottom edge ends 60 % in. - corners("textPlain", &[30_000.0], (0.4, 0.0), (1.0, 0.0), (0.0, 1.0), (0.6, 1.0)); - corners("textStop", &[], (0.0, 0.25), (1.0, 0.25), (0.0, 0.75), (1.0, 0.75)); - corners("textTriangle", &[], (0.0, 0.5), (1.0, 0.5), (0.0, 1.0), (1.0, 1.0)); - corners("textTriangleInverted", &[25_000.0], (0.0, 0.0), (1.0, 0.0), (0.0, 0.25), (1.0, 0.25)); - corners("textChevron", &[], (0.0, 0.25), (1.0, 0.25), (0.0, 1.0), (1.0, 1.0)); - corners("textChevronInverted", &[], (0.0, 0.0), (1.0, 0.0), (0.0, 0.75), (1.0, 0.75)); - corners("textFadeRight", &[], (0.0, 0.0), (1.0, 0.33333), (0.0, 1.0), (1.0, 0.66667)); - corners("textFadeLeft", &[], (0.0, 0.33333), (1.0, 0.0), (0.0, 0.66667), (1.0, 1.0)); - corners("textFadeUp", &[], (0.33333, 0.0), (0.66667, 0.0), (0.0, 1.0), (1.0, 1.0)); - corners("textFadeDown", &[], (0.0, 0.0), (1.0, 0.0), (0.33333, 1.0), (0.66667, 1.0)); - corners("textSlantUp", &[], (0.0, 0.55556), (1.0, 0.0), (0.0, 1.0), (1.0, 0.44444)); - corners("textSlantDown", &[], (0.0, 0.0), (1.0, 0.55556), (0.0, 0.44444), (1.0, 1.0)); - corners("textCascadeUp", &[], (0.0, 0.13889), (1.0, 0.0), (0.0, 1.0), (1.0, 0.44444)); - corners("textCascadeDown", &[], (0.0, 0.0), (1.0, 0.13889), (0.0, 0.44444), (1.0, 1.0)); -} - -#[test] -fn curved_presets_bend_where_powerpoint_bends_them() { - corners("textInflate", &[], (0.0, 0.1875), (1.0, 0.1875), (0.0, 0.8125), (1.0, 0.8125)); - assert!(close(land("textInflate", &[], 0.5, 0.0), (0.5, 0.0), 0.004)); - assert!(close(land("textInflate", &[], 0.5, 1.0), (0.5, 1.0), 0.004)); - corners("textDeflate", &[], (0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)); - assert!(close(land("textDeflate", &[], 0.5, 0.0), (0.5, 0.1875), 0.004)); - corners("textInflateBottom", &[], (0.0, 0.0), (1.0, 0.0), (0.0, 0.6), (1.0, 0.6)); - assert!(close(land("textInflateBottom", &[], 0.5, 1.0), (0.5, 0.8), 0.004)); - assert!(close(land("textDeflateBottom", &[], 0.5, 1.0), (0.5, 0.5), 0.004)); - assert!(close(land("textInflateTop", &[], 0.5, 0.0), (0.5, 0.2), 0.004)); - assert!(close(land("textDeflateTop", &[], 0.5, 0.0), (0.5, 0.5), 0.004)); - // Cans: half ellipses. - corners("textCanUp", &[], (0.0, 0.15), (1.0, 0.15), (0.0, 1.0), (1.0, 1.0)); - assert!(close(land("textCanUp", &[], 0.5, 0.0), (0.5, 0.0), 0.004)); - assert!(close(land("textCanUp", &[], 0.5, 1.0), (0.5, 0.85), 0.004)); - assert!(close(land("textCanDown", &[], 0.5, 0.0), (0.5, 0.14286), 0.004)); - // Curves and waves. - let a = 0.45977; - corners("textCurveUp", &[], (0.0, a), (1.0, 0.0), (0.0, 1.0 - 3.0 * a / 8.0), (1.0, 1.0 - 3.0 * a / 8.0)); - assert!(close(land("textCurveUp", &[], 0.5, 1.0), (0.5, 1.0), 0.004)); - corners("textCurveDown", &[], (0.0, 0.0), (1.0, a), (0.0, 1.0 - 3.0 * a / 8.0), (1.0, 1.0 - 3.0 * a / 8.0)); - corners("textWave1", &[], (0.0, 0.125), (1.0, 0.125), (0.0, 0.875), (1.0, 0.875)); - // Wave 1 rises first: its top is near the box top a quarter of the way along. - assert!(land("textWave1", &[], 0.25, 0.0).1 < 0.02); - assert!(land("textWave2", &[], 0.25, 0.0).1 > 0.23); - // A horizontal shift moves the bottom guide right. - corners("textWave1", &[12_500.0, 5_000.0], (0.0, 0.125), (0.9, 0.125), (0.1, 0.875), (1.0, 0.875)); - assert!(land("textDoubleWave1", &[], 0.125, 0.0).1 < 0.02); - assert!(land("textWave4", &[], 0.125, 0.0).1 > 0.1); -} - -#[test] -fn arc_presets_follow_ellipses() { - // Pour arches: the outer arc from the left end over the top; the inner one is scaled by adj2. - corners("textArchUpPour", &[], (0.0, 0.5), (1.0, 0.5), (0.25, 0.5), (0.75, 0.5)); - assert!(close(land("textArchUpPour", &[], 0.5, 0.0), (0.5, 0.0), 0.004)); - assert!(close(land("textArchUpPour", &[], 0.5, 1.0), (0.5, 0.25), 0.004)); - assert!(close(land("textArchUpPour", &[10_800_000.0, 30_000.0], 0.5, 1.0), (0.5, 0.35), 0.004)); - assert!(close(land("textArchDownPour", &[], 0.5, 0.0), (0.5, 0.625), 0.004)); - assert!(close(land("textArchDownPour", &[], 0.5, 1.0), (0.5, 1.0), 0.004)); - // Circle pour: once round from the left; the middle of the text is at the right. - assert!(close(land("textCirclePour", &[], 0.5, 0.0), (1.0, 0.5), 0.004)); - // Rings: the text goes round two stacked ellipses. - assert!(close(land("textRingInside", &[], 0.0, 0.0), (0.0, 0.3), 0.004)); - assert!(close(land("textRingInside", &[], 0.0, 1.0), (0.0, 0.7), 0.004)); - assert!(close(land("textRingInside", &[], 0.25, 0.0), (0.5, 0.0), 0.01)); - assert!(close(land("textRingOutside", &[], 0.25, 1.0), (0.5, 1.0), 0.01)); -} - -#[test] -fn follow_presets_keep_text_size_and_stack_lines_outwards() { - let w = warp("textArchUp", &[], rect()).unwrap(); - // A 40-wide centred line whose reference height is 80. - let line = WarpLine { ink: Some(Rect::new(190.0, 50.0, 230.0, 88.0)), extent: (190.0, 230.0), ref_y: 80.0 }; - let inner = Rect::new(7.2, 3.6, W - 7.2, H - 3.6); - let m = w.mapper(&[line], inner); - // The middle of the reference line lands on the top of the ellipse; 10 pt above it lands - // 10 pt above the top. - let p = m.map(0, Point::new(210.0, 80.0)); - assert!((p.x - 210.0).abs() < 0.05 && p.y.abs() < 0.05, "{p:?}"); - let q = m.map(0, Point::new(210.0, 70.0)); - assert!((q.x - 210.0).abs() < 0.15 && (q.y + 10.0).abs() < 0.05, "{q:?}"); - // Natural size: 40 pt of text spans about 40 pt of arc. - let (a, b) = (m.map(0, Point::new(190.0, 80.0)), m.map(0, Point::new(230.0, 80.0))); - assert!(((b - a).hypot() - 40.0).abs() < 0.5); - // Left-aligned text starts at the very start of the arc: insets don't shorten it. - let left = WarpLine { ink: Some(Rect::new(7.2, 50.0, 47.2, 88.0)), extent: (7.2, 47.2), ref_y: 80.0 }; - let m = w.mapper(&[left], inner); - let p = m.map(0, Point::new(7.2, 80.0)); - assert!(p.x.abs() < 0.01 && (p.y - 100.0).abs() < 0.01, "{p:?}"); - // Two lines on an arch up: the last sits on the arc, the first stacks outside it. - let l1 = WarpLine { ink: Some(Rect::new(190.0, 10.0, 230.0, 40.0)), extent: (190.0, 230.0), ref_y: 34.0 }; - let l2 = WarpLine { ink: Some(Rect::new(190.0, 50.0, 230.0, 80.0)), extent: (190.0, 230.0), ref_y: 74.0 }; - let m = w.mapper(&[l1, l2], inner); - assert!(m.map(1, Point::new(210.0, 74.0)).y.abs() < 0.05); - assert!((m.map(0, Point::new(210.0, 34.0)).y + 40.0).abs() < 0.05); - // Arch down: the first line sits on the bottom of the ellipse. - let w = warp("textArchDown", &[], rect()).unwrap(); - let m = w.mapper(&[l1, l2], inner); - assert!((m.map(0, Point::new(210.0, 34.0)).y - H).abs() < 0.05); - assert!((m.map(1, Point::new(210.0, 74.0)).y - H - 40.0).abs() < 0.05); - // Text longer than the arc is shrunk to fit it. - let w = warp("textArchUp", &[], rect()).unwrap(); - let long = WarpLine { ink: Some(Rect::new(-500.0, 50.0, 900.0, 88.0)), extent: (-500.0, 900.0), ref_y: 80.0 }; - let m = w.mapper(&[long], inner); - let (a, b) = (m.map(0, Point::new(-500.0, 80.0)), m.map(0, Point::new(900.0, 80.0))); - assert!(a.x < 5.0 && b.x > W - 5.0 && (a.y - 100.0).abs() < 10.0 && (b.y - 100.0).abs() < 10.0, "{a:?} {b:?}"); -} - -#[test] -fn lines_share_bands_in_order() { - assert_eq!((0..2).map(|i| band_of_line(i, 2, 2)).collect::>(), [0, 1]); - assert_eq!((0..3).map(|i| band_of_line(i, 3, 2)).collect::>(), [0, 0, 1]); - assert_eq!((0..5).map(|i| band_of_line(i, 5, 2)).collect::>(), [0, 0, 0, 1, 1]); - assert_eq!((0..5).map(|i| band_of_line(i, 5, 3)).collect::>(), [0, 0, 1, 1, 2]); - assert_eq!((0..4).map(|i| band_of_line(i, 4, 3)).collect::>(), [0, 0, 1, 2]); - assert_eq!((0..2).map(|i| band_of_line(i, 2, 3)).collect::>(), [0, 1]); - assert_eq!(band_of_line(0, 1, 3), 0); - assert_eq!(band_of_line(7, 9, 1), 0); - assert_eq!(band_of_line(0, 0, 3), 0); -} - -#[test] -fn deflate_inflate_maps_each_band_separately() { - let w = warp("textDeflateInflate", &[], rect()).unwrap(); - assert_eq!(w.bands.len(), 2); - let l1 = WarpLine { ink: Some(Rect::new(100.0, 10.0, 300.0, 40.0)), extent: (100.0, 300.0), ref_y: 34.0 }; - let l2 = WarpLine { ink: Some(Rect::new(100.0, 50.0, 300.0, 80.0)), extent: (100.0, 300.0), ref_y: 74.0 }; - let m = w.mapper(&[l1, l2], rect()); - // Band 1 ends at 45 % height on the sides, band 2 starts at 55 %. - assert!((m.map(0, Point::new(100.0, 40.0)).y / H - 0.45).abs() < 0.004); - assert!((m.map(1, Point::new(100.0, 50.0)).y / H - 0.55).abs() < 0.004); - assert!((m.map(1, Point::new(300.0, 80.0)).y / H - 1.0).abs() < 0.004); - // A band with fewer lines keeps them at the size of the fuller band, centred in its band: - // two lines (ink 10..60) in band 1, one line (ink 70..80) in band 2 of three. - let a = WarpLine { ink: Some(Rect::new(100.0, 10.0, 300.0, 30.0)), extent: (100.0, 300.0), ref_y: 28.0 }; - let b = WarpLine { ink: Some(Rect::new(100.0, 40.0, 300.0, 60.0)), extent: (100.0, 300.0), ref_y: 58.0 }; - let c = WarpLine { ink: Some(Rect::new(100.0, 70.0, 300.0, 80.0)), extent: (100.0, 300.0), ref_y: 78.0 }; - let m = w.mapper(&[a, b, c], rect()); - let (top, bot) = (m.map(2, Point::new(200.0, 70.0)).y / H, m.map(2, Point::new(200.0, 80.0)).y / H); - // Band 2 runs from 0.4 to 1 at the centre; the line takes the middle fifth of it. - assert!((top - 0.64).abs() < 0.005 && (bot - 0.76).abs() < 0.005, "{top} {bot}"); - // A shorter first line keeps its share of the width. - let short = WarpLine { ink: Some(Rect::new(150.0, 10.0, 250.0, 40.0)), extent: (150.0, 250.0), ref_y: 34.0 }; - let m = w.mapper(&[short, l2], rect()); - let p = m.map(0, Point::new(150.0, 10.0)); - assert!((p.x / W - 0.25).abs() < 0.01, "{p:?}"); -} - -#[test] -fn guides_extrapolate_and_wrap() { - let mut p = BezPath::new(); - p.move_to((0.0, 0.0)); - p.line_to((10.0, 0.0)); - let g = Guide::from_path(&p, false); - assert!((g.length() - 10.0).abs() < 1e-9); - assert!((g.at(15.0).0.x - 15.0).abs() < 1e-9); - assert!((g.at(-5.0).0.x + 5.0).abs() < 1e-9); - assert!(g.at(f64::NAN).0.x.is_finite()); - let w = warp("textCircle", &[], rect()).unwrap(); - let Some(Band::Follow { path, .. }) = w.bands.first() else { panic!() }; - assert!(path.is_closed()); - let l = path.length(); - let (a, b) = (path.at(5.0).0, path.at(l + 5.0).0); - assert!((a - b).hypot() < 1e-6); - let empty = Guide::default(); - assert_eq!(empty.length(), 0.0); - assert!(empty.at(3.0).0.x.is_finite()); -} - -#[test] -fn hostile_adjusts_and_boxes_stay_finite() { - let adjs: &[&[f64]] = - &[&[], &[f64::NAN, f64::INFINITY], &[f64::NEG_INFINITY, f64::NAN], &[1e300, -1e300], &[-1e9, 1e9], &[0.0, 0.0], &[21_599_999.0, 100_000.0]]; - let rects = [ - Rect::new(0.0, 0.0, 0.0, 0.0), - Rect::new(10.0, 10.0, 10.0, 200.0), - Rect::new(0.0, 0.0, 300.0, 0.0), - Rect::new(100.0, 100.0, -50.0, -20.0), - Rect::new(0.0, 0.0, 1e7, 1e7), - ]; - let lines = [ - WarpLine { ink: Some(Rect::new(0.0, 0.0, 0.0, 0.0)), extent: (0.0, 0.0), ref_y: 0.0 }, - WarpLine { ink: None, extent: (5.0, 5.0), ref_y: 3.0 }, - WarpLine { ink: Some(Rect::new(-1e6, -5.0, 1e6, 5.0)), extent: (-1e6, 1e6), ref_y: 4.0 }, - ]; - for name in CATALOG.iter().map(|p| p.id) { - for adj in adjs { - for r in rects { - let Some(w) = warp(name, adj, r) else { panic!("{name} {adj:?} {r:?}") }; - for b in &w.bands { - assert!(b.length().is_finite()); - } - let m = w.mapper(&lines, r); - assert!(m.zoom().is_finite() && m.zoom() >= 1.0); - let probes = [ - (0, Point::ZERO), - (1, Point::new(5.0, 3.0)), - (2, Point::new(1e6, -5.0)), - (2, Point::new(f64::NAN, 1.0)), - (9, Point::new(1.0, 1.0)), - ]; - for (i, p) in probes { - let q = m.map(i, p); - assert!(q.x.is_finite() || !p.x.is_finite(), "{name} {adj:?} {r:?}: {q:?}"); - assert!(q.y.is_finite(), "{name} {adj:?} {r:?}: {q:?}"); - } - } - } - } - assert!(warp("textPlain", &[], Rect::new(f64::NAN, 0.0, 1.0, 1.0)).is_none()); -} - -#[test] -fn every_preset_has_one_handle_per_adjust() { - let r = rect(); - for name in CATALOG.iter().map(|p| p.id) { - let hs = handles(name, &[], r); - assert_eq!(hs.len(), adjust_count(name), "{name}"); - let defaults = adjust_defaults(name); - for h in &hs { - assert!(h.pos.x.is_finite() && h.pos.y.is_finite(), "{name}"); - let back = h.value_at(h.pos); - let want = defaults[h.index]; - assert!((back - want).abs() <= 1.0, "{name} handle {}: {back} vs {want}", h.index); - } - } - assert!(handles("textNoShape", &[], r).is_empty()); - assert!(handles("textArchUp", &[], Rect::new(0.0, 0.0, f64::NAN, 10.0)).is_empty()); - assert!(handles("textArchUp", &[], Rect::new(0.0, 0.0, 0.0, 0.0)).is_empty()); - // A hostile adjust still places a finite handle on the clamped default. - let hs = handles("textInflate", &[f64::NAN], r); - assert_eq!(hs.len(), 1); - assert!(hs[0].pos.x.is_finite() && hs[0].pos.y.is_finite()); -} - -#[test] -fn arch_and_inflate_handles_follow_the_pointer() { - let r = rect(); - let arch = &handles("textArchUp", &[], r)[0]; - let deg = arch.value_at(Point::new(r.center().x, r.y0)) / 60_000.0; - assert!((deg - 270.0).abs() < 0.5, "{deg}"); - let down = &handles("textArchDown", &[], r)[0]; - // The arch-down handle starts on the left; a pointer at the bottom is 90°, which is adjust 90 - // (guide angle 180 − adj). - let deg = down.value_at(Point::new(r.center().x, r.y1)) / 60_000.0; - assert!((deg - 90.0).abs() < 0.5, "{deg}"); - let inf = &handles("textInflate", &[], r)[0]; - let more = inf.value_at(Point::new(inf.pos.x, r.y0 - 80.0)); - assert!(more > adjust_defaults("textInflate")[0], "{more}"); - assert!((more - 20_000.0).abs() < 1.0, "{more}"); -} - -#[test] -fn many_lines_on_a_follow_band_are_mapped_from_one_measurement() { - // 50,000 lines on an arch: each line's scale and anchor come from the band measured once. - let w = warp("textArchUp", &[], rect()).unwrap(); - let inner = Rect::new(7.2, 3.6, W - 7.2, H - 3.6); - let lines: Vec = (0..50_000) - .map(|i| { - let y = i as f64 * 0.01; - WarpLine { ink: Some(Rect::new(190.0, y, 230.0, y + 1.0)), extent: (190.0, 230.0), ref_y: y + 1.0 } - }) - .collect(); - let m = w.mapper(&lines, inner); - // The last line sits on the arc, as with two lines. - let last = lines.len() - 1; - assert!(m.map(last, Point::new(210.0, lines[last].ref_y)).y.abs() < 0.05); -} From f9bc097b4ef92e6b39725ea94716a5787e6565fc Mon Sep 17 00:00:00 2001 From: Hamza Naveed <45464935+Hamza0101@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:39:49 +0500 Subject: [PATCH 63/76] Shapes: the 3- and 4-bend elbow and curved connectors follow presetShapeDefinitions (#1851) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Shapes: the 3- and 4-bend elbow and curved connectors follow presetShapeDefinitions PowerPoint routes connectors around shapes with bentConnector4 and 5 and their curved counterparts. They were drawn as bentConnector3 and curvedConnector3, using adj1 alone, and curvedConnector2 as a two-cubic S where the spec has one cubic. Each now draws the spec's path, and the elbows get a handle per adjust value where the spec puts it. None of these is in the gallery, so their adjust values had no defaults: a file giving none, or only adj2, drew them at 0. adjust_defaults() adds the spec's 50000s for presets outside the gallery, and the reader, writer, Adjust command and handle drag use it. * Shapes: elbow handles take the spec's whole adjust range The handles clamped a dragged value to ±1000000, so dragging one on an imported route with a value beyond that moved the route. They now take presetShapeDefinitions' ±2147483647 (noted in review). --- crates/engine/src/cmd/shape/appearance.rs | 2 +- crates/engine/src/tools/drag.rs | 2 +- crates/pptx/src/read/shapes.rs | 24 ++++++++++++++++++++++- crates/pptx/src/write/shapes.rs | 2 +- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/shape/appearance.rs b/crates/engine/src/cmd/shape/appearance.rs index 4dd406ea3..c9a318abc 100644 --- a/crates/engine/src/cmd/shape/appearance.rs +++ b/crates/engine/src/cmd/shape/appearance.rs @@ -9,7 +9,7 @@ pub(super) fn adjust(s: &mut Session, p: &Value) -> Result { let v = f64_param(p, "value").ok_or_else(|| bad("shape.adjust", "missing `value`"))?; edit_geometry(s, p, "shape.adjust", |sh| { if let Geom::Preset { name, adj } = &mut sh.geom { - let defaults = deckcraft_geom::preset::info(name).map(|x| x.defaults).unwrap_or(&[]); + let defaults = deckcraft_geom::preset::adjust_defaults(name); while adj.len() <= i { let k = adj.len(); adj.push(defaults.get(k).copied().unwrap_or(0.0)); diff --git a/crates/engine/src/tools/drag.rs b/crates/engine/src/tools/drag.rs index 41ade3266..7e8b93a74 100644 --- a/crates/engine/src/tools/drag.rs +++ b/crates/engine/src/tools/drag.rs @@ -293,7 +293,7 @@ impl Session { if let Some(sh) = deckcraft_model::find_shape_mut(list, id) && let deckcraft_model::Geom::Preset { name, adj } = &mut sh.geom { - let defaults = deckcraft_geom::preset::info(name).map(|x| x.defaults).unwrap_or(&[]); + let defaults = deckcraft_geom::preset::adjust_defaults(name); for (i, v) in &vals { while adj.len() <= *i { let k = adj.len(); diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index b6b1c882b..bcef9f8c5 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -177,7 +177,7 @@ fn base(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, nv: Option<&El>) -> Shape { fn preset_geom(pg: &El) -> Geom { let name = pg.attr("prst").unwrap_or("rect").to_string(); - let defaults: Vec = preset::info(&name).map(|i| i.defaults.to_vec()).unwrap_or_default(); + let defaults: Vec = preset::adjust_defaults(&name).to_vec(); let mut adj = defaults; let mut any = false; if let Some(av) = pg.child("avLst") { @@ -897,3 +897,25 @@ fn cell(imp: &mut Imp, part: &Part, tc: &El) -> Cell { } c } + +#[cfg(test)] +mod preset_geom_tests { + use super::*; + + fn geom(xml: &str) -> Geom { + let doc = crate::xml::parse(xml.as_bytes()).unwrap(); + preset_geom(&doc.root) + } + + // A file may give some adjust values and rely on the defaults for the rest. A preset outside the + // gallery had no defaults, so a missing value read as 0: a bentConnector4 with only adj2 lost + // its middle leg. + #[test] + fn a_missing_adjust_value_takes_the_spec_default() { + let a = r#"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + let g = geom(&format!(r#""#)); + assert!(matches!(&g, Geom::Preset { name, adj } if name == "bentConnector4" && adj == &[50000.0, 25000.0]), "{g:?}"); + let g = geom(&format!(r#""#)); + assert!(matches!(&g, Geom::Preset { adj, .. } if adj == &[50000.0, 50000.0, 10000.0]), "{g:?}"); + } +} diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index 4b32264ff..df7a226df 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -94,7 +94,7 @@ pub fn geometry(w: &mut W, g: &Geom) { w.empty0("a:avLst"); } else { // PowerPoint wants the complete guide list once any is given. - let defaults = deckcraft_geom::preset::info(name).map(|i| i.defaults).unwrap_or(&[]); + let defaults = deckcraft_geom::preset::adjust_defaults(name); let mut vals: Vec = adj.iter().take(16).copied().collect(); while vals.len() < defaults.len() { vals.push(defaults.get(vals.len()).copied().unwrap_or(0.0)); From 1ec01a091a310d69a8b354dc64e7e9a2ebf48a22 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 14:31:55 -0500 Subject: [PATCH 64/76] refactor(pptx): reuse shared table style identifiers (#792) (#2189) --- Cargo.lock | 1 + crates/pptx/Cargo.toml | 1 + crates/pptx/src/tables.rs | 92 +++++++++------------------------------ 3 files changed, 22 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 56e5fbf5f..d51d6ce04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1329,6 +1329,7 @@ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ "craft-cfb", + "craft-drawingml", "craft-opc", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "deckcraft-color", diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index 7e66abf13..aceba9f72 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -12,6 +12,7 @@ workspace = true craft-opc.workspace = true craft-xml.workspace = true craft-cfb.workspace = true +craft-drawingml.workspace = true deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/pptx/src/tables.rs b/crates/pptx/src/tables.rs index 2f627796a..62dc983c4 100644 --- a/crates/pptx/src/tables.rs +++ b/crates/pptx/src/tables.rs @@ -4,83 +4,14 @@ use crate::opc::NS_A; use crate::xml::{A, W}; -/// Well-known built-in table style GUIDs (format identifiers) and our equivalent ids. -const KNOWN: &[(&str, &str)] = &[ - ("{2D5ABB26-0587-4C30-8999-92F81FD0307C}", "none"), - ("{5940675A-B579-460E-94D1-54222C63F5DA}", "grid"), - ("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}", "medium2-accent1"), - ("{073A0DAA-6AF3-43AB-8588-CEC1D06C72B9}", "medium2-tx1"), - ("{21E4AEA4-8DFA-4A89-87EB-49C32662AFE8}", "medium2-accent2"), - ("{F5AB1C69-6EDB-4FF4-983F-18BD219EF322}", "medium2-accent3"), - ("{00A15C55-8517-42AA-B614-E9B94910E393}", "medium2-accent4"), - ("{7DF18680-E054-41AD-8BC1-D1AEF772440D}", "medium2-accent5"), - ("{93296810-A885-4BE3-A3E7-6D5BEEA58F35}", "medium2-accent6"), -]; - -/// GUIDs we write as built-in references (no definition needed). -const BUILTIN_WRITE: [&str; 3] = ["none", "grid", "medium2-accent1"]; - -fn fnv(s: &str, seed: u64) -> u64 { - let mut h = 0xcbf2_9ce4_8422_2325u64 ^ seed; - for b in s.bytes() { - h ^= b as u64; - h = h.wrapping_mul(0x0100_0000_01b3); - } - h -} - -/// A stable GUID derived from text (version-4 layout). -pub fn guid(text: &str) -> String { - let a = fnv(text, 0x5163_7261_6674); - let b = fnv(text, 0x7461_626c_6573); - format!( - "{{{:08X}-{:04X}-4{:03X}-8{:03X}-{:012X}}}", - (a >> 32) as u32, - (a >> 16) as u16, - (a & 0x0fff) as u16, - (b >> 48) as u16 & 0x0fff, - b & 0xffff_ffff_ffff - ) -} +// Keep file-format identifiers in the shared DrawingML implementation. The local +// writer below still owns DeckCraft's table style definitions and XML policy. +pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid}; fn own_guid(style: &str) -> String { guid(&format!("deckcraft-table-style:{style}")) } -/// Is `g` the GUID DeckCraft writes for one of its own styles? -pub fn is_own_guid(g: &str) -> bool { - let up = g.to_ascii_uppercase(); - deckcraft_model::table::table_styles().iter().any(|(id, _)| own_guid(id) == up) -} - -/// Table style GUID → our style id (or the GUID itself when unknown). -pub fn style_from_guid(g: &str) -> String { - let up = g.to_ascii_uppercase(); - if let Some((_, s)) = KNOWN.iter().find(|(k, _)| *k == up) { - return s.to_string(); - } - for (id, _) in deckcraft_model::table::table_styles() { - if own_guid(&id) == up { - return id; - } - } - if g.is_empty() { "none".into() } else { g.to_string() } -} - -/// GUID to write for our style id, and whether a definition must be written. -pub fn guid_for_style(style: &str) -> (String, bool) { - if style.starts_with('{') { - return (style.to_string(), false); - } - if BUILTIN_WRITE.contains(&style) - && let Some((g, _)) = KNOWN.iter().find(|(_, s)| *s == style) - { - return (g.to_string(), false); - } - let known = deckcraft_model::table::table_styles().iter().any(|(id, _)| id == style); - if known { (own_guid(style), true) } else { ("{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}".into(), false) } -} - fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) { if mods.is_empty() { w.val("a:schemeClr", slot); @@ -254,6 +185,23 @@ pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableSt mod tests { use super::*; + #[test] + fn shared_style_catalog_matches_deckcraft() { + assert_eq!(deckcraft_model::table::table_styles(), craft_drawingml::table::table_styles()); + assert_eq!(style_from_guid(""), "none"); + let custom = "{abcdef00-0000-0000-0000-000000000000}"; + assert_eq!(style_from_guid(custom), custom); + assert_eq!(guid_for_style(custom), (custom.to_string(), false)); + assert_eq!(guid_for_style("unknown"), guid_for_style("medium2-accent1")); + for (id, _) in deckcraft_model::table::table_styles() { + let generated = own_guid(&id); + assert!(is_own_guid(&generated.to_ascii_lowercase())); + if guid_for_style(&id).1 { + assert_eq!(guid_for_style(&id).0, generated); + } + } + } + #[test] fn style_parts_follow_schema_order() { const ORDER: [&str; 14] = [ From fc6a3c4dbd3503ff41af805437f8939ad84ddaa8 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Tue, 17 Nov 2026 02:30:00 +0000 Subject: [PATCH 65/76] pptx: validate enclosing mainSeq id on onBegin timing exemption --- crates/pptx/src/read/timing.rs | 67 +++++++++++++++++++--------- crates/pptx/tests/it/media_timing.rs | 9 ++++ 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/crates/pptx/src/read/timing.rs b/crates/pptx/src/read/timing.rs index 3106c039b..ca29f4592 100644 --- a/crates/pptx/src/read/timing.rs +++ b/crates/pptx/src/read/timing.rs @@ -65,11 +65,38 @@ struct Found<'a> { #[derive(Clone, Copy)] struct At { trigger: Option, + main_seq_id: Option, group: usize, offset: u32, deferred: bool, } +/// Returns whether `st` (`p:stCondLst`) is PowerPoint's automatic main-sequence step wrapper: +/// `` paired only with `` +/// referencing the immediate enclosing `mainSeq` ``. +fn is_main_seq_auto(st: &El, main_seq_id: Option) -> bool { + let Some(ms_id) = main_seq_id else { + return false; + }; + let is_indefinite = |d: &El| { + d.attr("evt").is_none() + && d.attr("delay").map(str::trim) == Some("indefinite") + && d.child("tgtEl").is_none() + && d.child("tn").is_none() + && d.child("rtn").is_none() + }; + let is_main_seq_on_begin = |d: &El| { + d.attr("evt") == Some("onBegin") + && d.attr("delay").map(str::trim) == Some("0") + && d.child("tgtEl").is_none() + && d.child("rtn").is_none() + && d.child("tn").and_then(|tn| tn.u32("val")) == Some(ms_id) + }; + st.children_named("cond").any(is_indefinite) + && st.children_named("cond").any(is_main_seq_on_begin) + && st.children_named("cond").all(|d| is_indefinite(d) || is_main_seq_on_begin(d)) +} + fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, depth: usize) { if depth > 64 || out.len() > 10_000 { return; @@ -86,29 +113,25 @@ fn collect<'a>(e: &'a El, at: At, groups: &mut usize, out: &mut Vec>, && ctn.attr("nodeType") == Some("interactiveSeq") { at.trigger = ctn.path(&["stCondLst", "cond", "tgtEl", "spTgt"]).and_then(|s| s.u32("spid")); + at.main_seq_id = None; } - if c.is("cTn") - && let Some(st) = c.child("stCondLst") - { - let is_main_seq_auto = st.children_named("cond").any(|d| d.attr("delay").map(str::trim) == Some("indefinite")) - && st.children_named("cond").any(|d| { - d.attr("evt") == Some("onBegin") - && d.attr("delay").map(str::trim) == Some("0") - && d.child("tgtEl").is_none() - && d.child("rtn").is_none() - }); - if !is_main_seq_auto && defers_start(st) { - at.deferred = true; - } - if let Some(cond) = st.child("cond") { - if cond.attr("delay").map(str::trim) == Some("indefinite") { - *groups += 1; - at.group = *groups; - at.offset = 0; - } else { - at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + if c.is("cTn") { + let is_main_seq = c.attr("nodeType") == Some("mainSeq"); + if let Some(st) = c.child("stCondLst") { + if !(!is_main_seq && !at.deferred && is_main_seq_auto(st, at.main_seq_id)) && defers_start(st) { + at.deferred = true; + } + if let Some(cond) = st.child("cond") { + if cond.attr("delay").map(str::trim) == Some("indefinite") { + *groups += 1; + at.group = *groups; + at.offset = 0; + } else { + at.offset = at.offset.saturating_add(ms_attr(cond, "delay").unwrap_or(0)); + } } } + at.main_seq_id = if is_main_seq && !at.deferred { c.u32("id") } else { None }; } collect(c, at, groups, out, depth + 1); } @@ -293,7 +316,7 @@ pub fn media_settings(timing: &El, ctx: &IdCtx, shapes: &mut [Shape]) { let root_deferred = timing.path(&["tnLst", "par", "cTn", "stCondLst"]).is_some_and(defers_start); if !root_deferred && let Some(tn) = timing.child("tnLst") { let mut found = vec![]; - collect(tn, At { trigger: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); + collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); for f in found.into_iter().filter(|f| f.trigger.is_none()) { let c = f.ctn; if c.attr("nodeType") == Some("clickEffect") || f.deferred { @@ -321,7 +344,7 @@ pub fn animations(imp: &mut Imp, part: &Part, ctx: &IdCtx, timing: &El, shapes: let _ = (imp, part); let Some(tn) = timing.child("tnLst") else { return vec![] }; let mut found = vec![]; - collect(tn, At { trigger: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); + collect(tn, At { trigger: None, main_seq_id: None, group: 0, offset: 0, deferred: false }, &mut 0, &mut found, 0); // Paragraph builds (`bldP`) by (spid, grpId) -> whether `build="p"`. let bld_p: std::collections::HashMap<(u32, String), bool> = timing .child("bldLst") diff --git a/crates/pptx/tests/it/media_timing.rs b/crates/pptx/tests/it/media_timing.rs index 644a64b6f..43323500b 100644 --- a/crates/pptx/tests/it/media_timing.rs +++ b/crates/pptx/tests/it/media_timing.rs @@ -182,6 +182,15 @@ fn media_only_slide_exports_and_round_trips_video_and_audio_timing_nodes() { }); assert!(main_seq_play[0].autoplay, "main-sequence automatic Play effect sets autoplay"); + // An `indefinite` + `onBegin delay="0"` condition whose `` references a different + // click-dependent time node rather than the enclosing `mainSeq` must stay deferred. + let non_main_seq_tn_play = self::clips(|v, _| { + format!( + r#""# + ) + }); + assert!(!non_main_seq_tn_play[0].autoplay, "onBegin referencing non-mainSeq click-dependent node is not autoplay"); + // Command-based Play beneath an onClick or onEnd ancestor must not set autoplay. let deferred_cmd_play = self::clips(|v, a| { format!( From ac73229ef4adf64a6a450230246e7a8058003c0b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:57:53 -0500 Subject: [PATCH 66/76] pptx: reuse shared custom-geometry path tokenization (#2192) --- crates/pptx/src/custgeom.rs | 83 +++++++------------------------------ 1 file changed, 16 insertions(+), 67 deletions(-) diff --git a/crates/pptx/src/custgeom.rs b/crates/pptx/src/custgeom.rs index 383113847..a3590de16 100644 --- a/crates/pptx/src/custgeom.rs +++ b/crates/pptx/src/custgeom.rs @@ -348,73 +348,7 @@ fn arc_to(d: &mut String, cur: (f64, f64), wr: f64, hr: f64, st: f64, sw: f64) - } /// Parse our path syntax into commands. -pub fn parse_path(d: &str) -> Vec<(char, Vec)> { - let mut out = vec![]; - let mut cmd: Option = None; - let mut nums: Vec = vec![]; - let flush = |cmd: Option, nums: &mut Vec, out: &mut Vec<(char, Vec)>| { - if let Some(c) = cmd { - let n = match c { - 'M' | 'L' => 2, - 'C' => 6, - 'Q' => 4, - _ => 0, - }; - if n == 0 { - out.push((c, vec![])); - } else { - for (i, chunk) in nums.chunks(n).enumerate() { - if chunk.len() == n && out.len() < 1_000_000 { - // Repeated coordinates after M continue as L. - let c2 = if c == 'M' && i > 0 { 'L' } else { c }; - out.push((c2, chunk.to_vec())); - } - } - } - } - nums.clear(); - }; - let mut token = String::new(); - let push_tok = |token: &mut String, nums: &mut Vec| { - if !token.is_empty() { - if let Ok(v) = token.parse::() - && v.is_finite() - { - nums.push(v); - } - token.clear(); - } - }; - let cs: Vec = d.chars().collect(); - for (i, &ch) in cs.iter().enumerate() { - match ch { - // An 'E' inside a number followed by a digit (or a sign and a digit) is an exponent, - // not the end command. - 'E' if !token.is_empty() && { - let n1 = cs.get(i + 1).copied().unwrap_or(' '); - let n2 = cs.get(i + 2).copied().unwrap_or(' '); - n1.is_ascii_digit() || ((n1 == '-' || n1 == '+') && n2.is_ascii_digit()) - } => - { - token.push(ch) - } - 'M' | 'L' | 'C' | 'Q' | 'Z' | 'm' | 'l' | 'c' | 'q' | 'z' | 'E' => { - push_tok(&mut token, &mut nums); - flush(cmd, &mut nums, &mut out); - cmd = Some(ch.to_ascii_uppercase()); - } - ' ' | ',' | '\t' | '\n' => push_tok(&mut token, &mut nums), - '-' if !token.is_empty() && !token.ends_with(['e', 'E']) => { - push_tok(&mut token, &mut nums); - token.push(ch); - } - c => token.push(c), - } - } - push_tok(&mut token, &mut nums); - flush(cmd, &mut nums, &mut out); - out -} +pub use craft_drawingml::custgeom::parse_path; /// Write custom paths as `a:custGeom`. Coordinates are integers in the file, so small path spaces /// are scaled up. @@ -596,3 +530,18 @@ mod tests { assert!(parse_path("garbage ### C 1").is_empty() || parse_path("garbage").is_empty()); } } + +#[cfg(test)] +mod shared_path_tests { + use super::parse_path; + + #[test] + fn shared_path_tokens_preserve_exponents_repeats_and_dropped_tails() { + assert_eq!( + parse_path("M1E2 -3E-1 4 5 L6-7 Q8 9 10 11 Z"), + vec![('M', vec![100.0, -0.3]), ('L', vec![4.0, 5.0]), ('L', vec![6.0, -7.0]), ('Q', vec![8.0, 9.0, 10.0, 11.0]), ('Z', vec![]),] + ); + assert_eq!(parse_path("M0 0 L1"), vec![('M', vec![0.0, 0.0])]); + assert_eq!(parse_path("MNaN 0 1 2"), vec![('M', vec![0.0, 1.0])]); + } +} From f964d06cc5ffab0416d7bb925cec8c45e2f29865 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:57:57 -0500 Subject: [PATCH 67/76] docs: prefer shared Craft libraries for reusable features (#2178) --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 88d84ec92..03fa547d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -239,3 +239,7 @@ the `ROADMAP.md` progress log, and update each touched doc's status line and rev - Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. - Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. - Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## Shared libraries + +Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers. From 5c698493bc1f7ec36f90deb29df247b93330e654 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:58:00 -0500 Subject: [PATCH 68/76] ci: lock workflow actions through an actions.lock lockfile (#2078) --- .github/workflows/actions.lock | 31 +++++++++++++++++++++++++ .github/workflows/ci.yml | 4 ++-- .github/workflows/lockfile.yml | 34 ++++++++++++++++++++++++++++ .github/workflows/packaging-lint.yml | 4 ++-- sonar-project.properties | 9 ++++++++ 5 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/actions.lock create mode 100644 .github/workflows/lockfile.yml diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 000000000..5e478baa9 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,31 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/ci.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/freebsd.yml': [] + '.github/workflows/house-rules.yml': [] + '.github/workflows/lockfile.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nix.yml': [] + '.github/workflows/packaging-lint.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + '.github/workflows/release.yml': [] + '.github/workflows/sonarcloud.yml': [] + '.github/workflows/windows-arm64.yml': [] +dependencies: + 'actions/checkout@v7.0.1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'step-security/harden-runner@v2.22.4': + ref: 'v2.22.4' + commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' + owner_id: 88700172 + repo_id: 422287306 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 073423629..82de4815f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,11 +27,11 @@ jobs: CRAFT_FONTS_REF: 37827adc41fd165f9a9234ac40f94dbad353aa69 steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - name: Check out craft-fonts - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@v7.0.1 with: repository: storytold/craft-fonts ref: ${{ env.CRAFT_FONTS_REF }} diff --git a/.github/workflows/lockfile.yml b/.github/workflows/lockfile.yml new file mode 100644 index 000000000..e630c9a8f --- /dev/null +++ b/.github/workflows/lockfile.yml @@ -0,0 +1,34 @@ +name: Lockfile + +# Fails when .github/workflows/actions.lock is out of sync with the workflows, or when a locked pin +# no longer verifies upstream, so a moved tag cannot slip a different commit into a run. +# Docs: https://gh.io/actions-lockfile +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +env: + GH_TOKEN: ${{ github.token }} + +jobs: + lockfile: + name: Lockfile is in sync + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Install gh-actions-lock + run: gh extension install github/gh-actions-lock --pin v0.4.1 + - name: Verify the lockfile + run: gh actions-lock --verify diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 1771a35fe..fb9e3d4f7 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -28,10 +28,10 @@ jobs: runs-on: windows-latest steps: - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@v7.0.1 with: persist-credentials: false - name: Install the pinned packaging toolchain diff --git a/sonar-project.properties b/sonar-project.properties index 5d2418cb1..16a5e3800 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,2 +1,11 @@ sonar.projectKey=storytold_deckcraft sonar.organization=storytold + +# githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by +# .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned +# and the lockfile covers the actions those actions use too. Sonar does not read lockfiles yet, so +# the rule flags the tag refs anyway: +# https://community.sonarsource.com/t/githubactions-s7637-false-positives-for-actions-pinned-through-native-actions-lock/190814 +sonar.issue.ignore.multicriteria=gha-lockfile +sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 +sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** From e1ca71495c94a7cbcd31861fa3448e9b1398ada3 Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:35:55 +0100 Subject: [PATCH 69/76] Slide show: a slide's animations wait for its transition (#2089) (#2197) A first step that starts With or After Previous began with the slide, so its effects played under the transition. Its clock now starts when the transition has finished, as in PowerPoint. Slides without a transition, and Show without animation, start the step at once as before. --- crates/ui-egui/src/show.rs | 7 +++++-- crates/ui-egui/src/show/tests.rs | 35 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/show.rs b/crates/ui-egui/src/show.rs index db7983c2b..64f0b4dc7 100644 --- a/crates/ui-egui/src/show.rs +++ b/crates/ui-egui/src/show.rs @@ -552,7 +552,8 @@ impl Show { true } - /// On entering a slide: auto-play its first step when it begins With/After Previous. + /// On entering a slide: auto-play its first step when it begins With/After Previous, once the + /// slide's transition is over. /// `ShowState` already starts such a step when it enters the slide (#631: asking it for the /// next step again finished the step at once, so the slide appeared fully built), so only /// its clock starts here. Autoplay previews start an On Click first step themselves. @@ -568,7 +569,9 @@ impl Show { None }; if let Some(k) = started { - self.step_start = now; + // The slide's transition plays first; its animations start when it has finished, as + // in PowerPoint (#2089). + self.step_start = self.trans.as_ref().map_or(now, |t| now.max(t.start + t.dur)); self.media_clock = Some((k, f64::NEG_INFINITY)); } } diff --git a/crates/ui-egui/src/show/tests.rs b/crates/ui-egui/src/show/tests.rs index a01989ac0..58fa5ffa3 100644 --- a/crates/ui-egui/src/show/tests.rs +++ b/crates/ui-egui/src/show/tests.rs @@ -516,6 +516,41 @@ fn a_transition_keeps_the_old_slide_in_its_own_texture() { assert!(show.tex.is_none(), "the new slide gets a texture of its own instead of overwriting the old one"); } +/// #2089: a slide's With Previous entrance waits for the slide's transition to finish, as in +/// PowerPoint, instead of playing under it. +#[test] +fn animations_start_after_the_slides_transition() { + let mut s = deckcraft_engine::Session::with_new(); + s.execute("slide.new", &json!({})).unwrap(); + s.execute("transition.set", &json!({"kind": "fade", "index": 1, "duration": 400})).unwrap(); + let id = s.active().unwrap().doc.slides[1].shapes[0].id; + s.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id.0], "start": "withPrevious", "duration": 500})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let mut show = Show::new(&doc, 0, false, false); + let a = show.state.next(&doc); + assert_eq!(a, ShowAction::Slide(1)); + assert!(show.apply(a, &doc, 10.0)); + assert!(show.trans.is_some(), "the fade plays"); + assert!(show.state.playing, "the With Previous step is under way"); + assert!((show.clock_snapshot().step_start - 10.4).abs() < 1e-9, "its clock starts when the 0.4 s fade ends"); + let tl = ShowState::timeline(&doc, 1); + let at = |now: f64| state_for(&tl, id, show.state.step, now - show.clock_snapshot().step_start, &[], &[]); + assert!(!at(10.3).visible, "hidden while the transition plays"); + assert!(at(10.6).visible && at(10.6).opacity < 1.0, "fading in after it"); + // The step is not cut short by the time the transition took. + let mut actions = Vec::new(); + assert!(show.queue_clock_actions(&doc, 10.8, &mut actions)); + assert!(actions.is_empty(), "0.4 s into a 0.5 s step: still playing"); + + // Without a transition the step starts at once, as before. + s.execute("transition.set", &json!({"kind": "none", "index": 1})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let mut show = Show::new(&doc, 0, false, false); + let a = show.state.next(&doc); + assert!(show.apply(a, &doc, 10.0)); + assert_eq!(show.clock_snapshot().step_start, 10.0); +} + #[test] fn going_back_plays_the_left_slides_transition_reversed() { // #1531: Back from B to A played A's own entrance transition. PowerPoint plays the one B came From 497582406d51498c5da4cf7e96d89e45e5bf968b Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:36:53 +0100 Subject: [PATCH 70/76] Gradient stops: double-clicking a stop opens its colour menu (#2175) (#2196) Double-clicking a stop marker in the Format pane's gradient editor did nothing. It now selects the stop and opens the colour menu of the selected stop, as in PowerPoint. The menu button is also named for screen readers. --- crates/ui-egui/src/panels/fillui.rs | 64 ++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/fillui.rs b/crates/ui-egui/src/panels/fillui.rs index d1f807ae7..a8a29680d 100644 --- a/crates/ui-egui/src/panels/fillui.rs +++ b/crates/ui-egui/src/panels/fillui.rs @@ -232,6 +232,8 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) -> let (marks, _) = ui.allocate_exact_size(vec2(bar.width(), 14.0), Sense::hover()); let drag_id = ui.scope_id().with((id, "drag")); let mut dragging: Option<(usize, f64)> = ui.data_mut(|d| d.get_temp(drag_id)); + // A double-clicked stop opens its colour menu, as in PowerPoint (#2175). + let mut open_color = false; for (i, s) in g.stops.iter().enumerate() { let pos = dragging.filter(|d| d.0 == i).map_or(s.pos, |d| d.1); let x = bar.min.x + pos as f32 * bar.width(); @@ -245,6 +247,10 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) -> if resp.clicked() || resp.drag_started() { sel = i; } + if resp.double_clicked() { + sel = i; + open_color = true; + } if resp.dragged() && let Some(p) = resp.interact_pointer_pos() { @@ -287,7 +293,12 @@ pub fn gradient_editor(ui: &mut Ui, id: &str, g: &Gradient, sc: &ColorScheme) -> let (sw, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); ui.painter().rect(sw, CornerRadius::same(3), c32(&s.color, sc), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); let r = widgets::drop_button(ui, "", vec2(24.0, 20.0), true); - widgets::color_popup(&r).show(|ui| { + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Stop color")); + let mut popup = widgets::color_popup(&r); + if open_color { + popup = popup.open_memory(egui::SetOpenCommand::Bool(true)); + } + popup.show(|ui| { if let Some(Some(c)) = widgets::color_grid(ui, sc, None) { let mut ng = g.clone(); ng.stops[sel].color = with_alpha(c, alpha_of(&s.color)); @@ -516,7 +527,58 @@ pub fn pattern_editor(ui: &mut Ui, pt: &PatternFill, sc: &ColorScheme) -> Option #[cfg(test)] mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used)] + use super::*; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + /// #2175: double-clicking a gradient stop selects it and opens its colour menu; a colour + /// picked there colours that stop. + #[test] + fn double_clicking_a_stop_opens_its_color_menu() { + let sc = deckcraft_model::Theme::default().colors; + let start = Gradient { + stops: vec![ + GradientStop { pos: 0.0, color: ColorRef::scheme(SchemeSlot::Accent1) }, + GradientStop { pos: 1.0, color: ColorRef::scheme(SchemeSlot::Accent2) }, + ], + ..default_gradient(ColorRef::scheme(SchemeSlot::Accent1), 90.0) + }; + // The gradient, and whether the interface fonts are in (they apply from the next frame). + let mut h = Harness::builder().with_size(vec2(400.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, (g, fonts): &mut (Gradient, bool)| { + if !*fonts { + theme::install_fonts(ui.ctx()); + *fonts = true; + return; + } + if let Some(ng) = gradient_editor(ui, "test-grad", &g.clone(), &sc) { + *g = ng; + } + }, + (start, false), + ); + h.run_steps(3); + assert!(h.query_by_label("Theme Colors").is_none(), "the menu starts closed"); + let stop = h.get_by_label("Gradient stop 2").rect().center(); + h.hover_at(stop); + h.run_steps(1); + for _ in 0..2 { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: stop, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + } + } + h.run_steps(2); + assert!(h.query_by_label("Theme Colors").is_some(), "the colour menu opened"); + h.get_by_label(SchemeSlot::Accent6.label()).click(); + h.run_steps(2); + let g = &h.state().0; + assert_eq!(g.stops.len(), 2, "no stop was added"); + assert_eq!(g.stops[1].color, ColorRef::scheme(SchemeSlot::Accent6), "the double-clicked stop took the colour"); + assert_eq!(g.stops[0].color, ColorRef::scheme(SchemeSlot::Accent1)); + } #[test] fn gradient_json_retains_flip_mode() { From 1629e4d9533f1864b0fddd8ea976723eff03f5f6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:13:56 -0500 Subject: [PATCH 71/76] Tables: cap the grid and merge area before edits allocate or walk them (#1742) --- apps/deckcraft-cli/src/main.rs | 3 + crates/engine/src/cmd.rs | 9 ++ crates/engine/src/cmd/file.rs | 26 ++-- crates/engine/src/cmd/table.rs | 21 +++- crates/engine/src/drawtable.rs | 15 ++- crates/engine/src/tests.rs | 39 ++++++ crates/model/src/table.rs | 202 +++++++++++++++++++++++++++--- crates/pptx/src/lib.rs | 6 + crates/pptx/src/read.rs | 30 ++++- crates/pptx/src/read/shapes.rs | 3 + crates/pptx/src/write.rs | 9 ++ crates/pptx/src/write/shapes.rs | 4 +- crates/pptx/tests/it/malformed.rs | 38 ++++++ 13 files changed, 371 insertions(+), 34 deletions(-) diff --git a/apps/deckcraft-cli/src/main.rs b/apps/deckcraft-cli/src/main.rs index 5701b72f8..420f4f1a5 100644 --- a/apps/deckcraft-cli/src/main.rs +++ b/apps/deckcraft-cli/src/main.rs @@ -148,6 +148,9 @@ fn warn_if_damaged(path: &str, opened: &serde_json::Value) { if slides > 0 { eprintln!("deckcraft-cli: warning: {path}: {slides} slide{} couldn't be read and left out", if slides == 1 { "" } else { "s" }); } + for w in opened.get("importWarnings").and_then(|v| v.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { + eprintln!("deckcraft-cli: warning: {path}: {w}"); + } if media > 0 { eprintln!("deckcraft-cli: warning: {path}: {media} picture or media file{} couldn't be read", if media == 1 { "" } else { "s" }); } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 38e6c363c..4bf90c3a6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -433,6 +433,15 @@ pub(crate) fn shape_of(s: &Session, id: ShapeId) -> Result Xfrm { let mut x = shape.xfrm.unwrap_or_else(|| ctx_xfrm(doc, sel, shape)); if let deckcraft_model::ShapeKind::Table(t) = &shape.kind { + // A loaded table may not be normalized yet: measure the bounded grid an edit will + // leave, not every cell the file stored. + let normalized; + let t = if t.is_normalized() { + t + } else { + normalized = t.normalized(); + &normalized + }; let drawn: f64 = table_drawn_heights(doc, sel, t).iter().sum(); if drawn.is_finite() && drawn > x.h { x.h = drawn; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index a1c781f96..744950f4b 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -139,11 +139,13 @@ pub struct Damage { pub media: Vec, /// Slides a `.pptx` lists but that couldn't be read, so they are not in the presentation. pub slides: Vec, + /// Content a `.pptx` had that was cut to fit a limit; the file still opened. + pub warnings: Vec, } impl Damage { pub fn is_empty(&self) -> bool { - self.media.is_empty() && self.slides.is_empty() + self.media.is_empty() && self.slides.is_empty() && self.warnings.is_empty() } } @@ -151,17 +153,17 @@ impl Damage { pub fn open_checked(name: &str, bytes: &[u8]) -> Result<(Presentation, Damage)> { if deckcraft_format::sniff(bytes) { let (p, media) = deckcraft_format::load_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?; - return Ok((p, Damage { media, slides: vec![] })); + return Ok((p, Damage { media, ..Default::default() })); } - open_other(name, bytes).map(|(p, slides)| (p, Damage { media: vec![], slides })) + open_other(name, bytes).map(|(p, slides, warnings)| (p, Damage { slides, warnings, ..Default::default() })) } -fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec)> { +fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec, Vec)> { if deckcraft_pptx::sniff(bytes) { - let (mut p, lost_slides) = deckcraft_pptx::import_checked(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + let (mut p, lost_slides, warnings) = deckcraft_pptx::import_report(bytes).map_err(|e| EngineError::Other(e.to_string()))?; deckcraft_format::repair(&mut p); probe_clips(&mut p); - return Ok((p, lost_slides)); + return Ok((p, lost_slides, warnings)); } if deckcraft_pptx::is_encrypted(bytes) { return Err(EngineError::Other(format!("{name} is password-protected. DeckCraft can't open password-protected presentations yet."))); @@ -180,7 +182,7 @@ fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec)> { if p.slides.is_empty() { p = defaults::new_presentation(None); } - return Ok((p, vec![])); + return Ok((p, vec![], vec![])); } Err(EngineError::Other(format!("{name}: not a presentation DeckCraft can read"))) } @@ -276,7 +278,7 @@ fn adopt_loaded(s: &mut Session, f: LoadedFile) -> Result { let st = s.doc()?; Ok(json!({ "document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts, - "damagedMedia": damaged.media, "lostSlides": damaged.slides, + "damagedMedia": damaged.media, "lostSlides": damaged.slides, "importWarnings": damaged.warnings, })) } @@ -311,7 +313,9 @@ fn open_bytes(s: &mut Session, p: &Value) -> Result { let (doc, damaged) = open_checked(name, &data)?; let i = add_opened(s, name, None, doc); report_damage(s, &damaged)?; - Ok(json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides})) + Ok( + json!({"document": i, "missingFonts": s.doc()?.missing_fonts, "damagedMedia": damaged.media, "lostSlides": damaged.slides, "importWarnings": damaged.warnings}), + ) } /// Tell the user which pictures, media and slides a damaged file lost, and mark the copy repaired. @@ -339,6 +343,10 @@ fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> { if n == 1 { "was" } else { "were" }, )); } + for w in &damaged.warnings { + text.push_str(w); + text.push_str(". "); + } text.push_str("It was opened as a repaired copy; save it under a new name to keep the original file."); s.ui_requests.push(crate::UiRequest::Message { text }); Ok(()) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 86d753a2c..0034645f8 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -286,6 +286,12 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R }; let r = edit_shapes(s, &json!({"id": id}), cmd, |sh| match &mut sh.kind { ShapeKind::Table(t) => { + // Edits walk the grid: bound it first (a loaded table need not be normalized yet). + // An over-cap table is refused, not trimmed: a trim would delete rows while reporting success. + if t.over_cap() { + return Err(bad(cmd, format!("the table is larger than {} cells; edit refused", deckcraft_model::table::MAX_CELLS))); + } + t.normalize(); f(t)?; t.normalize(); let (w, h) = (t.width(), t.height()); @@ -319,10 +325,17 @@ fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result let op = op.to_string(); with_table(s, p, name, move |t| { match op.as_str() { - "rowAbove" => t.insert_row(r), - "rowBelow" => t.insert_row(r.saturating_add(1)), - "colLeft" => t.insert_col(c), - "colRight" => t.insert_col(c.saturating_add(1)), + "rowAbove" | "rowBelow" | "colLeft" | "colRight" => { + let ok = match op.as_str() { + "rowAbove" => t.insert_row(r), + "rowBelow" => t.insert_row(r.saturating_add(1)), + "colLeft" => t.insert_col(c), + _ => t.insert_col(c.saturating_add(1)), + }; + if !ok { + return Err(bad(name, format!("the table is at its {}-cell limit", deckcraft_model::table::MAX_CELLS))); + } + } "delRow" => { if !t.delete_row(r) { return Err(bad(name, "can't delete the last row")); diff --git a/crates/engine/src/drawtable.rs b/crates/engine/src/drawtable.rs index 2b49b7ac7..8c26e7ad5 100644 --- a/crates/engine/src/drawtable.rs +++ b/crates/engine/src/drawtable.rs @@ -115,7 +115,7 @@ fn split_rows(t: &mut Table, y: f64, x0: f64, x1: f64) -> bool { let b = match ys.iter().position(|e| (e - y).abs() <= SNAP) { Some(b) => b, None => { - if t.rows.len() >= MAX_GRID { + if t.rows.len() >= MAX_GRID || t.cols.len().saturating_mul(t.rows.len().saturating_add(1)) > deckcraft_model::table::MAX_CELLS { return false; } let Some(k) = ys.windows(2).position(|w| w[0] < y && y < w[1]) else { return false }; @@ -273,4 +273,17 @@ mod tests { } assert!(t.rows.len() <= MAX_GRID && n > 100, "{} rows", t.rows.len()); } + + #[test] + fn pencil_refuses_a_row_past_the_cell_cap() { + let cols = 1000; + let rows = deckcraft_model::table::MAX_CELLS / cols; + let mut t = Table { + cols: vec![10.0; cols], + rows: vec![deckcraft_model::table::Row { height: 50.0, cells: vec![Cell::new(""); cols] }; rows], + ..Default::default() + }; + assert!(!draw_line(&mut t, (0.0, 25.0), (10_000.0, 25.0))); + assert_eq!((t.n_rows(), t.n_cols()), (rows, cols)); + } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 66494ea22..7d9fff63b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7297,6 +7297,45 @@ fn master_body_placeholder_format_keeps_per_level_formatting() { assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]); } +#[test] +fn table_edits_past_the_cell_cap_are_refused_not_trimmed() { + use deckcraft_model::table::{MAX_CELLS, Row}; + let mut s = session(); + let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]])); + let cols = 200; + let rows = MAX_CELLS / cols; + let big = deckcraft_model::Table { + cols: vec![1.0; cols], + rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows], + ..Default::default() + }; + for sl in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).slides.iter_mut() { + for sh in std::sync::Arc::make_mut(sl).shapes.iter_mut() { + if sh.id == id { + sh.kind = deckcraft_model::ShapeKind::Table(big.clone()); + } + } + } + for cmd in ["table.insertRowAbove", "table.insertRowBelow"] { + let e = s.execute(cmd, &json!({"id": id.0, "row": 0})).unwrap_err().to_string(); + assert!(e.contains("cell limit"), "{cmd}: {e}"); + } + let e = s.execute("table.insertColumnLeft", &json!({"id": id.0, "col": 0})).unwrap_err().to_string(); + assert!(e.contains("cell limit"), "{e}"); + assert_eq!(table_of(&s, id), big, "a refused insert leaves every row in place"); + // A table already over the cap is refused too, not trimmed behind a success. + let huge = deckcraft_model::Table { rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows + 1], ..big.clone() }; + for sl in std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).slides.iter_mut() { + for sh in std::sync::Arc::make_mut(sl).shapes.iter_mut() { + if sh.id == id { + sh.kind = deckcraft_model::ShapeKind::Table(huge.clone()); + } + } + } + assert!(s.execute("table.deleteRow", &json!({"id": id.0, "row": 0})).is_err()); + assert_eq!(table_of(&s, id).n_rows(), rows + 1); +} + /// #2059: Decrease Font Size (Ctrl+[, Cmd+Shift+,) steps down one size at a time from any size: /// PowerPoint's list up to 96, then 8 points at a time above it, as Increase Font Size steps up. /// A size above 66 used to shrink straight to 66. diff --git a/crates/model/src/table.rs b/crates/model/src/table.rs index 118851ecd..9079c4058 100644 --- a/crates/model/src/table.rs +++ b/crates/model/src/table.rs @@ -83,6 +83,12 @@ impl Default for Table { } } +/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75). +pub const MAX_CELLS: usize = 100_000; +/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few +/// passes over the largest grid, where a real table needs one or two. +const MAX_MERGE_WORK: usize = 16 * MAX_CELLS; + impl Table { pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self { let rows = rows.clamp(1, 1000); @@ -113,15 +119,24 @@ impl Table { self.rows.iter().map(|r| r.height).sum() } /// Insert an empty row before `at`. A merge the new row falls inside grows to cover it. - pub fn insert_row(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`]. + pub fn insert_row(&mut self, at: usize) -> bool { + if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS { + return false; + } let at = at.min(self.rows.len()); let merges = self.merges(); let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0); self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() }); self.set_merges(merges.into_iter().map(|m| m.insert_row(at))); + true } /// Insert an empty column before `at`. A merge the new column falls inside grows to cover it. - pub fn insert_col(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`]. + pub fn insert_col(&mut self, at: usize) -> bool { + if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS { + return false; + } let at = at.min(self.cols.len()); let merges = self.merges(); let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0); @@ -131,6 +146,7 @@ impl Table { r.cells.insert(i, Cell::new("")); } self.set_merges(merges.into_iter().map(|m| m.insert_col(at))); + true } /// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and /// text) to the next row it covers. @@ -170,8 +186,12 @@ impl Table { true } /// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid. + /// Merges of a well-formed table do not overlap, so together they cover at most the grid; a + /// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells + /// without bound. fn merges(&self) -> Vec { let (nr, nc) = (self.rows.len(), self.cols.len()); + let mut area = nr.saturating_mul(nc); let mut out = vec![]; for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(nc) { @@ -180,7 +200,10 @@ impl Table { } let rs = (cell.row_span.max(1) as usize).min(nr - r); let gs = (cell.grid_span.max(1) as usize).min(nc - c); - if rs > 1 || gs > 1 { + if (rs > 1 || gs > 1) + && let Some(left) = area.checked_sub(rs.saturating_mul(gs)) + { + area = left; out.push(Merge { r, c, rs, gs }); } } @@ -233,9 +256,17 @@ impl Table { if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) { return false; } - // Grow the rectangle until no existing merge sticks out of it. + // Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole + // grid and may grow it by one row, so the passes are charged against + // [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed. let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1); + let pass = self.rows.len().saturating_mul(self.cols.len()).max(1); + let mut work = 0usize; loop { + work = work.saturating_add(pass); + if work > MAX_MERGE_WORK { + return false; + } let before = (r0, c0, r1, c1); for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) { @@ -289,21 +320,50 @@ impl Table { return false; } // Spans come from the file and may reach past the table; only walk the cells that exist. - for rr in r..r.saturating_add(rs).min(self.rows.len()) { - for cc in c..c.saturating_add(gs).min(self.cols.len()) { - if let Some(x) = self.cell_mut(rr, cc) { - x.h_merge = false; - x.v_merge = false; - x.grid_span = 1; - x.row_span = 1; - } + let end = r.saturating_add(rs).min(self.rows.len()); + let gs = gs.min(self.cols.len().saturating_sub(c)); + for row in self.rows.get_mut(r..end).unwrap_or_default() { + for x in row.cells.iter_mut().skip(c).take(gs) { + x.h_merge = false; + x.v_merge = false; + x.grid_span = 1; + x.row_span = 1; } } true } - /// Make every row have exactly `cols.len()` cells (repair after loading). - pub fn normalize(&mut self) { + /// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row + /// exactly `cols.len()` cells wide. + pub fn is_normalized(&self) -> bool { let n = self.cols.len(); + n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n) + } + /// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`]. + pub fn over_cap(&self) -> bool { + let n = self.cols.len(); + n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1) + } + /// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that + /// survive (an oversized table is not copied whole first). + pub fn normalized(&self) -> Table { + let n = self.cols.len().min(MAX_CELLS); + let keep = (MAX_CELLS / n.max(1)).max(1); + let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect(); + let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self }; + t.normalize(); + if self.over_cap() { + t.clip_spans(); + } + t + } + /// Make every row have exactly `cols.len()` cells (repair after loading). A grid over + /// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many + /// columns but few cells cannot make this allocate their product. + pub fn normalize(&mut self) { + let truncated = self.over_cap(); + self.cols.truncate(MAX_CELLS); + let n = self.cols.len(); + self.rows.truncate((MAX_CELLS / n.max(1)).max(1)); for r in &mut self.rows { r.cells.resize_with(n, || Cell::new("")); for c in &mut r.cells { @@ -311,6 +371,20 @@ impl Table { c.row_span = c.row_span.max(1); } } + if truncated { + self.clip_spans(); + } + } + /// Cut every merge span to the rows and columns that remain, so no merge reaches past a + /// table that lost rows or columns to the cell cap. + fn clip_spans(&mut self) { + let (nr, nc) = (self.rows.len(), self.cols.len()); + for (ri, r) in self.rows.iter_mut().enumerate() { + for (ci, c) in r.cells.iter_mut().enumerate() { + c.row_span = c.row_span.min((nr - ri) as u32).max(1); + c.grid_span = c.grid_span.min((nc - ci) as u32).max(1); + } + } } } @@ -519,6 +593,102 @@ mod tests { } } + /// Each cell spans two rows, uncovered: merging the last two rows would grow the rectangle a + /// row per pass over the whole grid, 10,000 passes. The merge is refused at its work bound + /// instead, leaving the table as it was; a small merge still works. + #[test] + fn merge_expansion_stops_at_its_work_bound() { + let mut t = Table::new(1_000, 10, 400.0, 30.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.row_span = 2; + } + } + let before = t.clone(); + assert!(!t.merge(998, 0, 999, 9)); + assert_eq!(t, before); + let mut small = Table::new(4, 4, 400.0, 30.0); + assert!(small.merge(0, 0, 1, 1)); + assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized()); + } + + #[test] + fn normalize_caps_a_sparse_grid_at_max_cells() { + // 1,000 columns and 1,000 empty rows would be a million cells. + let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() }; + t.normalize(); + assert_eq!(t.cols.len(), 1000); + assert_eq!(t.rows.len(), MAX_CELLS / 1000); + assert!(t.rows.iter().all(|r| r.cells.len() == 1000)); + // Columns alone past the cap keep one row of MAX_CELLS cells. + let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() }; + t.normalize(); + assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1)); + // `normalized` leaves what `normalize` does. + let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() }; + let mut n = wide.clone(); + n.normalize(); + assert_eq!(wide.normalized(), n); + // A normal table is untouched. + let mut t = Table::new(4, 4, 400.0, 30.0); + t.normalize(); + assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); + } + + #[test] + fn overlapping_file_spans_rebuild_in_bounded_work() { + // Every cell an uncovered anchor spanning to the far corner: their areas add up to about + // n^4 / 4, but only what fits the grid is kept, so an edit's rebuild stays near n^2. + let n = 200; + let mut t = Table::new(n, n, 400.0, 30.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.grid_span = u32::MAX; + c.row_span = u32::MAX; + } + } + assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid"); + assert!(t.insert_row(n)); + assert_eq!(t.n_rows(), n + 1); + assert!(t.split(0, 0)); + } + + /// A table at the cell cap refuses another row or column instead of losing rows to + /// normalization, and the cap sits above PowerPoint's own 75 x 75. + #[test] + fn insert_past_the_cap_is_refused() { + const { assert!(MAX_CELLS >= 75 * 75) }; + let mut t = + Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() }; + assert!(!t.over_cap()); + let before = t.clone(); + assert!(!t.insert_row(0)); + assert!(!t.insert_col(0)); + assert_eq!(t, before); + assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0)); + } + + /// A merge that crosses the truncation boundary is clipped to the rows and columns that remain. + #[test] + fn merges_are_clipped_when_the_cap_drops_rows() { + let cols = 1000; + let rows = MAX_CELLS / cols + 1; + let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() }; + t.rows[0].cells[0].row_span = rows as u32; + t.rows[0].cells[cols - 1].grid_span = 5; + let n = t.normalized(); + assert_eq!(n.rows.len(), rows - 1); + assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1); + assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1); + t.normalize(); + assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1); + // Within the cap, spans are left as the file wrote them. + let mut small = Table::new(3, 3, 30.0, 10.0); + small.rows[2].cells[2].grid_span = 4; + small.normalize(); + assert_eq!(small.rows[2].cells[2].grid_span, 4); + } + fn merged() -> Table { // 4x4 with a 2x2 merge at (1,1) holding "M". let mut t = Table::new(4, 4, 400.0, 30.0); @@ -552,10 +722,10 @@ mod tests { fn row_and_column_edits_keep_merges_consistent() { for at in 0..=4 { let mut t = merged(); - t.insert_row(at); + assert!(t.insert_row(at)); assert_topology(&t); let mut t = merged(); - t.insert_col(at); + assert!(t.insert_col(at)); assert_topology(&t); } for at in 0..4 { diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 2c86937e7..9335b4e26 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -71,6 +71,12 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxE read::import_checked(bytes) } +/// [`import_checked`], plus warnings for content cut to fit a limit (a table past the cell cap +/// keeps its leading rows); the file still opens. +pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec, Vec), PptxError> { + read::import_report(bytes) +} + /// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget /// path without a multi-million-point chart. #[doc(hidden)] diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 7ece2c628..2c0ec8810 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -71,6 +71,8 @@ pub struct Imp<'a> { pub tag_bytes: usize, /// The tag budget ran out and the warning was given. pub tags_capped: bool, + /// What the file lost that the reader kept going past (see [`MAX_IMPORT_WARNINGS`]). + pub warnings: Vec, /// Bytes of preserved theme XML kept by the masters read so far. pub theme_extra_bytes: usize, /// Shapes read from SmartArt drawings so far (see `shapes::MAX_SMARTART_SHAPES`). @@ -82,7 +84,17 @@ pub struct Imp<'a> { pub has_rels: HashMap, } +/// Import warnings kept; a hostile file with many oversized tables adds no more than this. +const MAX_IMPORT_WARNINGS: usize = 32; + impl Imp<'_> { + /// Record something the file lost, and log it. + pub fn warn(&mut self, msg: String) { + log::warn!("pptx: {msg}"); + if self.warnings.len() < MAX_IMPORT_WARNINGS { + self.warnings.push(msg); + } + } pub fn alloc(&mut self) -> u32 { self.next = self.next.saturating_add(1); self.next @@ -598,6 +610,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec< tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + warnings: vec![], theme_extra_bytes: 0, smartart_shapes: 0, diagram_xml_bytes: 0, @@ -616,13 +629,24 @@ pub fn import(bytes: &[u8]) -> Result { /// or truncated slide part, or an entry whose relationship is missing): those slides are left /// out, so a caller can say so (#203). pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), PptxError> { - import_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS) + import_report(bytes).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a +/// table past the cell cap keeps its leading rows). +pub fn import_report(bytes: &[u8]) -> Result<(Presentation, Vec, Vec), PptxError> { + import_report_with_chart_points(bytes, chart::MAX_PRESENTATION_CHART_POINTS) } const MAX_SLIDE_ENTRIES: usize = 10_000; /// [`import_checked`] with the presentation's chart point budget set (tests lower it). pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec), PptxError> { + import_report_with_chart_points(bytes, chart_points_cap).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_report`] with the presentation's chart point budget set. +fn import_report_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> Result<(Presentation, Vec, Vec), PptxError> { let mut lost_slides: Vec = vec![]; let pkg = Package::open(bytes)?; let root_rels = pkg.rels(""); @@ -663,6 +687,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + warnings: vec![], theme_extra_bytes: 0, smartart_shapes: 0, diagram_xml_bytes: 0, @@ -697,7 +722,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], chart_points_cap: usize) -> p.media = std::mem::take(&mut imp.media); p.next_id = imp.next; p.fix_next_id(); - Ok((p, lost_slides)) + Ok((p, lost_slides, std::mem::take(&mut imp.warnings))) } /// Masters, layouts and slides to read, in file order and without duplicates: (master paths, @@ -1637,6 +1662,7 @@ mod rollback_tests { tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + warnings: vec![], theme_extra_bytes: 0, smartart_shapes: 0, diagram_xml_bytes: 0, diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index bcef9f8c5..7ff66018a 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -856,6 +856,9 @@ fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table { let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0); t.cols = vec![72.0; n]; } + if t.over_cap() { + imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, deckcraft_model::table::MAX_CELLS)); + } t.normalize(); t } diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 2a5a2115b..6683615d9 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -65,6 +65,8 @@ pub struct Exp<'a> { n_kept: u32, pub slide_parts: HashMap, pub table_styles: Vec, + /// A table past the cell cap was met; export fails rather than write a trimmed one. + pub table_over_cap: bool, /// The ids in `table_styles`, for checking membership without a scan. pub table_style_set: std::collections::HashSet, placeholder: Option, @@ -558,6 +560,7 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { n_kept: 0, slide_parts: HashMap::new(), table_styles: vec![], + table_over_cap: false, table_style_set: Default::default(), placeholder: None, }; @@ -766,6 +769,12 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { root.add_new(&k.rel_type, &k.name, false); } x.pkg.rels("", &root); + if x.table_over_cap { + return Err(PptxError::Unsupported(format!( + "a table has more than {} cells; export refused rather than drop rows", + deckcraft_model::table::MAX_CELLS + ))); + } x.pkg.finish() } diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index df7a226df..a5833c4d1 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -724,8 +724,8 @@ fn frame_close(w: &mut W) { } fn table(w: &mut W, x: &mut Exp, o: &mut Out, t: &Table) { - let mut t = t.clone(); - t.normalize(); + x.table_over_cap |= t.over_cap(); + let t = t.normalized(); w.open0("a:tbl"); let (guid, _) = crate::tables::guid_for_style(&t.style); if x.table_style_set.insert(t.style.clone()) { diff --git a/crates/pptx/tests/it/malformed.rs b/crates/pptx/tests/it/malformed.rs index 04b219c29..6a4e88823 100644 --- a/crates/pptx/tests/it/malformed.rs +++ b/crates/pptx/tests/it/malformed.rs @@ -288,6 +288,44 @@ fn unreadable_slide_is_reported() { assert_eq!(deckcraft_pptx::import(&broken).expect("import").slides.len(), 1); } +fn table_deck(rows: usize, cols: usize) -> deckcraft_model::Presentation { + use deckcraft_model::table::Row; + use deckcraft_model::{Shape, ShapeId, ShapeKind, Table, Xfrm}; + let mut p = defaults::new_presentation(None); + let id = ShapeId(p.alloc_id().expect("ids")); + let t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Default::default(); cols] }; rows], ..Default::default() }; + let slide = std::sync::Arc::make_mut(&mut p.slides[0]); + slide.shapes.push(Shape { id, name: "T".into(), xfrm: Some(Xfrm::new(0.0, 0.0, 10.0, 10.0)), kind: ShapeKind::Table(t), ..Default::default() }); + p +} + +/// A table past the cell cap opens with its leading rows and an import warning; saving one that +/// is over the cap is an error, never a silent trim. +#[test] +fn oversized_table_warns_on_import_and_refuses_export() { + let max = deckcraft_model::table::MAX_CELLS; + let cols = 1000; + let rows = max / cols; + // A table exactly at the cap round-trips with no warning. + let bytes = deckcraft_pptx::export(&table_deck(rows, cols)).expect("export at the cap"); + let (_, _, warnings) = deckcraft_pptx::import_report(&bytes).expect("import"); + assert!(warnings.is_empty(), "{warnings:?}"); + // One more row in the file: kept truncated, and reported. + let mut es = entries(&bytes); + let slide = es.iter_mut().find(|(n, _)| n == "ppt/slides/slide1.xml").expect("slide1"); + let xml = String::from_utf8(std::mem::take(&mut slide.1)).expect("utf8"); + let start = xml.rfind("").expect("row end") + "".len(); + slide.1 = format!("{}{}{}", &xml[..end], &xml[start..end], &xml[end..]).into_bytes(); + let (q, _, warnings) = deckcraft_pptx::import_report(&rezip(&es)).expect("import"); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + let t = q.slides[0].shapes.iter().find_map(|s| if let deckcraft_model::ShapeKind::Table(t) = &s.kind { Some(t) } else { None }).expect("table"); + assert_eq!((t.rows.len(), t.cols.len()), (rows, cols)); + // A model table past the cap is refused on export. + let err = deckcraft_pptx::export(&table_deck(rows + 1, cols)).expect_err("over the cap"); + assert!(err.to_string().contains("table"), "{err}"); +} + /// Missing slide relationships must not turn a damaged deck into a clean partial load (#1910). #[test] fn missing_slide_relationships_are_reported() { From 82fddc8ffd3f8063d2396ceabaeb38f533e5eae1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:37:55 -0500 Subject: [PATCH 72/76] Use shared DrawingML table style XML writer Preserve the former writer as a test-only byte oracle, including the original Brandon Thomas and Nikita Rakitin implementation history. Keep app XML admission and all existing table tests unchanged. --- Cargo.lock | 28 +++- Cargo.toml | 2 + crates/pptx/Cargo.toml | 1 + crates/pptx/src/tables.rs | 219 ++++++------------------------- crates/pptx/src/tables_legacy.rs | 182 +++++++++++++++++++++++++ 5 files changed, 252 insertions(+), 180 deletions(-) create mode 100644 crates/pptx/src/tables_legacy.rs diff --git a/Cargo.lock b/Cargo.lock index d51d6ce04..98255c0f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -891,6 +891,17 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-drawingml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c#852d37fcff3d2c09bc7aee57e637d71a9725b04c" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c)", + "kurbo", + "log", + "serde", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" @@ -1064,6 +1075,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c#852d37fcff3d2c09bc7aee57e637d71a9725b04c" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -1209,7 +1230,7 @@ dependencies = [ name = "deckcraft-color" version = "0.19.0" dependencies = [ - "craft-drawingml", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", ] [[package]] @@ -1266,7 +1287,7 @@ dependencies = [ name = "deckcraft-geom" version = "0.19.0" dependencies = [ - "craft-drawingml", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", "kurbo", "serde", ] @@ -1329,7 +1350,8 @@ name = "deckcraft-pptx" version = "0.19.0" dependencies = [ "craft-cfb", - "craft-drawingml", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c)", "craft-opc", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "deckcraft-color", diff --git a/Cargo.toml b/Cargo.toml index bcb704a2d..5dd587513 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9 # XML writer primitives; parser admission and OOXML policy stay app-local. craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes. +# Isolated table XML writer; existing DrawingML model/readers keep their revision. +craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "852d37fcff3d2c09bc7aee57e637d71a9725b04c" } craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } diff --git a/crates/pptx/Cargo.toml b/crates/pptx/Cargo.toml index aceba9f72..6be4dd23e 100644 --- a/crates/pptx/Cargo.toml +++ b/crates/pptx/Cargo.toml @@ -13,6 +13,7 @@ craft-opc.workspace = true craft-xml.workspace = true craft-cfb.workspace = true craft-drawingml.workspace = true +craft-drawingml-table.workspace = true deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/pptx/src/tables.rs b/crates/pptx/src/tables.rs index 62dc983c4..081433243 100644 --- a/crates/pptx/src/tables.rs +++ b/crates/pptx/src/tables.rs @@ -1,190 +1,55 @@ -//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the -//! styles we write (generated from theme accents, matching how DeckCraft draws them). - -use crate::opc::NS_A; -use crate::xml::{A, W}; - -// Keep file-format identifiers in the shared DrawingML implementation. The local -// writer below still owns DeckCraft's table style definitions and XML policy. +//! Table style XML uses the shared writer; app XML admission remains unchanged. pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid}; +pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec { + craft_drawingml_table::table::styles::table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), "DeckCraft", |raw| { + crate::xml::parse(raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) + }) +} + +#[cfg(test)] +#[path = "tables_legacy.rs"] +mod legacy; + +#[cfg(test)] fn own_guid(style: &str) -> String { guid(&format!("deckcraft-table-style:{style}")) } -fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) { - if mods.is_empty() { - w.val("a:schemeClr", slot); - return; - } - w.open("a:schemeClr", A::new().a("val", slot)); - for (n, v) in mods { - w.val(n, v); - } - w.close("a:schemeClr"); -} - -fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) { - w.open0("a:fill"); - w.open0("a:solidFill"); - clr(w, slot, mods); - w.close("a:solidFill"); - w.close("a:fill"); -} - -fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) { - w.open0("a:tcBdr"); - if let Some((slot, mods, width)) = b { - for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] { - w.open0(side); - w.open("a:ln", A::new().a("w", width).a("cmpd", "sng")); - w.open0("a:solidFill"); - clr(w, slot, mods); - w.close("a:solidFill"); - w.close("a:ln"); - w.close(side); - } - } - w.close("a:tcBdr"); -} - -fn txt(w: &mut W, bold: bool, color: Option<&str>) { - w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on"))); - w.open("a:fontRef", A::new().a("idx", "minor")); - w.val("a:prstClr", "black"); - w.close("a:fontRef"); - match color { - Some(c) => w.val("a:schemeClr", c), - None => w.val("a:schemeClr", "dk1"), - } - w.close("a:tcTxStyle"); -} - -/// Write one `a:tblStyle` for our style id. -fn style_def(w: &mut W, id: &str, name: &str) { - let kind = id.split('-').next().unwrap_or("medium2"); - let acc = match id.rsplit('-').next().unwrap_or("accent1") { - "tx1" => "dk1", - a if a.starts_with("accent") => a, - _ => "accent1", - }; - let acc: &str = acc; - w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name)); - let part = - |w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| { - w.open0(tag); - if bold || text.is_some() { - txt(w, bold, text); - } - w.open0("a:tcStyle"); - borders(w, bdr); - if let Some((s, m)) = fill { - solid(w, s, m); - } - w.close("a:tcStyle"); - w.close(tag); - }; - match kind { - "grid" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525))); - } - "light1" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, None); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None); - part(w, "a:lastCol", true, None, None, None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700))); - } - "light2" => { - part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700))); - // Schema order: … lastCol, firstCol, lastRow, …, firstRow. - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700))); - } - "dark1" => { - part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700))); - part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None); - } - "medium4" => { - part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525))); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:lastCol", true, None, None, None); - part(w, "a:firstCol", true, None, None, None); - part(w, "a:lastRow", true, None, None, None); - part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None); - } - _ => { - // medium2 - part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700))); - part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); - part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None); - part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None); - } - } - w.close("a:tblStyle"); -} - -/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the -/// opened file defined (`defs`), written back as they were read. -pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec { - let mut w = W::new(); - w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}")); - let names = deckcraft_model::table::table_styles(); - // Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's - // definitions by lower-case id (the first wins). - let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); - let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); - let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); - for d in defs { - def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); - } - for s in used { - if !done.insert(s.as_str()) { - continue; - } - done_lower.insert(s.to_ascii_lowercase()); - if let Some(d) = def_of.get(&s.to_ascii_lowercase()) - && crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) - { - w.raw(&d.raw); - continue; - } - let (_, define) = guid_for_style(s); - if !define { - continue; - } - let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone()); - style_def(&mut w, s, &name); - } - // Styles the file defined but no table uses still belong to the deck. - for d in defs { - if done_lower.contains(&d.id.to_ascii_lowercase()) { - continue; - } - if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) { - done_lower.insert(d.id.to_ascii_lowercase()); - w.raw(&d.raw); - } - } - w.close("a:tblStyleLst"); - w.finish() -} - #[cfg(test)] mod tests { use super::*; + #[test] + fn shared_writer_matches_legacy_bytes_and_admission() { + use deckcraft_model::table::TableStyleDef; + let mut used: Vec = deckcraft_model::table::table_styles().into_iter().map(|(id, _)| id).collect(); + used.extend(["unknown<&\"".into(), "Custom".into(), "Custom".into(), "CUSTOM".into()]); + for raw in [ + "", + "", // Existing lenient partial-root policy. + "", + "", + "", + "", + "", + ] { + let defs = vec![ + TableStyleDef { id: "custom".into(), raw: raw.into(), ..Default::default() }, + TableStyleDef { id: "CUSTOM".into(), raw: "".into(), ..Default::default() }, + TableStyleDef { id: "unused".into(), raw: "".into(), ..Default::default() }, + ]; + for selection in [&used[..], &[][..]] { + assert_eq!(table_styles_xml(selection, &defs), legacy::table_styles_xml(selection, &defs), "{raw:?}"); + } + } + for depth in [255, 256, 257] { + let raw = format!("{}{}", "".repeat(depth), "".repeat(depth)); + let defs = [TableStyleDef { id: "custom".into(), raw, ..Default::default() }]; + assert_eq!(table_styles_xml(&used, &defs), legacy::table_styles_xml(&used, &defs)); + } + } + #[test] fn shared_style_catalog_matches_deckcraft() { assert_eq!(deckcraft_model::table::table_styles(), craft_drawingml::table::table_styles()); diff --git a/crates/pptx/src/tables_legacy.rs b/crates/pptx/src/tables_legacy.rs new file mode 100644 index 000000000..027bf9848 --- /dev/null +++ b/crates/pptx/src/tables_legacy.rs @@ -0,0 +1,182 @@ +//! Table styles: our style ids ↔ table style GUIDs, and `tableStyles.xml` definitions for the +//! styles we write (generated from theme accents, matching how DeckCraft draws them). + +use crate::opc::NS_A; +use crate::xml::{A, W}; + +// Keep file-format identifiers in the shared DrawingML implementation. The local +// writer below still owns DeckCraft's table style definitions and XML policy. +pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid}; + +fn own_guid(style: &str) -> String { + guid(&format!("deckcraft-table-style:{style}")) +} + +fn clr(w: &mut W, slot: &str, mods: &[(&str, i32)]) { + if mods.is_empty() { + w.val("a:schemeClr", slot); + return; + } + w.open("a:schemeClr", A::new().a("val", slot)); + for (n, v) in mods { + w.val(n, v); + } + w.close("a:schemeClr"); +} + +fn solid(w: &mut W, slot: &str, mods: &[(&str, i32)]) { + w.open0("a:fill"); + w.open0("a:solidFill"); + clr(w, slot, mods); + w.close("a:solidFill"); + w.close("a:fill"); +} + +fn borders(w: &mut W, b: Option<(&str, &[(&str, i32)], i32)>) { + w.open0("a:tcBdr"); + if let Some((slot, mods, width)) = b { + for side in ["a:left", "a:right", "a:top", "a:bottom", "a:insideH", "a:insideV"] { + w.open0(side); + w.open("a:ln", A::new().a("w", width).a("cmpd", "sng")); + w.open0("a:solidFill"); + clr(w, slot, mods); + w.close("a:solidFill"); + w.close("a:ln"); + w.close(side); + } + } + w.close("a:tcBdr"); +} + +fn txt(w: &mut W, bold: bool, color: Option<&str>) { + w.open("a:tcTxStyle", A::new().o("b", bold.then_some("on"))); + w.open("a:fontRef", A::new().a("idx", "minor")); + w.val("a:prstClr", "black"); + w.close("a:fontRef"); + match color { + Some(c) => w.val("a:schemeClr", c), + None => w.val("a:schemeClr", "dk1"), + } + w.close("a:tcTxStyle"); +} + +/// Write one `a:tblStyle` for our style id. +fn style_def(w: &mut W, id: &str, name: &str) { + let kind = id.split('-').next().unwrap_or("medium2"); + let acc = match id.rsplit('-').next().unwrap_or("accent1") { + "tx1" => "dk1", + a if a.starts_with("accent") => a, + _ => "accent1", + }; + let acc: &str = acc; + w.open("a:tblStyle", A::new().a("styleId", own_guid(id)).a("styleName", name)); + let part = + |w: &mut W, tag: &str, bold: bool, text: Option<&str>, fill: Option<(&str, &[(&str, i32)])>, bdr: Option<(&str, &[(&str, i32)], i32)>| { + w.open0(tag); + if bold || text.is_some() { + txt(w, bold, text); + } + w.open0("a:tcStyle"); + borders(w, bdr); + if let Some((s, m)) = fill { + solid(w, s, m); + } + w.close("a:tcStyle"); + w.close(tag); + }; + match kind { + "grid" => { + part(w, "a:wholeTbl", false, Some("dk1"), None, Some(("dk1", &[], 9525))); + } + "light1" => { + part(w, "a:wholeTbl", false, Some("dk1"), None, None); + part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 20000)])), None); + part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 20000)])), None); + part(w, "a:lastCol", true, None, None, None); + part(w, "a:firstCol", true, None, None, None); + part(w, "a:lastRow", true, None, None, None); + part(w, "a:firstRow", true, None, None, Some((acc, &[], 12700))); + } + "light2" => { + part(w, "a:wholeTbl", false, Some("dk1"), None, Some((acc, &[], 12700))); + // Schema order: … lastCol, firstCol, lastRow, …, firstRow. + part(w, "a:firstCol", true, None, None, None); + part(w, "a:lastRow", true, None, None, None); + part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), Some((acc, &[], 12700))); + } + "dark1" => { + part(w, "a:wholeTbl", false, Some("lt1"), Some((acc, &[("a:shade", 75000)])), Some(("lt1", &[], 12700))); + part(w, "a:band1H", false, None, Some((acc, &[("a:shade", 60000)])), None); + part(w, "a:band1V", false, None, Some((acc, &[("a:shade", 60000)])), None); + part(w, "a:firstCol", true, None, None, None); + part(w, "a:lastRow", true, None, None, None); + part(w, "a:firstRow", true, Some("lt1"), Some(("dk1", &[])), None); + } + "medium4" => { + part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some((acc, &[], 9525))); + part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); + part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); + part(w, "a:lastCol", true, None, None, None); + part(w, "a:firstCol", true, None, None, None); + part(w, "a:lastRow", true, None, None, None); + part(w, "a:firstRow", true, None, Some((acc, &[("a:tint", 40000)])), None); + } + _ => { + // medium2 + part(w, "a:wholeTbl", false, Some("dk1"), Some((acc, &[("a:tint", 20000)])), Some(("lt1", &[], 12700))); + part(w, "a:band1H", false, None, Some((acc, &[("a:tint", 40000)])), None); + part(w, "a:band1V", false, None, Some((acc, &[("a:tint", 40000)])), None); + part(w, "a:lastCol", true, Some("lt1"), Some((acc, &[])), None); + part(w, "a:firstCol", true, Some("lt1"), Some((acc, &[])), None); + part(w, "a:lastRow", true, Some("lt1"), Some((acc, &[])), None); + part(w, "a:firstRow", true, Some("lt1"), Some((acc, &[])), None); + } + } + w.close("a:tblStyle"); +} + +/// `ppt/tableStyles.xml` with definitions for the styles in `used`: ours, generated, and those the +/// opened file defined (`defs`), written back as they were read. +pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableStyleDef]) -> Vec { + let mut w = W::new(); + w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}")); + let names = deckcraft_model::table::table_styles(); + // Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's + // definitions by lower-case id (the first wins). + let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); + let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); + let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); + for d in defs { + def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); + } + for s in used { + if !done.insert(s.as_str()) { + continue; + } + done_lower.insert(s.to_ascii_lowercase()); + if let Some(d) = def_of.get(&s.to_ascii_lowercase()) + && crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) + { + w.raw(&d.raw); + continue; + } + let (_, define) = guid_for_style(s); + if !define { + continue; + } + let name = names.iter().find(|(id, _)| id == s).map(|(_, n)| format!("DeckCraft {n}")).unwrap_or_else(|| s.clone()); + style_def(&mut w, s, &name); + } + // Styles the file defined but no table uses still belong to the deck. + for d in defs { + if done_lower.contains(&d.id.to_ascii_lowercase()) { + continue; + } + if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) { + done_lower.insert(d.id.to_ascii_lowercase()); + w.raw(&d.raw); + } + } + w.close("a:tblStyleLst"); + w.finish() +} From 352b1ee17094a24b622f23ddd64636566621dc82 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 11:31:14 -0500 Subject: [PATCH 73/76] Pin table-style writer to merged shared implementation --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98255c0f6..20fc1c938 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -894,9 +894,9 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c#852d37fcff3d2c09bc7aee57e637d71a9725b04c" +source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b" dependencies = [ - "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)", "kurbo", "log", "serde", @@ -1078,7 +1078,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c#852d37fcff3d2c09bc7aee57e637d71a9725b04c" +source = "git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b#cff5af869dbf6926801c9ac63a927d155202ba3b" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1351,7 +1351,7 @@ version = "0.19.0" dependencies = [ "craft-cfb", "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=44d83fa8f635333dcb3c231f87381387a1f5631b)", - "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=852d37fcff3d2c09bc7aee57e637d71a9725b04c)", + "craft-drawingml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cff5af869dbf6926801c9ac63a927d155202ba3b)", "craft-opc", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ea24422ae9859dc5da398d0462bc87f8e02e0d10)", "deckcraft-color", diff --git a/Cargo.toml b/Cargo.toml index 5dd587513..b8baca81a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9 craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ea24422ae9859dc5da398d0462bc87f8e02e0d10", version = "0.1.0" } # DrawingML colours, themes and text (craft-libs#778, #792): the model DeckCraft reads and writes. # Isolated table XML writer; existing DrawingML model/readers keep their revision. -craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "852d37fcff3d2c09bc7aee57e637d71a9725b04c" } +craft-drawingml-table = { package = "craft-drawingml", git = "https://github.com/storytold/craft-libs", rev = "cff5af869dbf6926801c9ac63a927d155202ba3b" } craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "44d83fa8f635333dcb3c231f87381387a1f5631b", version = "0.1.0" } # internal deckcraft-geom = { path = "crates/geom" } From 2c135484c1555583c8175cb5744be35648b10dd0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 11:50:07 -0500 Subject: [PATCH 74/76] Drop unused test-oracle GUID reexports --- crates/pptx/src/tables_legacy.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pptx/src/tables_legacy.rs b/crates/pptx/src/tables_legacy.rs index 027bf9848..b5d71dc4b 100644 --- a/crates/pptx/src/tables_legacy.rs +++ b/crates/pptx/src/tables_legacy.rs @@ -6,7 +6,7 @@ use crate::xml::{A, W}; // Keep file-format identifiers in the shared DrawingML implementation. The local // writer below still owns DeckCraft's table style definitions and XML policy. -pub use craft_drawingml::table::styles::{guid, guid_for_style, is_own_guid, style_from_guid}; +pub use craft_drawingml::table::styles::{guid, guid_for_style}; fn own_guid(style: &str) -> String { guid(&format!("deckcraft-table-style:{style}")) From 2ba369f5d8fb4d0d17475768a9be03cab7e0102f Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:20:42 +0000 Subject: [PATCH 75/76] Apply review fixes - crates/ui-egui/src/dialogs/tests.rs --- crates/ui-egui/src/dialogs/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 7378a6a8b..452ff079c 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -28,7 +28,7 @@ fn header_footer_apply_keeps_an_existing_date_format() { use crate::SlideApp; let mut session = deckcraft_engine::Session::with_new(); session.execute("design.headerFooter", &json!({"date": true, "dateText": "", "dateFormat": "datetime4", "all": true})).unwrap(); - // A file whose document-level format is unset, as an imported deck's is. + // A file whose document-level format is unset, as an imported deck's is when its date field is not one of the thirteen kinds. Arc::make_mut(&mut session.doc_mut().unwrap().doc).header_footer.date_format = String::new(); let date_fields = |app: &SlideApp| -> Vec { app.session From e419262c4c59931afe644e6f90049287f7aa7eff Mon Sep 17 00:00:00 2001 From: VladimirCeric Date: Wed, 18 Nov 2026 10:29:25 +0100 Subject: [PATCH 76/76] =?UTF-8?q?Review=20=E2=80=BA=20Language:=20Serbian?= =?UTF-8?q?=20in=20Cyrillic=20and=20Latin,=20each=20with=20its=20own=20dic?= =?UTF-8?q?tionary=20(#1619)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Language list offers Serbian (Cyrillic) sr-Cyrl-RS and Serbian (Latin) sr-Latn-RS. A dictionary is used only for text in its own script (LibreOffice's sr and sr-Latn, Hunspell's sr_RS and sr_Latn_RS, Fedora's sr_RS@latin), Serbian dictionaries are tried before the Serbo-Croatian sh alias, and only Latin and Cyrillic subtags or modifiers are read as a dictionary's script. Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/spell.rs | 153 ++++++++++++++++++++++--- crates/text/src/tests.rs | 31 +++++ crates/ui-egui/src/canvas/squiggles.rs | 2 + docs/localization-parity.md | 16 ++- 4 files changed, 183 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/spell.rs b/crates/engine/src/spell.rs index 8bc88e646..44879a893 100644 --- a/crates/engine/src/spell.rs +++ b/crates/engine/src/spell.rs @@ -538,7 +538,57 @@ fn valid_lang(lang: &str) -> bool { (1..=16).contains(&lang.len()) && lang.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } -/// The `.aff`/`.dic` pair for `lang` in `dirs`: the exact locale first, then any of its language. +/// The script a language tag or a dictionary's name states, lowercased: a script subtag +/// (`sr-Latn`, `sr_Latn_RS`) or a `@latin`/`@cyrillic` modifier (Fedora's `sr_RS@latin`). Only +/// the scripts a dictionary is chosen by are read (Latin and Cyrillic), so another part of a name +/// (a variant such as `de-1996`, a suffix such as `en_US-wiki`) is never taken for one. +fn named_script(name: &str) -> Option { + name.split(['-', '_', '@']).skip(1).find_map(|p| match p.to_ascii_lowercase().as_str() { + "latn" | "latin" => Some("latn".to_string()), + "cyrl" | "cyrillic" => Some("cyrl".to_string()), + _ => None, + }) +} + +/// The script of a language written in more than one, when a tag or a dictionary's name doesn't +/// state it: Serbian is Cyrillic (`sr-RS`, and LibreOffice's and Hunspell's `sr` dictionary), its +/// Latin dictionary says so (`sr-Latn`, `sr_Latn_RS`, `sr_RS@latin`). +fn default_script(base: &str) -> Option<&'static str> { + match base { + "sr" => Some("cyrl"), + _ => None, + } +} + +/// Another language code a language's dictionaries are filed under, and their script: Serbian +/// Latin dictionaries are often Serbo-Croatian ones (Hunspell's `sh_RS`, `sh_YU`). +fn alias(base: &str) -> Option<(&'static str, &'static str)> { + match base { + "sr" => Some(("sh", "latn")), + _ => None, + } +} + +/// The language code a dictionary is named for (`sr_Latn_RS`, `sr-Latn` → `sr`), lowercased. +fn stem_language(stem: &str) -> String { + stem.split(['-', '_', '@']).next().unwrap_or("").to_ascii_lowercase() +} + +/// Is the dictionary named `stem` for text in the script of `lang` (language `base`)? A Cyrillic +/// dictionary would flag every word of Latin text, and the other way round. The run's language tag +/// decides, not the letters of the text. When either side's script is unknown, any dictionary of +/// the language fits, as before. +fn same_script(lang: &str, stem: &str, base: &str) -> bool { + let default = || default_script(base).map(str::to_string); + let aliased = alias(base).filter(|(code, _)| stem_language(stem) == *code).map(|(_, script)| script.to_string()); + match (named_script(lang).or_else(default), named_script(stem).or(aliased).or_else(default)) { + (Some(want), Some(have)) => want == have, + _ => true, + } +} + +/// The `.aff`/`.dic` pair for `lang` in `dirs`: the exact locale first, then any of its language +/// (or the language its dictionaries are also filed under, [`alias`]) in the same script. pub fn find_in(dirs: &[PathBuf], lang: &str) -> Option<(PathBuf, PathBuf)> { // A language tag names a file in the dictionary folders and nothing else: no `..`, no separators. if !valid_lang(lang) { @@ -550,23 +600,33 @@ pub fn find_in(dirs: &[PathBuf], lang: &str) -> Option<(PathBuf, PathBuf)> { (a.is_file() && b.is_file()).then_some((a, b)) }; for d in dirs { - if let Some(p) = pair(d, &full) { + if let Some(p) = pair(d, &full).or_else(|| pair(d, lang)) { return Some(p); } } - for d in dirs { - if let Some(p) = pair(d, &base) { - return Some(p); - } - let Ok(rd) = std::fs::read_dir(d) else { continue }; - let mut stems: Vec = rd - .filter_map(|e| e.ok()?.file_name().into_string().ok()) - .filter_map(|n| n.strip_suffix(".aff").map(str::to_string)) - .filter(|n| n.to_lowercase().starts_with(&format!("{base}_"))) - .collect(); - stems.sort(); - if let Some(p) = stems.iter().find_map(|s| pair(d, s)) { - return Some(p); + // The language's own dictionaries first, in every folder; then those filed under its alias + // (a Serbian Latin dictionary before a Serbo-Croatian one). + let codes = std::iter::once(base.as_str()).chain(alias(&base).map(|(code, _)| code)); + for code in codes { + for d in dirs { + if same_script(lang, code, &base) + && let Some(p) = pair(d, code) + { + return Some(p); + } + let Ok(rd) = std::fs::read_dir(d) else { continue }; + // `sr_Latn_RS`, LibreOffice's `sr-Latn` and Fedora's `sr_RS@latin` all name a Serbian + // dictionary. + let mut stems: Vec = rd + .filter_map(|e| e.ok()?.file_name().into_string().ok()) + .filter_map(|n| n.strip_suffix(".aff").map(str::to_string)) + .filter(|n| stem_language(n) == code && !n.eq_ignore_ascii_case(code)) + .filter(|n| same_script(lang, n, &base)) + .collect(); + stems.sort(); + if let Some(p) = stems.iter().find_map(|s| pair(d, s)) { + return Some(p); + } } } None @@ -1078,4 +1138,67 @@ SFX D Y 1\nSFX D 0 ed/S .\n"; assert_eq!(stem("fr-FR"), None); let _ = std::fs::remove_dir_all(&dir); } + + /// Serbian is written in two scripts, and each finds its own dictionary: LibreOffice names + /// the Cyrillic one `sr` and the Latin one `sr-Latn`, Hunspell packages `sr_RS` and + /// `sr_Latn_RS`, Fedora `sr_RS` and `sr_RS@latin`, and Latin ones may be Serbo-Croatian + /// (`sh_RS`, `sh_YU`). A dictionary of the other script is never used: it would flag every word. + #[test] + fn serbian_finds_the_dictionary_of_its_script() { + let dir = std::env::temp_dir().join(format!("deckcraft-dict-sr-{}", std::process::id())); + let stem = |names: &[&str], l: &str| { + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::create_dir_all(&dir); + for n in names { + let _ = std::fs::write(dir.join(format!("{n}.aff")), ""); + let _ = std::fs::write(dir.join(format!("{n}.dic")), ""); + } + find_in(std::slice::from_ref(&dir), l).and_then(|(a, _)| a.file_stem().map(|s| s.to_string_lossy().into_owned())) + }; + let libreoffice = ["sr", "sr-Latn"]; + assert_eq!(stem(&libreoffice, "sr-Cyrl-RS").as_deref(), Some("sr")); + assert_eq!(stem(&libreoffice, "sr-RS").as_deref(), Some("sr")); + assert_eq!(stem(&libreoffice, "sr-Latn-RS").as_deref(), Some("sr-Latn")); + let hunspell = ["sr_Latn_RS", "sr_RS"]; + assert_eq!(stem(&hunspell, "sr-Cyrl-RS").as_deref(), Some("sr_RS")); + assert_eq!(stem(&hunspell, "sr-Latn-RS").as_deref(), Some("sr_Latn_RS")); + let fedora = ["sr_RS", "sr_RS@latin"]; + assert_eq!(stem(&fedora, "sr-Cyrl-RS").as_deref(), Some("sr_RS")); + assert_eq!(stem(&fedora, "sr-Latn-RS").as_deref(), Some("sr_RS@latin")); + assert_eq!(stem(&["sr_RS@latin"], "sr-Cyrl-RS"), None); + // Serbo-Croatian dictionaries are Latin: they serve Serbian Latin, never Cyrillic. + assert_eq!(stem(&["sh_RS"], "sr-Latn-RS").as_deref(), Some("sh_RS")); + assert_eq!(stem(&["sh_YU"], "sr-Latn-RS").as_deref(), Some("sh_YU")); + assert_eq!(stem(&["sh"], "sr-Latn-RS").as_deref(), Some("sh")); + assert_eq!(stem(&["sh_RS"], "sr-Cyrl-RS"), None); + assert_eq!(stem(&["sh_RS", "sr"], "sr-RS").as_deref(), Some("sr")); + // A Serbian Latin dictionary comes before a Serbo-Croatian one. + assert_eq!(stem(&["sh_RS", "sr-Latn"], "sr-Latn-RS").as_deref(), Some("sr-Latn")); + assert_eq!(stem(&["sh", "sr_RS@latin"], "sr-Latn-RS").as_deref(), Some("sr_RS@latin")); + // Only the other script installed: no dictionary, so no marks, rather than every word. + assert_eq!(stem(&["sr"], "sr-Latn-RS"), None); + assert_eq!(stem(&["sr-Latn"], "sr-Cyrl-RS"), None); + // Languages in one script are unchanged. + assert_eq!(stem(&["de_DE"], "de-AT").as_deref(), Some("de_DE")); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The script is read from a script subtag or a `@latin`/`@cyrillic` modifier, in tags and + /// dictionary names alike; a variant, a region or another suffix is not a script. + #[test] + fn a_script_is_read_only_from_a_script_subtag() { + let script = |n| named_script(n); + assert_eq!(script("sr-Cyrl").as_deref(), Some("cyrl")); + assert_eq!(script("sr-Cyrl-RS").as_deref(), Some("cyrl")); + assert_eq!(script("sr-Latn").as_deref(), Some("latn")); + assert_eq!(script("sr_Latn_RS").as_deref(), Some("latn")); + assert_eq!(script("sr_RS@latin").as_deref(), Some("latn")); + assert_eq!(script("sr_RS@cyrillic").as_deref(), Some("cyrl")); + for none in ["sr", "sr-RS", "sr_RS", "de-1996", "de_DE", "en_US-wiki", "en-GB-oxendict", "zh-Hans"] { + assert_eq!(script(none), None, "{none}"); + } + // Plain Serbian, with no script, is Cyrillic. + assert!(same_script("sr", "sr", "sr") && same_script("sr-RS", "sr_Cyrl_RS", "sr")); + assert!(!same_script("sr", "sr-Latn", "sr")); + } } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index a747af045..f70237448 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1992,3 +1992,34 @@ fn signed_insets_are_preserved_when_they_fit() { assert_eq!(l.lines.len(), 1); assert_eq!(l.inner.x0, -10.0); } + +/// Each run is shaped in its own language (Review › Language), so a font's forms for that language +/// (OpenType `locl`) are drawn: the Serbian б, not the Russian one, in a Serbian run beside a +/// Russian run of the same word. +#[test] +fn serbian_runs_draw_the_fonts_serbian_forms() { + let b = |f: &FontFace, lang: &str| { + let params = deckcraft_fonts::ShapeParams { language: Some(lang), ..Default::default() }; + deckcraft_fonts::shape_range(f, "б", 0.."б".len(), ¶ms, |c| c).first().map(|g| g.gid) + }; + let serbian_form = |f: &FontFace| b(f, "sr-Cyrl-RS") != b(f, "ru-RU"); + let Some(family) = first_family(&["DejaVu Sans", "DejaVu Serif", "Source Sans 3", "Source Serif 4", "Noto Sans", "Noto Serif"], serbian_form) + else { + eprintln!("skipped: no font with a Serbian б"); + return; + }; + let run = |text: &str, lang: &str| { + let mut r = Run::new(text); + r.props.lang = Some(lang.into()); + r.props.font = Some(family.clone()); + r + }; + let (p, sh) = bidi_setup(vec![run("грб ", "sr-Cyrl-RS"), run("грб", "ru-RU")], 2000.0, false, Align::Left); + let l = lay(&p, &sh, 2000.0, 300.0); + // Glyph of each paragraph character. + let at = |i: usize| l.runs.iter().find_map(|r| r.cells.iter().position(|&(k, _)| k == i).and_then(|g| r.glyphs.get(g)).map(|g| g.0)); + // г р б, space, г р б: each б is the one its language gives. + let face = FontDb::global().face(&family, "Regular"); + assert_eq!(at(2), b(&face, "sr-Cyrl-RS"), "{family}: the Serbian б"); + assert_eq!(at(6), b(&face, "ru-RU"), "{family}: the Russian б"); +} diff --git a/crates/ui-egui/src/canvas/squiggles.rs b/crates/ui-egui/src/canvas/squiggles.rs index 30a94a25b..f4437ef42 100644 --- a/crates/ui-egui/src/canvas/squiggles.rs +++ b/crates/ui-egui/src/canvas/squiggles.rs @@ -230,6 +230,8 @@ pub const LANGS: &[(&str, &str)] = &[ ("Українська", "uk-UA"), ("Русский", "ru-RU"), ("Беларуская", "be-BY"), + ("Српски (ћирилица)", "sr-Cyrl-RS"), + ("Srpski (latinica)", "sr-Latn-RS"), ("Türkçe", "tr-TR"), ("Ελληνικά", "el-GR"), ("日本語", "ja-JP"), diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 5fb39d1e6..764660b06 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity with PowerPoint -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-24 · **Change:** minor (opt-in native LXGW WenKai Lite fallback and interface CJK tests; local implementation only, managed validation pending; previous: minor, IME composition underlined in table cells; previous: minor, IME composition and CJK interface text, #101; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-31 · **Change:** minor (Review › Language offers Serbian in Cyrillic and Latin, each with its own dictionary; previous: minor, opt-in native LXGW WenKai Lite fallback and interface CJK tests; local implementation only, managed validation pending; previous: minor, IME composition underlined in table cells; previous: minor, IME composition and CJK interface text, #101; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) DeckCraft's interface is English only today: strings are literals in the UI and engine code, with no catalog and no language switch. Requests: #15 (follow the system language), #30 and PR #34 @@ -51,15 +51,23 @@ the next re-measure. ## Proofing languages PowerPoint checks spelling in dozens of languages and lets each run carry a proofing language. -DeckCraft keeps `a:rPr/@lang` on round trip but its spelling check is a small English list of -common misspellings (`crates/engine/src/cmd/review.rs`); see [gaps.md](gaps.md#proofing-spelling-thesaurus-autocorrect). +DeckCraft keeps `a:rPr/@lang` on round trip and checks each run in its own language against the +Hunspell dictionaries installed on the system (`crates/engine/src/spell.rs`), falling back to a +built-in list of common English misspellings when there is none (`review.spelling`); see +[gaps.md](gaps.md#proofing-spelling-thesaurus-autocorrect). Review › Language sets the proofing language of the selected text or, with *Whole presentation*, -of every text in the file and the default for new text (`format.languageAll`). +of every text in the file and the default for new text (`format.languageAll`). Each run is shaped +in its language, so fonts draw their forms for it (OpenType `locl`: the Serbian б, г, д, п, т). +Serbian is offered in both scripts (`sr-Cyrl-RS`, `sr-Latn-RS`). The run's language tag picks the +dictionary, and only one in the script the tag names: LibreOffice's `sr` and `sr-Latn`, Hunspell's +`sr_RS` and `sr_Latn_RS`, Fedora's `sr_RS@latin`, and the Serbo-Croatian `sh_RS`/`sh_YU` for Latin. +A dictionary of the other script would flag every word, so it is never used. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | Review › Language offers Serbian (Cyrillic and Latin); each run's language tag picks a dictionary in the script it names | | 2026-10-24 | minor | Local 0.37 candidate adds an opt-in native LXGW WenKai Lite glyph fallback and CJK interface-test coverage. This records local implementation only: managed tests, formatting, clippy, wasm-size and native GUI qualification remain pending. Browser font budget and uniform Chinese typography are unchanged. | | 2026-10-21 | minor | Review › Language can set the proofing language of the whole presentation | | 2026-10-14 | minor | IME composition in a table cell is underlined in place; the candidate window sits on that cell's caret |