mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-04 22:50:29 +00:00
Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
078493b2ad | ||
|
|
65debf460c | ||
|
|
c6484283e9 | ||
|
|
4dbcf0e653 | ||
|
|
0091d8c95e | ||
|
|
b5758001aa | ||
|
|
bf9717fb5b | ||
|
|
d606418f11 | ||
|
|
c397003ac5 | ||
|
|
37949a580d | ||
|
|
8f551eac19 | ||
|
|
258db944e9 | ||
|
|
073ccb5a6f | ||
|
|
b309f6c3f3 | ||
|
|
1cf8191390 | ||
|
|
e08af8eaca | ||
|
|
0f8b63636e | ||
|
|
120812fdc5 | ||
|
|
d89ad70d81 | ||
|
|
383e7d2f55 | ||
|
|
fa0201d76d | ||
|
|
98988563ea | ||
|
|
df1adf5aa2 | ||
|
|
209c343a12 | ||
|
|
35095e8f90 | ||
|
|
6d0cf8e5d3 | ||
|
|
89273445e1 | ||
|
|
be6c83acf4 | ||
|
|
10a319f002 | ||
|
|
1ab2766576 | ||
|
|
e74f1101dc | ||
|
|
ef4a4f4fd5 | ||
|
|
f51dc225a6 | ||
|
|
0458818244 | ||
|
|
7df135e8ec | ||
|
|
29f90a373f | ||
|
|
b6c8adbaff | ||
|
|
218bf7fa7d | ||
|
|
e1738a5b1d | ||
|
|
d1b9662e9f | ||
|
|
865198fdc1 | ||
|
|
881517624d | ||
|
|
97ca37727f | ||
|
|
a43846ddb5 | ||
|
|
20012e35ca | ||
|
|
a01bc8f89e | ||
|
|
910f4e86d1 | ||
|
|
46b8dfa222 | ||
|
|
1fdc52ce76 | ||
|
|
6b766e8d37 | ||
|
|
d4bfc8c87a | ||
|
|
c8b0ea548e | ||
|
|
3e221ccb50 | ||
|
|
9e73fef158 | ||
|
|
239f293ca7 | ||
|
|
5cc5d9b8c3 | ||
|
|
e3781b10eb | ||
|
|
d7702e7420 | ||
|
|
6dfad5678f | ||
|
|
ad49f99bfe | ||
|
|
0cc4e2ab3d | ||
|
|
cc634de30a | ||
|
|
58e0aa3a4a | ||
|
|
5ee6022a10 | ||
|
|
2092cc975b | ||
|
|
d2a4dd03cb | ||
|
|
82c2bf3315 | ||
|
|
069f783c25 | ||
|
|
39fd7ed90f | ||
|
|
7ebc2cb906 | ||
|
|
ad6e17590d | ||
|
|
2327905e6c | ||
|
|
6a1affd141 | ||
|
|
0b1399df94 | ||
|
|
7e3c6d13d9 | ||
|
|
51958983b0 | ||
|
|
cf3aa057cd | ||
|
|
2359e5c066 | ||
|
|
ca3b02653a | ||
|
|
ec53a162db | ||
|
|
c3deb83ec5 | ||
|
|
39d54845c0 | ||
|
|
4885a1724d | ||
|
|
72e3055b3b | ||
|
|
115070fbb9 | ||
|
|
d276e5df1d | ||
|
|
e3423744d2 | ||
|
|
af03e3840d | ||
|
|
057dba07da | ||
|
|
949562d90a | ||
|
|
657686d623 | ||
|
|
873b46a85b | ||
|
|
c462f658ab | ||
|
|
554274630b | ||
|
|
e770e72fa6 | ||
|
|
e662477fd2 | ||
|
|
1f4a7afc95 | ||
|
|
cbbc3347cf | ||
|
|
fface3030c | ||
|
|
89a2746ee5 | ||
|
|
25ea1eb064 | ||
|
|
e9dbf10433 | ||
|
|
9c600da847 | ||
|
|
9e00c7ae9b | ||
|
|
23f0cd1c9f | ||
|
|
bb345f2828 | ||
|
|
dd18f64d3f | ||
|
|
8519680df0 |
Generated
+13
@@ -2487,6 +2487,7 @@ dependencies = [
|
||||
"image",
|
||||
"js-sys",
|
||||
"log",
|
||||
"memory-stats",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2672,6 +2673,7 @@ dependencies = [
|
||||
"egui",
|
||||
"egui_kittest",
|
||||
"log",
|
||||
"memory-stats",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
@@ -2695,6 +2697,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
@@ -4951,6 +4954,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memory-stats"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c73f5c649995a115e1a0220b35e4df0a1294500477f97a91d0660fb5abeb574a"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.18"
|
||||
|
||||
@@ -29,3 +29,6 @@ wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
|
||||
@@ -215,3 +215,28 @@ impl eframe::App for WebShell {
|
||||
self.app.ui(ui);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod wasm_smoke_tests {
|
||||
use deckcraft_engine::Session;
|
||||
|
||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
||||
|
||||
// Run with wasm-bindgen-test-runner in a real browser. wasm panic=abort means a panic here
|
||||
// would stop the test process; the hostile requests below must return Results instead.
|
||||
#[wasm_bindgen_test::wasm_bindgen_test]
|
||||
fn malformed_commands_return_errors_and_the_session_remains_usable() {
|
||||
let mut session = Session::new();
|
||||
|
||||
assert!(session.execute("file.new", &serde_json::json!({})).is_ok(), "a presentation must be active before shape commands");
|
||||
|
||||
let bad_font = session.execute("font.add", &serde_json::json!({"data": "AAAA"}));
|
||||
assert!(bad_font.is_err(), "invalid font data must return an error");
|
||||
|
||||
let bad_geometry = session.execute("shape.insert", &serde_json::json!({"preset": "not-a-shape"}));
|
||||
assert!(bad_geometry.is_err(), "unknown geometry must return an error");
|
||||
|
||||
let valid = session.execute("shape.insert", &serde_json::json!({"preset": "rect", "rect": [0, 0, 10, 10]}));
|
||||
assert!(valid.is_ok(), "a valid command must still work after malformed requests");
|
||||
}
|
||||
}
|
||||
|
||||
+178
-12
@@ -1,6 +1,7 @@
|
||||
//! Morph: matching shapes between two slides, interpolating their boxes and building the frames.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use deckcraft_model::resolve::{self, Ctx};
|
||||
use deckcraft_model::{ColorRef, Fill, Geom, Presentation, Rgba, Shape, ShapeId, ShapeKind, Slide, Xfrm, walk};
|
||||
@@ -12,14 +13,45 @@ fn text_of(s: &Shape) -> String {
|
||||
s.text.as_ref().map(|t| t.text()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn content_hash(s: &Shape) -> u64 {
|
||||
shape_hash(&content(s))
|
||||
}
|
||||
|
||||
fn geom_hash(s: &Shape) -> u64 {
|
||||
shape_hash(&Shape { geom: Geom::default(), ..content(s) })
|
||||
}
|
||||
|
||||
fn crop_hash(s: &Shape) -> u64 {
|
||||
shape_hash(&uncropped(s))
|
||||
}
|
||||
|
||||
fn shape_hash(s: &Shape) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
// `PartialEq` treats -0.0 and 0.0 as equal; Debug does not, so normalise it before hashing.
|
||||
format!("{s:?}").replace("-0.0", "0.0").hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
fn outlined(s: &Shape) -> bool {
|
||||
matches!(s.kind, ShapeKind::Shape | ShapeKind::Picture { .. } | ShapeKind::Connector { .. })
|
||||
}
|
||||
|
||||
fn picture(s: &Shape) -> bool {
|
||||
matches!(s.kind, ShapeKind::Picture { .. })
|
||||
}
|
||||
|
||||
/// Pairs of (shape on `a`, shape on `b`) that Morph animates from one to the other: first by
|
||||
/// `!!name` (forced match), then by exact name, then by the same kind and text, then by the same
|
||||
/// kind and preset geometry if neither carries text. A text box with neither a name nor its text on
|
||||
/// the other slide stays unpaired and fades in place, as in PowerPoint (#119). Each shape is used
|
||||
/// `!!name` (forced match), then by exact name when the two are the same object, then by the same
|
||||
/// kind and text, then by the same kind and preset geometry if neither carries text and they are
|
||||
/// the same object. The same object means the same content, or a difference only in what Morph
|
||||
/// interpolates (a geometry or a picture's crop): different text, pictures or kinds fade in place
|
||||
/// unless the name starts with `!!` (#2467). A text box with neither a name nor its text on the
|
||||
/// other slide stays unpaired and fades in place, as in PowerPoint (#119). Each shape is used
|
||||
/// once; top-level shapes only (groups move whole).
|
||||
///
|
||||
/// Each pass compares a key of the two shapes, so the shapes of `b` are indexed by key once per
|
||||
/// pass: matching costs the sum of the two shape lists, not their product.
|
||||
/// pass. A strict pass also indexes the exact content and the two properties Morph can interpolate,
|
||||
/// so a candidate that differs in anything else never shares a queue; matching stays linear.
|
||||
pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
|
||||
let mut pairs: Vec<(ShapeId, ShapeId)> = Vec::new();
|
||||
let mut used_a = vec![false; a.shapes.len()];
|
||||
@@ -34,17 +66,17 @@ pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
|
||||
Some(g) if t.trim().is_empty() => Some(MorphKey::Geom(s.kind_name(), g.to_string())),
|
||||
_ => None,
|
||||
};
|
||||
let passes: [&dyn Fn(&Shape, &str) -> Option<MorphKey>; 4] = [&forced, &named, &same_text, &same_geom];
|
||||
for key in passes {
|
||||
// Unused shapes of `b` by key, in slide order: the front of each queue is the first unused
|
||||
// match, which is the one a search through `b` would find.
|
||||
let mut index: HashMap<MorphKey, VecDeque<usize>> = HashMap::new();
|
||||
// Forced names pair anything; ordinary names and the geometry fallback pair only the same
|
||||
// object; the text pass keeps pairing shapes that share their text (#316).
|
||||
let passes: [(&dyn Fn(&Shape, &str) -> Option<MorphKey>, bool); 4] = [(&forced, false), (&named, true), (&same_text, false), (&same_geom, true)];
|
||||
for (key, strict) in passes {
|
||||
let mut index = MatchIndex::new(strict);
|
||||
for (j, sb) in b.shapes.iter().enumerate() {
|
||||
if used_b.get(j).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if let Some(k) = key(sb, text_b.get(j).map_or("", String::as_str)) {
|
||||
index.entry(k).or_default().push_back(j);
|
||||
index.insert(k, j, sb);
|
||||
}
|
||||
}
|
||||
if index.is_empty() {
|
||||
@@ -55,7 +87,7 @@ pub fn morph_pairs(a: &Slide, b: &Slide) -> Vec<(ShapeId, ShapeId)> {
|
||||
continue;
|
||||
}
|
||||
let Some(k) = key(sa, text_a.get(i).map_or("", String::as_str)) else { continue };
|
||||
let Some(j) = index.get_mut(&k).and_then(VecDeque::pop_front) else { continue };
|
||||
let Some(j) = index.take(k, sa, b, &used_b) else { continue };
|
||||
let Some(sb) = b.shapes.get(j) else { continue };
|
||||
if let Some(u) = used_a.get_mut(i) {
|
||||
*u = true;
|
||||
@@ -77,6 +109,84 @@ enum MorphKey {
|
||||
Geom(&'static str, String),
|
||||
}
|
||||
|
||||
/// The indexed `b` shapes for one pass. A strict pass can pair exact content, a geometry-only
|
||||
/// change or a crop-only change, so it keeps three queues; any other difference is a different
|
||||
/// content hash and can never be scanned.
|
||||
enum MatchIndex {
|
||||
Plain(HashMap<MorphKey, VecDeque<usize>>),
|
||||
Strict {
|
||||
exact: HashMap<(MorphKey, u64), VecDeque<usize>>,
|
||||
geom: HashMap<(MorphKey, u64), VecDeque<usize>>,
|
||||
crop: HashMap<(MorphKey, u64), VecDeque<usize>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl MatchIndex {
|
||||
fn new(strict: bool) -> Self {
|
||||
if strict { Self::Strict { exact: HashMap::new(), geom: HashMap::new(), crop: HashMap::new() } } else { Self::Plain(HashMap::new()) }
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Self::Plain(map) => map.is_empty(),
|
||||
Self::Strict { exact, geom, crop } => exact.is_empty() && geom.is_empty() && crop.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&mut self, k: MorphKey, j: usize, sb: &Shape) {
|
||||
match self {
|
||||
Self::Plain(map) => map.entry(k).or_default().push_back(j),
|
||||
Self::Strict { exact, geom, crop } => {
|
||||
exact.entry((k.clone(), content_hash(sb))).or_default().push_back(j);
|
||||
if outlined(sb) {
|
||||
geom.entry((k.clone(), geom_hash(sb))).or_default().push_back(j);
|
||||
}
|
||||
if picture(sb) {
|
||||
crop.entry((k, crop_hash(sb))).or_default().push_back(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, k: MorphKey, sa: &Shape, b: &Slide, used: &[bool]) -> Option<usize> {
|
||||
match self {
|
||||
Self::Plain(map) => {
|
||||
let q = map.get_mut(&k)?;
|
||||
first_plain(q, used)
|
||||
}
|
||||
Self::Strict { exact, geom, crop } => {
|
||||
let exact_key = (k.clone(), content_hash(sa));
|
||||
let geom_key = outlined(sa).then(|| (k.clone(), geom_hash(sa)));
|
||||
let crop_key = picture(sa).then(|| (k.clone(), crop_hash(sa)));
|
||||
first(exact.get_mut(&exact_key), sa, b, used)
|
||||
.into_iter()
|
||||
.chain(geom_key.as_ref().and_then(|k| first(geom.get_mut(k), sa, b, used)))
|
||||
.chain(crop_key.as_ref().and_then(|k| first(crop.get_mut(k), sa, b, used)))
|
||||
.min()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first candidate in a hash bucket that is actually the same object. Candidates already used
|
||||
/// by an earlier shape are popped from the front and skipped, so a sibling queue never rescans
|
||||
/// them; incompatible candidates stay in place for another source or pass.
|
||||
fn first(q: Option<&mut VecDeque<usize>>, sa: &Shape, b: &Slide, used: &[bool]) -> Option<usize> {
|
||||
let q = q?;
|
||||
while q.front().is_some_and(|&j| used.get(j).copied().unwrap_or(true)) {
|
||||
q.pop_front();
|
||||
}
|
||||
q.iter().copied().find(|&j| !used.get(j).copied().unwrap_or(true) && b.shapes.get(j).is_some_and(|sb| morph_match(sa, sb)))
|
||||
}
|
||||
|
||||
/// The non-strict queues hold only matching keys, so the first unused candidate is the pick.
|
||||
fn first_plain(q: &mut VecDeque<usize>, used: &[bool]) -> Option<usize> {
|
||||
while q.front().is_some_and(|&j| used.get(j).copied().unwrap_or(true)) {
|
||||
q.pop_front();
|
||||
}
|
||||
q.front().copied()
|
||||
}
|
||||
|
||||
fn lerp(a: f64, b: f64, t: f64) -> f64 {
|
||||
let v = a + (b - a) * t;
|
||||
if v.is_finite() {
|
||||
@@ -186,7 +296,56 @@ fn box_of(ctx: Option<&Ctx>, s: &Shape) -> Option<Xfrm> {
|
||||
|
||||
/// The content of a shape apart from what Morph interpolates (identity, box and fill).
|
||||
fn content(s: &Shape) -> Shape {
|
||||
Shape { id: ShapeId(0), name: String::new(), xfrm: None, fill: None, ..s.clone() }
|
||||
let mut c = Shape { id: ShapeId(0), name: String::new(), xfrm: None, fill: None, ..s.clone() };
|
||||
if matches!(c.kind, ShapeKind::Group { .. } | ShapeKind::Connector { .. }) {
|
||||
let mut ids = HashMap::new();
|
||||
let mut next = 0u32;
|
||||
normalize_ids(&mut c, &mut next, &mut ids, 0);
|
||||
remap_refs(&mut c, &ids, 0);
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Gives a shape and its descendants deterministic ids in traversal order. `slide.duplicate`
|
||||
/// reallocates every descendant id, so the duplicated group must compare equal to its source.
|
||||
fn normalize_ids(s: &mut Shape, next: &mut u32, ids: &mut HashMap<ShapeId, ShapeId>, depth: u32) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
let old = s.id;
|
||||
let new = ShapeId(*next);
|
||||
*next += 1;
|
||||
ids.insert(old, new);
|
||||
s.id = new;
|
||||
if let ShapeKind::Group { children, .. } = &mut s.kind {
|
||||
for child in children {
|
||||
normalize_ids(child, next, ids, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites a connector's endpoints through the normalized id map; a reference outside the walked
|
||||
/// subtree (an external shape) becomes `ShapeId(0)`, as `reid` would leave it outside this group.
|
||||
fn remap_refs(s: &mut Shape, ids: &HashMap<ShapeId, ShapeId>, depth: u32) {
|
||||
if depth > 64 {
|
||||
return;
|
||||
}
|
||||
match &mut s.kind {
|
||||
ShapeKind::Group { children, .. } => {
|
||||
for child in children {
|
||||
remap_refs(child, ids, depth + 1);
|
||||
}
|
||||
}
|
||||
ShapeKind::Connector { start, end } => {
|
||||
if let Some((id, _)) = start {
|
||||
*id = ids.get(id).copied().unwrap_or(ShapeId(0));
|
||||
}
|
||||
if let Some((id, _)) = end {
|
||||
*id = ids.get(id).copied().unwrap_or(ShapeId(0));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two shapes differ in their geometry only, and it is drawn as an outline (shapes,
|
||||
@@ -217,6 +376,13 @@ fn recropped(a: &Shape, b: &Shape) -> bool {
|
||||
matches!(a.kind, ShapeKind::Picture { .. }) && crop_of(a) != crop_of(b) && uncropped(a) == uncropped(b)
|
||||
}
|
||||
|
||||
/// Whether two shapes are the same object for Morph matching: their content matches, or differs
|
||||
/// only in a property Morph interpolates (a geometry or a picture's crop). A different text,
|
||||
/// picture or kind is another object; it fades in place unless its name starts with `!!` (#2467).
|
||||
fn morph_match(a: &Shape, b: &Shape) -> bool {
|
||||
content(a) == content(b) || reshaped(a, b) || recropped(a, b)
|
||||
}
|
||||
|
||||
/// The crop (left, top, right, bottom) of a picture morphing from box `xa` cropped by `ca` to box
|
||||
/// `xb` cropped by `cb`, when its box is `x` at progress `t`: the whole image moves and scales
|
||||
/// linearly between where it lies on either slide, and the crop is what of it `x` shows. Falls back
|
||||
|
||||
+213
-10
@@ -575,11 +575,161 @@ fn morph_pairs_leaves_unrelated_text_boxes_alone() {
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
let xs: Vec<(&str, f64)> = f.shapes.iter().map(|(s, _)| (s.name.as_str(), s.xfrm.map_or(f64::NAN, |x| x.x))).collect();
|
||||
assert_eq!(xs, [("TextBox 1", 0.0), ("TextBox 2", 400.0)]);
|
||||
// Empty shapes of one kind and geometry still pair, and a named text box keeps its partner.
|
||||
// Empty shapes of one kind and geometry still pair. A shared name is not enough when the
|
||||
// text differs: the text boxes fade in place and only the rectangles pair (#2467).
|
||||
a.shapes.push(shape(3, "Rect A"));
|
||||
b.shapes.push(shape(4, "Rect B"));
|
||||
b.shapes[0].name = "TextBox 1".into();
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2)), (ShapeId(3), ShapeId(4))]);
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(3), ShapeId(4))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_changed_text_fades_in_place() {
|
||||
// #2467: the same name is not enough when the text changed; only `!!` forces a pair.
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let tb = |id, x, text| Shape { xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)), text: Some(TextBody::from_text(text)), ..shape(id, "Text Box 1") };
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![tb(1, 0.0, "Before")];
|
||||
b.shapes = vec![tb(2, 400.0, "After")];
|
||||
assert!(morph_pairs(&a, &b).is_empty(), "a changed text must not pair");
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
let s = f.mix;
|
||||
assert_eq!(f.shapes.len(), 2);
|
||||
// The old box fades out where it was and the new one fades in where it is: no travel to 200.
|
||||
assert_eq!(f.shapes[0].0.text.as_ref().map(|t| t.text()).as_deref(), Some("Before"));
|
||||
assert!(f.shapes[0].1);
|
||||
assert_eq!(f.shapes[0].0.xfrm.unwrap().x, 0.0);
|
||||
assert_eq!(f.shapes[1].0.text.as_ref().map(|t| t.text()).as_deref(), Some("After"));
|
||||
assert!(!f.shapes[1].1);
|
||||
assert_eq!(f.shapes[1].0.xfrm.unwrap().x, 400.0);
|
||||
assert!((f.opacity_of(f.shapes[0].0.id) - (1.0 - s)).abs() < 1e-9);
|
||||
assert!((f.opacity_of(f.shapes[1].0.id) - s).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_skips_an_incompatible_candidate() {
|
||||
// #2467 review: a `Box` that changed its text must not block a later empty `Box` ellipse
|
||||
// from pairing with the empty `Box` rectangle of the old slide.
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![Shape { geom: deckcraft_model::Geom::preset("rect"), ..shape(1, "Box") }];
|
||||
b.shapes = vec![
|
||||
Shape { text: Some(TextBody::from_text("Hi")), ..shape(2, "Box") },
|
||||
Shape { geom: deckcraft_model::Geom::preset("ellipse"), ..shape(3, "Box") },
|
||||
];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(3))], "the empty ellipse is the same object");
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
// One morphing shape (the ellipse) plus the text-bearing rectangle fading in.
|
||||
assert_eq!(f.shapes.iter().filter(|(_, old)| !old).count(), 2);
|
||||
assert_eq!(f.paths.len(), 1, "the rectangle turns into the ellipse");
|
||||
assert_eq!(f.paths[0].from, deckcraft_model::Geom::preset("rect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_geometry_match_does_not_leave_the_candidate_for_another_shape() {
|
||||
let geo = |id, g| Shape { geom: deckcraft_model::Geom::preset(g), ..shape(id, "Box") };
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![geo(1, "ellipse"), geo(2, "rect")];
|
||||
b.shapes = vec![geo(3, "rect")];
|
||||
let pairs = morph_pairs(&a, &b);
|
||||
assert_eq!(pairs, [(ShapeId(1), ShapeId(3))], "the candidate is paired once");
|
||||
let mut b_ids: Vec<_> = pairs.iter().map(|p| p.1).collect();
|
||||
b_ids.sort();
|
||||
b_ids.dedup();
|
||||
assert_eq!(b_ids.len(), pairs.len(), "no b shape is used twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_pairs_a_picture_after_an_incompatible_same_media_candidate() {
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
let pic = |id, geom: &str, crop, x| Shape {
|
||||
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
|
||||
geom: deckcraft_model::Geom::preset(geom),
|
||||
kind: deckcraft_model::ShapeKind::Picture {
|
||||
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(10), crop, ..Default::default() },
|
||||
},
|
||||
..shape(id, "Picture 1")
|
||||
};
|
||||
a.shapes = vec![pic(1, "rect", [0.0; 4], 0.0)];
|
||||
b.shapes = vec![
|
||||
pic(2, "ellipse", [0.5, 0.0, 0.0, 0.0], 200.0), // same name and media, but geometry and crop both changed
|
||||
pic(3, "rect", [0.0; 4], 400.0), // the same object
|
||||
];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(3))], "the later compatible picture pairs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_group_on_a_duplicated_slide_still_pairs() {
|
||||
// #2467 review: slide.duplicate gives every descendant a new id; the group is still the same
|
||||
// object and must morph as one unit after the move.
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let group = |root: u32, child: u32, x: f64| Shape {
|
||||
id: ShapeId(root),
|
||||
name: "Group 1".into(),
|
||||
xfrm: Some(Xfrm::new(x, 100.0, 300.0, 200.0)),
|
||||
kind: deckcraft_model::ShapeKind::Group {
|
||||
children: vec![Shape { id: ShapeId(child), ..shape(child, "Child 1") }, Shape { id: ShapeId(child + 1), ..shape(child + 1, "Child 2") }],
|
||||
child: Xfrm::new(0.0, 0.0, 1.0, 1.0),
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![group(1, 2, 100.0)];
|
||||
b.shapes = vec![group(10, 11, 250.0)];
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
assert_eq!(f.shapes.len(), 1, "the duplicated group morphs as one unit");
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(10))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_same_named_pictures_pair_in_slide_order() {
|
||||
let n = 1000u32;
|
||||
let pic = |id, x, crop| Shape {
|
||||
xfrm: Some(Xfrm::new(x, 100.0, 100.0, 100.0)),
|
||||
kind: deckcraft_model::ShapeKind::Picture {
|
||||
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(1), crop, ..Default::default() },
|
||||
},
|
||||
..shape(id, "Logo")
|
||||
};
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = (0..n).map(|i| pic(i + 1, f64::from(i) * 10.0, [0.0; 4])).collect();
|
||||
b.shapes = (0..n).map(|i| pic(n + i + 1, f64::from(i) * 10.0, [0.1, 0.0, 0.0, 0.0])).collect();
|
||||
let pairs = morph_pairs(&a, &b);
|
||||
assert_eq!(pairs.len(), n as usize);
|
||||
assert!(pairs.windows(2).all(|w| w[0].1.0 < w[1].1.0), "targets keep slide order");
|
||||
assert_eq!(pairs[0], (ShapeId(1), ShapeId(n + 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_name_pictures_with_different_images_fade_in_place() {
|
||||
// #2467: the same name is not enough when the picture changed; the geometry fallback must not
|
||||
// pair them either.
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let pic = |id, media, x| Shape {
|
||||
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
|
||||
kind: deckcraft_model::ShapeKind::Picture {
|
||||
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(media), ..Default::default() },
|
||||
},
|
||||
..shape(id, "Picture 1")
|
||||
};
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![pic(1, 10, 0.0)];
|
||||
b.shapes = vec![pic(2, 11, 400.0)];
|
||||
assert!(morph_pairs(&a, &b).is_empty(), "a different picture must not pair");
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
let s = f.mix;
|
||||
assert_eq!(f.shapes.len(), 2);
|
||||
assert_eq!(f.shapes[0].0.xfrm.unwrap().x, 0.0);
|
||||
assert_eq!(f.shapes[1].0.xfrm.unwrap().x, 400.0);
|
||||
assert!((f.opacity_of(f.shapes[0].0.id) - (1.0 - s)).abs() < 1e-9);
|
||||
assert!((f.opacity_of(f.shapes[1].0.id) - s).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -608,6 +758,7 @@ fn morph_frame_morphs_a_picture_crop() {
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![pic(1, [0.0, 0.0, 0.5, 0.0])];
|
||||
b.shapes = vec![pic(2, [0.5, 0.0, 0.0, 0.0])];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2))], "a crop change still pairs");
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
assert_eq!(f.shapes.len(), 1);
|
||||
assert!(f.opacity.is_empty());
|
||||
@@ -668,12 +819,14 @@ fn morph_frame_moves_blends_and_fades() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn morph_frame_cross_fades_changed_content() {
|
||||
fn forced_name_cross_fades_changed_content() {
|
||||
// #2467: `!!` forces a pair even when the text changed; the two cross-fade on the moving box.
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![Shape { text: Some(TextBody::from_text("Before")), ..shape(1, "T") }];
|
||||
b.shapes = vec![Shape { text: Some(TextBody::from_text("After")), ..shape(1, "T") }];
|
||||
a.shapes = vec![Shape { text: Some(TextBody::from_text("Before")), ..shape(1, "!!T") }];
|
||||
b.shapes = vec![Shape { text: Some(TextBody::from_text("After")), ..shape(1, "!!T") }];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(1))]);
|
||||
let f = morph_frame(&p, &a, &b, 0.25, &|_| false);
|
||||
// The new text under the fading old one, both on the moving box.
|
||||
assert_eq!(f.shapes.len(), 2);
|
||||
@@ -689,8 +842,8 @@ fn morph_frame_lists_texts_for_words_and_characters() {
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![Shape { text: Some(TextBody::from_text("The Science")), ..shape(1, "T") }];
|
||||
b.shapes = vec![Shape { text: Some(TextBody::from_text("Science rocks")), ..shape(1, "T") }];
|
||||
a.shapes = vec![Shape { text: Some(TextBody::from_text("The Science")), ..shape(1, "!!T") }];
|
||||
b.shapes = vec![Shape { text: Some(TextBody::from_text("Science rocks")), ..shape(1, "!!T") }];
|
||||
for (option, want) in [("objects", None), ("words", Some(false)), ("characters", Some(true))] {
|
||||
b.transition = Some(Transition { kind: "morph".into(), option: option.into(), ..Default::default() });
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
@@ -713,6 +866,7 @@ fn morph_frame_morphs_the_outline_of_a_changed_geometry() {
|
||||
let geo = |s: Shape, g: &str| Shape { geom: deckcraft_model::Geom::preset(g), ..s };
|
||||
a.shapes = vec![solid(geo(shape(1, "Form"), "ellipse"), 0)];
|
||||
b.shapes = vec![solid(Shape { xfrm: Some(Xfrm::new(300.0, 100.0, 100.0, 100.0)), ..geo(shape(1, "Form"), "star5") }, 200)];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(1))], "a geometry change still pairs");
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
// One shape: the new one, on the moving box, its colour blending and its outline listed to morph.
|
||||
assert_eq!(f.shapes.len(), 1);
|
||||
@@ -1116,6 +1270,7 @@ fn same_text_morphs_even_by_objects() {
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![titled(1, 100.0, 60.0, "TEST")];
|
||||
b.shapes = vec![titled(2, 40.0, 44.0, "TEST")];
|
||||
assert_eq!(morph_pairs(&a, &b).len(), 1, "the shapes with the shared text pair");
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
assert_eq!(f.text.len(), 1, "the shared text morphs");
|
||||
assert!(!f.text[0].chars);
|
||||
@@ -1243,16 +1398,64 @@ fn morph_of_large_slides_stays_linear() {
|
||||
// Text no shape on the other slide shares: every pass looks for a partner and finds none.
|
||||
a.shapes = (0..n).map(|i| Shape { text: text(i, "a"), ..shape(i + 1, "") }).collect();
|
||||
b.shapes = (0..n).map(|i| Shape { text: text(i, "b"), ..shape(n + i + 1, "") }).collect();
|
||||
// One named pair at opposite ends.
|
||||
// One named pair at opposite ends with the same content.
|
||||
a.shapes[0].name = "Logo".into();
|
||||
b.shapes[n as usize - 1].name = "Logo".into();
|
||||
b.shapes[n as usize - 1].text = a.shapes[0].text.clone();
|
||||
// No wall-clock bound (it would flake on a loaded runner): at this size a quadratic pairing
|
||||
// takes minutes, so a regression shows as a test that hangs rather than a failed assertion.
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2 * n))]);
|
||||
let p = deckcraft_model::defaults::new_presentation(None);
|
||||
let f = morph_frame(&p, &a, &b, 0.5, &|_| false);
|
||||
// Every shape fades in place; the named pair differs in text, so it cross-fades as two.
|
||||
assert_eq!(f.shapes.len(), 2 * n as usize);
|
||||
// Every other shape fades in place; the named pair has the same content and moves as one.
|
||||
assert_eq!(f.shapes.len(), 2 * n as usize - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_same_name_shapes_with_distinct_text_stay_linear() {
|
||||
let n = 20_000u32;
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
// Every shape shares the name but no text: the strict name pass must look up one text key
|
||||
// per shape, not scan all 20,000 same-name candidates.
|
||||
a.shapes = (0..n).map(|i| Shape { text: Some(TextBody::from_text(&format!("a {i}"))), ..shape(i + 1, "Box") }).collect();
|
||||
b.shapes = (0..n).map(|i| Shape { text: Some(TextBody::from_text(&format!("b {i}"))), ..shape(n + i + 1, "Box") }).collect();
|
||||
assert!(morph_pairs(&a, &b).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_zero_content_still_pairs() {
|
||||
let pic = |id, alpha| Shape {
|
||||
kind: deckcraft_model::ShapeKind::Picture {
|
||||
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(1), alpha: Some(alpha), ..Default::default() },
|
||||
},
|
||||
..shape(id, "Picture 1")
|
||||
};
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
a.shapes = vec![pic(1, -0.0)];
|
||||
b.shapes = vec![pic(2, 0.0)];
|
||||
assert_eq!(morph_pairs(&a, &b), [(ShapeId(1), ShapeId(2))], "-0.0 and 0.0 are equal content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_same_name_pictures_with_distinct_alpha_stay_linear() {
|
||||
let n = 20_000u32;
|
||||
let pic = |id, alpha, x| Shape {
|
||||
xfrm: Some(Xfrm::new(x, 100.0, 200.0, 100.0)),
|
||||
geom: deckcraft_model::Geom::preset("rect"),
|
||||
kind: deckcraft_model::ShapeKind::Picture {
|
||||
fill: deckcraft_model::style::PictureFill { media: deckcraft_model::MediaId(10), alpha: Some(alpha), ..Default::default() },
|
||||
},
|
||||
..shape(id, "Picture 1")
|
||||
};
|
||||
let mut a = Slide::default();
|
||||
let mut b = Slide::default();
|
||||
// Same name, media, geometry and crop; only the alpha differs, so no pair exists and the
|
||||
// named and geometry passes must not scan all 20,000 candidates.
|
||||
a.shapes = (0..n).map(|i| pic(i + 1, 0.5, 0.0)).collect();
|
||||
b.shapes = (0..n).map(|i| pic(n + i + 1, 1.0, 400.0)).collect();
|
||||
assert!(morph_pairs(&a, &b).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -39,12 +39,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hsl_roundtrip() {
|
||||
for c in [Rgba::rgb(10, 200, 30), Rgba::rgb(255, 0, 0), Rgba::rgb(128, 128, 128), Rgba::rgb(21, 96, 130)] {
|
||||
let (h, s, l) = c.to_hsl();
|
||||
let d = Rgba::from_hsl(h, s, l, 255);
|
||||
for color in [Rgba::rgb(10, 200, 30), Rgba::rgb(255, 0, 0), Rgba::rgb(128, 128, 128), Rgba::rgb(21, 96, 130)] {
|
||||
let (hue, saturation, lightness) = color.to_hsl();
|
||||
let converted = Rgba::from_hsl(hue, saturation, lightness, 255);
|
||||
assert!(
|
||||
(d.r as i32 - c.r as i32).abs() <= 1 && (d.g as i32 - c.g as i32).abs() <= 1 && (d.b as i32 - c.b as i32).abs() <= 1,
|
||||
"{c:?} {d:?}"
|
||||
(i32::from(converted.r) - i32::from(color.r)).abs() <= 1
|
||||
&& (i32::from(converted.g) - i32::from(color.g)).abs() <= 1
|
||||
&& (i32::from(converted.b) - i32::from(color.b)).abs() <= 1,
|
||||
"{color:?} {converted:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ chrono = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
deckcraft-anim = { workspace = true }
|
||||
memory-stats = "1.2.0"
|
||||
zip = { workspace = true }
|
||||
craft-metafile = { workspace = true, features = ["write"] }
|
||||
|
||||
|
||||
@@ -390,11 +390,12 @@ fn report_damage(s: &mut Session, damaged: &Damage) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `pdf`, `gif`).
|
||||
/// Encode the presentation in `format` (`deckcraft`, `pptx`, `potx`, `ppsx`, `outline`, `txt`, `pdf`, `gif`).
|
||||
pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
|
||||
match format {
|
||||
f @ ("pptx" | "potx" | "ppsx") => deckcraft_pptx::export_as(doc, f).map_err(|e| EngineError::Other(e.to_string())),
|
||||
"outline" | "txt" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
|
||||
"outline" => Ok(deckcraft_format::slides_to_outline(doc).into_bytes()),
|
||||
"txt" => Ok(outline_txt_bytes(&deckcraft_format::slides_to_outline(doc))),
|
||||
"rtf" => Ok(deckcraft_format::rtf::slides_to_rtf(doc).into_bytes()),
|
||||
"pdf" => deckcraft_pdf::export(doc, &Default::default()).map_err(|e| EngineError::Other(e.to_string())),
|
||||
"gif" => gif_bytes(doc, &Value::Null),
|
||||
@@ -404,6 +405,16 @@ pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.txt` outline bytes: CRLF for the reference app, without doubling a CR that is
|
||||
/// already in the text. A lone CR is an in-paragraph character, not a line break, so it becomes
|
||||
/// a space (as `slides_to_outline` does for a vertical tab): writing it as CRLF would split the
|
||||
/// paragraph into an unindented line on re-import. `TextBody::from_text` normalizes CR and CRLF
|
||||
/// (`text.rs:739`), but imported text can still carry one, so normalize before adding CRLF.
|
||||
/// Crate-visible so the regression test can feed it a CRLF string directly.
|
||||
pub(crate) fn outline_txt_bytes(text: &str) -> Vec<u8> {
|
||||
text.replace("\r\n", "\n").replace('\r', " ").replace('\n', "\r\n").into_bytes()
|
||||
}
|
||||
|
||||
/// Paper sizes for notes and handouts, for the UI's Print page.
|
||||
pub use deckcraft_pdf::{PAPERS, paper_size};
|
||||
|
||||
@@ -515,6 +526,12 @@ fn same_save_format(path: &str, path_format: &str, format: &str) -> bool {
|
||||
|| matches!((path_format, format), ("jpeg", "jpg") | ("jpg", "jpeg"))
|
||||
}
|
||||
|
||||
/// `.txt` needs CRLF for the reference app's outline importer; every other outline target
|
||||
/// keeps LF.
|
||||
fn outline_format<'a>(path: &str, format: &'a str) -> &'a str {
|
||||
if format == "outline" && path.to_ascii_lowercase().ends_with(".txt") { "txt" } else { format }
|
||||
}
|
||||
|
||||
/// Animated GIF bytes for `doc` with the options in `p` (see [`crate::gif_export::GifOptions::from_params`]).
|
||||
pub fn gif_bytes(doc: &Presentation, p: &Value) -> Result<Vec<u8>> {
|
||||
Ok(crate::gif_export::encode(doc, &crate::gif_export::GifOptions::from_params(p)?)?.bytes)
|
||||
@@ -536,7 +553,9 @@ pub fn format_for_path(path: &str) -> &'static str {
|
||||
"pdf"
|
||||
} else if l.ends_with(".gif") {
|
||||
"gif"
|
||||
} else if l.ends_with(".txt") || l.ends_with(".md") {
|
||||
} else if l.ends_with(".txt") {
|
||||
"txt"
|
||||
} else if l.ends_with(".md") {
|
||||
"outline"
|
||||
} else if l.ends_with(".rtf") {
|
||||
"rtf"
|
||||
@@ -571,6 +590,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"{path}: format `{format}` does not match the file type; save as {path_format} or choose a matching extension"
|
||||
)));
|
||||
}
|
||||
let format = outline_format(&path, format);
|
||||
let bytes = save_bytes(&s.doc()?.doc, format)?;
|
||||
write_file(&path, &bytes)?;
|
||||
mark_saved(s, Some(path.clone()))?;
|
||||
@@ -661,6 +681,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(f) => f.to_string(),
|
||||
None => writable_format(&path)?.to_string(),
|
||||
};
|
||||
let format = outline_format(&path, &format).to_string();
|
||||
let st = s.doc()?;
|
||||
let scale = finite_scale(f64_or(p, "scale", 2.0));
|
||||
let transparent = bool_or(p, "transparentBackground", false);
|
||||
|
||||
@@ -287,8 +287,16 @@ fn current_run(s: &Session) -> RunProps {
|
||||
}
|
||||
None => {
|
||||
let Some(sh) = st.selected_shapes().first().map(|x| (*x).clone()) else { return RunProps::default() };
|
||||
let para = sh.text.as_ref().and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
|
||||
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_default();
|
||||
// A selected table reads its first selected cell (the whole table without a range: its first cell).
|
||||
let body = match &sh.kind {
|
||||
deckcraft_model::ShapeKind::Table(tb) => {
|
||||
let first = super::table::selected_range(st.selection.cells, sh.id, tb).map_or((0, 0), |(a, _)| a);
|
||||
tb.cell(first.0, first.1).map(|c| &c.text)
|
||||
}
|
||||
_ => sh.text.as_ref(),
|
||||
};
|
||||
let para = body.and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
|
||||
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| para.end_props.clone());
|
||||
(sh, para, rp)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -344,6 +344,13 @@ fn album_items(p: &Value) -> Result<Vec<AlbumItem>> {
|
||||
}
|
||||
|
||||
fn image_px(bytes: &[u8]) -> (f64, f64) {
|
||||
// A metafile's frame gives its aspect; the raster reader can't size it.
|
||||
if craft_metafile::is_metafile(bytes)
|
||||
&& let Ok(pic) = craft_metafile::parse(bytes)
|
||||
&& pic.has_size()
|
||||
{
|
||||
return (f64::from(pic.width), f64::from(pic.height));
|
||||
}
|
||||
image::ImageReader::new(std::io::Cursor::new(bytes))
|
||||
.with_guessed_format()
|
||||
.ok()
|
||||
|
||||
@@ -247,15 +247,90 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Whether alternative text is a picture's file name and nothing else: one word ending in a
|
||||
/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), or the name of the file the
|
||||
/// picture came from, which may have spaces (`Screenshot 2024 at 10.00.png`).
|
||||
/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), a spaced name with a file
|
||||
/// name's shape (`Screenshot 2024 at 10.00.png`), or the exact name of the file the picture
|
||||
/// came from, spaces and all.
|
||||
const PICTURE_EXTENSIONS: [&str; 15] = ["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"];
|
||||
|
||||
fn is_file_name(alt: &str, file: Option<&str>) -> bool {
|
||||
const PICTURE_EXTENSIONS: [&str; 15] =
|
||||
["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"];
|
||||
let alt = alt.trim();
|
||||
let one_word = !alt.is_empty() && !alt.contains(char::is_whitespace);
|
||||
(one_word && alt.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))))
|
||||
|| file.is_some_and(|f| !alt.is_empty() && f.trim().eq_ignore_ascii_case(alt))
|
||||
if alt.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if file.is_some_and(|f| f.trim().eq_ignore_ascii_case(alt)) {
|
||||
return true;
|
||||
}
|
||||
let Some((stem, ext)) = alt.rsplit_once('.') else {
|
||||
return false;
|
||||
};
|
||||
if stem.is_empty() || !PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e)) {
|
||||
return false;
|
||||
}
|
||||
!alt.contains(char::is_whitespace) || is_spaced_file_name(stem)
|
||||
}
|
||||
|
||||
/// Whether a stem that ends in a picture extension has a file name's shape rather than a
|
||||
/// sentence's. A path is a name even when a folder has spaces. Otherwise a stem of three words or
|
||||
/// fewer is a name, and a longer stem must have at least two name parts: digits, `_`, `-`, an
|
||||
/// internal `.`, an uppercase after the first letter, or a multi-letter all-caps word.
|
||||
fn is_spaced_file_name(stem: &str) -> bool {
|
||||
// A path is a file name even when a folder has spaces; a slash inside a descriptive clause is
|
||||
// not, so the clause check still follows for non-path stems.
|
||||
if is_path_shaped(stem) {
|
||||
return true;
|
||||
}
|
||||
// A description that mentions a file inside a sentence is prose, not a file name.
|
||||
if mentions_a_file(stem) {
|
||||
return false;
|
||||
}
|
||||
// Clause punctuation introduces a description: "A red square, from IMG_2041.png".
|
||||
if stem.contains([',', ';', ':', '!', '?']) {
|
||||
return false;
|
||||
}
|
||||
let words: Vec<&str> = stem.split_whitespace().collect();
|
||||
if words.len() <= 3 {
|
||||
return !words.is_empty();
|
||||
}
|
||||
words.iter().filter(|word| is_name_part(word)).count() >= 2
|
||||
}
|
||||
|
||||
/// Whether the stem starts like a path: a root (`/`, `\`, `~`), a drive letter, or one unspaced
|
||||
/// first segment followed by a separator. `"A red square, from photos/IMG_2041"` is a clause, not a
|
||||
/// path, while `C:\Users\Jane, Doe\...` and `photos/IMG 2041` are paths.
|
||||
fn is_path_shaped(stem: &str) -> bool {
|
||||
let Some(at) = stem.find(['/', '\\']) else {
|
||||
return false;
|
||||
};
|
||||
let head = &stem[..at];
|
||||
head.is_empty()
|
||||
|| head == "~"
|
||||
|| (head.len() == 2 && head.as_bytes()[0].is_ascii_alphabetic() && head.as_bytes()[1] == b':')
|
||||
|| !head.contains(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Whether a word names a file inside a longer description: a picture extension follows its last
|
||||
/// dot (`IMG_2041.png`). A trailing dot (`Dr.`) has no extension after it.
|
||||
fn mentions_a_file(stem: &str) -> bool {
|
||||
stem.split_whitespace().any(|word| {
|
||||
let Some((before, ext)) = word.rsplit_once('.') else {
|
||||
return false;
|
||||
};
|
||||
!before.is_empty() && PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether one word looks like part of a file name rather than ordinary prose: a digit, a
|
||||
/// separator, an internal dot, an uppercase after the first letter, or a multi-letter all-caps word.
|
||||
fn is_name_part(word: &str) -> bool {
|
||||
let mut chars = word.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
let internal_dot = word.split('.').count() > 1 && !word.starts_with('.') && !word.ends_with('.');
|
||||
word.chars().any(|c| c.is_ascii_digit() || matches!(c, '_' | '-'))
|
||||
|| internal_dot
|
||||
|| chars.any(char::is_uppercase)
|
||||
|| (word.len() > 1 && first.is_uppercase() && word.chars().all(|c| c.is_uppercase() || c.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// The name of the file a picture shape's picture came from, if it has one.
|
||||
@@ -1102,8 +1177,144 @@ mod accessibility_contrast_tests {
|
||||
assert!(!is_file_name("Version 2.0", None), "a version number is not a picture's extension");
|
||||
assert!(!is_file_name(".png", None));
|
||||
assert!(!is_file_name("A red square, from IMG_2041.png", None));
|
||||
// The picture's own file name counts, spaces and all.
|
||||
// A file name with spaces counts by its shape, with or without the picture's own name.
|
||||
assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png")));
|
||||
assert!(!is_file_name("Screenshot 2024 at 10.00.png", None));
|
||||
assert!(is_file_name("Screenshot 2024 at 10.00.png", None), "a spaced name is recognised after the media item is renamed");
|
||||
}
|
||||
|
||||
fn test_png() -> Vec<u8> {
|
||||
vec![
|
||||
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 8, 0, 0, 0, 8, 8, 2, 0, 0, 0, 75, 109, 41, 220, 0, 0, 0, 17, 73,
|
||||
68, 65, 84, 120, 156, 99, 184, 163, 161, 129, 21, 49, 12, 45, 9, 0, 123, 123, 75, 1, 251, 162, 81, 240, 0, 0, 0, 0, 73, 69, 78, 68, 174,
|
||||
66, 96, 130,
|
||||
]
|
||||
}
|
||||
|
||||
fn file_name_issue_count(s: &mut Session) -> usize {
|
||||
s.execute("review.accessibility", &json!({}))
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|issue| issue["issue"] == "Alternative text is a file name")
|
||||
.count()
|
||||
}
|
||||
|
||||
fn pptx_round_trip(s: &mut Session) {
|
||||
let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).unwrap();
|
||||
s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaced_file_names_are_recognised_by_shape() {
|
||||
for name in [
|
||||
"Screenshot 2024 at 10.00.png",
|
||||
"rough draft preview.png",
|
||||
"Screen Shot 2024-11-30 at 09.41.12.png",
|
||||
r"C:\Users\Me\My Pictures\holiday.png",
|
||||
r"C:\Users\Jane, Doe\Pictures\holiday.png",
|
||||
] {
|
||||
assert!(is_file_name(name, None), "{name:?} is a file name");
|
||||
}
|
||||
assert!(
|
||||
is_file_name("Screenshot 2024 at 10.00.png", Some("image1.png")),
|
||||
"the shape rule works when the media item was renamed by the round trip"
|
||||
);
|
||||
for text in [
|
||||
"A red square, from IMG_2041.png",
|
||||
"A red square, from photos/IMG_2041.png",
|
||||
"A red square from IMG_2041.png",
|
||||
"A Red Square From IMG_2041.png",
|
||||
"A comparison of IMG_2041.png and IMG_2042.png",
|
||||
"Portrait of Dr. A. Smith.png",
|
||||
"Three markers in the upper corner of caption alt.png",
|
||||
"The chart shows revenue in 2024.png",
|
||||
"Version 2.0",
|
||||
".png",
|
||||
"A red square",
|
||||
] {
|
||||
assert!(!is_file_name(text, None), "{text:?} is not a file name");
|
||||
}
|
||||
for name in ["IMG_2041.png", "photo.JPEG", r"C:\Users\me\Pictures\holiday.png"] {
|
||||
assert!(is_file_name(name, None), "{name:?} is still a file name");
|
||||
}
|
||||
assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spaced_picture_file_name_is_still_reported_after_a_pptx_round_trip() {
|
||||
let png = test_png();
|
||||
let mut s = Session::with_new();
|
||||
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap();
|
||||
assert_eq!(file_name_issue_count(&mut s), 1, "reported before the save");
|
||||
|
||||
pptx_round_trip(&mut s);
|
||||
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
assert!(doc["media"].as_array().unwrap().iter().any(|m| m["name"] == "image1.png"), "the round trip renamed the media item: {doc}");
|
||||
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
|
||||
assert!(
|
||||
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "Screenshot 2024 at 10.00.png"),
|
||||
"the alt text survives the round trip: {slide}"
|
||||
);
|
||||
assert_eq!(file_name_issue_count(&mut s), 1, "reported after the save and reopen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_description_that_mentions_a_file_is_not_reported_after_a_pptx_round_trip() {
|
||||
let png = test_png();
|
||||
let mut s = Session::with_new();
|
||||
let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone();
|
||||
s.execute("shape.altText", &json!({"text": "A red square, from IMG_2041.png", "ids": [id]})).unwrap();
|
||||
assert_eq!(file_name_issue_count(&mut s), 0, "a description that mentions a file is clear");
|
||||
|
||||
pptx_round_trip(&mut s);
|
||||
|
||||
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
|
||||
assert!(
|
||||
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "A red square, from IMG_2041.png"),
|
||||
"the description survives the round trip: {slide}"
|
||||
);
|
||||
assert_eq!(file_name_issue_count(&mut s), 0, "the description stays clear after the round trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_decorative_picture_with_a_spaced_file_name_is_not_reported_after_a_pptx_round_trip() {
|
||||
let png = test_png();
|
||||
let mut s = Session::with_new();
|
||||
let id =
|
||||
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap()["id"]
|
||||
.clone();
|
||||
s.execute("shape.altText", &json!({"text": "Screenshot 2024 at 10.00.png", "decorative": true, "ids": [id]})).unwrap();
|
||||
assert_eq!(file_name_issue_count(&mut s), 0, "a decorative picture is exempt");
|
||||
|
||||
pptx_round_trip(&mut s);
|
||||
|
||||
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
|
||||
assert!(
|
||||
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == "Screenshot 2024 at 10.00.png"),
|
||||
"the alt text survives, so only decorative suppresses the finding: {slide}"
|
||||
);
|
||||
assert_eq!(file_name_issue_count(&mut s), 0, "the decorative picture stays exempt after the round trip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_word_names_and_paths_are_still_reported_after_a_pptx_round_trip() {
|
||||
let png = test_png();
|
||||
let mut s = Session::with_new();
|
||||
let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone();
|
||||
assert_eq!(file_name_issue_count(&mut s), 1, "the inserted file name is reported");
|
||||
|
||||
s.execute("shape.altText", &json!({"text": r"C:\Users\me\Pictures\holiday.png", "ids": [id]})).unwrap();
|
||||
assert_eq!(file_name_issue_count(&mut s), 1, "a one-word path is reported");
|
||||
|
||||
pptx_round_trip(&mut s);
|
||||
|
||||
let slide = s.execute("slide.inspect", &json!({"index": 0})).unwrap();
|
||||
assert!(
|
||||
slide["shapes"].as_array().unwrap().iter().any(|sh| sh["altText"] == r"C:\Users\me\Pictures\holiday.png"),
|
||||
"the path survives the round trip: {slide}"
|
||||
);
|
||||
assert_eq!(file_name_issue_count(&mut s), 1, "the one-word path is still reported after the round trip");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,8 @@ pub(super) fn change(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let info = deckcraft_geom::preset::info(name).ok_or_else(|| bad("shape.change", format!("unknown preset `{name}`")))?;
|
||||
edit_geometry(s, p, "shape.change", |sh| {
|
||||
sh.geom = Geom::preset(info.name);
|
||||
let (tag, value) = crate::icons::INSERTED_ICON_TAG;
|
||||
sh.tags.retain(|(key, tag_value)| key != tag || tag_value != value);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -262,6 +262,13 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad("slide.delete", "no such slide"));
|
||||
}
|
||||
s.edit(|doc, sel| {
|
||||
// Count only slides that are in the deck, each once: an id that names no slide, or a
|
||||
// repeat, deletes nothing and must not be reported as deleted.
|
||||
let mut seen = HashSet::new();
|
||||
let ids: Vec<SlideId> = ids.iter().copied().filter(|id| doc.slide_index(*id).is_some() && seen.insert(*id)).collect();
|
||||
if ids.is_empty() {
|
||||
return Err(bad("slide.delete", "no such slide"));
|
||||
}
|
||||
let first = ids.iter().filter_map(|id| doc.slide_index(*id)).min().unwrap_or(0);
|
||||
doc.slides.retain(|x| !ids.contains(&x.id));
|
||||
for sec in &mut doc.sections {
|
||||
@@ -987,6 +994,17 @@ mod tests {
|
||||
assert_eq!(selected(&s), (0, vec![ids[2]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_reports_only_slides_it_deleted() {
|
||||
let (mut s, ids) = deck(3);
|
||||
assert!(s.execute("slide.delete", &json!({"ids": [999_999]})).is_err(), "an id that names no slide deletes nothing");
|
||||
assert_eq!(order(&s), ids);
|
||||
let r = s.execute("slide.delete", &json!({"ids": [ids[1], ids[1], 999_999]})).expect("delete");
|
||||
assert_eq!(order(&s), [ids[0], ids[2]]);
|
||||
assert_eq!(r["deleted"], 1, "{r}");
|
||||
assert_eq!(r["remaining"], 2, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_section_with_its_slides_prunes_them_from_custom_shows() {
|
||||
let (mut s, ids) = deck(4);
|
||||
|
||||
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Change Layout",
|
||||
["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}",
|
||||
"{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} → {id, ids: the regenerated shapes}",
|
||||
has_diagram,
|
||||
change_layout
|
||||
),
|
||||
@@ -279,7 +279,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Diagram Styles",
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick}",
|
||||
"{id?, style: flat|subtle|intense|outline|polished|inset|cartoon|powder|brick} → {id, ids: the regenerated shapes}",
|
||||
has_diagram,
|
||||
change_style
|
||||
),
|
||||
@@ -288,7 +288,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Change Colors",
|
||||
["Diagram Design", "Diagram Styles"],
|
||||
None,
|
||||
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad}",
|
||||
"{id?, colors: colorful|range23|range34|range45|range56|accent1|…|accent6|accent1Grad|…|accent6Grad} → {id, ids: the regenerated shapes}",
|
||||
has_diagram,
|
||||
change_colors
|
||||
),
|
||||
|
||||
@@ -339,33 +339,47 @@ pub(super) fn set_picture(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The answer of a command that regenerated a graphic's shapes: the group's id and its new children's ids.
|
||||
fn regenerated(s: &Session, gid: ShapeId) -> Value {
|
||||
let kids: Vec<u32> = match s.doc().ok().and_then(|st| st.shape(gid).map(|g| g.kind.clone())) {
|
||||
Some(ShapeKind::Group { children, .. }) => children.iter().map(|c| c.id.0).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
json!({"id": gid.0, "ids": kids})
|
||||
}
|
||||
|
||||
pub(super) fn change_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "smartArt.style";
|
||||
let v = str_param(p, "style").filter(|k| STYLES.iter().any(|(id, _)| id == k)).ok_or_else(|| bad(CMD, "unknown style"))?.to_string();
|
||||
let gid = target_group(s, p, CMD)?;
|
||||
edit_diagram(s, p, CMD, |d| {
|
||||
if d.style != v {
|
||||
d.style_xml = None;
|
||||
}
|
||||
d.style = v;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
})?;
|
||||
Ok(regenerated(s, gid))
|
||||
}
|
||||
|
||||
pub(super) fn change_colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "smartArt.colors";
|
||||
let v = str_param(p, "colors").filter(|k| COLORS.iter().any(|(id, _)| id == k)).ok_or_else(|| bad(CMD, "unknown colours"))?.to_string();
|
||||
let gid = target_group(s, p, CMD)?;
|
||||
edit_diagram(s, p, CMD, |d| {
|
||||
if d.colors != v {
|
||||
d.colors_xml = None;
|
||||
}
|
||||
d.colors = v;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
})?;
|
||||
Ok(regenerated(s, gid))
|
||||
}
|
||||
|
||||
pub(super) fn change_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "smartArt.layout";
|
||||
let kind = str_param(p, "kind").filter(|k| is_kind(k)).ok_or_else(|| bad(CMD, "unknown layout"))?.to_string();
|
||||
let gid = target_group(s, p, CMD)?;
|
||||
edit_diagram(s, p, CMD, |d| {
|
||||
if d.kind != kind {
|
||||
// PowerPoint's own layout no longer applies.
|
||||
@@ -374,5 +388,6 @@ pub(super) fn change_layout(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
d.kind = kind;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
})?;
|
||||
Ok(regenerated(s, gid))
|
||||
}
|
||||
|
||||
@@ -267,12 +267,31 @@ fn cell_param(p: &Value, key: &str, cmd: &str) -> Result<Option<(usize, usize)>>
|
||||
}
|
||||
}
|
||||
|
||||
/// The table's row/col to act on: params, the edited cell, or the selected cells.
|
||||
/// A present but invalid `row`/`col` is an error; only an absent one falls back.
|
||||
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
|
||||
enum TableIndex {
|
||||
Explicit(usize),
|
||||
Selected(usize),
|
||||
Default,
|
||||
}
|
||||
|
||||
impl TableIndex {
|
||||
fn value(&self) -> usize {
|
||||
match *self {
|
||||
Self::Explicit(i) | Self::Selected(i) => i,
|
||||
Self::Default => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve each axis from its parameter, the edited or selected cell, then index zero.
|
||||
/// Invalid parameters are rejected before any fallback.
|
||||
fn at(s: &Session, p: &Value, cmd: &str) -> Result<(TableIndex, TableIndex)> {
|
||||
let st = s.active();
|
||||
let cell = st.and_then(|d| d.selection.text.as_ref().and_then(|t| t.cell)).or_else(|| st.and_then(|d| d.selection.cells.map(|c| c.1)));
|
||||
Ok((opt_usize_param(p, "row", cmd)?.or(cell.map(|c| c.0)).unwrap_or(0), opt_usize_param(p, "col", cmd)?.or(cell.map(|c| c.1)).unwrap_or(0)))
|
||||
let resolve = |key, selected: Option<usize>| -> Result<TableIndex> {
|
||||
let explicit = opt_usize_param(p, key, cmd)?;
|
||||
Ok(explicit.map(TableIndex::Explicit).or(selected.map(TableIndex::Selected)).unwrap_or(TableIndex::Default))
|
||||
};
|
||||
Ok((resolve("row", cell.map(|c| c.0))?, resolve("col", cell.map(|c| c.1))?))
|
||||
}
|
||||
|
||||
fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> Result<()>) -> Result<Value> {
|
||||
@@ -328,6 +347,7 @@ fn with_table(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut Table) -> R
|
||||
|
||||
fn rows_cols(s: &mut Session, p: &Value, op: &str, name: &'static str) -> Result<Value> {
|
||||
let (r, c) = at(s, p, name)?;
|
||||
let (r, c) = (r.value(), c.value());
|
||||
// Absent: the table grows, as in PowerPoint; present, it must be a bool, so a mistyped value is refused
|
||||
// rather than silently taken as the default.
|
||||
let keep_width = match (op, p.get("keepWidth")) {
|
||||
@@ -465,7 +485,10 @@ fn merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cell = match cell_param(p, "cell", "table.split")? {
|
||||
Some(c) => c,
|
||||
None => at(s, p, "table.split")?,
|
||||
None => {
|
||||
let (r, c) = at(s, p, "table.split")?;
|
||||
(r.value(), c.value())
|
||||
}
|
||||
};
|
||||
with_table(s, p, "table.split", move |t| if t.split(cell.0, cell.1) { Ok(()) } else { Err(bad("table.split", "that cell isn't merged")) })
|
||||
}
|
||||
@@ -727,8 +750,17 @@ fn distribute(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {
|
||||
|
||||
/// A row or column the table doesn't have is an error, like a malformed index (#2260): checked
|
||||
/// inside the edit, so a refused resize changes nothing and adds no undo step.
|
||||
fn index_in_table(cmd: &str, key: &str, i: usize, n: usize, what: &str) -> Result<()> {
|
||||
if i < n { Ok(()) } else { Err(bad(cmd, format!("`{key}` {i} is out of range: the table has {n} {what}"))) }
|
||||
fn index_in_table(cmd: &str, key: &str, index: &TableIndex, n: usize, axis: &str) -> Result<usize> {
|
||||
let i = index.value();
|
||||
if i < n {
|
||||
return Ok(i);
|
||||
}
|
||||
let source = match index {
|
||||
TableIndex::Explicit(_) => format!("`{key}` {i}"),
|
||||
TableIndex::Selected(_) => format!("the selected cell's {axis} {i}"),
|
||||
TableIndex::Default => format!("the default {axis} {i}"),
|
||||
};
|
||||
Err(bad(cmd, format!("{source} is out of range: the table has {n} {axis}s")))
|
||||
}
|
||||
|
||||
fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -736,7 +768,7 @@ fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let w = f64_param(p, "width").ok_or_else(|| bad("table.columnWidth", "missing `width`"))?.clamp(4.0, 4000.0);
|
||||
let keep_total = bool_or(p, "keepTotal", false);
|
||||
with_table(s, p, "table.columnWidth", move |t| {
|
||||
index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?;
|
||||
let c = index_in_table("table.columnWidth", "col", &c, t.n_cols(), "column")?;
|
||||
// Keeping the table's width, the column to the right gives or takes the difference (dragging
|
||||
// an inner border). The last column has none: the table gets wider or narrower.
|
||||
let pair = t.cols.get(c).zip(t.cols.get(c.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
|
||||
@@ -765,7 +797,7 @@ fn row_height(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (r, _) = at(s, p, "table.rowHeight")?;
|
||||
let h = f64_param(p, "height").ok_or_else(|| bad("table.rowHeight", "missing `height`"))?.clamp(4.0, 4000.0);
|
||||
with_table(s, p, "table.rowHeight", move |t| {
|
||||
index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?;
|
||||
let r = index_in_table("table.rowHeight", "row", &r, t.n_rows(), "row")?;
|
||||
if let Some(x) = t.rows.get_mut(r) {
|
||||
x.height = h;
|
||||
}
|
||||
|
||||
@@ -168,9 +168,9 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
|
||||
while start > 0 && line.get(start - 1).is_some_and(|c| !c.is_whitespace()) {
|
||||
start -= 1;
|
||||
}
|
||||
// "word," and "word." also count: the punctuation was typed before the space.
|
||||
// "word," and "word." also count when the text came in one piece; a typed punctuation mark already ran AutoCorrect on the word, and an Undo of that correction stays (#2184).
|
||||
let mut word: String = line.get(start..word_end).map(|w| w.iter().collect()).unwrap_or_default();
|
||||
if replacement(&s.prefs, &word).is_none() {
|
||||
if !typing && replacement(&s.prefs, &word).is_none() {
|
||||
let trimmed = word.trim_end_matches(|c: char| ".,;:!?".contains(c));
|
||||
if !trimmed.is_empty() && trimmed.len() < word.len() && !word.ends_with("...") {
|
||||
word_end -= word.chars().count() - trimmed.chars().count();
|
||||
@@ -195,6 +195,7 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
|
||||
};
|
||||
let delta = rep.chars().count() as isize - word.chars().count() as isize;
|
||||
let st = s.doc_mut()?;
|
||||
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
|
||||
let mut d = (*st.doc).clone();
|
||||
let sel = st.selection.clone();
|
||||
if let Some(b) = body_mut(&mut d, &sel, &t) {
|
||||
@@ -315,6 +316,7 @@ fn superscript_suffix(s: &mut Session, t: &crate::TextSel, end: usize) -> Result
|
||||
if body_of(st, t).is_none_or(|body| ed::props_at(body, b).baseline.unwrap_or(0.0) > 0.0) {
|
||||
return Ok(());
|
||||
}
|
||||
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
|
||||
let mut d = (*st.doc).clone();
|
||||
let sel = st.selection.clone();
|
||||
if let Some(body) = body_mut(&mut d, &sel, t) {
|
||||
|
||||
@@ -338,7 +338,10 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => Some(sh.text.get_or_insert_with(TextBody::default)),
|
||||
};
|
||||
let Some(body) = target else { return Err(bad("text.set", "no text here (tables need `cell`)")) };
|
||||
let keep = body.paragraphs.first().and_then(|p| p.runs.first()).map(|r| r.props.clone()).unwrap_or_default();
|
||||
// The first run's formatting, or for text that is still empty the formatting its end
|
||||
// mark holds (format.* before any text lands there), so a size set before text.set survives.
|
||||
let keep =
|
||||
body.paragraphs.first().map(|p| p.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| p.end_props.clone())).unwrap_or_default();
|
||||
let levels: Vec<(u8, deckcraft_model::text::ParaProps)> = body.paragraphs.iter().map(|p| (p.level, p.props.clone())).collect();
|
||||
let mut nb = TextBody::from_text(&text);
|
||||
for (i, para) in nb.paragraphs.iter_mut().enumerate() {
|
||||
@@ -353,6 +356,11 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for r in &mut para.runs {
|
||||
r.props = keep.clone();
|
||||
}
|
||||
// The end mark keeps it too, so an empty `text` (no runs) carries the formatting to
|
||||
// the text set next.
|
||||
para.end_props = keep.clone();
|
||||
// A run emptied by stripping leading tabs would shadow the end mark for the text typed next.
|
||||
para.normalize();
|
||||
}
|
||||
body.paragraphs = nb.paragraphs;
|
||||
Ok(())
|
||||
|
||||
@@ -25,6 +25,10 @@ pub(crate) fn format_run_levels(
|
||||
// Only the levels of the paragraphs the selected range touches.
|
||||
let levels = if a == b { Vec::new() } else { master_levels(st, &t, t.ordered()) };
|
||||
edit_text(s, |body, _| {
|
||||
// A body with no paragraph has no end mark to hold the formatting of the text typed next.
|
||||
if body.paragraphs.is_empty() {
|
||||
body.paragraphs.push(Default::default());
|
||||
}
|
||||
if levels.is_empty() {
|
||||
ed::format(body, a, b, f);
|
||||
} else {
|
||||
@@ -65,6 +69,9 @@ pub(crate) fn format_run_levels(
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
if crate::cmd::table::in_range(range, r, c) {
|
||||
if cell.text.paragraphs.is_empty() {
|
||||
cell.text.paragraphs.push(Default::default());
|
||||
}
|
||||
ed::format_all(&mut cell.text, f);
|
||||
}
|
||||
}
|
||||
@@ -72,6 +79,11 @@ pub(crate) fn format_run_levels(
|
||||
}
|
||||
_ => {
|
||||
let body = sh.text.get_or_insert_with(TextBody::default);
|
||||
// Text that is still empty keeps the formatting on an end mark, so a size set
|
||||
// before the text lands survives it; a body with no paragraph has none.
|
||||
if body.paragraphs.is_empty() {
|
||||
body.paragraphs.push(Default::default());
|
||||
}
|
||||
let eff = effective.iter().find(|(i, _)| *i == id).map(|(_, e)| e);
|
||||
match eff {
|
||||
Some(eff) => {
|
||||
|
||||
@@ -255,6 +255,54 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_shape_clears_icon_identity_until_undone() {
|
||||
let mut s = Session::with_new();
|
||||
let insert_icon = |s: &mut Session| s.execute("insert.icon", &json!({"name": "star"})).unwrap()["id"].as_u64().unwrap();
|
||||
let missing = insert_icon(&mut s);
|
||||
let described = insert_icon(&mut s);
|
||||
let untouched = insert_icon(&mut s);
|
||||
let targets = json!({"ids": [missing, described]});
|
||||
crate::cmd::edit_shapes(&mut s, &targets, "shape.change", |shape| {
|
||||
shape.tags.push(("CUSTOM_TAG".into(), "kept".into()));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("shape.altText", &json!({"ids": [described], "text": "Five-point outline"})).unwrap();
|
||||
|
||||
let missing_alt = |s: &mut Session| {
|
||||
s.execute("review.accessibility", &json!({}))
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|issue| issue["issue"] == "Missing alternative text")
|
||||
.map(|issue| issue["shape"].as_u64().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let shapes = |s: &Session| [missing, described].map(|id| s.doc().unwrap().shape(ShapeId(id as u32)).unwrap().clone());
|
||||
assert_eq!(missing_alt(&mut s), [missing, untouched]);
|
||||
let original = shapes(&s);
|
||||
let selection = s.doc().unwrap().selection.shapes.clone();
|
||||
let converted = original.clone().map(|mut shape| {
|
||||
shape.geom = Geom::preset("ellipse");
|
||||
shape.tags = vec![("CUSTOM_TAG".into(), "kept".into())];
|
||||
shape
|
||||
});
|
||||
|
||||
s.execute("shape.change", &json!({"ids": [missing, described], "preset": "ellipse"})).unwrap();
|
||||
assert_eq!(shapes(&s), converted);
|
||||
assert_eq!(s.doc().unwrap().selection.shapes, selection);
|
||||
assert_eq!(missing_alt(&mut s), [untouched]);
|
||||
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(shapes(&s), original);
|
||||
assert_eq!(missing_alt(&mut s), [missing, untouched]);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(shapes(&s), converted);
|
||||
assert_eq!(missing_alt(&mut s), [untouched]);
|
||||
}
|
||||
|
||||
fn ink_in(img: &deckcraft_render::Image, x: f64, y: f64, w: f64, h: f64, scale: f64) -> usize {
|
||||
let x0 = (x * scale).floor().max(0.0) as u32;
|
||||
let y0 = (y * scale).floor().max(0.0) as u32;
|
||||
|
||||
@@ -168,6 +168,8 @@ impl Session {
|
||||
"end" => "End",
|
||||
"tab" => "Tab",
|
||||
"space" | " " => "Space",
|
||||
// Ctrl+Shift+= reaches us as the shifted character, `+`; shortcuts are written with `=`.
|
||||
"+" if mods.shift => "=",
|
||||
_ => k,
|
||||
};
|
||||
let found = crate::command_specs().iter().find(|c| c.shortcut.is_some_and(|s| shortcut_matches(s, key_name, mods))).map(|c| c.id);
|
||||
|
||||
@@ -237,6 +237,9 @@ pub struct DocState {
|
||||
/// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after
|
||||
/// can put the typed text back.
|
||||
pub auto_list: Option<cmd::text::AutoList>,
|
||||
/// The presentation and selection between a typed character and the AutoCorrect it set off,
|
||||
/// so the command's undo step splits in two and Undo takes back only the correction (#2184).
|
||||
pub autocorrected: Option<(Arc<Presentation>, Selection)>,
|
||||
/// The slide whose editor's consecutive notes changes share one undo step.
|
||||
pub notes_run: Option<SlideId>,
|
||||
notes_before: Option<Arc<Presentation>>,
|
||||
@@ -269,6 +272,7 @@ impl DocState {
|
||||
compare: None,
|
||||
last_duplicate: None,
|
||||
auto_list: None,
|
||||
autocorrected: None,
|
||||
notes_run: None,
|
||||
notes_before: None,
|
||||
}
|
||||
@@ -729,6 +733,9 @@ impl Session {
|
||||
}
|
||||
if outer {
|
||||
self.tool.vertex_kind = vertex_kind;
|
||||
if let Some(st) = self.active_mut() {
|
||||
st.autocorrected = None;
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
@@ -736,6 +743,7 @@ impl Session {
|
||||
if let Some(st) = self.active_mut() {
|
||||
clamp_selection(st);
|
||||
}
|
||||
let autocorrected = if outer { self.active_mut().and_then(|st| st.autocorrected.take()) } else { None };
|
||||
if let (Some((uid, old, sel)), Some(st)) = (before, self.active_mut())
|
||||
&& st.uid == uid
|
||||
&& !Arc::ptr_eq(&old, &st.doc)
|
||||
@@ -753,8 +761,12 @@ impl Session {
|
||||
}
|
||||
} else {
|
||||
let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone());
|
||||
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind });
|
||||
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind: vertex_kind.clone() });
|
||||
st.notes_before = notes_before;
|
||||
// The text as typed, before AutoCorrect changed it: its own step, undone first.
|
||||
if let Some((doc, selection)) = autocorrected.filter(|(doc, _)| !Arc::ptr_eq(doc, &st.doc)) {
|
||||
push_undo(st, HistoryEntry { label: "AutoCorrect".into(), doc, selection, vertex_kind });
|
||||
}
|
||||
}
|
||||
}
|
||||
if spec.journal && outer {
|
||||
|
||||
@@ -64,6 +64,42 @@ fn params(r: &mut Rng, s: &Session) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory in use, in bytes: the resident set size on Linux and macOS, the working set on
|
||||
/// Windows. `None` where the platform cannot say.
|
||||
fn rss_bytes() -> Option<u64> {
|
||||
memory_stats::memory_stats().map(|m| m.physical_mem as u64)
|
||||
}
|
||||
|
||||
/// Whether this process may run the named soak itself, so its memory reading is its own.
|
||||
///
|
||||
/// The reading is for the whole process, and plain `cargo test` runs every test of the crate on
|
||||
/// threads of one process, so other tests' allocations would count against the budget. nextest
|
||||
/// runs each test in its own process (and sets `NEXTEST`). Anywhere else the test runs itself again
|
||||
/// in a child process of its own, which takes this branch, and fails if the child does.
|
||||
fn alone(test: &str) -> bool {
|
||||
const MARK: &str = "DECKCRAFT_SOAK_ALONE";
|
||||
if std::env::var_os("NEXTEST").is_some() || std::env::var_os(MARK).is_some() {
|
||||
return true;
|
||||
}
|
||||
let path = module_path!().split_once("::").map_or(module_path!(), |(_, rest)| rest);
|
||||
let out = std::process::Command::new(std::env::current_exe().expect("test binary path"))
|
||||
.args(["--exact", &format!("{path}::{test}"), "--include-ignored", "--test-threads=1", "--nocapture"])
|
||||
.env(MARK, "1")
|
||||
.output()
|
||||
.expect("run the soak in its own process");
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"soak {test} failed in its own process:\n{}\n{}",
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// RSS growth allowed between the warmed-up start and the end of a soak, with the test alone in
|
||||
/// its process (see `alone`).
|
||||
const MAX_RSS_GROWTH: u64 = 256 << 20;
|
||||
|
||||
fn doc(s: &Session) -> Option<deckcraft_model::Presentation> {
|
||||
s.active().map(|d| (*d.doc).clone())
|
||||
}
|
||||
@@ -91,7 +127,12 @@ fn soak(seed: u64, steps: usize) {
|
||||
let mut r = Rng(seed | 1);
|
||||
let mut log: VecDeque<String> = VecDeque::new();
|
||||
let mut edits = 0usize;
|
||||
let mut rss_start = None;
|
||||
for step in 0..steps {
|
||||
// Sample after a quarter of the run so one-off caches and allocator arenas are warm.
|
||||
if step == steps / 4 {
|
||||
rss_start = rss_bytes();
|
||||
}
|
||||
let id = *r.pick(&ids).unwrap();
|
||||
let p = params(&mut r, &s);
|
||||
log.push_back(format!("{id} {p}"));
|
||||
@@ -140,7 +181,13 @@ fn soak(seed: u64, steps: usize) {
|
||||
}
|
||||
// The soak must really edit, not just bounce off disabled commands.
|
||||
assert!(edits * 10 >= steps, "only {edits} of {steps} steps changed the document; seed {seed}");
|
||||
eprintln!("soak seed {seed}: {edits} of {steps} steps edited");
|
||||
if let (Some(start), Some(end)) = (rss_start, rss_bytes()) {
|
||||
let grew = end.saturating_sub(start);
|
||||
eprintln!("soak seed {seed}: {edits} of {steps} steps edited, memory {} -> {} MiB", start >> 20, end >> 20);
|
||||
assert!(grew <= MAX_RSS_GROWTH, "memory grew {} MiB over {} MiB; seed {seed}", grew >> 20, MAX_RSS_GROWTH >> 20);
|
||||
} else {
|
||||
eprintln!("soak seed {seed}: {edits} of {steps} steps edited");
|
||||
}
|
||||
}
|
||||
|
||||
fn steps(default: usize) -> usize {
|
||||
@@ -149,6 +196,9 @@ fn steps(default: usize) -> usize {
|
||||
|
||||
#[test]
|
||||
fn soak_random_edits_keep_the_document_valid() {
|
||||
if !alone("soak_random_edits_keep_the_document_valid") {
|
||||
return;
|
||||
}
|
||||
for seed in [1, 0xDEC0_C2AF, 42, 7_777_777] {
|
||||
soak(seed, steps(400));
|
||||
}
|
||||
@@ -157,6 +207,9 @@ fn soak_random_edits_keep_the_document_valid() {
|
||||
#[test]
|
||||
#[ignore = "long soak; set DECKCRAFT_SOAK_STEPS"]
|
||||
fn soak_long() {
|
||||
if !alone("soak_long") {
|
||||
return;
|
||||
}
|
||||
let seed = std::env::var("DECKCRAFT_SOAK_SEED").ok().and_then(|v| v.parse().ok()).unwrap_or(0x5EED);
|
||||
soak(seed, steps(20_000));
|
||||
}
|
||||
|
||||
+278
-2
@@ -1399,13 +1399,107 @@ fn writable_format_for_path_rejects_formats_deckcraft_does_not_write() {
|
||||
assert_eq!(f("dir/A.PPTX"), Some("pptx"));
|
||||
assert_eq!(f("a.pdf"), Some("pdf"));
|
||||
assert_eq!(f("a.jpg"), Some("jpeg"));
|
||||
assert_eq!(f("a.txt"), Some("outline"));
|
||||
assert_eq!(f("a.txt"), Some("txt"));
|
||||
assert_eq!(f("a.md"), Some("outline"));
|
||||
assert_eq!(f("a.gif"), Some("gif"));
|
||||
for path in ["a.odp", "a.bmp", "a.svg", "a.outline", "a", "dir.v2/a"] {
|
||||
assert_eq!(f(path), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_export_uses_crlf_even_with_explicit_outline() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-txt-export-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let path = dir.join("outline.txt").to_string_lossy().to_string();
|
||||
s.execute("file.export", &json!({"path": path, "format": "outline"})).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains("\r\n"), "TXT must use CRLF: {text:?}");
|
||||
assert!(!text.replace("\r\n", "").contains('\n'), "no bare LF: {text:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn md_export_keeps_lf() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-md-export-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let path = dir.join("outline.md").to_string_lossy().to_string();
|
||||
s.execute("file.export", &json!({"path": path, "format": "outline"})).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert!(!bytes.windows(2).any(|w| w == b"\r\n"), "Markdown must stay LF");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_outline_export_round_trips_two_slides() {
|
||||
let mut p = deckcraft_model::defaults::new_presentation(None);
|
||||
p.slides.clear();
|
||||
let n = deckcraft_format::outline_to_slides(&mut p, "Alpha heading\n\tFirst body\nBeta heading\n\tSecond body\n");
|
||||
assert_eq!(n, 2);
|
||||
let bytes = crate::cmd::file::save_bytes(&p, "txt").unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains("\r\n"), "{text:?}");
|
||||
assert!(!text.contains("\r\r\n"), "a CRLF input must not double the CR: {text:?}");
|
||||
|
||||
let mut q = deckcraft_model::defaults::new_presentation(None);
|
||||
q.slides.clear();
|
||||
assert_eq!(deckcraft_format::outline_to_slides(&mut q, &text), 2);
|
||||
assert_eq!(q.slides[0].title(), "Alpha heading");
|
||||
assert_eq!(q.slides[1].title(), "Beta heading");
|
||||
let bodies: Vec<String> =
|
||||
q.slides.iter().map(|s| s.shapes.iter().filter_map(|sh| sh.text.as_ref()).map(|t| t.text()).collect::<Vec<_>>().join(" ")).collect();
|
||||
assert!(bodies[0].contains("First body"), "{:?}", bodies[0]);
|
||||
assert!(bodies[1].contains("Second body"), "{:?}", bodies[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_export_does_not_double_existing_crlf() {
|
||||
let text = String::from_utf8(crate::cmd::file::outline_txt_bytes("Alpha\r\nBeta\r\n")).unwrap();
|
||||
assert_eq!(text, "Alpha\r\nBeta\r\n");
|
||||
assert!(!text.contains("\r\r\n"), "{text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_export_replaces_a_lone_cr_with_a_space() {
|
||||
// A `.txt` import can leave a lone CR inside a body paragraph (`str::lines` splits on LF only).
|
||||
let mut p = deckcraft_model::defaults::new_presentation(None);
|
||||
p.slides.clear();
|
||||
assert_eq!(deckcraft_format::outline_to_slides(&mut p, "Title\n\tGamma\rDelta\n"), 1);
|
||||
let text = String::from_utf8(crate::cmd::file::save_bytes(&p, "txt").unwrap()).unwrap();
|
||||
assert!(!text.replace("\r\n", "").contains('\r'), "a bare CR is a line terminator: {text:?}");
|
||||
assert!(text.contains("\tGamma Delta\r\n"), "{text:?}");
|
||||
|
||||
// The paragraph must stay one line: the CR is not turned into a second outline line.
|
||||
let mut q = deckcraft_model::defaults::new_presentation(None);
|
||||
q.slides.clear();
|
||||
assert_eq!(deckcraft_format::outline_to_slides(&mut q, &text), 1);
|
||||
assert_eq!(q.slides[0].title(), "Title");
|
||||
let body: String = q.slides[0].shapes.iter().filter_map(|sh| sh.text.as_ref()).map(|t| t.text()).collect::<Vec<_>>().join(" ");
|
||||
assert!(body.contains("Gamma Delta"), "{body:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_txt_uses_crlf() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-txt-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let path = dir.join("outline.txt").to_string_lossy().to_string();
|
||||
s.execute("file.saveAs", &json!({"path": path})).unwrap();
|
||||
let text = String::from_utf8(std::fs::read(&path).unwrap()).unwrap();
|
||||
assert!(text.contains("\r\n"), "TXT must use CRLF");
|
||||
assert!(!text.replace("\r\n", "").contains('\n'), "no bare LF");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_reopen_native() {
|
||||
let mut s = Session::new();
|
||||
@@ -5359,6 +5453,51 @@ fn autocorrect_options_as_you_type() {
|
||||
assert_eq!(s.execute("text.get", &json!({"id": title})).unwrap()["text"], "monday notes ");
|
||||
}
|
||||
|
||||
/// #2184: Undo right after AutoCorrect takes back only the correction; the space that set it off
|
||||
/// stays, and typing on does not correct the word again. A second Undo removes the space.
|
||||
#[test]
|
||||
fn undo_takes_back_only_the_autocorrect() {
|
||||
let mut s = session();
|
||||
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
|
||||
let text = |s: &Session| {
|
||||
s.doc().unwrap().current_slide().unwrap().shapes.iter().find(|sh| sh.id.0 == title).unwrap().text.as_ref().unwrap().paragraphs[0].text()
|
||||
};
|
||||
s.execute("text.edit", &json!({"id": title})).unwrap();
|
||||
for c in "hello ".chars() {
|
||||
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
|
||||
}
|
||||
assert_eq!(text(&s), "Hello ");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "hello ", "the correction is undone, the space stays");
|
||||
assert_eq!(s.doc().unwrap().selection.text.as_ref().map(|t| t.caret), Some((0, 6)), "the caret stays after the space");
|
||||
// Redo brings the correction back.
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "Hello ");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for c in "world ".chars() {
|
||||
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
|
||||
}
|
||||
assert_eq!(text(&s), "hello world ", "typing on leaves the word as it is");
|
||||
for _ in 0.."world ".len() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "hello", "the next Undo removes the space");
|
||||
// Typing that AutoCorrect leaves alone is still one step per character.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s), "hell");
|
||||
// A typed comma sets AutoCorrect off too; the space after it leaves the undone word alone.
|
||||
s.execute("text.selectAll", &json!({})).ok();
|
||||
s.execute("text.delete", &json!({"dir": "backward"})).ok();
|
||||
for c in "hello,".chars() {
|
||||
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
|
||||
}
|
||||
assert_eq!(text(&s), "Hello,");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": " "})).unwrap();
|
||||
assert_eq!(text(&s), "hello, ", "the space after the comma leaves the undone word alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autocorrect_superscripts_ordinals_as_you_type() {
|
||||
let mut s = session();
|
||||
@@ -5859,15 +5998,30 @@ fn a_long_ink_stroke_is_extended_in_place_and_capped() {
|
||||
fn double_clicking_a_capped_freeform_keeps_its_vertices() {
|
||||
let mut s = session();
|
||||
let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 3.0, pressure: None };
|
||||
let point_cap = 16;
|
||||
s.set_tool(tools::ToolKind::Shape { preset: "freeform".into() });
|
||||
assert_eq!(s.tool.press_point_cap(), tools::MAX_GESTURE_POINTS);
|
||||
s.tool.freeform_press_point_cap = Some(point_cap);
|
||||
s.pointer(ev(tools::PointerKind::Down, 100.0, 100.0)).unwrap();
|
||||
// Densely clicked vertices, each within the double-click tolerance of the last.
|
||||
for i in 0..tools::MAX_GESTURE_POINTS + 10 {
|
||||
// The first press counts toward the cap, so 11 of these presses add no point.
|
||||
for i in 0..point_cap + 10 {
|
||||
s.pointer(ev(tools::PointerKind::Down, 300.0 + i as f64 * 0.001, 100.0)).unwrap();
|
||||
}
|
||||
s.pointer(ev(tools::PointerKind::DoubleClick, 300.0, 100.0)).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let deckcraft_model::Geom::Custom { paths } = &st.shapes().last().unwrap().geom else { panic!("no freeform") };
|
||||
assert_eq!(paths[0].d.matches(" L ").count(), point_cap - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeform_command_keeps_points_up_to_the_gesture_cap() {
|
||||
let mut s = session();
|
||||
// Send one point beyond the real cap to check that the command keeps as many as the tool can draw.
|
||||
let points: Vec<_> = (0..=tools::MAX_GESTURE_POINTS).map(|i| [i % 500, i / 500]).collect();
|
||||
let r = s.execute("shape.freeform", &json!({"points": points, "closed": false, "smooth": false})).unwrap();
|
||||
let id = ShapeId(r["id"].as_u64().unwrap() as u32);
|
||||
let deckcraft_model::Geom::Custom { paths } = &s.doc().unwrap().shape(id).unwrap().geom else { panic!("no freeform") };
|
||||
assert_eq!(paths[0].d.matches(" L ").count(), tools::MAX_GESTURE_POINTS - 1);
|
||||
}
|
||||
|
||||
@@ -6128,6 +6282,8 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
|
||||
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
|
||||
let e = s.execute(cmd, ¶ms).expect_err(&format!("{cmd} {params} should be rejected"));
|
||||
assert!(e.to_string().contains(cmd), "the error should name {cmd}: {e}");
|
||||
let key = if params.get("row").is_some() { "row" } else { "col" };
|
||||
assert!(e.to_string().contains(&format!("`{key}`")), "the error should name the explicit parameter: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{cmd} {params} must leave the presentation unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params} must not add an undo step");
|
||||
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{cmd} {params} must keep the redo step");
|
||||
@@ -6137,6 +6293,40 @@ fn table_resize_rejects_a_row_or_column_past_the_table() {
|
||||
assert_eq!(table_of(&s, id).rows.first().map(|r| r.height), Some(30.0), "the redo step is still the row height");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_resize_names_the_source_of_an_out_of_range_implicit_index() {
|
||||
let mut s = session();
|
||||
let source = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
|
||||
let target = table_at(&mut s, &[100.0], json!([["e"]]));
|
||||
let check = |s: &mut Session, row_error: &str, column_error: &str| {
|
||||
let before = s.doc().unwrap();
|
||||
let doc = before.doc.clone();
|
||||
let history = (before.history.undo.len(), before.history.redo.len());
|
||||
for (cmd, params, expected) in [
|
||||
("table.rowHeight", json!({"id": target.0, "height": 50.0}), row_error),
|
||||
("table.columnWidth", json!({"id": target.0, "width": 50.0}), column_error),
|
||||
] {
|
||||
let err = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(err.contains(expected), "{cmd}: {err}");
|
||||
let after = s.doc().unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&after.doc, &doc), "{cmd} must leave the presentation unchanged");
|
||||
assert_eq!((after.history.undo.len(), after.history.redo.len()), history);
|
||||
}
|
||||
};
|
||||
|
||||
s.execute("table.selectCells", &json!({"id": source.0, "from": [1, 1]})).unwrap();
|
||||
check(&mut s, "the selected cell's row 1 is out of range", "the selected cell's column 1 is out of range");
|
||||
|
||||
s.execute("edit.deselect", &json!({})).unwrap();
|
||||
// A table without rows or columns has no index zero to fall back to.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let slide = std::sync::Arc::make_mut(&mut doc.slides[0]);
|
||||
let deckcraft_model::ShapeKind::Table(table) = &mut slide.shape_mut(target).unwrap().kind else { panic!("not a table") };
|
||||
table.rows.clear();
|
||||
table.cols.clear();
|
||||
check(&mut s, "the default row 0 is out of range", "the default column 0 is out of range");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_resize_in_range_still_works() {
|
||||
let mut s = session();
|
||||
@@ -7424,6 +7614,67 @@ fn style_commands_refuse_only_nulls_and_take_one_key() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A size (or colour, bold…) set on a shape before it has any text survives the text that is
|
||||
/// then set: text.set keeps the first run's properties, and an empty paragraph keeps them on its
|
||||
/// end mark, which is what the agent's format.size then set_text sequence relies on.
|
||||
#[test]
|
||||
fn text_set_keeps_the_formatting_of_an_empty_shape() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("format.size", &json!({"size": 30})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
s.execute("text.set", &json!({"id": id, "text": "Hello"})).unwrap();
|
||||
let props =
|
||||
|s: &Session| s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
|
||||
let run = props(&s);
|
||||
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "{run:?}");
|
||||
// Emptied and filled again: the empty paragraph's end mark carried the formatting.
|
||||
s.execute("text.set", &json!({"id": id, "text": ""})).unwrap();
|
||||
s.execute("text.set", &json!({"id": id, "text": "Again"})).unwrap();
|
||||
let run = props(&s);
|
||||
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "after an empty text.set: {run:?}");
|
||||
}
|
||||
|
||||
/// The same while editing the text: a bold set in the text editor of a shape with an empty body
|
||||
/// (no paragraph at all) is what the next typed text gets.
|
||||
#[test]
|
||||
fn text_insert_keeps_the_formatting_set_in_an_empty_editor() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit(|doc, sel| {
|
||||
let sh = deckcraft_model::find_shape_mut(crate::shapes_mut(doc, sel).unwrap(), deckcraft_model::ShapeId(id as u32)).unwrap();
|
||||
sh.text = Some(deckcraft_model::text::TextBody::default());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Hi"})).unwrap();
|
||||
let run = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
|
||||
assert_eq!(run.bold, Some(true), "{run:?}");
|
||||
}
|
||||
|
||||
/// Font toggles on a selected table read the first selected cell, so the second Bold turns it off
|
||||
/// again, also for a cell whose empty text got its paragraph from the first toggle.
|
||||
#[test]
|
||||
fn bold_toggles_on_a_selected_table_cell() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[100.0, 100.0], json!([["", "b"], ["c", "d"]]));
|
||||
let bold = |s: &Session, r: usize, c: usize| {
|
||||
let st = s.doc().unwrap();
|
||||
let deckcraft_model::ShapeKind::Table(t) = &st.shape(id).unwrap().kind else { panic!("table") };
|
||||
let p = &t.cell(r, c).unwrap().text.paragraphs[0];
|
||||
p.runs.first().map_or(p.end_props.bold, |r| r.props.bold)
|
||||
};
|
||||
s.execute("table.selectCells", &json!({"id": id, "from": [0, 0], "to": [0, 1]})).unwrap();
|
||||
s.execute("format.bold", &json!({})).unwrap();
|
||||
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(true), Some(true)));
|
||||
assert_eq!(s.execute("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
s.execute("format.bold", &json!({})).unwrap();
|
||||
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(false), Some(false)));
|
||||
assert_eq!(bold(&s, 1, 0), None, "cells outside the range keep their formatting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_with_an_invalid_colour_is_rejected_and_keeps_the_highlight() {
|
||||
let mut s = session();
|
||||
@@ -8220,3 +8471,28 @@ fn editor_replacements_report_autocorrection_and_cancel_only_the_open_session()
|
||||
assert!(std::sync::Arc::ptr_eq(&restored, &s.doc().unwrap().doc));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smartart_colors_layout_and_style_answer_the_regenerated_ids() {
|
||||
let mut s = session();
|
||||
let r = s.execute("insert.smartArt", &json!({"kind": "process"})).unwrap();
|
||||
let gid = r["id"].clone();
|
||||
for (cmd, params) in [
|
||||
("smartArt.colors", json!({"id": gid, "colors": "colorful"})),
|
||||
("smartArt.layout", json!({"id": gid, "kind": "cycle"})),
|
||||
("smartArt.style", json!({"id": gid, "style": "intense"})),
|
||||
] {
|
||||
let a = s.execute(cmd, ¶ms).unwrap();
|
||||
assert_eq!(a["id"], gid, "{cmd}: {a}");
|
||||
let st = s.doc().unwrap();
|
||||
let g = st
|
||||
.doc
|
||||
.slides
|
||||
.iter()
|
||||
.find_map(|sl| deckcraft_model::find_shape(&sl.shapes, deckcraft_model::ShapeId(gid.as_u64().unwrap() as u32)))
|
||||
.unwrap();
|
||||
let deckcraft_model::ShapeKind::Group { children, .. } = &g.kind else { panic!("group") };
|
||||
let kids: Vec<u32> = children.iter().map(|c| c.id.0).collect();
|
||||
assert_eq!(a["ids"], json!(kids), "{cmd}: {a}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,6 +274,9 @@ pub struct ToolState {
|
||||
pub path_closing: bool,
|
||||
/// Whether the last freeform press added a vertex (it adds none at the point cap).
|
||||
pub press_added_vertex: bool,
|
||||
/// A smaller cap for tests that exercise freeform presses.
|
||||
#[cfg(test)]
|
||||
pub(crate) freeform_press_point_cap: Option<usize>,
|
||||
/// The shape in Edit Points: its vertices are handles instead of the box's.
|
||||
pub edit_points: Option<ShapeId>,
|
||||
/// The vertex (path, index) whose control handles show in Edit Points.
|
||||
@@ -310,6 +313,15 @@ impl ToolState {
|
||||
pub fn drawing_freeform(&self) -> bool {
|
||||
matches!(self.drag, Some(Drag::Freeform { .. }))
|
||||
}
|
||||
|
||||
/// Most vertices freeform presses place: [`MAX_GESTURE_POINTS`], or a smaller cap a test sets.
|
||||
pub(crate) fn press_point_cap(&self) -> usize {
|
||||
#[cfg(test)]
|
||||
if let Some(cap) = self.freeform_press_point_cap {
|
||||
return cap;
|
||||
}
|
||||
MAX_GESTURE_POINTS
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle positions in slide coordinates for a box (8 resize + rotate).
|
||||
|
||||
@@ -262,7 +262,7 @@ impl Session {
|
||||
self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false });
|
||||
return self.finish_freeform(true);
|
||||
}
|
||||
self.tool.press_added_vertex = points.len() < super::MAX_GESTURE_POINTS;
|
||||
self.tool.press_added_vertex = points.len() < self.tool.press_point_cap();
|
||||
if self.tool.press_added_vertex {
|
||||
points.push(p);
|
||||
}
|
||||
|
||||
@@ -60,3 +60,20 @@ fn standalone_emf_and_wmf_files_insert_as_pictures_and_save_as_metafile_parts()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_photo_album_lays_out_a_metafile_with_its_own_aspect() {
|
||||
let (ops, region) = two_rects();
|
||||
let emf = emf(&ops, region, "DeckCraft", "two rects").expect("EMF");
|
||||
let wmf = wmf(&ops, region).expect("WMF").bytes;
|
||||
for (name, bytes) in [("wide.emf", emf), ("wide.wmf", wmf)] {
|
||||
let mut s = Session::with_new();
|
||||
let item = json!({"data": base64_encode(&bytes), "name": name});
|
||||
s.execute("insert.photoAlbum", &json!({"pictures": [item], "layout": "1"})).expect(name);
|
||||
let doc = &s.doc().expect("doc").doc;
|
||||
let sh = doc.slides.iter().flat_map(|sl| &sl.shapes).find(|sh| matches!(sh.kind, ShapeKind::Picture { .. })).expect("album picture");
|
||||
let x = sh.xfrm.expect("xfrm");
|
||||
let aspect = x.w / x.h;
|
||||
assert!((aspect - 2.0).abs() < 0.05, "{name} keeps its 2:1 frame in the album, got {aspect}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +113,9 @@ struct Outline {
|
||||
/// non-ASCII `Token::Symbol`.
|
||||
skip_cont: usize,
|
||||
line: String,
|
||||
/// The document's code page (`\ansicpg`), which `\'hh` bytes are in: Windows-1252 until it
|
||||
/// names another single-byte one (#2394).
|
||||
/// The document's code page for `\'hh` bytes (Windows-1252 unless `\ansicpg` names a supported page).
|
||||
code_page: u16,
|
||||
hex_decoder: craft_rtf::TextDecoder,
|
||||
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
|
||||
out: Vec<(usize, String)>,
|
||||
}
|
||||
@@ -203,6 +203,7 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
skip_cont: 0,
|
||||
line: String::new(),
|
||||
code_page: 1252,
|
||||
hex_decoder: craft_rtf::TextDecoder::new(),
|
||||
out: vec![],
|
||||
};
|
||||
p.run(rtf);
|
||||
@@ -214,6 +215,10 @@ impl Outline {
|
||||
fn run(&mut self, rtf: &str) {
|
||||
let mut tokens = craft_rtf::Tokens::new(rtf.as_bytes());
|
||||
while let Some(token) = tokens.next() {
|
||||
// Text and escaped literals can supply trail bytes. Structural and semantic tokens end the run.
|
||||
if !matches!(token, craft_rtf::Token::Hex(_) | craft_rtf::Token::Text(_) | craft_rtf::Token::Symbol(b'\\' | b'{' | b'}')) {
|
||||
self.hex_decoder.finish(&mut self.line);
|
||||
}
|
||||
match token {
|
||||
craft_rtf::Token::Open => self.open_group(),
|
||||
craft_rtf::Token::Close => self.close_group(),
|
||||
@@ -235,6 +240,7 @@ impl Outline {
|
||||
craft_rtf::Token::Bin(_) => self.skip_cont = 0,
|
||||
}
|
||||
}
|
||||
self.hex_decoder.finish(&mut self.line);
|
||||
}
|
||||
|
||||
fn open_group(&mut self) {
|
||||
@@ -277,9 +283,10 @@ impl Outline {
|
||||
self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1);
|
||||
}
|
||||
"li" => self.indent = i64::from(arg.unwrap_or(0)),
|
||||
// A code page read a byte at a time; any other (East Asian multibyte, unknown) keeps Windows-1252.
|
||||
"ansicpg" => {
|
||||
if let Some(cp) = arg.and_then(|a| u16::try_from(a).ok()).filter(|cp| craft_rtf::codepage::is_byte_code_page(*cp)) {
|
||||
use craft_rtf::codepage::{is_byte_code_page, multibyte_encoding_name};
|
||||
let cp = arg.and_then(|a| u16::try_from(a).ok());
|
||||
if let Some(cp) = cp.filter(|&cp| is_byte_code_page(cp) || multibyte_encoding_name(cp).is_some()) {
|
||||
self.code_page = cp;
|
||||
}
|
||||
}
|
||||
@@ -311,7 +318,7 @@ impl Outline {
|
||||
return;
|
||||
}
|
||||
if !self.st.skip && h != 0 {
|
||||
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
|
||||
self.hex_decoder.byte(h, self.code_page, &mut self.line);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,7 +338,7 @@ impl Outline {
|
||||
return;
|
||||
}
|
||||
match n {
|
||||
b'\\' | b'{' | b'}' => self.line.push(n as char),
|
||||
b'\\' | b'{' | b'}' => self.hex_decoder.byte(n, self.code_page, &mut self.line),
|
||||
b'~' => self.line.push('\u{a0}'),
|
||||
b'_' => self.line.push('\u{2011}'),
|
||||
b'\n' | b'\r' => self.flush(true),
|
||||
@@ -358,6 +365,15 @@ impl Outline {
|
||||
}
|
||||
}
|
||||
if !self.st.skip {
|
||||
// The decoder consumes the first ASCII byte as a trail only when the code page allows it.
|
||||
// Any remaining text is already UTF-8.
|
||||
if craft_rtf::codepage::multibyte_encoding_name(self.code_page).is_some()
|
||||
&& let Some(&first) = s.as_bytes().first().filter(|b| b.is_ascii())
|
||||
{
|
||||
self.hex_decoder.byte(first, self.code_page, &mut self.line);
|
||||
s = &s[1..];
|
||||
}
|
||||
self.hex_decoder.finish(&mut self.line);
|
||||
self.line.push_str(s);
|
||||
}
|
||||
}
|
||||
@@ -631,9 +647,7 @@ mod tests {
|
||||
assert_eq!(crate::slides_to_outline(&reopened), expected);
|
||||
}
|
||||
|
||||
/// A writer on a non-Western Windows locale names its code page with `\ansicpg` and writes
|
||||
/// non-ASCII letters as `\'hh` bytes of that page (#2394); `\ansicpg1252` and no `\ansicpg`
|
||||
/// both stay Windows-1252.
|
||||
/// `\ansicpg` names the code page of the escapes, including pages with multibyte letters.
|
||||
#[test]
|
||||
fn hex_escapes_decode_in_the_code_page_ansicpg_names() {
|
||||
let outline = |cpg: &str, title: &str, body: &str| {
|
||||
@@ -651,6 +665,40 @@ mod tests {
|
||||
assert_eq!(outline(r"\ansicpg1251", r"\'cf\'f0\'e8\'e2\'e5\'f2", r"\'ec\'e8\'f0"), "Привет\n\tмир\nPlain\n");
|
||||
assert_eq!(outline(r"\ansicpg1252", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
|
||||
assert_eq!(outline("", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
|
||||
assert_eq!(outline(r"\ansicpg932", r"\'93\'fa\'96\'7b", r"\'8c\'ea"), "日本\n\t語\nPlain\n");
|
||||
assert_eq!(outline(r"\ansicpg936", r"\'d6\'d0\'ce\'c4", r"\'bc\'f2\'cc\'e5"), "中文\n\t简体\nPlain\n");
|
||||
assert_eq!(outline(r"\ansicpg949", r"\'c7\'d1\'b1\'b9", r"\'be\'ee"), "한국\n\t어\nPlain\n");
|
||||
assert_eq!(outline(r"\ansicpg950", r"\'a4\'a4\'a4\'e5", r"\'a4\'e5"), "中文\n\t文\nPlain\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_ascii_trail_bytes_match_hex_escaped_trail_bytes() {
|
||||
for (cp, lead) in [(932, "83"), (936, "81"), (949, "81"), (950, "a4")] {
|
||||
let mixed = format!(r"{{\rtf1\ansi\ansicpg{cp} \'{lead}A\par}}");
|
||||
let escaped = format!(r"{{\rtf1\ansi\ansicpg{cp} \'{lead}\'41\par}}");
|
||||
let decoded = rtf_to_outline(&mixed);
|
||||
assert_eq!(decoded, rtf_to_outline(&escaped), "CP{cp}");
|
||||
assert!(!decoded.contains('\u{fffd}'), "CP{cp}: {decoded:?}");
|
||||
}
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1\ansi\ansicpg932 \'83AB界\par}"), "アB界\n");
|
||||
assert_eq!(rtf_to_outline(r"{\rtf1\ansi\ansicpg932 \'83!\'83界\par}"), "\u{fffd}!\u{fffd}界\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_literals_match_hex_escaped_trail_bytes() {
|
||||
let mixed = r"{\rtf1\ansi\ansicpg932 \'95\\\'93\{\'93\}\par}";
|
||||
let escaped = r"{\rtf1\ansi\ansicpg932 \'95\'5c\'93\'7b\'93\'7d\par}";
|
||||
assert_eq!(rtf_to_outline(mixed), "表怒党\n");
|
||||
assert_eq!(rtf_to_outline(mixed), rtf_to_outline(escaped));
|
||||
|
||||
let literals = r"{\rtf1\ansi\ansicpg932 \{\}\\{\*\ignored \'95\\}\uc1\u65\{\'83\b B\par}";
|
||||
assert_eq!(rtf_to_outline(literals), "{}\\A\u{fffd}B\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multibyte_escapes_respect_unicode_fallback_and_group_boundaries() {
|
||||
let rtf = r"{\rtf1\ansi\ansicpg932\outlinelevel0 \'93\'fa{\uc2\u26412\'96A}\'8c\'ea\par\pard\outlinelevel1 {\'93}A\'93\{\b \'93\'fa\par}";
|
||||
assert_eq!(rtf_to_outline(rtf), "日本語\n\t\u{fffd}A怒日\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -81,10 +81,10 @@ pub fn decode(bytes: &Bytes) -> Result<Pcm> {
|
||||
Some(r) => r,
|
||||
None => contained(|| decode_symphonia(bytes, "mkv")),
|
||||
},
|
||||
Container::Mp4 | Container::Unknown | Container::Mp3 if !crate::mp4guard::probe_fits(bytes) => {
|
||||
Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into()))
|
||||
c => {
|
||||
crate::mp4guard::check(c, bytes)?;
|
||||
contained(|| decode_symphonia(bytes, c.name()))
|
||||
}
|
||||
c => contained(|| decode_symphonia(bytes, c.name())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +297,8 @@ pub(crate) fn probe_symphonia(bytes: &Bytes, ext: &str) -> Option<(String, u32,
|
||||
}
|
||||
|
||||
/// Length in milliseconds of the track playback decodes, summed from its packet durations: the
|
||||
/// file is demuxed but not decoded. `None` when the demuxer reports no durations.
|
||||
/// file is demuxed but not decoded. `None` when the demuxer reports no durations. Callers must
|
||||
/// pass [`crate::mp4guard::check`] first: the demuxer reads each sample whole at its `stsz` size.
|
||||
pub(crate) fn demux_duration_ms(bytes: &Bytes, ext: &str) -> Option<u64> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let mss = MediaSourceStream::new(Box::new(Cursor::new(Shared(bytes.clone()))), MediaSourceStreamOptions::default());
|
||||
|
||||
@@ -35,6 +35,17 @@ pub(crate) fn probe_fits(b: &[u8]) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The check every path into symphonia's demuxer runs first: `Corrupt` when symphonia would read
|
||||
/// `b` (sniffed as `c`) as an MP4 whose tables do not fit the file. Other known containers skip
|
||||
/// it (a WAV's audio bytes can spell an `ftyp`, but symphonia opens it as a WAV).
|
||||
pub(crate) fn check(c: crate::Container, b: &[u8]) -> crate::Result<()> {
|
||||
use crate::Container;
|
||||
if matches!(c, Container::Mp4 | Container::Unknown | Container::Mp3) && !probe_fits(b) {
|
||||
return Err(crate::MediaError::Corrupt("the MP4's sample tables do not fit the file".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
use craft_media::isobmff::boxes::BoxIter;
|
||||
|
||||
fn be32(b: &[u8], at: usize) -> Option<u64> {
|
||||
|
||||
@@ -52,7 +52,11 @@ pub fn probe(bytes: &Bytes) -> Result<MediaInfo> {
|
||||
if info.duration_ms == 0 && info.audio.as_ref().is_some_and(|a| a.decodable) && info.video.is_none() {
|
||||
// No length in the header (raw MP3 / ADTS without an index): add up the packet
|
||||
// lengths. This only demuxes, so a long file neither allocates its PCM nor stalls the caller.
|
||||
if let Some(d) = crate::audio::demux_duration_ms(bytes, Container::sniff(bytes).name()) {
|
||||
// Our MP4 parser can describe a track whose `stsz` claims a sample symphonia would read
|
||||
// whole, so the tables are checked first here too.
|
||||
let c = Container::sniff(bytes);
|
||||
crate::mp4guard::check(c, bytes)?;
|
||||
if let Some(d) = crate::audio::demux_duration_ms(bytes, c.name()) {
|
||||
info.duration_ms = d;
|
||||
}
|
||||
}
|
||||
@@ -72,10 +76,8 @@ pub fn probe_headers(bytes: &Bytes) -> Result<MediaInfo> {
|
||||
};
|
||||
if info.audio.is_none() && info.video.is_none() || info.audio.as_ref().is_some_and(|a| a.sample_rate == 0) {
|
||||
// Plain audio files (and anything our demuxers didn't describe): symphonia's probe.
|
||||
// Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too); other known containers (a WAV's audio bytes can spell an `ftyp`) skip the check.
|
||||
if matches!(c, Container::Mp4 | Container::Unknown | Container::Mp3) && !crate::mp4guard::probe_fits(bytes) {
|
||||
return Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into()));
|
||||
}
|
||||
// Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too).
|
||||
crate::mp4guard::check(c, bytes)?;
|
||||
let (codec, rate, channels, frames) = std::panic::catch_unwind(|| crate::audio::probe_symphonia(bytes, c.name()))
|
||||
.ok()
|
||||
.flatten()
|
||||
|
||||
@@ -434,3 +434,29 @@ fn mp4_sample_tables_that_overrun_the_file_are_corrupt() {
|
||||
assert!(audio::decode(&fixture(name)).is_ok() || name.starts_with("clip"), "{name} still decodes");
|
||||
}
|
||||
}
|
||||
|
||||
/// `stsz-size.m4a` with its mvhd, tkhd and mdhd durations zeroed: `probe_headers` describes the
|
||||
/// AAC track but finds no length, so `probe` demuxes it. The 4 GB sample must not reach symphonia.
|
||||
#[test]
|
||||
fn probe_rejects_damaged_stsz_without_header_duration() {
|
||||
let mut b = fixture("damaged/stsz-size.m4a").to_vec();
|
||||
// The duration fields of mvhd, tkhd and mdhd (all version 0).
|
||||
for at in [4538, 4658, 4790] {
|
||||
b[at..at + 4].copy_from_slice(&[0; 4]);
|
||||
}
|
||||
let b: Bytes = Arc::new(b);
|
||||
let head = probe::probe_headers(&b).expect("our MP4 parser still accepts the file");
|
||||
assert_eq!(head.duration_ms, 0);
|
||||
assert!(head.audio.as_ref().is_some_and(|a| a.decodable && a.sample_rate > 0));
|
||||
assert!(matches!(probe::probe(&b), Err(MediaError::Corrupt(_))), "probe must reject the damaged sample table");
|
||||
// Control: the intact file with the same fields zeroed takes the same demux path, and the
|
||||
// table check must let it through, with the length coming from the demux.
|
||||
let mut intact = fixture("tone.m4a").to_vec();
|
||||
for at in [4538, 4658, 4790] {
|
||||
intact[at..at + 4].copy_from_slice(&[0; 4]);
|
||||
}
|
||||
let intact: Bytes = Arc::new(intact);
|
||||
assert_eq!(probe::probe_headers(&intact).expect("headers parse").duration_ms, 0, "the header gives no length");
|
||||
let info = probe::probe(&intact).expect("an intact MP4 without a header duration still probes");
|
||||
assert!(info.duration_ms > 0, "the demux still finds a length");
|
||||
}
|
||||
|
||||
@@ -1175,3 +1175,72 @@ mod shape_owner_scoping_tests {
|
||||
assert!(patched.contains(r#"fmla="val 3000000000""#), "child id=11 should be patched: {patched}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod group_fill_roundtrip_tests {
|
||||
use std::io::Read;
|
||||
|
||||
use deckcraft_model::style::{Fill, PictureFill, PictureMode};
|
||||
use deckcraft_model::{Shape, ShapeId, ShapeKind, Xfrm, defaults};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn group_picture_fill_survives_a_pptx_round_trip() {
|
||||
// Regression coverage for #1798: the group's own picture fill (a:blipFill in its p:grpSpPr)
|
||||
// and its members' grpFill markers (a:grpFill in each member's p:spPr) must survive a
|
||||
// save/reload unchanged. The media bytes are opaque to the round trip; the PNG signature
|
||||
// is enough for the content type.
|
||||
let mut p = defaults::new_presentation(None);
|
||||
let png = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
let media = p.add_media("t.png", "image/png", png.clone()).expect("media");
|
||||
let member =
|
||||
|id: u32, x: f64| Shape { id: ShapeId(id), xfrm: Some(Xfrm::new(x, 0.0, 120.0, 60.0)), fill: Some(Fill::Group), ..Default::default() };
|
||||
let group = Shape {
|
||||
id: ShapeId(21),
|
||||
xfrm: Some(Xfrm::new(100.0, 100.0, 240.0, 60.0)),
|
||||
fill: Some(Fill::Picture(PictureFill { media, mode: PictureMode::Stretch { fill_rect: [0.0; 4] }, ..Default::default() })),
|
||||
kind: ShapeKind::Group { children: vec![member(22, 0.0), member(23, 120.0)], child: Xfrm::new(0.0, 0.0, 240.0, 60.0) },
|
||||
..Default::default()
|
||||
};
|
||||
Arc::make_mut(&mut p.slides[0]).shapes.push(group);
|
||||
let bytes = crate::export(&p).expect("export");
|
||||
// The markers themselves must be in the exported slide XML, not only in the
|
||||
// reimported model: an exporter writing a:noFill for the members could still
|
||||
// pass the round trip below if the importer reconstructed Fill::Group for them.
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes.clone())).expect("exported package");
|
||||
let mut xml = String::new();
|
||||
z.by_name("ppt/slides/slide1.xml").expect("slide part").read_to_string(&mut xml).expect("slide xml");
|
||||
// Inspect the markers through the parsed XML tree, scoped to the group's
|
||||
// direct children: string splitting on exact tag spellings would miss a
|
||||
// member whose p:sp tag gained an attribute, and a slice running to the
|
||||
// end of the slide would count a later sibling shape as a member. The
|
||||
// slide's own root grpSpPr and its layout placeholders are not inside
|
||||
// the group element, so they cannot be mistaken for its fills.
|
||||
let doc = crate::parse_xml(xml.as_bytes()).expect("the slide XML parses");
|
||||
let sp_tree = doc.root.path(&["cSld", "spTree"]).expect("the slide has a spTree");
|
||||
let grp = sp_tree.children_named("grpSp").next().expect("the group is written as a grpSp child of the spTree");
|
||||
let grp_sp_pr = grp.child("grpSpPr").expect("the group's grpSpPr");
|
||||
assert!(grp_sp_pr.child("blipFill").is_some(), "the group's picture fill is a:blipFill in its grpSpPr: {}", grp_sp_pr.to_xml());
|
||||
assert!(grp_sp_pr.child("grpFill").is_none(), "the group's grpSpPr carries no a:grpFill: {}", grp_sp_pr.to_xml());
|
||||
let members: Vec<_> = grp.children_named("sp").collect();
|
||||
assert_eq!(members.len(), 2, "both members are direct p:sp children of the group: {xml}");
|
||||
for m in &members {
|
||||
let sp_pr = m.child("spPr").expect("a member's spPr");
|
||||
assert!(sp_pr.child("grpFill").is_some(), "each member's spPr carries a:grpFill: {}", sp_pr.to_xml());
|
||||
}
|
||||
let rt = crate::import(&bytes).expect("import");
|
||||
let g = rt.slides[0].shapes.iter().find(|s| matches!(s.kind, ShapeKind::Group { .. })).expect("the group survives");
|
||||
let Some(Fill::Picture(pic)) = &g.fill else { panic!("the group keeps its picture fill, got {:?}", g.fill) };
|
||||
assert!(matches!(pic.mode, PictureMode::Stretch { .. }), "the fill stays a stretch, not a tile");
|
||||
let item = rt.media.iter().find(|m| m.id == pic.media).expect("the media the fill names");
|
||||
assert_eq!(*item.data, png, "the media bytes survive the round trip");
|
||||
if let ShapeKind::Group { children, .. } = &g.kind {
|
||||
assert_eq!(children.len(), 2, "both members survive");
|
||||
assert!(
|
||||
children.iter().all(|c| c.fill == Some(Fill::Group)),
|
||||
"the members keep grpFill: {:?}",
|
||||
children.iter().map(|c| &c.fill).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,6 +339,38 @@ fn children_filled_with_the_group_fill_show_one_fill_across_the_group() {
|
||||
assert!(close(img.pixel(200, 150), WHITE, 5), "the gap between the children stays empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stretched_picture_on_a_group_spans_the_group_not_each_member() {
|
||||
use deckcraft_model::style::{PictureFill, PictureMode};
|
||||
// Regression coverage for #1798: a picture fill set on the group itself is resolved once
|
||||
// against the group's bounds, and members filled with grpFill show their slice of that one
|
||||
// image — not a copy of the whole picture in each member.
|
||||
let mut p = Presentation::default();
|
||||
let media = p.add_media("t.png", "image/png", half_red_half_blue()).expect("media");
|
||||
let member = |id: u32, x: f64| Shape {
|
||||
id: ShapeId(id),
|
||||
xfrm: Some(Xfrm::new(x, 0.0, 120.0, 60.0)),
|
||||
fill: Some(Fill::Group),
|
||||
line: no_line(),
|
||||
..Default::default()
|
||||
};
|
||||
let g = Shape {
|
||||
id: ShapeId(31),
|
||||
xfrm: Some(Xfrm::new(100.0, 100.0, 240.0, 60.0)),
|
||||
fill: Some(Fill::Picture(PictureFill { media, mode: PictureMode::Stretch { fill_rect: [0.0; 4] }, ..Default::default() })),
|
||||
kind: ShapeKind::Group { children: vec![member(32, 0.0), member(33, 120.0)], child: Xfrm::new(0.0, 0.0, 240.0, 60.0) },
|
||||
..Default::default()
|
||||
};
|
||||
std::sync::Arc::make_mut(&mut p.slides[0]).shapes = vec![g];
|
||||
let img = render_slide(&p, 0, &RenderOpts { scale: 1.0, ..Default::default() });
|
||||
let blue = Rgba::rgb(0, 0, 255);
|
||||
// The samples sit where the two readings disagree: had each member stretched its own
|
||||
// copy, the left member would turn blue at x=160 and the right member would start red
|
||||
// until x=280; under one mapping across the group, the turn is at the group's middle.
|
||||
assert!(close(img.pixel(190, 130), RED, 30), "the left member is still in the picture's left half: {:?}", img.pixel(190, 130));
|
||||
assert!(close(img.pixel(250, 130), blue, 30), "the right member is already in the picture's right half: {:?}", img.pixel(250, 130));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_freeforms_take_arrowheads_even_when_filled() {
|
||||
// An open custom path with a fill and a tail arrow: PowerPoint draws the arrow.
|
||||
|
||||
+112
-38
@@ -181,11 +181,12 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
let adv = if c == '\t' {
|
||||
let (adv, seg) = if c == '\t' {
|
||||
let seg = tab_segment(&p.cells, i);
|
||||
// The implicit stop is for the first line only: later lines start at the margin.
|
||||
tab_advance(x0 + x, tab_stops, default_tab, tab_segment(&p.cells, i), if lines.is_empty() { hang_stop } else { None }, x0 + avail)
|
||||
(tab_advance(x0 + x, tab_stops, default_tab, seg, if lines.is_empty() { hang_stop } else { None }, x0 + avail), seg)
|
||||
} else {
|
||||
p.cells.get(i).map(|c| c.adv).unwrap_or(0.0)
|
||||
(p.cells.get(i).map(|c| c.adv).unwrap_or(0.0), (0.0, 0.0, 0.0))
|
||||
};
|
||||
let breakable = |j: usize| p.cells.get(j).is_none_or(|c| c.breakable(j));
|
||||
if i > start && allowed.get(i).copied().unwrap_or(false) && breakable(i) {
|
||||
@@ -198,8 +199,22 @@ pub(crate) fn break_lines(p: &ParaShaped, params: &BreakParams) -> Vec<RawLine>
|
||||
next = i + 1;
|
||||
break;
|
||||
}
|
||||
// A tab that would run past the end moves to the next line (and to its first stop there).
|
||||
if wrap && c == '\t' && x + adv > avail + 0.01 && i > start {
|
||||
// A tab that runs past the end moves to the next line. For a right, centre or
|
||||
// decimal stop only (left and default tabs wrap between the words after them as
|
||||
// usual), also keep it with its following segment when x + adv + seg.2 overflows here but fresh_tab_adv + seg.2
|
||||
// fits within rest_w: a clamped tab can have zero advance while its text still
|
||||
// overflows, and moving only the text would lose its tab alignment. The fresh-line
|
||||
// check includes the tab advance, not just the text width. seg.2 excludes trailing
|
||||
// whitespace so spaces alone cannot move visible text; an oversized segment that
|
||||
// cannot fit with its tab on a fresh line uses the ordinary wrapping rules.
|
||||
let tab_overflow = wrap
|
||||
&& c == '\t'
|
||||
&& (x + adv > avail + 0.01
|
||||
|| (seg.2 > 0.0
|
||||
&& takes_aligned_stop(x0 + x, tab_stops)
|
||||
&& x + adv + seg.2 > avail + 0.01
|
||||
&& tab_advance(x0_rest, tab_stops, default_tab, seg, None, x0_rest + rest_w) + seg.2 <= rest_w + 0.01));
|
||||
if tab_overflow && i > start {
|
||||
end = i;
|
||||
next = i;
|
||||
while end > start && p.cells.get(end - 1).is_some_and(|c| c.ch == ' ') {
|
||||
@@ -289,11 +304,12 @@ pub(crate) fn tabs_of(props: &ParaProps) -> Vec<Tab> {
|
||||
tabs
|
||||
}
|
||||
|
||||
/// Width of the text after the tab at cell `i` up to the next tab or line break, and the width of
|
||||
/// that text before its first ".".
|
||||
pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
|
||||
/// Width of the text after the tab at cell `i` up to the next tab or line break, the width of
|
||||
/// that text before its first ".", and the width excluding trailing whitespace.
|
||||
pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64, f64) {
|
||||
let mut w = 0.0;
|
||||
let mut dec = None;
|
||||
let mut last_non_ws = 0.0;
|
||||
for c in cells.iter().skip(i + 1) {
|
||||
if matches!(c.ch, '\t'..='\u{b}') {
|
||||
break;
|
||||
@@ -302,47 +318,78 @@ pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) {
|
||||
dec = Some(w);
|
||||
}
|
||||
w += c.adv;
|
||||
if !c.ch.is_whitespace() {
|
||||
last_non_ws = w;
|
||||
}
|
||||
}
|
||||
(w, dec.unwrap_or(w))
|
||||
(w, dec.unwrap_or(w), last_non_ws)
|
||||
}
|
||||
|
||||
/// Advance of a tab at `x` (from the start edge) to the next stop, placing the text after it
|
||||
/// (`seg`: its width, and its width before the decimal point) as the stop aligns it but never
|
||||
/// moving back, as PowerPoint does; past the last stop, to the next default stop.
|
||||
/// `hang` is the hanging-indent implicit stop (`marL`): the first tab on a first line that
|
||||
/// starts left of the margin goes there instead, as PowerPoint does. The nearer of the
|
||||
/// implicit and the regular stops wins; an explicit stop within 0.5 pt of it keeps its
|
||||
/// own alignment.
|
||||
/// The configured stop a tab at `x` takes, by configured position. `stops` is in position order
|
||||
/// (`tabs_of`). A NaN `x` has none.
|
||||
fn next_stop(x: f64, stops: &[Tab]) -> Option<&Tab> {
|
||||
if x.is_nan() { None } else { stops.get(stops.partition_point(|s| s.pos <= x + 0.5)) }
|
||||
}
|
||||
|
||||
/// Whether a tab at `x` takes a right, centre or decimal stop: the stops whose following text
|
||||
/// is placed relative to the stop, so the tab and that text belong together.
|
||||
fn takes_aligned_stop(x: f64, stops: &[Tab]) -> bool {
|
||||
next_stop(x, stops).is_some_and(|s| s.align != TabAlign::Left)
|
||||
}
|
||||
|
||||
/// Advance of a tab at `x` to the next stop, aligning the following text without moving back;
|
||||
/// past the last explicit stop, advance to the next default stop.
|
||||
///
|
||||
/// `right` is the line's right edge in the same coordinate space as `x` (the text area's left
|
||||
/// edge plus the line's start offset and width): a stop set past that edge acts as one at the
|
||||
/// edge, as PowerPoint treats it (a right-aligned stop there ends the text at the margin).
|
||||
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64), hang: Option<f64>, right: f64) -> f64 {
|
||||
// `stops` is in position order (`tabs_of`): the next stop is the first past x.
|
||||
// A NaN `x` (a NaN spacing upstream) skips the lookup and takes the finite default-stop path.
|
||||
/// `x`, stop positions and `right` are distances from the same text-column start edge, not
|
||||
/// from the current line's indented start. `right` is the right-margin coordinate, not the
|
||||
/// remaining width: both breaking and layout pass the line's `x0 + avail`. Nonfinite or
|
||||
/// nonpositive edges disable clamping.
|
||||
///
|
||||
/// `seg` is `(total_width, width_before_first_decimal_point, width_without_trailing_whitespace)`,
|
||||
/// from [`tab_segment`]; the second value equals the total width when no "." occurs.
|
||||
/// Alignment uses the first two values; breaking uses the third for its visible-segment fit
|
||||
/// check, including the fresh line's tab advance (without its first-line-only implicit stop).
|
||||
///
|
||||
/// Stops are selected by their configured position before clamping. Beyond a positive finite
|
||||
/// `right`, left and right stops take effect at the edge; center and decimal stops subtract
|
||||
/// the width after their alignment point so the whole segment fits. Stops at or inside the
|
||||
/// edge and default stops retain their configured positions. Advances never move backward.
|
||||
///
|
||||
/// `hang` is the hanging-indent implicit stop (`marL`): on a first line that starts left of
|
||||
/// the margin, the nearer implicit or regular stop wins. An explicit stop taking effect
|
||||
/// within 0.5 pt of it keeps its own alignment.
|
||||
pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64, f64), hang: Option<f64>, right: f64) -> f64 {
|
||||
let effective_pos = |s: &Tab| {
|
||||
if right.is_finite() && right > 0.0 && s.pos > right {
|
||||
match s.align {
|
||||
TabAlign::Left | TabAlign::Right => right,
|
||||
TabAlign::Center => (right - seg.0 / 2.0).max(0.0),
|
||||
TabAlign::Decimal => (right - (seg.0 - seg.1).max(0.0)).max(0.0),
|
||||
}
|
||||
} else {
|
||||
s.pos
|
||||
}
|
||||
};
|
||||
// `stops` is in position order (`tabs_of`): select by the configured position, not the
|
||||
// clamped one. A NaN `x` skips the lookup and takes the finite default-stop path.
|
||||
let explicit = next_stop(x, stops);
|
||||
if !x.is_nan()
|
||||
&& let Some(h) = hang
|
||||
&& h.is_finite()
|
||||
&& x < h - 0.5
|
||||
{
|
||||
let explicit = stops.get(stops.partition_point(|s| s.pos <= x + 0.5));
|
||||
let d = if default_tab > 1.0 { default_tab } else { 72.0 };
|
||||
let default_next = ((x / d).floor() + 1.0) * d;
|
||||
let explicit_wins = match explicit {
|
||||
// Compared where the stop takes effect: one past the line's edge ends there (below).
|
||||
Some(s) => {
|
||||
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
|
||||
pos < h - 0.5 || (pos - h).abs() <= 0.5
|
||||
}
|
||||
Some(s) => effective_pos(s) <= h + 0.5,
|
||||
None => h >= default_next - 0.5,
|
||||
};
|
||||
if !explicit_wins {
|
||||
return (h - x).max(1.0);
|
||||
}
|
||||
}
|
||||
if let Some(s) = stops.get(stops.partition_point(|s| s.pos <= x + 0.5)).filter(|_| !x.is_nan()) {
|
||||
let pos = if right.is_finite() && right > 0.0 { s.pos.min(right) } else { s.pos };
|
||||
let to = (pos - x).max(0.0);
|
||||
if let Some(s) = explicit {
|
||||
let to = (effective_pos(s) - x).max(0.0);
|
||||
return match s.align {
|
||||
TabAlign::Left => to,
|
||||
TabAlign::Right => (to - seg.0).max(0.0),
|
||||
@@ -362,8 +409,8 @@ mod tab_tests {
|
||||
#[test]
|
||||
fn a_nan_position_takes_the_finite_default_stop() {
|
||||
let stops = [Tab { pos: 100.0, align: TabAlign::Left }];
|
||||
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0), None, 600.0).is_finite());
|
||||
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0), None, 600.0), 90.0);
|
||||
assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0, 0.0), None, 600.0).is_finite());
|
||||
assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0, 0.0), None, 600.0), 90.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -371,16 +418,16 @@ mod tab_tests {
|
||||
// The 700 pt stop takes effect at the 60 pt edge, which comes before the 80 pt hang: it
|
||||
// wins, and right-aligned text after it ends at the edge (60 - 20), not at the hang.
|
||||
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 20.0), Some(80.0), 60.0), 40.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 20.0, 20.0), Some(80.0), 60.0), 40.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stop_past_the_line_ends_at_its_edge() {
|
||||
let stops = [Tab { pos: 700.0, align: TabAlign::Right }];
|
||||
// Right-aligned text after the tab ends at the line's right edge, not 700.
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 600.0), 500.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0, 100.0), None, 600.0), 500.0);
|
||||
// A stop inside the line keeps its own position.
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0), None, 800.0), 600.0);
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (100.0, 100.0, 100.0), None, 800.0), 600.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -388,8 +435,35 @@ mod tab_tests {
|
||||
// The stop and the edge are absolute coordinates: a 100 pt start offset does not move the
|
||||
// edge in to 500 pt, so an inside stop at 550 stays there and one past 600 ends at 600.
|
||||
let inside = [Tab { pos: 550.0, align: TabAlign::Right }];
|
||||
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.0, 100.0), None, 600.0), 350.0);
|
||||
assert_eq!(tab_advance(100.0, &inside, 72.0, (100.0, 100.0, 100.0), None, 600.0), 350.0);
|
||||
let past = [Tab { pos: 700.0, align: TabAlign::Right }];
|
||||
assert_eq!(tab_advance(100.0, &past, 72.0, (100.0, 100.0), None, 600.0), 400.0);
|
||||
assert_eq!(tab_advance(100.0, &past, 72.0, (100.0, 100.0, 100.0), None, 600.0), 400.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_centered_segment_keeps_its_configured_stop() {
|
||||
// Eligibility uses the configured stop, even when clamping puts its center at x.
|
||||
let stops = [Tab { pos: 550.0, align: TabAlign::Center }];
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (1100.0, 1100.0, 1100.0), None, 500.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_center_and_decimal_stops_keep_their_alignment_points() {
|
||||
let center = [Tab { pos: 490.0, align: TabAlign::Center }];
|
||||
assert_eq!(tab_advance(0.0, ¢er, 72.0, (40.0, 40.0, 40.0), None, 500.0), 470.0);
|
||||
let decimal = [Tab { pos: 490.0, align: TabAlign::Decimal }];
|
||||
assert_eq!(tab_advance(0.0, &decimal, 72.0, (40.0, 20.0, 40.0), None, 500.0), 470.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clamped_aligned_stops_compete_with_the_hang_at_their_effective_position() {
|
||||
for align in [TabAlign::Center, TabAlign::Decimal] {
|
||||
let stops = [Tab { pos: 700.0, align }];
|
||||
// The alignment point moves to 50; its text ends at the 60 pt edge.
|
||||
assert_eq!(tab_advance(0.0, &stops, 72.0, (20.0, 10.0, 20.0), Some(55.0), 60.0), 40.0);
|
||||
}
|
||||
// Keep main's edge clamp for left stops as well.
|
||||
let left = [Tab { pos: 700.0, align: TabAlign::Left }];
|
||||
assert_eq!(tab_advance(0.0, &left, 72.0, (20.0, 20.0, 20.0), Some(80.0), 60.0), 60.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1477,6 +1477,106 @@ fn a_tab_past_the_end_moves_to_the_next_line() {
|
||||
assert!((l.lines[1].edges[1].0 - l.inner.x0 - 72.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// #1663: a right-aligned tab stop past the right edge of the text area clamps to the edge
|
||||
/// and right-aligns the text there, instead of wrapping.
|
||||
#[test]
|
||||
fn right_tab_stop_past_right_edge_aligns_at_margin_without_wrapping() {
|
||||
let l = tabbed("\tCorrie Ten Boom", &[(550.0, "r")], 500.0);
|
||||
assert_eq!(l.lines.len(), 1, "must not wrap to a second line");
|
||||
assert!((l.lines[0].extent.1 - l.inner.x1).abs() < 1.0, "text right edge {:?} should align with inner.x1 {}", l.lines[0].extent.1, l.inner.x1);
|
||||
}
|
||||
|
||||
/// #1663: center and decimal tab stops beyond the text area right edge clamp so their content
|
||||
/// remains bounded by the margin without wrapping onto a new line.
|
||||
#[test]
|
||||
fn center_and_decimal_tab_stops_past_right_edge_align_without_wrapping() {
|
||||
let l_ctr = tabbed("\tCentered", &[(550.0, "ctr")], 500.0);
|
||||
assert_eq!(l_ctr.lines.len(), 1, "center stop must not wrap to a second line");
|
||||
assert!(
|
||||
(l_ctr.lines[0].extent.1 - l_ctr.inner.x1).abs() < 1.0,
|
||||
"text right edge {:?} should align with inner.x1 {}",
|
||||
l_ctr.lines[0].extent.1,
|
||||
l_ctr.inner.x1
|
||||
);
|
||||
|
||||
let l_dec = tabbed("\t123.45", &[(550.0, "dec")], 500.0);
|
||||
assert_eq!(l_dec.lines.len(), 1, "decimal stop must not wrap to a second line");
|
||||
assert!(
|
||||
(l_dec.lines[0].extent.1 - l_dec.inner.x1).abs() < 1.0,
|
||||
"text right edge {:?} should align with inner.x1 {}",
|
||||
l_dec.lines[0].extent.1,
|
||||
l_dec.inner.x1
|
||||
);
|
||||
|
||||
// Stops inside the margin remain untouched:
|
||||
let l_inside = tabbed("\tCentered", &[(300.0, "ctr")], 500.0);
|
||||
assert_eq!(l_inside.lines.len(), 1);
|
||||
let (s, e) = (l_inside.lines[0].edges[1].0, l_inside.lines[0].edges[8].1);
|
||||
assert!(((s + e) / 2.0 - l_inside.inner.x0 - 300.0).abs() < 1.0, "center stop inside margin must stay at 300.0");
|
||||
}
|
||||
|
||||
/// #1663: a tab whose following word fits on a fresh line but not in the remaining space
|
||||
/// moves to the next line with its word so alignment is preserved.
|
||||
#[test]
|
||||
fn tab_moves_to_next_line_with_word_when_word_does_not_fit_remaining_space() {
|
||||
for (align, suffix) in [("r", "Aligned"), ("ctr", "Aligned"), ("dec", "123.45")] {
|
||||
let l = tabbed(&format!("leading text here\t{suffix}"), &[(250.0, align)], 200.0);
|
||||
assert_eq!(l.lines.len(), 2, "{align}");
|
||||
assert_eq!(l.lines[1].start, 17, "tab must start line 2 for {align}");
|
||||
assert!((l.lines[1].extent.1 - l.inner.x1).abs() < 1.0, "suffix should end at the margin on line 2 for {align}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1663: trailing spaces after a tabbed word do not force the tab to wrap to a new line
|
||||
/// if the visible word fits in the remaining space.
|
||||
#[test]
|
||||
fn trailing_spaces_after_tab_do_not_force_line_break() {
|
||||
let l = tabbed("a\tWord ", &[(150.0, "r")], 200.0);
|
||||
assert_eq!(l.lines.len(), 1, "trailing spaces do not force a line break; fits on one line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_spaces_cannot_move_a_zero_advance_tab_with_visible_text_that_fits() {
|
||||
// Derive the width from the active font so only the trailing spaces exceed the margin.
|
||||
let probe = tabbed("leading text hereWord", &[], 1000.0);
|
||||
let width = probe.lines[0].extent.1 - probe.lines[0].extent.0 + 5.0;
|
||||
let insets = 1000.0 - probe.inner.width();
|
||||
for align in ["r", "ctr", "dec"] {
|
||||
let l = tabbed("leading text here\tWord ", &[(width + 50.0, align)], width + insets);
|
||||
assert_eq!(l.lines.len(), 1, "only trailing spaces overflow for {align}");
|
||||
assert!(l.lines[0].edges[21].1 <= l.inner.x1 + 0.01, "visible text fits for {align}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_does_not_move_with_a_segment_that_cannot_fit_at_the_fresh_default_stop() {
|
||||
let probe = tabbed("Word", &[], 1000.0);
|
||||
let word_w = probe.lines[0].extent.1 - probe.lines[0].extent.0;
|
||||
let insets = 1000.0 - probe.inner.width();
|
||||
// The word fits alone, but not after the 72 pt default tab on a fresh line.
|
||||
let l = tabbed("Word\tWord", &[], 72.0 + word_w / 2.0 + insets);
|
||||
assert_eq!(l.lines.len(), 2, "do not add a line for a tab whose segment still cannot fit");
|
||||
assert_eq!(l.lines[1].start, 5, "the tab stays on the first line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn left_and_default_tabs_still_wrap_between_the_words_after_them() {
|
||||
// Only right, centre and decimal stops keep their tab with the text after it. After a left or
|
||||
// default tab, words that fit on the first line stay there and the rest wraps between words.
|
||||
let tab_at = "Label text:".chars().count();
|
||||
for w in [200.0, 250.0] {
|
||||
for stops in [&[][..], &[(100.0, "l")][..]] {
|
||||
let l = tabbed("Label text:\tone two three four", stops, w);
|
||||
assert!(l.lines.len() >= 2, "{w}");
|
||||
assert!(
|
||||
l.lines[1].start > tab_at + 1,
|
||||
"the tab and a word after it stay on line 1 at {w}: {:?}",
|
||||
l.lines.iter().map(|x| (x.start, x.end)).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One paragraph `text` with a hanging indent (`marL`/`indent`), no bullet or explicit stops.
|
||||
fn hanging_tabbed(text: &str, margin: f64, indent: f64, w: f64) -> TextLayout {
|
||||
let (p, mut sh) = setup(text, w, 300.0);
|
||||
|
||||
@@ -40,6 +40,7 @@ skrifa = { workspace = true }
|
||||
# kittest's own dev-dependencies do not propagate; tests need both font features explicitly.
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
|
||||
memory-stats = "1.2.0"
|
||||
|
||||
[build-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -35,12 +35,7 @@ impl SlideApp {
|
||||
match self.session.active() {
|
||||
Some(d) => {
|
||||
let uid = d.uid;
|
||||
let name = d
|
||||
.path
|
||||
.as_deref()
|
||||
.and_then(|path| std::path::Path::new(path).file_name())
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| format!("{}.deckcraft", d.title()));
|
||||
let (name, _, _) = super::files::save_target(d.path.as_deref(), &d.title());
|
||||
match self.save_document(uid) {
|
||||
SaveOutcome::Saved | SaveOutcome::Downloaded => Ok(json!({"path": name})),
|
||||
SaveOutcome::Pending => Ok(json!({"path": name, "pending": true})),
|
||||
@@ -399,6 +394,16 @@ impl SlideApp {
|
||||
if fired.source == FireSource::Palette {
|
||||
CommandPalette::remember(&mut self.palette_recents, fired.command.clone());
|
||||
}
|
||||
// Ctrl+= and Ctrl+Shift+= are also Subscript and Superscript: the key formats while text or shapes are
|
||||
// selected and zooms only with nothing to format. Buttons keep zooming.
|
||||
let id = if id == "view.zoomIn"
|
||||
&& fired.source == FireSource::Key
|
||||
&& self.session.active().is_some_and(|d| d.selection.text.is_some() || !d.selection.shapes.is_empty())
|
||||
{
|
||||
if fired.mods.shift || ctx.input(|i| i.modifiers.shift) { "format.superscript" } else { "format.subscript" }
|
||||
} else {
|
||||
id
|
||||
};
|
||||
match id {
|
||||
"edit.paste" => self.paste(ctx, fired.pasted.clone()),
|
||||
"edit.copy" | "edit.cut" if fired.command.key_text().as_ref() == fired.command.id.as_str() => {
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{PickId, PickRequest, Picked, WriteIntent};
|
||||
use deckcraft_engine::cmd::file::{format_for_path, mark_saved_snapshot, save_bytes};
|
||||
use deckcraft_engine::cmd::file::{WRITABLE_EXTENSIONS, format_for_path, mark_saved_snapshot, save_bytes, writable_format_for_path};
|
||||
use deckcraft_model::Presentation;
|
||||
|
||||
use super::{FilePlace, FilePurpose, FileTarget, LocatedPlace, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, json, media};
|
||||
@@ -310,6 +310,9 @@ impl SlideApp {
|
||||
}
|
||||
|
||||
pub fn open_path(&mut self, path: &str) -> Result<(), String> {
|
||||
if self.show_if_open(path) {
|
||||
return Ok(());
|
||||
}
|
||||
let files = self.host.files();
|
||||
let loaded = deckcraft_engine::cmd::file::read_presentation_file_with(
|
||||
path,
|
||||
@@ -478,9 +481,10 @@ impl SlideApp {
|
||||
/// It opens as File › Open opens it on the desktop: a presentation as itself, an outline
|
||||
/// (.txt, .md, .rtf) as a new untitled presentation. The name is the presentation's file only
|
||||
/// when the page sent one with a presentation extension and the file is an intact
|
||||
/// presentation, so Save hands it back under that name and format; anything else (no name, an
|
||||
/// outline, a damaged file opened as a repaired copy) is untitled, and its first Save is a new
|
||||
/// file. The first presentation that opens takes the place of the empty one host mode started
|
||||
/// presentation, so Save hands it back under that name and format (except a type DeckCraft
|
||||
/// can't write, such as a legacy .slidecraft, which Save writes as a new .deckcraft); anything
|
||||
/// else (no name, an outline, a damaged file opened as a repaired copy) is untitled, and its
|
||||
/// first Save is a new file. The first presentation that opens takes the place of the empty one host mode started
|
||||
/// with ([`Self::start_for_host`]), if that one is still open, untitled and unchanged; later
|
||||
/// files open beside the others.
|
||||
pub fn open_from_host(&mut self, name: Option<&str>, bytes: &[u8]) {
|
||||
@@ -825,13 +829,17 @@ impl SlideApp {
|
||||
return outcome;
|
||||
};
|
||||
let snapshot = d.doc.clone();
|
||||
let own = d.path.clone();
|
||||
let name = own
|
||||
.as_deref()
|
||||
.and_then(|p| Path::new(p).file_name())
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("{}.deckcraft", d.title()));
|
||||
let bytes = match save_bytes(&snapshot, format_for_path(&name)) {
|
||||
let mut own = d.path.clone();
|
||||
let title = d.title();
|
||||
let (name, format, refused) = save_target(own.as_deref(), &title);
|
||||
if let Some(original) = refused {
|
||||
// A file DeckCraft can't write (.pptm, a legacy .slidecraft …) is never written in
|
||||
// place: Save asks for a new file instead, as an untitled document's Save does.
|
||||
let ext = Path::new(&name).extension().unwrap_or_default().to_string_lossy();
|
||||
self.set_status(format!("DeckCraft can't save {original} in its file type; choose a name to save a copy as .{ext}"));
|
||||
own = None;
|
||||
}
|
||||
let bytes = match save_bytes(&snapshot, format) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
let outcome = self.file_failure(e.to_string());
|
||||
@@ -1012,14 +1020,22 @@ impl SlideApp {
|
||||
path.to_path_buf()
|
||||
};
|
||||
let encoded;
|
||||
let bytes = if let Some(snapshot) = &transfer.snapshot
|
||||
&& format_for_path(name) != format_for_path(&out.to_string_lossy())
|
||||
{
|
||||
// The picker may choose a different writable extension; the captured snapshot stays fixed.
|
||||
encoded = save_bytes(snapshot, format_for_path(&out.to_string_lossy())).map_err(|e| e.to_string())?;
|
||||
&encoded
|
||||
} else {
|
||||
bytes
|
||||
let bytes = match &transfer.snapshot {
|
||||
Some(snapshot) => {
|
||||
// A document is never written under a name whose type DeckCraft can't write
|
||||
// (a Save As typed back to .pptm): its bytes would not be that type.
|
||||
let format = writable_format_for_path(&out.to_string_lossy()).ok_or_else(|| {
|
||||
format!("DeckCraft can't save the file type of {}; it saves as .{}", out.display(), WRITABLE_EXTENSIONS.join(", ."))
|
||||
})?;
|
||||
if format == format_for_path(name) {
|
||||
bytes
|
||||
} else {
|
||||
// The picker may choose a different writable extension; the captured snapshot stays fixed.
|
||||
encoded = save_bytes(snapshot, format).map_err(|e| e.to_string())?;
|
||||
&encoded
|
||||
}
|
||||
}
|
||||
None => bytes,
|
||||
};
|
||||
self.host.files().write(&out, bytes, intent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
@@ -1027,6 +1043,27 @@ impl SlideApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file name Save writes or suggests for a document at `path` titled `title`, the format it
|
||||
/// is written in, and, when the file at `path` is of a type DeckCraft can't write, that file's
|
||||
/// name: Save never writes it in place but asks for `<title>.pptx` (`<title>.deckcraft` for a
|
||||
/// legacy `.slidecraft`) instead. An untitled document is suggested `<title>.deckcraft`.
|
||||
pub(crate) fn save_target(path: Option<&str>, title: &str) -> (String, &'static str, Option<String>) {
|
||||
let Some(current) = path.and_then(|p| Path::new(p).file_name()).map(|n| n.to_string_lossy().into_owned()) else {
|
||||
let name = format!("{title}.deckcraft");
|
||||
let format = format_for_path(&name);
|
||||
return (name, format, None);
|
||||
};
|
||||
match writable_format_for_path(¤t) {
|
||||
Some(format) => (current, format, None),
|
||||
None => {
|
||||
let ext = if current.to_ascii_lowercase().ends_with(".slidecraft") { "deckcraft" } else { "pptx" };
|
||||
let name = format!("{title}.{ext}");
|
||||
let format = format_for_path(&name);
|
||||
(name, format, Some(current))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn image_file_name(stem: &str, ext: &str, index: usize, single: bool) -> String {
|
||||
if single { format!("{stem}.{ext}") } else { format!("{stem}{}.{ext}", index + 1) }
|
||||
}
|
||||
|
||||
@@ -249,6 +249,56 @@ fn save_as_and_export_run_the_file_commands() {
|
||||
assert_eq!(files.requests().len(), picks, "saving in place asks for no path");
|
||||
}
|
||||
|
||||
/// The bug this prevents: Save of an opened .pptm (Open XML bytes, so it keeps its path) wrote
|
||||
/// native DeckCraft bytes over it in place.
|
||||
#[test]
|
||||
fn save_of_an_opened_pptm_asks_for_a_new_file_and_leaves_it_alone() {
|
||||
let original = deckcraft_engine::cmd::file::save_bytes(&Session::with_new().doc().unwrap().doc, "pptx").unwrap();
|
||||
let pptm = Path::new("deck.pptm");
|
||||
let files = Arc::new(ScriptedFiles::new().saving_suggested().with_file(pptm, original.clone()));
|
||||
let mut h = harness(Session::new(), files.clone());
|
||||
h.state_mut().open_path("deck.pptm").unwrap();
|
||||
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("deck.pptm"));
|
||||
h.state_mut().run("slide.new", json!({})).unwrap();
|
||||
let slides = h.state().session.active().unwrap().doc.slides.len();
|
||||
|
||||
h.state_mut().save();
|
||||
|
||||
assert_eq!(files.file(pptm), Some(original), "the macro-enabled file is never written");
|
||||
let requests = files.requests();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].kind, PickKind::Save);
|
||||
assert!(requests[0].save_as);
|
||||
let copy = saved_path(&files, "pptx");
|
||||
assert_ne!(copy.as_path(), pptm);
|
||||
let doc = h.state().session.active().unwrap();
|
||||
assert_eq!(doc.path.as_deref(), copy.to_str());
|
||||
assert!(!doc.is_dirty());
|
||||
let mut reopened = Session::new();
|
||||
reopened
|
||||
.execute("file.openBytes", &json!({"name": "copy.pptx", "data": deckcraft_engine::cmd::base64_encode(&files.file(©).unwrap())}))
|
||||
.unwrap();
|
||||
assert_eq!(reopened.doc().unwrap().doc.slides.len(), slides, "the copy is a PowerPoint file with the edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_to_an_unwritable_extension_is_refused() {
|
||||
let files = Arc::new(ScriptedFiles::answering([Picked::Saved { path: PathBuf::from("other.pptm"), file_type: None }]));
|
||||
let mut h = harness(Session::with_new(), files.clone());
|
||||
h.state_mut().run("slide.new", json!({})).unwrap();
|
||||
let before = h.state().session.active().unwrap().path.clone();
|
||||
|
||||
h.state_mut().save_as_dialog("deckcraft");
|
||||
|
||||
assert!(files.file(Path::new("other.pptm")).is_none(), "nothing is written under a type DeckCraft can't write");
|
||||
assert!(files.written().is_empty());
|
||||
let status = h.state().status.as_ref().map(|(msg, _)| msg.clone()).unwrap_or_default();
|
||||
assert!(status.contains("file type"), "the status says why: {status}");
|
||||
let doc = h.state().session.active().unwrap();
|
||||
assert!(doc.is_dirty());
|
||||
assert_eq!(doc.path, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_file_type_exports_all_slides_as_pictures() {
|
||||
let files = Arc::new(ScriptedFiles::new().saving_suggested());
|
||||
|
||||
@@ -32,10 +32,23 @@ impl Opening {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path as compared for "the same file": resolved on disk where it exists (so `a/../deck.pptx`
|
||||
/// and a different case on Windows match), else as given.
|
||||
fn same_file_key(path: &str) -> std::path::PathBuf {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Ok(p) = std::fs::canonicalize(path) {
|
||||
return p;
|
||||
}
|
||||
std::path::PathBuf::from(path)
|
||||
}
|
||||
|
||||
impl SlideApp {
|
||||
/// Open `path` through the host's queue while showing progress.
|
||||
/// The browser opens through its host bytes immediately.
|
||||
pub fn open_path_in_background(&mut self, path: &str) {
|
||||
if self.show_if_open(path) {
|
||||
return;
|
||||
}
|
||||
if let Some(o) = &self.opening {
|
||||
let name = o.name();
|
||||
self.set_status(format!("Still opening {name}"));
|
||||
@@ -56,6 +69,21 @@ impl SlideApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// When the presentation at `path` is already open, bring it forward instead of reading the
|
||||
/// file again, as PowerPoint does: a second copy from disk would show none of the unsaved
|
||||
/// edits, which look lost (#2191). Returns whether it was open.
|
||||
pub(crate) fn show_if_open(&mut self, path: &str) -> bool {
|
||||
let wanted = same_file_key(path);
|
||||
let Some(i) = self.session.documents().iter().position(|d| d.path.as_deref().is_some_and(|p| same_file_key(p) == wanted)) else {
|
||||
return false;
|
||||
};
|
||||
self.session.set_active(i);
|
||||
let title = self.session.active().map(|d| d.title()).unwrap_or_default();
|
||||
self.note_recent(path);
|
||||
self.set_status(format!("{title} is already open"));
|
||||
true
|
||||
}
|
||||
|
||||
/// Stop waiting for the file being opened; the presentation stays as it is.
|
||||
pub fn cancel_opening(&mut self) {
|
||||
if let Some(o) = self.opening.take() {
|
||||
@@ -205,6 +233,33 @@ mod tests {
|
||||
assert_eq!(h.state().session.journal.iter().filter(|(id, _)| id == "file.adopt").count(), before_adopts + 1);
|
||||
}
|
||||
|
||||
/// #2191: opening the file that is already open shows it, unsaved edits and all, instead of
|
||||
/// a fresh copy from disk.
|
||||
#[test]
|
||||
fn opening_an_open_file_shows_it_with_its_edits() {
|
||||
let (path, bytes) = saved_as("reopen.deckcraft", 2);
|
||||
let files = Arc::new(ScriptedFiles::new().with_file(&path, bytes));
|
||||
let mut h = scripted(Session::new(), files);
|
||||
inline_jobs(&mut h);
|
||||
h.state_mut().open_path_in_background(&path);
|
||||
finish(&mut h);
|
||||
h.state_mut().run("slide.new", serde_json::json!({})).unwrap();
|
||||
h.state_mut().run("file.new", serde_json::json!({})).unwrap();
|
||||
assert_eq!(h.state().session.active_index(), Some(1));
|
||||
h.state_mut().open_path_in_background(&path);
|
||||
assert!(h.state().opening.is_none(), "nothing is read from disk");
|
||||
assert_eq!(h.state().session.documents().len(), 2, "no second copy");
|
||||
assert_eq!(h.state().session.active_index(), Some(0), "the open copy comes forward");
|
||||
let st = h.state().session.active().unwrap();
|
||||
assert!(st.is_dirty());
|
||||
assert_eq!(st.doc.slides.len(), 3, "with its unsaved slide");
|
||||
assert!(h.state().fresh_status().is_some_and(|m| m.ends_with("is already open")));
|
||||
// The synchronous path does the same.
|
||||
h.state_mut().session.set_active(1);
|
||||
h.state_mut().open_path(&path).unwrap();
|
||||
assert_eq!((h.state().session.documents().len(), h.state().session.active_index()), (2, Some(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_drops_the_result() {
|
||||
let (path, bytes) = saved_as("cancel.deckcraft", 2);
|
||||
@@ -294,7 +349,9 @@ mod tests {
|
||||
assert!(h.state_mut().open_from_system(std::slice::from_ref(&pptx)).is_empty());
|
||||
assert!(h.state().show.is_none());
|
||||
assert!(h.state_mut().open_from_system(&[ppsx.clone(), pptx.clone()]).is_empty());
|
||||
assert_eq!(h.state().session.documents().len(), 3);
|
||||
// The .pptx is already open, so it comes forward instead of opening twice (#2191).
|
||||
assert_eq!(h.state().session.documents().len(), 2);
|
||||
assert!(h.state().session.active().is_some_and(|d| d.path.as_deref() == Some(pptx.as_str())));
|
||||
assert!(h.state().show.is_none(), "the last file is a .pptx");
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,9 @@ pub struct Show {
|
||||
slide_start: f64,
|
||||
step_end: f64,
|
||||
trans: Option<Transition>,
|
||||
/// When an input cut the slide's transition short (#2084): timed advancement waits until a
|
||||
/// later pass, so the revealed slide is drawn before an elapsed After timing moves on.
|
||||
trans_cut: Option<f64>,
|
||||
remote_preview: Option<crate::presenter::Preview>,
|
||||
/// All slides thumbnails sent to the web presenter window while its grid is open (#1866).
|
||||
remote_grid: Vec<crate::presenter::Preview>,
|
||||
@@ -218,6 +221,7 @@ impl Show {
|
||||
slide_start: 0.0,
|
||||
step_end: 0.0,
|
||||
trans: None,
|
||||
trans_cut: None,
|
||||
remote_preview: None,
|
||||
remote_grid: vec![],
|
||||
remote_sent: f64::NEG_INFINITY,
|
||||
@@ -358,7 +362,8 @@ impl Show {
|
||||
let cur_step = self.state.step;
|
||||
let n_steps = self.timeline(doc).steps();
|
||||
let step_due = self.autoplay && cur_step < n_steps && idle > AUTOPLAY_DELAY;
|
||||
let holding = self.clock_navigation_held();
|
||||
// The pass whose input cut the transition short draws the revealed slide first.
|
||||
let holding = self.clock_navigation_held() || self.trans_cut.is_some_and(|cut| now <= cut);
|
||||
if !holding && (step_due || (!self.rehearse && self.state.auto_advance_due(doc, idle) && !self.ended)) {
|
||||
actions.push(self.state.next(doc));
|
||||
} else if self.preview_only && cur_step >= n_steps && idle > PREVIEW_DELAY {
|
||||
@@ -368,6 +373,19 @@ impl Show {
|
||||
true
|
||||
}
|
||||
|
||||
/// A click, a forward key, the wheel or a Next button while the slide's transition is still
|
||||
/// playing finishes the transition instead of going on, as PowerPoint does (#2084): the slide
|
||||
/// shows in full and the next animation waits for another input. Returns whether a transition
|
||||
/// was cut short.
|
||||
pub(crate) fn finish_transition(&mut self, now: f64) -> bool {
|
||||
let playing = self.trans.as_ref().is_some_and(|t| now - t.start < t.dur.max(0.01));
|
||||
if playing {
|
||||
self.trans = None;
|
||||
self.trans_cut = Some(now);
|
||||
}
|
||||
playing
|
||||
}
|
||||
|
||||
/// The clock origins used by the show, for deterministic hidden/resume regressions.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clock_snapshot(&self) -> ClockSnapshot {
|
||||
|
||||
@@ -151,6 +151,9 @@ pub(crate) fn run_command(
|
||||
if show.ended {
|
||||
keep = false;
|
||||
None
|
||||
} else if show.finish_transition(now) {
|
||||
// While the slide's transition plays, Next only finishes it (#2084).
|
||||
None
|
||||
} else {
|
||||
Some(show.state.next(doc))
|
||||
}
|
||||
|
||||
@@ -1620,3 +1620,89 @@ fn transition_preview_for_first_slide_transitions_from_black() {
|
||||
assert_eq!(tr.from, None, "slide 0 transitions from black (None)");
|
||||
assert_eq!(tr.dur, 0.5);
|
||||
}
|
||||
|
||||
/// A two-slide show whose second slide comes in with a 3 s fade, played at 0.25 s a frame.
|
||||
fn show_with_slow_fade(after_ms: Option<u32>) -> egui_kittest::Harness<'static, SlideApp> {
|
||||
let mut session = deckcraft_engine::Session::with_new();
|
||||
session.execute("slide.new", &json!({})).unwrap();
|
||||
session.execute("transition.set", &json!({"kind": "fade", "index": 1, "duration": 3000})).unwrap();
|
||||
session.execute("transition.timing", &json!({"index": 1, "after": after_ms})).unwrap();
|
||||
let id = session.active().unwrap().doc.slides[1].shapes[0].id;
|
||||
session.execute("animation.add", &json!({"effect": "fade", "class": "entrance", "ids": [id.0], "start": "onClick", "duration": 500})).unwrap();
|
||||
let mut harness =
|
||||
harness_with(session, Services::default(), egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(0.25), |_| {});
|
||||
harness.state_mut().ui.presenter_view = false;
|
||||
harness.run_steps(3);
|
||||
harness.state_mut().start_show(0, false);
|
||||
harness.run_steps(2);
|
||||
harness
|
||||
}
|
||||
|
||||
/// (slide, step, playing, transition still playing) of the running show.
|
||||
fn fade_state(harness: &egui_kittest::Harness<'static, SlideApp>) -> (usize, usize, bool, bool) {
|
||||
let show = harness.state().show.as_ref().unwrap();
|
||||
(show.state.slide, show.state.step, show.state.playing, show.trans.is_some())
|
||||
}
|
||||
|
||||
/// #2084: a click, →/Space or the wheel while the slide's transition plays finishes the
|
||||
/// transition and does not start the slide's first On Click animation; the next one does.
|
||||
#[test]
|
||||
fn a_click_during_a_transition_only_finishes_it() {
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true), "slide 2 comes in with its 3 s fade");
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "→ finishes the fade, the animation waits");
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, true, false), "the next → plays the animation");
|
||||
|
||||
// A mouse click does the same.
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true));
|
||||
let center = pos2(500.0, 350.0);
|
||||
harness.hover_at(center);
|
||||
harness.run_steps(1);
|
||||
click_at(&mut harness, center);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "a click finishes the fade, the animation waits");
|
||||
click_at(&mut harness, center);
|
||||
assert_eq!(fade_state(&harness), (1, 0, true, false), "the next click plays the animation");
|
||||
|
||||
// So does a wheel notch forward.
|
||||
let mut harness = show_with_slow_fade(None);
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(1);
|
||||
harness.hover_at(center);
|
||||
harness.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: vec2(0.0, -1.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
});
|
||||
harness.run_steps(1);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, false), "the wheel finishes the fade, the animation waits");
|
||||
}
|
||||
|
||||
/// #2084: with Use Timings and an After timing shorter than the time the fade has run, the
|
||||
/// input that cuts the fade short draws the revealed slide before the timing moves on.
|
||||
#[test]
|
||||
fn finishing_a_transition_holds_an_elapsed_after_timing_for_that_pass() {
|
||||
let mut harness = show_with_slow_fade(Some(500));
|
||||
harness.key_press(egui::Key::ArrowRight);
|
||||
harness.run_steps(4);
|
||||
assert_eq!(fade_state(&harness), (1, 0, false, true), "a second into the 3 s fade");
|
||||
let doc = harness.state().session.active().unwrap().doc.clone();
|
||||
let show = harness.state_mut().show.as_mut().unwrap();
|
||||
let now = show.trans.as_ref().unwrap().start + 1.0;
|
||||
assert!(show.finish_transition(now));
|
||||
let mut actions = Vec::new();
|
||||
assert!(show.queue_clock_actions(&doc, now, &mut actions));
|
||||
assert!(actions.is_empty(), "the pass that finished the fade queues no timed step: {actions:?}");
|
||||
assert!(show.queue_clock_actions(&doc, now + 0.25, &mut actions));
|
||||
assert!(!actions.is_empty(), "a later pass takes the elapsed After timing");
|
||||
}
|
||||
|
||||
@@ -71,9 +71,11 @@ impl ShowTool<'_> {
|
||||
self.under = if self.on_slide() { shapes_under_pointer(self.show, self.doc, at, now) } else { None };
|
||||
}
|
||||
|
||||
fn next(&mut self) {
|
||||
fn next(&mut self, now: f64) {
|
||||
if self.show.ended {
|
||||
self.out.keep = false;
|
||||
} else if self.show.finish_transition(now) {
|
||||
// The wheel only finishes the slide's transition while it plays (#2084).
|
||||
} else {
|
||||
self.out.actions.push(self.show.state.next(self.doc));
|
||||
}
|
||||
@@ -121,7 +123,8 @@ impl CanvasTool for ShowTool<'_> {
|
||||
let notch = f64::from(NavigationOptions::default().wheel_line);
|
||||
if let Some(next) = wheel_turn(&wheel, Some(forward), notch, TurnAxis::Stronger) {
|
||||
if next {
|
||||
self.next();
|
||||
let now = self.time(cx);
|
||||
self.next(now);
|
||||
} else {
|
||||
self.previous();
|
||||
}
|
||||
@@ -236,6 +239,8 @@ impl CanvasTool for ShowTool<'_> {
|
||||
self.out.keep = false;
|
||||
} else if self.show.blank.is_some() {
|
||||
self.show.blank = None;
|
||||
} else if self.show.finish_transition(now) {
|
||||
// The click only finishes the slide's transition (#2084).
|
||||
} else {
|
||||
let none = Under::default();
|
||||
match self.show.click_slide(self.doc, self.under.as_ref().unwrap_or(&none), now) {
|
||||
|
||||
@@ -147,7 +147,7 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
// gestures keep the canvas's own page turn.
|
||||
show.wheel_taken = false;
|
||||
if !show.pen && !show.zoomed {
|
||||
wheel_lines(&ctx, show, p.doc, out);
|
||||
wheel_lines(&ctx, show, p.doc, p.now, out);
|
||||
}
|
||||
let mut media_wake = None;
|
||||
with_env(
|
||||
@@ -232,7 +232,7 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
/// and free-spin wheels send fractions of a line, accumulated in `show.wheel_carry`; a change of
|
||||
/// direction drops the leftover. The line events are taken out of the frame so the canvas's own
|
||||
/// wheel navigation does not turn the page a second time.
|
||||
fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, out: &mut Out) {
|
||||
fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, now: f64, out: &mut Out) {
|
||||
// A multi-pass layout replays the frame's events; only the pass that is kept may move slides,
|
||||
// but every pass must take the lines out so the canvas does not also turn the page.
|
||||
let act = !ctx.will_discard();
|
||||
@@ -293,6 +293,10 @@ fn wheel_lines(ctx: &egui::Context, show: &mut Show, doc: &Presentation, out: &m
|
||||
continue;
|
||||
}
|
||||
let forward = by > 0;
|
||||
// A forward notch only finishes the slide's transition while it plays (#2084).
|
||||
if forward && show.finish_transition(show.clock(now)) {
|
||||
continue;
|
||||
}
|
||||
match show.state.visible_step_clamped(doc, show.state.slide, forward, count) {
|
||||
Some(target) if target != show.state.slide => out.actions.push(show.state.goto(doc, target)),
|
||||
Some(_) | None if forward => {
|
||||
|
||||
@@ -23,6 +23,16 @@ const MAX_JOURNAL: usize = 10_000;
|
||||
/// Mean wall time per frame, generous for slow CI machines (the test profile is optimized).
|
||||
const MAX_MEAN_FRAME: Duration = Duration::from_millis(250);
|
||||
|
||||
/// RSS growth allowed between the warmed-up start and the end of a soak; generous because
|
||||
/// `cargo test` threads share the process.
|
||||
const MAX_RSS_GROWTH: u64 = 256 << 20;
|
||||
|
||||
/// Physical memory in use, in bytes: the resident set size on Linux and macOS, the working set on
|
||||
/// Windows. `None` where the platform cannot say.
|
||||
fn rss_bytes() -> Option<u64> {
|
||||
memory_stats::memory_stats().map(|m| m.physical_mem as u64)
|
||||
}
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
@@ -161,6 +171,7 @@ fn soak(seed: u64, steps: usize) {
|
||||
let mut log = VecDeque::new();
|
||||
let t0 = Instant::now();
|
||||
let mut frames = 0usize;
|
||||
let mut rss_start = None;
|
||||
for step in 0..steps {
|
||||
log.push_back(act(&mut h, &mut r));
|
||||
if log.len() > 20 {
|
||||
@@ -168,6 +179,11 @@ fn soak(seed: u64, steps: usize) {
|
||||
}
|
||||
h.run_steps(2);
|
||||
frames += 8;
|
||||
// Sample after a quarter of the run and its frames, so texture caches and allocator arenas
|
||||
// are warm. Short runs sample only after their first completed action.
|
||||
if step + 1 == (steps / 4).max(1) {
|
||||
rss_start = rss_bytes();
|
||||
}
|
||||
if step % 10 == 9 {
|
||||
check(&h, seed, step, &log);
|
||||
}
|
||||
@@ -184,6 +200,11 @@ fn soak(seed: u64, steps: usize) {
|
||||
let mean = t0.elapsed() / frames.max(1) as u32;
|
||||
eprintln!("ui soak seed {seed}: {steps} actions, {edits} commands, ~{frames} frames, mean frame {mean:?}");
|
||||
assert!(mean <= MAX_MEAN_FRAME, "mean frame {mean:?} over {MAX_MEAN_FRAME:?}; seed {seed}");
|
||||
if let (Some(start), Some(end)) = (rss_start, rss_bytes()) {
|
||||
let grew = end.saturating_sub(start);
|
||||
eprintln!("ui soak seed {seed}: memory {} -> {} MiB", start >> 20, end >> 20);
|
||||
assert!(grew <= MAX_RSS_GROWTH, "memory grew {} MiB over {} MiB; seed {seed}", grew >> 20, MAX_RSS_GROWTH >> 20);
|
||||
}
|
||||
}
|
||||
|
||||
fn env(name: &str, default: u64) -> u64 {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
//! #1926: Ctrl+= (Subscript) and Ctrl+Shift+= (Superscript) zoomed or twitched the screen instead.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_ui_egui::{Platform, Services, SlideApp};
|
||||
use egui::{Key, Modifiers};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
struct Window(SlideApp);
|
||||
|
||||
impl eframe::App for Window {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.0.raw_input_hook(ctx, raw);
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.0.logic(ctx);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
self.0.ui(ui);
|
||||
}
|
||||
}
|
||||
|
||||
fn window(cc: &mut eframe::CreationContext<'_>, session: Session) -> Window {
|
||||
let host = craft::host::Host::builder(craft::host::AppInfo { id: "deckcraft", name: "DeckCraft", version: "0" })
|
||||
.files(Arc::new(craft::host::ScriptedFiles::new()))
|
||||
.build();
|
||||
let clipboard = craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::MemoryClipboard::default());
|
||||
let platform = Platform {
|
||||
install: craft::ui::runtime::InstallSpec::new(Default::default(), Arc::new(craft::window::system::SystemWindows))
|
||||
.app_id("deckcraft")
|
||||
.clipboard(clipboard),
|
||||
host,
|
||||
settings: craft::settings::Location::Memory,
|
||||
intake: None,
|
||||
audio_out: None,
|
||||
control: None,
|
||||
frame: craft::window::policy::Frame::Native,
|
||||
at_exit: None,
|
||||
};
|
||||
let mut app = SlideApp::new(&cc.egui_ctx, platform).unwrap_or_else(|error| panic!("window installation failed: {error}"));
|
||||
app.session = session;
|
||||
app.services = Services::default();
|
||||
Window(app)
|
||||
}
|
||||
|
||||
fn harness_of(session: Session) -> Harness<'static, Window> {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |cc| window(cc, session));
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn harness() -> Harness<'static, Window> {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("shape.insert", &json!({"preset": "rect", "rect": [80.0, 80.0, 320.0, 80.0], "text": "Hello"})).unwrap();
|
||||
// A selected shape, not a caret: the shortcuts then format the text that is already there.
|
||||
let _ = s.execute("text.exit", &json!({}));
|
||||
harness_of(s)
|
||||
}
|
||||
|
||||
fn baseline_of(h: &Harness<'_, Window>) -> Option<f64> {
|
||||
let st = h.state().0.session.active().unwrap();
|
||||
st.selected_shapes()
|
||||
.first()
|
||||
.and_then(|sh| sh.text.as_ref())
|
||||
.and_then(|t| t.paragraphs.first())
|
||||
.and_then(|p| p.runs.first())
|
||||
.and_then(|r| r.props.baseline)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_equals_subscripts_without_zooming() {
|
||||
let mut h = harness();
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Equals);
|
||||
h.run_steps(1);
|
||||
assert_eq!(baseline_of(&h), Some(-0.25), "status {:?}", h.state().0.status);
|
||||
assert!(!h.ctx.options(|o| o.zoom_with_keyboard), "egui's own keyboard zoom must not act on Ctrl+=");
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
assert!(h.state().0.ui.zoom.is_none(), "Ctrl+= must not zoom the slide while there is text to format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_shift_equals_superscripts_without_zooming() {
|
||||
let mut h = harness();
|
||||
// Ctrl+Shift+= is the shifted character, so egui reports it as `Plus`.
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, Key::Plus);
|
||||
h.run_steps(1);
|
||||
assert_eq!(baseline_of(&h), Some(0.3), "status {:?}", h.state().0.status);
|
||||
assert!(!h.ctx.options(|o| o.zoom_with_keyboard), "egui's own keyboard zoom must not act on Ctrl+Shift+=");
|
||||
assert_eq!(h.ctx.zoom_factor(), 1.0);
|
||||
assert!(h.state().0.ui.zoom.is_none(), "Ctrl+Shift+= must not zoom the slide while there is text to format");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctrl_equals_zooms_with_nothing_to_format() {
|
||||
let mut h = harness_of(Session::with_new());
|
||||
h.key_press_modifiers(Modifiers::COMMAND, Key::Equals);
|
||||
h.run_steps(1);
|
||||
assert!(h.state().0.ui.zoom.is_some(), "Ctrl+= zooms in when no text or shape is selected");
|
||||
}
|
||||
@@ -60,6 +60,26 @@ comes from `anim::timeline` each frame. Animations ▸ Preview plays that same s
|
||||
canvas for the current slide, then draws the slide at rest. PDF export renders each slide at print resolution and
|
||||
overlays an invisible real-text layer with embedded font subsets.
|
||||
|
||||
### Text tab alignment and wrapping
|
||||
|
||||
Tab positions, the current cursor and the right edge share the text column's start-edge
|
||||
coordinate system. Breaking and placement use the same absolute right edge (`x0 + avail`),
|
||||
including paragraph indents and right margins. Explicit stops are sorted once and selected
|
||||
by their configured positions before any clamping.
|
||||
|
||||
Beyond the right edge, right-aligned segments end at the margin. Center and decimal stops
|
||||
also account for the segment width after their alignment point, keeping the whole segment
|
||||
inside the margin when it fits without moving backward. Stops at or inside the edge keep
|
||||
their alignment points, even when their suffix extends past the margin. Left stops beyond
|
||||
the edge also clamp to it; default stops retain their regular grid.
|
||||
|
||||
Wrapping measures the following segment up to the next tab or line break. If its visible
|
||||
text does not fit here but fits together with its tab on a fresh line, the tab moves with
|
||||
it; trailing whitespace alone cannot trigger that move. Oversized segments still use
|
||||
ordinary wrapping. The hanging-indent implicit stop applies only to LTR first lines, and
|
||||
competes with explicit stops at their effective clamped positions. Fresh-line fit checks
|
||||
never reuse that first-line-only stop.
|
||||
|
||||
## File I/O
|
||||
|
||||
- **PPTX** (`crates/pptx`): lenient reader (unknown parts skipped, malformed parts logged and
|
||||
@@ -87,6 +107,7 @@ macOS, Windows, Linux, FreeBSD and web artifacts.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-30 | minor | PR #1671 merge: center/decimal tab clamping and visible-segment wrapping retain absolute-edge coordinates, binary-search stop selection and first-line hanging-indent behavior |
|
||||
| 2026-11-12 | trivial | The `metafile` crate is gone: `render` reads EMF/WMF with craft-metafile from craft-libs |
|
||||
| 2026-11-12 | trivial | The `bitstream`, `h264`, `hevc`, `vp9` and `av1` crates are gone: `media` decodes video with craft-video from craft-libs |
|
||||
| 2026-11-11 | trivial | The `opus`, `ogg`, `isobmff` and `matroska` crates are gone: `media` uses craft-audio and craft-media from craft-libs |
|
||||
|
||||
+9
-4
@@ -49,7 +49,7 @@ revision history.
|
||||
- **Estimate:** 4–8 h (backend probing outside the process or a safe-mode fallback, a software
|
||||
renderer path). Needs a tester with the hardware. **Beta blocker.**
|
||||
|
||||
### Soak testing has no memory or timing budgets
|
||||
### Soak memory budgets run in CI on Linux only
|
||||
- **Evidence:** `crates/engine/src/soak_tests.rs` runs seeded random command sequences over a
|
||||
~100-slide deck (validity, selection, undo/redo exactness, bounded undo, save/reopen in both
|
||||
formats every 100 steps); `DECKCRAFT_SOAK_STEPS` runs it long. It found a chart `clamp` panic
|
||||
@@ -57,9 +57,13 @@ revision history.
|
||||
seeded random clicks, drags, keys (plain, Ctrl, Shift), typing and scrolling over the sample
|
||||
deck, checking document validity, bounded undo/journal/thumbnail/texture caches, zero caught
|
||||
command and render panics (`Session::panics_caught`, `deckcraft_render::panics_caught`) and a
|
||||
mean frame under 250 ms; 4 × 3000-action runs are clean.
|
||||
- **Impact:** long-session crash rate is sampled in CI; RSS is not measured directly.
|
||||
- **Estimate:** 1–2 h (RSS sampling per platform).
|
||||
mean frame under 250 ms; 4 × 3000-action runs are clean. Both soaks also sample resident memory
|
||||
(`memory-stats`: `/proc` on Linux, `GetProcessMemoryInfo` on Windows, Mach task info on macOS)
|
||||
after a quarter of the run and fail if it then grows by more than 256 MiB.
|
||||
- **Impact:** long-session crash rate is sampled in CI; the RSS budget is only exercised on Linux
|
||||
(`ci.yml`), and the Windows and macOS code paths have never run in CI. The engine soak has no
|
||||
wall-time budget.
|
||||
- **Estimate:** 1 h (a Windows and macOS test job; a timing budget).
|
||||
|
||||
## File formats
|
||||
|
||||
@@ -370,6 +374,7 @@ Detail in [localization-parity.md](localization-parity.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-26 | trivial | The engine and UI soaks fail if resident memory grows by more than 256 MiB after warm-up (through `memory-stats`: Linux, Windows and macOS; only Linux runs in CI) |
|
||||
| 2026-11-02 | trivial | Run alternate-language metadata now survives native and PPTX saves; UI and proofing gaps remain; scores unchanged |
|
||||
| 2026-11-02 | trivial | PPTX reflection geometry is retained through native and PPTX resaves; no rendering parity claim |
|
||||
| 2026-11-02 | trivial | Reused slide geometry and content scale to the destination; picker thumbnails remain the reuse gap |
|
||||
|
||||
Reference in New Issue
Block a user