mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-04 03:27:50 -06:00
Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
052435f0d2 | ||
|
|
c405f4005f | ||
|
|
076a95b713 | ||
|
|
577ada30b4 | ||
|
|
75c29c27db | ||
|
|
e7b67fb029 | ||
|
|
8413f81acd | ||
|
|
628777ddad | ||
|
|
655c4d2490 | ||
|
|
6e3f978dd6 | ||
|
|
86c8111089 | ||
|
|
ce493cf0af | ||
|
|
ec62fd85d5 | ||
|
|
2c6699ad4d | ||
|
|
98cc22869d | ||
|
|
6eb23b7779 | ||
|
|
6526e3783a | ||
|
|
abc82cb4cb | ||
|
|
3a6082b4b9 | ||
|
|
56d84237ad | ||
|
|
68f2a099f3 | ||
|
|
80cc9b65c8 | ||
|
|
432db38d6a | ||
|
|
e8c207e673 | ||
|
|
cf7d35c955 | ||
|
|
0da7712a29 | ||
|
|
488aca4e7f | ||
|
|
4f959912b4 | ||
|
|
f9a328a147 | ||
|
|
d01e5a1c5e | ||
|
|
fce2a88d31 | ||
|
|
e00af8eea2 | ||
|
|
e1ce3b95eb | ||
|
|
ca1cc70a30 | ||
|
|
237718c81a | ||
|
|
2ee3785c5e | ||
|
|
5503791117 | ||
|
|
4ca6a795d9 | ||
|
|
43815b285f | ||
|
|
eec73f3396 | ||
|
|
75f798124e | ||
|
|
62e00839c7 | ||
|
|
6921db0f83 | ||
|
|
d163b84e53 | ||
|
|
4bc331c46d | ||
|
|
cca3f4ba8b | ||
|
|
74f6e2c9b4 | ||
|
|
77cc922b7f | ||
|
|
e79e653839 | ||
|
|
6c068ffc30 | ||
|
|
77d0ad61c2 | ||
|
|
6cee207f77 | ||
|
|
7a51671ebd | ||
|
|
d5741616c1 | ||
|
|
877e6db673 | ||
|
|
b697455ea7 | ||
|
|
5c179822d9 |
Generated
+1
@@ -2469,6 +2469,7 @@ name = "deckcraft-engine"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-metafile",
|
||||
"craft-mime",
|
||||
"deckcraft-anim",
|
||||
"deckcraft-color",
|
||||
|
||||
@@ -40,7 +40,7 @@ pub use interact::{Click, HitShape, Target};
|
||||
pub use mesh::{MeshVertex, layer_mesh};
|
||||
pub use morph::{MorphFrame, MorphPath, MorphText, morph_crop, morph_frame, morph_pairs, morph_xfrm};
|
||||
pub use path::{MotionPath, default_path};
|
||||
pub use show::{LinkJump, ShowAction, ShowState, safe_url, show_order};
|
||||
pub use show::{LinkJump, ShowAction, ShowState, looping, safe_url, show_order};
|
||||
pub use timeline::{EffectTiming, Sequence, StepStamp, Timeline, TriggerPlay};
|
||||
pub use transition::{DEFAULT_ASPECT, Layer, Source, transition_frame, transition_layers, uses_slide_parts};
|
||||
|
||||
|
||||
+45
-10
@@ -117,7 +117,7 @@ fn custom_indices(pres: &Presentation, name: &str) -> Option<Vec<usize>> {
|
||||
if order.is_empty() { None } else { Some(order) }
|
||||
}
|
||||
|
||||
fn looping(pres: &Presentation) -> bool {
|
||||
pub fn looping(pres: &Presentation) -> bool {
|
||||
pres.show.loop_until_esc || pres.show.show_type == "kiosk"
|
||||
}
|
||||
|
||||
@@ -236,19 +236,54 @@ impl ShowState {
|
||||
}
|
||||
|
||||
fn next_index(&self, pres: &Presentation) -> Option<usize> {
|
||||
let order = self.visit(pres);
|
||||
match order.iter().position(|&i| i == self.slide) {
|
||||
Some(p) => order.get(p + 1).copied(),
|
||||
None => order.iter().copied().find(|&i| i > self.slide),
|
||||
}
|
||||
self.visible_step(pres, self.slide, true, 1)
|
||||
}
|
||||
|
||||
fn prev_index(&self, pres: &Presentation) -> Option<usize> {
|
||||
let order = self.visit(pres);
|
||||
match order.iter().position(|&i| i == self.slide) {
|
||||
Some(p) => p.checked_sub(1).and_then(|q| order.get(q).copied()),
|
||||
None => order.iter().copied().rev().find(|&i| i < self.slide),
|
||||
self.visible_step(pres, self.slide, false, 1)
|
||||
}
|
||||
|
||||
/// Show the end screen without advancing a step (the pointer wheel past the last visible
|
||||
/// slide). A later forward input leaves the show through the end screen's own handling.
|
||||
pub fn end(&mut self) {
|
||||
self.ended = true;
|
||||
self.playing = false;
|
||||
}
|
||||
|
||||
/// `steps` slides after (`forward`) or before `from` in this show's visible order (the custom
|
||||
/// show or range, hidden slides skipped), without entering them; `None` when the order ends
|
||||
/// first. The pointer wheel turns slides through this, so it skips hidden slides as ←/→ do.
|
||||
pub fn visible_step(&self, pres: &Presentation, from: usize, forward: bool, steps: usize) -> Option<usize> {
|
||||
self.visible_step_in(pres, from, forward, steps, false)
|
||||
}
|
||||
|
||||
/// Like [`Self::visible_step`], but stops at the first/last visible slide instead of running
|
||||
/// past it: one fast wheel gesture lands on the end slide rather than leaving the order.
|
||||
pub fn visible_step_clamped(&self, pres: &Presentation, from: usize, forward: bool, steps: usize) -> Option<usize> {
|
||||
self.visible_step_in(pres, from, forward, steps, true)
|
||||
}
|
||||
|
||||
fn visible_step_in(&self, pres: &Presentation, from: usize, forward: bool, steps: usize, clamp: bool) -> Option<usize> {
|
||||
if steps == 0 {
|
||||
return None;
|
||||
}
|
||||
let order = self.visit(pres);
|
||||
// A `from` that is not in the order (a hidden slide opened by number) reaches the
|
||||
// nearest visible slide in the direction, which counts as the first step.
|
||||
let (start, used) = match order.iter().position(|&i| i == from) {
|
||||
Some(p) => (p, 0),
|
||||
None if forward => (order.iter().position(|&i| i > from)?, 1),
|
||||
None => (order.iter().rposition(|&i| i < from)?, 1),
|
||||
};
|
||||
let rest = steps.saturating_sub(used);
|
||||
let q = if forward {
|
||||
if clamp { start.saturating_add(rest).min(order.len().checked_sub(1)?) } else { start.checked_add(rest)? }
|
||||
} else if clamp {
|
||||
start.saturating_sub(rest)
|
||||
} else {
|
||||
start.checked_sub(rest)?
|
||||
};
|
||||
order.get(q).copied()
|
||||
}
|
||||
|
||||
/// Click / → / Space: finish the playing step, else play the next step, else go to the next slide.
|
||||
|
||||
@@ -763,6 +763,21 @@ fn show_skips_hidden_slides() {
|
||||
assert_eq!(s.goto(&p, 99), ShowAction::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wheel_step_from_a_hidden_slide_counts_its_first_visible_neighbour() {
|
||||
// A hidden slide opened by number is not in the show order; the nearest visible slide in the
|
||||
// direction is the first step, and the rest of the notches still apply.
|
||||
let mut p = pres(5);
|
||||
Arc::make_mut(&mut p.slides[1]).hidden = true;
|
||||
let s = ShowState::new(&p);
|
||||
assert_eq!(s.visible_step_clamped(&p, 1, true, 2), Some(3));
|
||||
assert_eq!(s.visible_step_clamped(&p, 1, false, 2), Some(0));
|
||||
assert_eq!(s.visible_step(&p, 1, true, 2), Some(3));
|
||||
// Clamped steps stop at the ends of the visible order.
|
||||
assert_eq!(s.visible_step_clamped(&p, 4, true, 3), Some(4));
|
||||
assert_eq!(s.visible_step_clamped(&p, 0, false, 3), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_remembers_a_slide_was_reached_by_going_back() {
|
||||
// #1531: the UI plays the left slide's transition reversed only for Back.
|
||||
|
||||
+96
-19
@@ -1,5 +1,6 @@
|
||||
//! A slide's animation sequence: click steps, effect start times and per-shape state over time.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -105,13 +106,15 @@ pub struct Timeline {
|
||||
groups: Vec<(ShapeId, usize, usize)>,
|
||||
/// Lookups built with the timeline, so evaluating a shape or paragraph costs its own effects
|
||||
/// rather than a scan of every effect, group and colour on the slide.
|
||||
index: TimelineIndex,
|
||||
index: Arc<TimelineIndex>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct TimelineIndex {
|
||||
/// Effects (indices into `effects`, in order) by target shape and paragraph.
|
||||
/// Effects in Animation Pane order by target shape and paragraph.
|
||||
by_target: HashMap<(ShapeId, Option<usize>), Vec<usize>>,
|
||||
/// Main-sequence media cues in start-time order, with pane order breaking ties.
|
||||
media_by_step: HashMap<usize, Vec<EffectTiming>>,
|
||||
/// Effects (indices into `effects`, in order) by target shape.
|
||||
by_shape: HashMap<ShapeId, Vec<usize>>,
|
||||
/// Owner paragraph of each member paragraph (the first group recorded wins).
|
||||
@@ -128,6 +131,15 @@ impl TimelineIndex {
|
||||
for (i, e) in effects.iter().enumerate() {
|
||||
ix.by_target.entry((e.timing.shape, e.timing.paragraph)).or_default().push(i);
|
||||
ix.by_shape.entry(e.timing.shape).or_default().push(i);
|
||||
if e.timing.class == AnimClass::Media && e.timing.sequence == Sequence::Main {
|
||||
ix.media_by_step.entry(e.timing.step).or_default().push(e.timing.clone());
|
||||
}
|
||||
}
|
||||
for indices in ix.by_target.values_mut() {
|
||||
indices.sort_by_key(|&i| effects.get(i).map(|effect| effect.timing.anim));
|
||||
}
|
||||
for cues in ix.media_by_step.values_mut() {
|
||||
cues.sort_by(|a, b| a.start.total_cmp(&b.start));
|
||||
}
|
||||
for &(shape, member, owner) in groups {
|
||||
ix.owner.entry((shape, member)).or_insert(owner);
|
||||
@@ -359,7 +371,7 @@ impl Timeline {
|
||||
};
|
||||
tl.colors.push((id, c));
|
||||
}
|
||||
tl.index = TimelineIndex::build(&tl.effects, &tl.groups, &tl.colors);
|
||||
tl.index = Arc::new(TimelineIndex::build(&tl.effects, &tl.groups, &tl.colors));
|
||||
tl
|
||||
}
|
||||
|
||||
@@ -382,15 +394,13 @@ impl Timeline {
|
||||
/// Media effects (Play, Pause, Stop) of main step `step` that start after `from` and by `to`
|
||||
/// seconds into it, in order: what a show running the step from `from` to `to` sets off.
|
||||
pub fn media_cues(&self, step: usize, from: f64, to: f64) -> Vec<EffectTiming> {
|
||||
let mut v: Vec<EffectTiming> = self
|
||||
.effects
|
||||
.iter()
|
||||
.map(|e| &e.timing)
|
||||
.filter(|e| e.class == AnimClass::Media && e.sequence == Sequence::Main && e.step == step && e.start > from && e.start <= to)
|
||||
.cloned()
|
||||
.collect();
|
||||
v.sort_by(|a, b| a.start.total_cmp(&b.start));
|
||||
v
|
||||
let Some(cues) = self.index.media_by_step.get(&step) else { return Vec::new() };
|
||||
if from.partial_cmp(&to) != Some(std::cmp::Ordering::Less) {
|
||||
return Vec::new();
|
||||
}
|
||||
let first = cues.partition_point(|cue| cue.start <= from);
|
||||
let past_last = cues.partition_point(|cue| cue.start <= to);
|
||||
cues.get(first..past_last).unwrap_or_default().to_vec()
|
||||
}
|
||||
|
||||
/// Total duration of the main sequence played without pauses.
|
||||
@@ -492,28 +502,27 @@ impl Timeline {
|
||||
stamps: &[StepStamp],
|
||||
) -> AnimState {
|
||||
let para = para.map(|p| self.index.owner.get(&(shape, p)).copied().unwrap_or(p));
|
||||
let mine = self.index.by_target.get(&(shape, para)).map_or(&[][..], Vec::as_slice).iter().filter_map(|&i| self.effects.get(i));
|
||||
let mine = self.index.by_target.get(&(shape, para)).map_or(&[][..], Vec::as_slice);
|
||||
let base_color = self.index.color.get(&shape).copied().unwrap_or(Rgba::rgb(0x15, 0x60, 0x82));
|
||||
let mut st = AnimState::default();
|
||||
// Initial visibility comes from the first effect in the Animation Pane order.
|
||||
let mut ordered: Vec<&Effect> = mine.collect();
|
||||
ordered.sort_by_key(|e| e.timing.anim);
|
||||
if let Some(e0) = ordered.first()
|
||||
if let Some(e0) = mine.first().and_then(|&i| self.effects.get(i))
|
||||
&& e0.timing.class == AnimClass::Entrance
|
||||
{
|
||||
st.visible = false;
|
||||
}
|
||||
// Then play in time order: main sequence first, then triggered sequences as they were clicked.
|
||||
if !stamps.is_empty() {
|
||||
let mut ordered = Cow::Borrowed(mine);
|
||||
if !stamps.is_empty() && mine.iter().filter_map(|&i| self.effects.get(i)).any(|effect| effect.timing.sequence != Sequence::Main) {
|
||||
let when = |e: &Effect| match e.timing.sequence {
|
||||
Sequence::Main => 0,
|
||||
Sequence::Trigger(tr) => {
|
||||
stamps.iter().find(|s| s.trigger == tr && s.step == e.timing.step).map_or(u64::MAX, |s| s.at.saturating_add(1))
|
||||
}
|
||||
};
|
||||
ordered.sort_by_key(|e| (when(e), e.timing.anim));
|
||||
ordered.to_mut().sort_by_key(|&i| self.effects.get(i).map(|effect| (when(effect), effect.timing.anim)));
|
||||
}
|
||||
for e in &ordered {
|
||||
for e in ordered.iter().filter_map(|&i| self.effects.get(i)) {
|
||||
let (pstep, pt) = match e.timing.sequence {
|
||||
Sequence::Main => (step, t),
|
||||
Sequence::Trigger(tr) => triggers.iter().find(|p| p.trigger == tr).map(|p| (p.step, p.t)).unwrap_or((0, 0.0)),
|
||||
@@ -622,3 +631,71 @@ fn build_spec(a: &Animation, xf: Xfrm, sw: f64, sh: f64, resolve: &dyn Fn(&deckc
|
||||
slide_h: sh,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn indexes_keep_pane_order_and_media_cue_boundaries() {
|
||||
let shape = ShapeId(1);
|
||||
let trigger = ShapeId(2);
|
||||
let fade = Animation { shape, class: AnimClass::Entrance, effect: "fade".into(), duration_ms: 1000, ..Default::default() };
|
||||
let play = Animation { shape, class: AnimClass::Media, effect: "play".into(), duration_ms: 1000, ..Default::default() };
|
||||
let slide = Slide {
|
||||
animations: vec![
|
||||
Animation { trigger: Some(trigger), ..fade.clone() },
|
||||
fade,
|
||||
Animation { start: AnimStart::WithPrevious, ..play.clone() },
|
||||
Animation { start: AnimStart::WithPrevious, delay_ms: 250, ..play.clone() },
|
||||
Animation { start: AnimStart::WithPrevious, ..play.clone() },
|
||||
Animation { trigger: Some(trigger), ..play.clone() },
|
||||
play,
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let timeline = Timeline::new(&slide, 960.0, 540.0);
|
||||
assert!(Arc::ptr_eq(&timeline.index, &timeline.clone().index));
|
||||
let pane_order: Vec<_> = timeline.index.by_target[&(shape, None)].iter().map(|&i| timeline.effects[i].timing.anim).collect();
|
||||
assert_eq!(pane_order, (0..7).collect::<Vec<_>>());
|
||||
assert_eq!(timeline.index.media_by_step[&0].iter().map(|cue| cue.anim).collect::<Vec<_>>(), [2, 4, 3]);
|
||||
let cues = |step, from, to| timeline.media_cues(step, from, to).into_iter().map(|cue| cue.anim).collect::<Vec<_>>();
|
||||
assert_eq!(cues(0, f64::NEG_INFINITY, 0.0), [2, 4]);
|
||||
assert_eq!(cues(0, 0.0, 0.25), [3]);
|
||||
assert!(cues(0, 0.25, f64::INFINITY).is_empty());
|
||||
assert!(cues(0, f64::NAN, 1.0).is_empty());
|
||||
assert_eq!(cues(1, f64::NEG_INFINITY, f64::INFINITY), [6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_follows_pane_order_and_the_order_triggers_were_clicked() {
|
||||
let shape = ShapeId(1);
|
||||
let (first_trigger, second_trigger) = (ShapeId(2), ShapeId(3));
|
||||
let fade = Animation { shape, effect: "fade".into(), duration_ms: 1000, ..Default::default() };
|
||||
let slide = Slide {
|
||||
animations: vec![
|
||||
Animation { class: AnimClass::Exit, trigger: Some(first_trigger), ..fade.clone() },
|
||||
Animation { class: AnimClass::Entrance, trigger: Some(second_trigger), ..fade.clone() },
|
||||
Animation { class: AnimClass::Entrance, ..fade },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let timeline = Timeline::new(&slide, 960.0, 540.0);
|
||||
|
||||
// The first effect in the Animation Pane is an exit, so the shape starts out visible even though
|
||||
// the main sequence, which the index lists first, enters it.
|
||||
assert!(timeline.state_at(shape, None, 0.0).visible);
|
||||
let entering = timeline.state_at(shape, None, 0.5);
|
||||
assert!(entering.visible && entering.opacity > 0.0 && entering.opacity < 1.0);
|
||||
|
||||
// Both triggered steps are played: the click that came later decides if the shape stays.
|
||||
let played = [TriggerPlay { trigger: first_trigger, step: 1, t: 0.0 }, TriggerPlay { trigger: second_trigger, step: 1, t: 0.0 }];
|
||||
let visible_after = |first_click, second_click| {
|
||||
let stamps =
|
||||
[StepStamp { trigger: first_trigger, step: 0, at: first_click }, StepStamp { trigger: second_trigger, step: 0, at: second_click }];
|
||||
timeline.state_ordered(shape, None, 1, 0.0, &played, &stamps).visible
|
||||
};
|
||||
assert!(visible_after(0, 1));
|
||||
assert!(!visible_after(1, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-mime = { workspace = true }
|
||||
# Tells EMF from WMF when a picture is inserted (#2392).
|
||||
craft-metafile = { workspace = true }
|
||||
deckcraft-geom = { workspace = true }
|
||||
deckcraft-color = { workspace = true }
|
||||
deckcraft-model = { workspace = true }
|
||||
@@ -32,6 +34,7 @@ chrono = { workspace = true }
|
||||
[dev-dependencies]
|
||||
deckcraft-anim = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
craft-metafile = { workspace = true, features = ["write"] }
|
||||
|
||||
# The browser clock for comment timestamps (wasm has no std::time::SystemTime).
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
|
||||
@@ -181,7 +181,7 @@ fn open_other(name: &str, bytes: &[u8]) -> Result<(Presentation, Vec<String>, Ve
|
||||
let lower = name.to_ascii_lowercase();
|
||||
let rtf = deckcraft_format::rtf::sniff_rtf(bytes);
|
||||
if rtf || lower.ends_with(".txt") || lower.ends_with(".md") {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let text = if rtf { String::from_utf8_lossy(bytes).into_owned() } else { decode_outline_bytes(bytes) };
|
||||
let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
|
||||
if rtf {
|
||||
deckcraft_format::rtf::rtf_to_slides(&mut p, &text);
|
||||
@@ -234,10 +234,37 @@ fn probe_clips(p: &mut Presentation) {
|
||||
}
|
||||
}
|
||||
|
||||
/// An outline file's text: RTF is read into the tab-indented outline, anything else as UTF-8.
|
||||
/// Decode outline text bytes by BOM: `EF BB BF` strips the UTF-8 BOM, `FF FE` decodes UTF-16LE,
|
||||
/// `FE FF` decodes UTF-16BE, and anything else keeps lossy UTF-8 decoding.
|
||||
fn decode_outline_bytes(bytes: &[u8]) -> String {
|
||||
if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
|
||||
String::from_utf8_lossy(rest).into_owned()
|
||||
} else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
|
||||
decode_utf16(rest, u16::from_le_bytes)
|
||||
} else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
|
||||
decode_utf16(rest, u16::from_be_bytes)
|
||||
} else {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_utf16(bytes: &[u8], decode: fn([u8; 2]) -> u16) -> String {
|
||||
let (chunks, tail) = bytes.as_chunks::<2>();
|
||||
let mut out: String = char::decode_utf16(chunks.iter().copied().map(decode)).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect();
|
||||
if !tail.is_empty() {
|
||||
out.push(char::REPLACEMENT_CHARACTER);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An outline file's text: RTF is read into the tab-indented outline; plain text and Markdown
|
||||
/// honour UTF-8, UTF-16LE and UTF-16BE BOMs and otherwise decode as UTF-8.
|
||||
pub fn outline_text(bytes: &[u8]) -> String {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
if deckcraft_format::rtf::sniff_rtf(bytes) { deckcraft_format::rtf::rtf_to_outline(&text) } else { text.into_owned() }
|
||||
if deckcraft_format::rtf::sniff_rtf(bytes) {
|
||||
deckcraft_format::rtf::rtf_to_outline(&String::from_utf8_lossy(bytes))
|
||||
} else {
|
||||
decode_outline_bytes(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_opened(s: &mut Session, name: &str, path: Option<String>, p: Presentation) -> usize {
|
||||
@@ -372,7 +399,8 @@ pub fn save_bytes(doc: &Presentation, format: &str) -> Result<Vec<u8>> {
|
||||
"pdf" => deckcraft_pdf::export(doc, &Default::default()).map_err(|e| EngineError::Other(e.to_string())),
|
||||
"gif" => gif_bytes(doc, &Value::Null),
|
||||
"png" | "jpeg" | "jpg" => Err(EngineError::Other("saving a presentation as a single image isn't supported; use file.export".into())),
|
||||
_ => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())),
|
||||
"deckcraft" => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())),
|
||||
_ => Err(EngineError::Other(format!("unknown save format `{format}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,6 +494,27 @@ pub fn writable_format_for_path(path: &str) -> Option<&'static str> {
|
||||
WRITABLE_EXTENSIONS.contains(&ext.as_str()).then(|| format_for_path(path))
|
||||
}
|
||||
|
||||
/// The format a save path names, or an error listing the file types DeckCraft writes.
|
||||
fn writable_format(path: &str) -> Result<&'static str> {
|
||||
writable_format_for_path(path).ok_or_else(|| {
|
||||
EngineError::Other(format!(
|
||||
"{path}: DeckCraft cannot save this file type; save as .pptx, .potx, .ppsx, .deckcraft, .pdf, .png, .jpg/.jpeg, .gif, .txt, .md or .rtf"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an explicit save format names the same writer as the path. `txt`/`outline` are the
|
||||
/// same writer only for a `.txt` path, and `jpg`/`jpeg` are aliases; every other mismatch would
|
||||
/// write bytes that lie about the file type.
|
||||
fn same_save_format(path: &str, path_format: &str, format: &str) -> bool {
|
||||
if format == path_format {
|
||||
return true;
|
||||
}
|
||||
let lower = path.to_ascii_lowercase();
|
||||
(lower.ends_with(".txt") && matches!((path_format, format), ("outline", "txt") | ("txt", "outline")))
|
||||
|| matches!((path_format, format), ("jpeg", "jpg") | ("jpg", "jpeg"))
|
||||
}
|
||||
|
||||
/// 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)
|
||||
@@ -515,7 +564,13 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.ui_requests.push(crate::UiRequest::PickFile { purpose: "saveAs".into() });
|
||||
return Ok(json!({"needsPath": true}));
|
||||
};
|
||||
let format = str_param(p, "format").unwrap_or(format_for_path(&path));
|
||||
let path_format = writable_format(&path)?;
|
||||
let format = str_param(p, "format").unwrap_or(path_format);
|
||||
if !same_save_format(&path, path_format, format) {
|
||||
return Err(EngineError::Other(format!(
|
||||
"{path}: format `{format}` does not match the file type; save as {path_format} or choose a matching extension"
|
||||
)));
|
||||
}
|
||||
let bytes = save_bytes(&s.doc()?.doc, format)?;
|
||||
write_file(&path, &bytes)?;
|
||||
mark_saved(s, Some(path.clone()))?;
|
||||
@@ -602,7 +657,10 @@ fn color_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path").ok_or_else(|| bad("file.export", "missing `path`"))?.to_string();
|
||||
let format = str_param(p, "format").unwrap_or(format_for_path(&path)).to_string();
|
||||
let format = match str_param(p, "format") {
|
||||
Some(f) => f.to_string(),
|
||||
None => writable_format(&path)?.to_string(),
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let scale = finite_scale(f64_or(p, "scale", 2.0));
|
||||
let transparent = bool_or(p, "transparentBackground", false);
|
||||
|
||||
@@ -287,16 +287,8 @@ fn current_run(s: &Session) -> RunProps {
|
||||
}
|
||||
None => {
|
||||
let Some(sh) = st.selected_shapes().first().map(|x| (*x).clone()) else { return RunProps::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());
|
||||
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();
|
||||
(sh, para, rp)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -279,6 +279,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if rect.w < 1.0 || rect.h < 1.0 {
|
||||
return Err(bad("insert.icon", "rect needs a positive width and height"));
|
||||
}
|
||||
let (tag, value) = crate::icons::INSERTED_ICON_TAG;
|
||||
let shape = Shape {
|
||||
name: icon.label.to_string(),
|
||||
xfrm: Some(rect),
|
||||
@@ -300,6 +301,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
..Default::default()
|
||||
}),
|
||||
style: Some(ShapeStyle::line(SchemeSlot::Tx1)),
|
||||
tags: vec![(tag.into(), value.into())],
|
||||
..Default::default()
|
||||
};
|
||||
let id = add_shape(s, "insert.icon", shape, true)?;
|
||||
|
||||
@@ -33,6 +33,12 @@ pub fn content_type(name: &str, bytes: &[u8]) -> &'static str {
|
||||
"image/bmp"
|
||||
} else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") {
|
||||
"image/tiff"
|
||||
} else if let Some(kind) = craft_metafile::sniff(bytes) {
|
||||
// The MIME types the PPTX writer saves as `.emf` / `.wmf` parts (#2392).
|
||||
match kind {
|
||||
craft_metafile::Kind::Emf => "image/x-emf",
|
||||
craft_metafile::Kind::Wmf => "image/x-wmf",
|
||||
}
|
||||
} else if bytes.starts_with(b"fLaC") {
|
||||
"audio/flac"
|
||||
} else if bytes.starts_with(b"OggS") {
|
||||
@@ -73,6 +79,19 @@ pub fn content_type(name: &str, bytes: &[u8]) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio MIME for a container whose bytes are audio-only, so the PPTX writer stores it as
|
||||
/// sound rather than a movie. Video-bearing containers keep their `video/*` type.
|
||||
fn audio_content_type(ct: &'static str) -> &'static str {
|
||||
match ct {
|
||||
"video/x-ms-wmv" => "audio/x-ms-wma",
|
||||
"video/mp4" => "audio/mp4",
|
||||
"video/webm" => "audio/webm",
|
||||
"video/ogg" => "audio/ogg",
|
||||
"video/quicktime" => "audio/mp4",
|
||||
_ => ct,
|
||||
}
|
||||
}
|
||||
|
||||
/// Natural size of an image in points (96 dpi), fitted inside the slide.
|
||||
fn fitted(s: &Session, bytes: &[u8]) -> (f64, f64) {
|
||||
let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes))
|
||||
@@ -175,6 +194,10 @@ fn media(s: &mut Session, p: &Value, video: bool) -> Result<Value> {
|
||||
Err(_) if !video && !ct.starts_with("audio/") => return Err(bad(cmd, format!("{name} is not a supported audio file ({ct})"))),
|
||||
_ => {}
|
||||
}
|
||||
// The extension decides the container's MIME even when the probe finds only an audio stream
|
||||
// (#2390): keep it `audio/*` so the writer stores sound, not a movie. The validation above
|
||||
// still uses the original `ct`, because an unreadable file has no audio stream.
|
||||
let ct = if !video && has_audio && !has_video { audio_content_type(ct) } else { ct };
|
||||
let (duration_ms, width, height, playable) = match &info {
|
||||
Ok(i) => {
|
||||
let (w, h) = i.video.as_ref().map(|v| (v.width, v.height)).unwrap_or((0, 0));
|
||||
@@ -244,3 +267,23 @@ pub(super) fn audio(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn video(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
media(s, p, true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::audio_content_type;
|
||||
|
||||
#[test]
|
||||
fn audio_content_type_maps_every_audio_only_container() {
|
||||
for (video, audio) in [
|
||||
("video/x-ms-wmv", "audio/x-ms-wma"),
|
||||
("video/mp4", "audio/mp4"),
|
||||
("video/webm", "audio/webm"),
|
||||
("video/ogg", "audio/ogg"),
|
||||
("video/quicktime", "audio/mp4"),
|
||||
] {
|
||||
assert_eq!(audio_content_type(video), audio, "{video}");
|
||||
}
|
||||
assert_eq!(audio_content_type("audio/mpeg"), "audio/mpeg");
|
||||
assert_eq!(audio_content_type("application/octet-stream"), "application/octet-stream");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,7 +182,7 @@ mod tests {
|
||||
use deckcraft_model::ShapeId;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::cmd::base64_encode;
|
||||
use crate::cmd::{base64_decode, base64_encode};
|
||||
use crate::{MediaStatus, Session, UiRequest};
|
||||
|
||||
fn wav() -> Vec<u8> {
|
||||
@@ -291,6 +291,72 @@ mod tests {
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("can't be played")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_only_asf_saves_as_sound() {
|
||||
let mut s = Session::with_new();
|
||||
let bytes = include_bytes!("../../../media/tests/fixtures/tone.wma");
|
||||
let r = s.execute("insert.audio", &json!({"name": "tone.asf", "data": base64_encode(bytes)})).expect("insert");
|
||||
assert_eq!(r["contentType"], "audio/x-ms-wma", "{r}");
|
||||
|
||||
let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save");
|
||||
let zip = base64_decode(saved["data"].as_str().unwrap()).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(zip)).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
|
||||
assert!(names.iter().any(|n| n == "ppt/media/media1.wma"), "{names:?}");
|
||||
assert!(!names.iter().any(|n| n.ends_with(".wmv")), "{names:?}");
|
||||
|
||||
s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).expect("open");
|
||||
let info = s.execute("media.info", &json!({})).expect("info");
|
||||
assert_eq!(info["video"], false, "{info}");
|
||||
assert!(info["durationMs"].as_u64().is_some_and(|ms| ms > 0), "{info}");
|
||||
assert_eq!(info["contentType"], "audio/x-ms-wma", "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_video_container_inserted_as_video_stays_a_movie() {
|
||||
let mut s = Session::with_new();
|
||||
let clip = include_bytes!("../../../media/tests/fixtures/clip-h264.mp4");
|
||||
let r = s.execute("insert.video", &json!({"name": "clip.mp4", "data": base64_encode(clip)})).expect("insert");
|
||||
assert_eq!(r["contentType"], "video/mp4", "{r}");
|
||||
|
||||
let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save");
|
||||
s.execute("file.openBytes", &json!({"name": "deck.pptx", "data": saved["data"]})).expect("open");
|
||||
let info = s.execute("media.info", &json!({})).expect("info");
|
||||
assert_eq!(info["video"], true, "{info}");
|
||||
assert_eq!(info["contentType"], "video/mp4", "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_video_still_rejects_an_audio_only_file() {
|
||||
let mut s = Session::with_new();
|
||||
let bytes = include_bytes!("../../../media/tests/fixtures/tone.wma");
|
||||
let err = s.execute("insert.video", &json!({"name": "tone.asf", "data": base64_encode(bytes)})).unwrap_err();
|
||||
assert!(err.to_string().contains("has no video"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_audio_is_still_refused() {
|
||||
let mut s = Session::with_new();
|
||||
let err = s.execute("insert.audio", &json!({"name": "tone.wma", "data": base64_encode(b"not media")})).unwrap_err();
|
||||
assert!(err.to_string().contains("is not a supported audio file"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_only_ogv_saves_as_sound() {
|
||||
let mut s = Session::with_new();
|
||||
let _ = s.execute("slide.new", &json!({"layout": "blank"}));
|
||||
let bytes = include_bytes!("../../../media/tests/fixtures/tone.ogg");
|
||||
let r = s.execute("insert.audio", &json!({"name": "tone.ogv", "data": base64_encode(bytes)})).expect("insert");
|
||||
assert_eq!(r["contentType"], "audio/ogg", "{r}");
|
||||
|
||||
let saved = s.execute("file.saveBytes", &json!({"format": "pptx"})).expect("save");
|
||||
let zip = base64_decode(saved["data"].as_str().unwrap()).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(zip)).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
|
||||
assert!(names.iter().any(|n| n == "ppt/media/media1.ogg"), "{names:?}");
|
||||
assert!(!names.iter().any(|n| n.ends_with(".ogv")), "{names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vp8_webm_is_playable_and_warns_that_only_the_audio_plays() {
|
||||
let mut s = Session::with_new();
|
||||
|
||||
@@ -501,15 +501,19 @@ pub(crate) fn import_master(
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// The content type of a tags part (`p:custDataLst`/`p:tags`), which belongs to exactly one owner.
|
||||
const TAGS_CONTENT_TYPE: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml";
|
||||
|
||||
/// Copy the source media `used` into `doc` under fresh ids, once each (identical bytes already in
|
||||
/// `doc` are shared; a linked item keeps its link).
|
||||
/// `doc` are shared; a linked item keeps its link). A tags part is never shared: identical tag lists
|
||||
/// on a master and its layouts must stay one part per owner, or PowerPoint repairs the file.
|
||||
fn copy_media(cmd: &str, doc: &mut Presentation, src: &Presentation, used: &[MediaId], map: &mut HashMap<MediaId, MediaId>) -> Result<()> {
|
||||
for &id in used {
|
||||
if map.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
let Some(m) = src.media(id) else { continue };
|
||||
let new = if m.link.is_some() {
|
||||
let new = if m.link.is_some() || m.content_type.eq_ignore_ascii_case(TAGS_CONTENT_TYPE) {
|
||||
let mut item = m.clone();
|
||||
item.id = MediaId(doc.alloc_id().ok_or_else(|| bad(cmd, NO_ID_SPACE))?);
|
||||
let new = item.id;
|
||||
@@ -792,6 +796,94 @@ mod tests {
|
||||
assert_eq!(got, want, "every reference resolves to its own copied bytes");
|
||||
}
|
||||
|
||||
/// A tags part belongs to one owner. Identical tag lists on a master and its layouts (a
|
||||
/// think-cell or OLE object on each) come over as one item per owner, never one shared item,
|
||||
/// so the saved file has a part for each and PowerPoint opens it without a repair.
|
||||
#[test]
|
||||
fn reused_master_keeps_a_tags_part_per_owner() {
|
||||
const TAGS: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml";
|
||||
const TAGS_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tags";
|
||||
let tags = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:tagLst xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:tag name="THINKCELLSHAPEDONOTDELETE" val="t1"/></p:tagLst>"#.to_vec();
|
||||
let mut src = defaults::new_presentation(None);
|
||||
let ids: Vec<MediaId> = (0..3)
|
||||
.map(|_| {
|
||||
let id = MediaId(src.alloc_id().expect("id"));
|
||||
src.media.push(deckcraft_model::MediaItem {
|
||||
id,
|
||||
name: "tag1.xml".into(),
|
||||
content_type: TAGS.into(),
|
||||
data: Arc::new(tags.clone()),
|
||||
link: None,
|
||||
});
|
||||
id
|
||||
})
|
||||
.collect();
|
||||
let object = |id: MediaId| {
|
||||
Shape {
|
||||
id: ShapeId(9100),
|
||||
kind: ShapeKind::Opaque {
|
||||
xml: r#"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="9100" name="think-cell data"/><p:cNvGraphicFramePr/><p:nvPr><p:custDataLst><p:tags r:id="rId2"/></p:custDataLst></p:nvPr></p:nvGraphicFramePr></p:graphicFrame>"#.into(),
|
||||
preview: None,
|
||||
label: "think-cell".into(),
|
||||
parts: vec![("rId2".into(), TAGS_REL.into(), id)],
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let master = src.masters.first_mut().map(Arc::make_mut).expect("master");
|
||||
assert!(master.layouts.len() >= 2, "the default master has layouts to share the tags");
|
||||
master.shapes = vec![object(ids[0])];
|
||||
for (layout, id) in master.layouts.iter_mut().zip(&ids[1..]) {
|
||||
layout.shapes = vec![object(*id)];
|
||||
}
|
||||
let bytes = deckcraft_format::save(&src).expect("save");
|
||||
|
||||
let mut s = Session::with_new();
|
||||
let own = s.edit(|doc, _| Ok(doc.add_media("tag1.xml", TAGS, tags.clone()).expect("media"))).expect("own tags");
|
||||
s.execute(
|
||||
"slide.reuse",
|
||||
&json!({"data": super::super::base64_encode(&bytes), "name": "src.deckcraft", "slides": [0], "keepFormatting": true}),
|
||||
)
|
||||
.expect("reuse");
|
||||
let doc = &s.doc().expect("doc").doc;
|
||||
let imported = doc.masters.last().expect("imported master");
|
||||
let parts = |shapes: &[Shape]| -> Vec<MediaId> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|sh| match &sh.kind {
|
||||
ShapeKind::Opaque { parts, .. } => Some(parts.iter().map(|(_, _, m)| *m)),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
};
|
||||
let mut got = parts(&imported.shapes);
|
||||
for layout in imported.layouts.iter().take(2) {
|
||||
got.extend(parts(&layout.shapes));
|
||||
}
|
||||
assert_eq!(got.len(), 3, "the master and two layouts each hold their object");
|
||||
for m in &got {
|
||||
let item = doc.media(*m).expect("copied tags item");
|
||||
assert_eq!((item.content_type.as_str(), item.data.as_slice()), (TAGS, tags.as_slice()), "each copy keeps the tag list");
|
||||
assert_ne!(*m, own, "a copied tags part is not shared with the destination's own");
|
||||
}
|
||||
let mut distinct = got.clone();
|
||||
distinct.sort_by_key(|m| m.0);
|
||||
distinct.dedup();
|
||||
assert_eq!(distinct.len(), got.len(), "each owner has its own tags item: {got:?}");
|
||||
|
||||
let pptx = deckcraft_pptx::export(doc).expect("export");
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&pptx)).expect("zip");
|
||||
let mut written = 0;
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).expect("entry");
|
||||
let mut body = Vec::new();
|
||||
std::io::Read::read_to_end(&mut f, &mut body).expect("read");
|
||||
written += usize::from(body == tags);
|
||||
}
|
||||
assert!(written >= 3, "the saved file has a tags part per owner, found {written}");
|
||||
}
|
||||
|
||||
fn link_to(slide: SlideId) -> Hyperlink {
|
||||
Hyperlink {
|
||||
action: Action::Slide { slide },
|
||||
|
||||
@@ -246,6 +246,26 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result<Value> {
|
||||
Ok(json!({"slide": slide, "index": index, "text": text}))
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
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))
|
||||
}
|
||||
|
||||
/// The name of the file a picture shape's picture came from, if it has one.
|
||||
fn picture_file<'a>(doc: &'a deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> Option<&'a str> {
|
||||
match &sh.kind {
|
||||
deckcraft_model::ShapeKind::Picture { fill } => doc.media(fill.media).map(|m| m.name.as_str()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut out = vec![];
|
||||
@@ -261,8 +281,12 @@ fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
| deckcraft_model::ShapeKind::Media(_)
|
||||
| deckcraft_model::ShapeKind::Group { .. }
|
||||
);
|
||||
if needs_alt && sh.descr.trim().is_empty() && !sh.decorative {
|
||||
if sh.descr.trim().is_empty() && !sh.decorative && (needs_alt || crate::icons::is_inserted_icon(sh)) {
|
||||
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Missing alternative text"}));
|
||||
} else if needs_alt && !sh.decorative && is_file_name(&sh.descr, picture_file(&st.doc, sh)) {
|
||||
// Insert Picture names a picture after its file, which is all a screen reader
|
||||
// would then say (#2224).
|
||||
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Alternative text is a file name"}));
|
||||
}
|
||||
});
|
||||
// Low-contrast text against the slide background.
|
||||
@@ -1041,4 +1065,45 @@ mod accessibility_contrast_tests {
|
||||
assert!(!contrasts.iter().any(|issue| issue["shape"] == 6), "black control warned: {issues}");
|
||||
assert!(!contrasts.iter().any(|issue| issue["shape"] == 8), "white break or spaces warned: {issues}");
|
||||
}
|
||||
|
||||
/// #2224: Insert Picture's alt text is the file name, which says nothing; it is reported until
|
||||
/// it is described or marked decorative. A description that mentions a file is fine.
|
||||
#[test]
|
||||
fn alt_text_that_is_a_file_name_is_reported() {
|
||||
let 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,
|
||||
];
|
||||
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();
|
||||
let named = |s: &mut Session| {
|
||||
let issues = s.execute("review.accessibility", &json!({})).unwrap();
|
||||
issues.as_array().unwrap().iter().filter(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name").count()
|
||||
};
|
||||
assert_eq!(named(&mut s), 1);
|
||||
for (text, decorative, expected) in [
|
||||
("photo.JPEG", false, 1),
|
||||
("C:\\Users\\me\\Pictures\\holiday.png", false, 1),
|
||||
("A red square", false, 0),
|
||||
("A red square, from IMG_2041.png", false, 0),
|
||||
("IMG_2041.png", true, 0),
|
||||
] {
|
||||
s.execute("shape.altText", &json!({"text": text, "decorative": decorative, "ids": [id]})).unwrap();
|
||||
assert_eq!(named(&mut s), expected, "{text:?} decorative {decorative}");
|
||||
}
|
||||
// A file name with spaces is reported when it is the picture's own file's.
|
||||
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();
|
||||
let issues = s.execute("review.accessibility", &json!({})).unwrap();
|
||||
assert!(issues.as_array().unwrap().iter().any(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name"), "{issues}");
|
||||
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.
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,7 +330,7 @@ fn slide_ids_param(v: &Value, doc: &Presentation, cmd: &str) -> Result<HashSet<S
|
||||
|
||||
/// Keeps sections in step after `moved` landed as a run at `at`: the run joins the section of
|
||||
/// the slide just before it (the first section when it opens the deck), in document order.
|
||||
fn reassign_sections(doc: &mut Presentation, moved: &[SlideId], at: usize) {
|
||||
pub(crate) fn reassign_sections(doc: &mut Presentation, moved: &[SlideId], at: usize) {
|
||||
if doc.sections.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -690,6 +690,11 @@ fn section_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let sec = doc.sections.remove(i);
|
||||
if with_slides {
|
||||
doc.slides.retain(|x| !sec.slides.contains(&x.id));
|
||||
// As in slide.delete: the deleted slides leave every custom show and the selection.
|
||||
for show in &mut doc.custom_shows {
|
||||
show.slides.retain(|x| !sec.slides.contains(x));
|
||||
}
|
||||
sel.slides.retain(|x| !sec.slides.contains(x));
|
||||
sel.slide = sel.slide.min(doc.slides.len().saturating_sub(1));
|
||||
} else if let Some(prev) = i.checked_sub(1).and_then(|k| doc.sections.get_mut(k)) {
|
||||
prev.slides.extend(sec.slides);
|
||||
@@ -982,6 +987,29 @@ mod tests {
|
||||
assert_eq!(selected(&s), (0, vec![ids[2]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_section_with_its_slides_prunes_them_from_custom_shows() {
|
||||
let (mut s, ids) = deck(4);
|
||||
s.execute("section.add", &json!({"name": "A", "at": 0})).expect("A");
|
||||
s.execute("section.add", &json!({"name": "B", "at": 2})).expect("B");
|
||||
let show = vec![deckcraft_model::SlideId(ids[0]), deckcraft_model::SlideId(ids[2]), deckcraft_model::SlideId(ids[3])];
|
||||
s.edit(|doc, _| {
|
||||
doc.custom_shows = vec![deckcraft_model::CustomShow { name: "Short".into(), slides: show.clone() }];
|
||||
Ok(())
|
||||
})
|
||||
.expect("set custom show");
|
||||
s.execute("slide.selectSlides", &json!({"ids": [ids[1], ids[3]]})).expect("select");
|
||||
|
||||
s.execute("section.remove", &json!({"index": 1, "slides": true})).expect("remove B and its slides");
|
||||
assert_eq!(order(&s), [ids[0], ids[1]]);
|
||||
let st = s.doc().expect("doc");
|
||||
assert_eq!(st.doc.custom_shows[0].slides, [deckcraft_model::SlideId(ids[0])], "the deleted slides leave the custom show");
|
||||
assert!(st.selection.slides.iter().all(|x| st.doc.slide_index(*x).is_some()), "the selection names only slides of the deck");
|
||||
|
||||
s.execute("edit.undo", &json!({})).expect("undo");
|
||||
assert_eq!(s.doc().expect("doc").doc.custom_shows[0].slides, show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_keeps_section_order_in_step_with_slides() {
|
||||
let mut s = Session::with_new();
|
||||
|
||||
@@ -725,11 +725,18 @@ 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 column_width(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (_, c) = at(s, p, "table.columnWidth")?;
|
||||
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")?;
|
||||
// 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());
|
||||
@@ -758,6 +765,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")?;
|
||||
if let Some(x) = t.rows.get_mut(r) {
|
||||
x.height = h;
|
||||
}
|
||||
|
||||
@@ -338,10 +338,7 @@ 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`)")) };
|
||||
// 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 keep = body.paragraphs.first().and_then(|p| p.runs.first()).map(|r| r.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() {
|
||||
@@ -356,11 +353,6 @@ 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,10 +25,6 @@ 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 {
|
||||
@@ -69,9 +65,6 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -79,11 +72,6 @@ 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) => {
|
||||
|
||||
@@ -514,14 +514,24 @@ pub fn accept(doc: &mut Presentation, rev: &Presentation, change: &Change) -> cr
|
||||
let Some(b) = change.revised.and_then(|r| rev.slides.get(r)).cloned() else { return Ok(None) };
|
||||
let sl = adopt(doc, rev, &b, None)?;
|
||||
let at = change.slide.min(doc.slides.len());
|
||||
let id = sl.id;
|
||||
doc.slides.insert(at, Arc::new(sl));
|
||||
// The new slide joins the section of the slide before it, as slide.new does.
|
||||
crate::cmd::slide::reassign_sections(doc, &[id], at);
|
||||
Ok(Some(at))
|
||||
}
|
||||
ChangeKind::Deleted => {
|
||||
if change.slide >= doc.slides.len() || doc.slides.len() <= 1 {
|
||||
return Ok(None);
|
||||
}
|
||||
doc.slides.remove(change.slide);
|
||||
let gone = doc.slides.remove(change.slide).id;
|
||||
// As in slide.delete: the slide leaves its section and every custom show.
|
||||
for sec in &mut doc.sections {
|
||||
sec.slides.retain(|x| *x != gone);
|
||||
}
|
||||
for show in &mut doc.custom_shows {
|
||||
show.slides.retain(|x| *x != gone);
|
||||
}
|
||||
Ok(Some(change.slide.min(doc.slides.len().saturating_sub(1))))
|
||||
}
|
||||
}
|
||||
@@ -811,6 +821,33 @@ mod tests {
|
||||
assert!(s.execute("review.accept", &json!({"all": true})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_slides_keep_sections_and_custom_shows_in_step() {
|
||||
let (mut s, rev, _) = decks();
|
||||
let ids = |s: &Session| -> Vec<deckcraft_model::SlideId> { s.doc().unwrap().doc.slides.iter().map(|x| x.id).collect() };
|
||||
let before = ids(&s);
|
||||
assert!(!s.doc().unwrap().doc.sections.is_empty(), "the sample deck has sections");
|
||||
let show: Vec<_> = before.iter().take(3).copied().collect();
|
||||
s.edit(|doc, _| {
|
||||
doc.custom_shows = vec![deckcraft_model::CustomShow { name: "Short".into(), slides: show.clone() }];
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("review.compare", &json!({"name": "rev.deckcraft", "data": rev})).unwrap();
|
||||
s.execute("review.accept", &json!({"all": true})).unwrap();
|
||||
|
||||
let st = s.doc().unwrap();
|
||||
let after = ids(&s);
|
||||
let gone = before[1];
|
||||
assert!(!after.contains(&gone), "the revision deleted slide 2");
|
||||
let in_sections: Vec<_> = st.doc.sections.iter().flat_map(|x| x.slides.iter().copied()).collect();
|
||||
assert_eq!(in_sections, after, "every slide is in one section, in deck order, and no section keeps the deleted slide");
|
||||
let new = st.doc.slides.iter().find(|x| super::slide_title(x) == "Brand new").unwrap().id;
|
||||
assert!(st.doc.section_of(new).is_some(), "the inserted slide joins a section");
|
||||
assert!(!st.doc.custom_shows[0].slides.contains(&gone), "the deleted slide leaves the custom show");
|
||||
assert_eq!(st.doc.custom_shows[0].slides.len(), show.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_keeps_the_open_deck_and_accept_all_skips_rejected_revisions() {
|
||||
let (mut s, rev, n) = decks();
|
||||
|
||||
@@ -12,6 +12,14 @@ use deckcraft_geom::{BezPath, PathEl};
|
||||
/// Design size of every icon, in path units. Lucide's viewBox is `0 0 24 24`.
|
||||
pub const VIEW: f64 = 24.0;
|
||||
|
||||
/// Shape tag that preserves gallery icon identity in native and PPTX files.
|
||||
pub(crate) const INSERTED_ICON_TAG: (&str, &str) = ("DECKCRAFT_INSERTED_ICON", "1");
|
||||
|
||||
pub(crate) fn is_inserted_icon(shape: &deckcraft_model::Shape) -> bool {
|
||||
let (name, value) = INSERTED_ICON_TAG;
|
||||
shape.tags.iter().any(|(key, tag_value)| key == name && tag_value == value)
|
||||
}
|
||||
|
||||
/// One icon from the Insert gallery.
|
||||
pub struct Icon {
|
||||
pub name: &'static str,
|
||||
@@ -210,6 +218,43 @@ mod tests {
|
||||
assert!((width - 8.0).abs() < 0.05, "{width}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_icon_alt_text_is_reported_after_round_trips() {
|
||||
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 decorative = insert_icon(&mut s);
|
||||
let freeform = s.execute("shape.freeform", &json!({"points": [[0, 0], [20, 10], [5, 25]], "closed": true})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("shape.rename", &json!({"ids": [freeform], "name": "Star"})).unwrap();
|
||||
s.execute("shape.rename", &json!({"ids": [missing], "name": "Repainted symbol"})).unwrap();
|
||||
s.execute("shape.altText", &json!({"ids": [described], "text": "Five-point outline"})).unwrap();
|
||||
s.execute("shape.altText", &json!({"ids": [decorative], "decorative": true})).unwrap();
|
||||
|
||||
let assert_alert = |s: &mut Session| {
|
||||
let issues = s.execute("review.accessibility", &json!({})).unwrap();
|
||||
let shapes: Vec<_> = issues
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|issue| issue["issue"] == "Missing alternative text")
|
||||
.map(|issue| issue["shape"].as_u64().unwrap())
|
||||
.collect();
|
||||
assert_eq!(shapes, [missing], "{issues}");
|
||||
};
|
||||
assert_alert(&mut s);
|
||||
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let native = deckcraft_format::load(&deckcraft_format::save(doc).unwrap()).unwrap();
|
||||
let pptx = deckcraft_pptx::import(&deckcraft_pptx::export(doc).unwrap()).unwrap();
|
||||
let second_pptx = deckcraft_pptx::import(&deckcraft_pptx::export(&pptx).unwrap()).unwrap();
|
||||
for doc in [native, pptx, second_pptx] {
|
||||
let mut reopened = Session::new();
|
||||
reopened.add_document(crate::DocState::new(doc, None, "Reopened deck".into()));
|
||||
assert_alert(&mut reopened);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
+176
-23
@@ -22,6 +22,14 @@ enum FlagMode {
|
||||
Num,
|
||||
}
|
||||
|
||||
/// Where a part sits in a compound.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Pos {
|
||||
First,
|
||||
Middle,
|
||||
Last,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Cond {
|
||||
Any,
|
||||
@@ -108,6 +116,8 @@ pub struct Dictionary {
|
||||
compound_begin: Option<Flag>,
|
||||
compound_middle: Option<Flag>,
|
||||
compound_end: Option<Flag>,
|
||||
/// `COMPOUNDPERMITFLAG`: an affix carrying it may sit inside a compound, not only at its ends.
|
||||
compound_permit: Option<Flag>,
|
||||
compound_min: usize,
|
||||
compound_max: usize,
|
||||
}
|
||||
@@ -167,6 +177,7 @@ impl Dictionary {
|
||||
["COMPOUNDBEGIN", f, ..] => d.compound_begin = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIDDLE", f, ..] => d.compound_middle = one_flag(Some(f), mode),
|
||||
["COMPOUNDEND", f, ..] | ["COMPOUNDLAST", f, ..] => d.compound_end = one_flag(Some(f), mode),
|
||||
["COMPOUNDPERMITFLAG", f, ..] => d.compound_permit = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIN", n, ..] => d.compound_min = n.parse::<usize>().unwrap_or(3).max(1),
|
||||
["COMPOUNDWORDMAX", n, ..] => d.compound_max = n.parse().unwrap_or(0),
|
||||
["REP", n] => {
|
||||
@@ -250,11 +261,26 @@ impl Dictionary {
|
||||
self.words.get(word).is_some_and(|hs| hs.iter().any(|f| self.has(f, self.forbidden)))
|
||||
}
|
||||
|
||||
/// An affix that may only be used inside a compound (`ONLYINCOMPOUND` among its continuation
|
||||
/// flags): frami's zero suffixes that turn `Vor` into a compound's first part don't make `Vor`
|
||||
/// a word of its own (#2145).
|
||||
fn only_in_compound_affix(&self, a: &Affix) -> bool {
|
||||
self.only_in_compound.is_some_and(|o| a.cont.contains(&o))
|
||||
}
|
||||
|
||||
/// An affix that needs a further affix (`NEEDAFFIX` among its continuation flags): it can't be
|
||||
/// the last affix of a word or of a compound part.
|
||||
fn needs_another_affix(&self, a: &Affix) -> bool {
|
||||
self.need_affix.is_some_and(|n| a.cont.contains(&n))
|
||||
}
|
||||
|
||||
/// Strip suffixes from `w` (one, or two through continuation flags); `extra` flags must also be
|
||||
/// on the root, `cross` means the suffix must allow a prefix.
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool) -> bool {
|
||||
/// on the root, `cross` means the suffix must allow a prefix. `completed`: a prefix that needs
|
||||
/// nothing more is already on the word, so a suffix that needs another affix has it
|
||||
/// (`work/US` with `SFX S 0 s/N` makes `unworks`, not `works`).
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool, completed: bool) -> bool {
|
||||
for s in &self.sfx {
|
||||
if cross && !s.cross {
|
||||
if (cross && !s.cross) || self.only_in_compound_affix(s) || (self.needs_another_affix(s) && !completed) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_end(w, &s.add, &s.strip) else { continue };
|
||||
@@ -269,7 +295,7 @@ impl Dictionary {
|
||||
}
|
||||
// A second suffix whose continuation allows this one (`walk/A` + `ing/B`…).
|
||||
for s2 in &self.sfx {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) || self.only_in_compound_affix(s2) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem2) = strip_end(&stem, &s2.add, &s2.strip) else { continue };
|
||||
@@ -285,24 +311,47 @@ impl Dictionary {
|
||||
false
|
||||
}
|
||||
|
||||
/// A root (or, for the last part, a suffixed root) carrying `flag`, as a compound part.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, last: bool) -> bool {
|
||||
/// A root carrying `flag`, or a root with one affix, as a compound part at `pos`.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
let word: String = part.iter().collect();
|
||||
let ok = self.words.get(&word).is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag)));
|
||||
ok || (last && self.suffixed_compound_end(part, flag))
|
||||
ok || self.affixed_compound_part(part, flag, pos)
|
||||
}
|
||||
|
||||
/// The last part of a compound with a suffix: the root must carry the compound `flag`.
|
||||
fn suffixed_compound_end(&self, w: &[char], flag: Flag) -> bool {
|
||||
self.sfx.iter().any(|s| {
|
||||
strip_end(w, &s.add, &s.strip).is_some_and(|stem| {
|
||||
s.cond_ok(&stem, false)
|
||||
&& self
|
||||
.words
|
||||
.get(&stem.iter().collect::<String>())
|
||||
.is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag) && f.contains(&s.flag)))
|
||||
})
|
||||
})
|
||||
/// A compound part made of a root and one affix, as Hunspell reads them: a suffix ends the last
|
||||
/// part and a prefix starts the first; anywhere else the affix needs `COMPOUNDPERMITFLAG`.
|
||||
/// An affix that carries `NEEDAFFIX` needs a second one and doesn't count. A suffix found
|
||||
/// through the plain compound flag whose continuation flags carry `COMPOUNDEND` may only be on
|
||||
/// the last part. The compound `flag`
|
||||
/// may be on the root or among the affix's continuation flags. German frami gives many first
|
||||
/// parts their flag that way: `Vor/hij` with `SFX j 0 0/xoc` begins `Vorschlag` (#2145).
|
||||
fn affixed_compound_part(&self, w: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
let permit = |a: &Affix| self.compound_permit.is_some_and(|p| a.cont.contains(&p));
|
||||
// An affix that itself needs another (`NEEDAFFIX` among its continuation flags) doesn't
|
||||
// finish a part on its own.
|
||||
let fits = |a: &Affix, stem: &[char], suffix: bool| {
|
||||
!self.needs_another_affix(a)
|
||||
// Only the last part may take a suffix found through the plain compound flag whose
|
||||
// continuation flags carry the compound end flag; the begin, middle and prefix
|
||||
// lookups don't check it, as in Hunspell.
|
||||
&& (pos == Pos::Last || !suffix || Some(flag) != self.compound || !self.compound_end.is_some_and(|e| a.cont.contains(&e)))
|
||||
&& self.words.get(&stem.iter().collect::<String>()).is_some_and(|hs| {
|
||||
hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&a.flag) && (f.contains(&flag) || a.cont.contains(&flag)))
|
||||
})
|
||||
};
|
||||
let suffixed = self
|
||||
.sfx
|
||||
.iter()
|
||||
// At the end of a compound, Hunspell refuses a suffix that adds letters and may only be
|
||||
// used inside compounds; a zero-length one is accepted.
|
||||
.filter(|s| if pos == Pos::Last { s.add.is_empty() || !self.only_in_compound_affix(s) } else { permit(s) })
|
||||
.any(|s| strip_end(w, &s.add, &s.strip).is_some_and(|stem| s.cond_ok(&stem, false) && fits(s, &stem, true)));
|
||||
suffixed
|
||||
|| self
|
||||
.pfx
|
||||
.iter()
|
||||
.filter(|p| pos == Pos::First || permit(p))
|
||||
.any(|p| strip_start(w, &p.add, &p.strip).is_some_and(|stem| p.cond_ok(&stem, true) && fits(p, &stem, false)))
|
||||
}
|
||||
|
||||
/// `w` made of dictionary parts allowed in compounds (`COMPOUNDFLAG`, or the begin, middle and
|
||||
@@ -323,11 +372,12 @@ impl Dictionary {
|
||||
let role = if index == 0 { self.compound_begin } else { self.compound_middle };
|
||||
for i in min..=w.len() - min {
|
||||
let (head, rest) = w.split_at(i);
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, false));
|
||||
let pos = if index == 0 { Pos::First } else { Pos::Middle };
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, pos));
|
||||
if !head_ok {
|
||||
continue;
|
||||
}
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, true)) {
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, Pos::Last)) {
|
||||
return true;
|
||||
}
|
||||
if self.compounded(rest, index + 1, failed) {
|
||||
@@ -346,18 +396,21 @@ impl Dictionary {
|
||||
return true;
|
||||
}
|
||||
let w: Vec<char> = word.chars().collect();
|
||||
if self.suffixed(&w, &[], false) {
|
||||
if self.suffixed(&w, &[], false, false) {
|
||||
return true;
|
||||
}
|
||||
for p in &self.pfx {
|
||||
if self.only_in_compound_affix(p) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_start(&w, &p.add, &p.strip) else { continue };
|
||||
if !p.cond_ok(&stem, true) {
|
||||
continue;
|
||||
}
|
||||
if self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
if !self.needs_another_affix(p) && self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
return true;
|
||||
}
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true) {
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true, !self.needs_another_affix(p)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1032,6 +1085,106 @@ SFX D Y 1\nSFX D 0 ed/S .\n";
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_give_compound_parts_their_flags() {
|
||||
// #2145, the way German frami builds compounds: the first and middle parts get their flags
|
||||
// from zero affixes' continuation classes, not from the root, and those roots need an affix.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDMIDDLE M\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nONLYINCOMPOUND O\nNEEDAFFIX N\n\
|
||||
COMPOUNDMIN 2\nSFX j Y 1\nSFX j 0 0/BOP .\nSFX m Y 1\nSFX m 0 0/MOP .\nPFX q Y 1\nPFX q 0 0/BO .\n\
|
||||
SFX s Y 1\nSFX s 0 e .\nSFX u Y 1\nSFX u 0 s .\nPFX v Y 1\nPFX v 0 un .\nSFX t Y 1\nSFX t 0 0/BNP .\n";
|
||||
let dic = "8\nvor/Nj\nschlag/OEs\nwerk/Njm\nzeug/OEs\nding/Nq\nhaus/Ev\ntag/Bs\ntor/t\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), dic.as_bytes());
|
||||
// First part through SFX j, middle part through SFX m (it carries the permit flag), last
|
||||
// part from its root, with or without a suffix there.
|
||||
for w in ["vorschlag", "vorschlage", "werkzeug", "werkzeuge", "vorwerkzeug", "werkhaus", "dinghaus"] {
|
||||
assert!(d.check(w), "{w}");
|
||||
}
|
||||
for w in [
|
||||
// A NEEDAFFIX or ONLYINCOMPOUND root alone, or a part with no compound flag at all.
|
||||
"vor",
|
||||
"werk",
|
||||
"schlag",
|
||||
"hausvor",
|
||||
"schlagzeug",
|
||||
// A suffix on the first part without the permit flag (s), and a prefix on a later part
|
||||
// without it (v).
|
||||
"vorschlageschlag",
|
||||
"werkunhaus",
|
||||
// tag carries B but its suffix s has no permit flag; SFX t gives B but carries NEEDAFFIX.
|
||||
"tageschlag",
|
||||
"torhaus",
|
||||
// Not words.
|
||||
"vorschlagx",
|
||||
"xvorschlag",
|
||||
] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_that_need_another_or_only_live_in_compounds_follow_hunspell() {
|
||||
// Each row as Hunspell 1.7.6 reads the same dictionary: `sun/X` and `cat/S`, `SFX S` adding
|
||||
// the compound flag X and NEEDAFFIX (N) or ONLYINCOMPOUND (O).
|
||||
let dict = |sfx: &str| {
|
||||
let aff = format!("COMPOUNDFLAG X\nCOMPOUNDMIN 3\nNEEDAFFIX N\nONLYINCOMPOUND O\nSFX S Y 1\nSFX S {sfx} .\n");
|
||||
Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice())
|
||||
};
|
||||
let rows: [(&str, &[&str], &[&str]); 4] = [
|
||||
// An affix that needs another finishes neither a word nor a compound part.
|
||||
("0 s/XN", &["sun", "cat"], &["cats", "suncats", "catssun"]),
|
||||
("0 0/XN", &["sun", "cat"], &["suncat"]),
|
||||
// At the end of a compound a compound-only suffix may be empty, not add letters.
|
||||
("0 s/XO", &["sun", "cat"], &["cats", "suncats"]),
|
||||
("0 0/XO", &["sun", "cat", "suncat"], &["catsun", "suncatsun"]),
|
||||
];
|
||||
for (sfx, good, bad) in rows {
|
||||
let d = dict(sfx);
|
||||
for w in good {
|
||||
assert!(d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_completes_a_suffix_that_needs_another_affix() {
|
||||
// As Hunspell 1.7.6 reads it: `work/US`, a suffix needing another affix (N). The prefix
|
||||
// completes it (`unworks`); alone it doesn't (`works`); when both need another, neither
|
||||
// completes the other.
|
||||
for (pfx, good, bad) in
|
||||
[("0 un", &["work", "unwork", "unworks"][..], &["works"][..]), ("0 un/N", &["work"][..], &["works", "unwork", "unworks"][..])]
|
||||
{
|
||||
let aff = format!("NEEDAFFIX N\nPFX U Y 1\nPFX U {pfx} .\nSFX S Y 1\nSFX S 0 s/N .\n");
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"1\nwork/US\n".as_slice());
|
||||
for w in good {
|
||||
assert!(d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_affix_carrying_the_compound_end_flag_only_ends_a_compound() {
|
||||
let aff = "COMPOUNDFLAG X\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/XEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice());
|
||||
assert!(d.check("suncats"));
|
||||
assert!(d.check("cats"));
|
||||
assert!(!d.check("catssun"));
|
||||
// Through the begin flag, the end flag on the suffix doesn't matter: Hunspell 1.7.6
|
||||
// accepts `catssun` here (and `cats`), and rejects `catsun`, `suncats` and `suncat`.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/BEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/E\ncat/S\n".as_slice());
|
||||
assert!(d.check("catssun"));
|
||||
assert!(d.check("cats"));
|
||||
for w in ["catsun", "suncats", "suncat"] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_compound_roots_with_a_failing_ending_stay_cheap() {
|
||||
// Roots a..aaaaaaaa overlap, so many splits of "aaa…ab" reach the same (tail, part) state; unmemoized that is millions of searches.
|
||||
|
||||
+242
-66
@@ -2779,6 +2779,64 @@ fn plain_outlines_are_unchanged() {
|
||||
assert_eq!(p.slides.first().map(|s| s.title()).as_deref(), Some("# Intro"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_outline_decodes_utf16_boms() {
|
||||
let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n";
|
||||
let want = vec![
|
||||
("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]),
|
||||
("Second".to_string(), vec![(0, "More".to_string())]),
|
||||
];
|
||||
|
||||
let mut utf16_le = vec![0xFF, 0xFE];
|
||||
utf16_le.extend(source.encode_utf16().flat_map(u16::to_le_bytes));
|
||||
|
||||
let mut utf16_be = vec![0xFE, 0xFF];
|
||||
utf16_be.extend(source.encode_utf16().flat_map(u16::to_be_bytes));
|
||||
|
||||
for (label, bytes) in [("utf-16le bom", utf16_le.as_slice()), ("utf-16be bom", utf16_be.as_slice())] {
|
||||
let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap();
|
||||
assert_eq!(outline_of(&p), want, "open_presentation ({label})");
|
||||
assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})");
|
||||
}
|
||||
|
||||
// Truncated trailing byte and unpaired surrogate in UTF-16LE replace rather than panic.
|
||||
let truncated_le = [0xFF, 0xFE, b'O', 0x00, b'k', 0x00, 0x00, 0xD8, 0x42];
|
||||
let p = crate::cmd::file::open_presentation("truncated.txt", &truncated_le).unwrap();
|
||||
assert_eq!(p.slides.len(), 1);
|
||||
assert_eq!(p.slides[0].title(), "Ok\u{FFFD}\u{FFFD}");
|
||||
assert_eq!(crate::cmd::file::outline_text(&truncated_le), "Ok\u{FFFD}\u{FFFD}");
|
||||
|
||||
// BOM-only UTF-16 files open as one blank slide.
|
||||
for bom in [&[0xFF, 0xFE][..], &[0xFE, 0xFF][..]] {
|
||||
let p = crate::cmd::file::open_presentation("empty.txt", bom).unwrap();
|
||||
assert_eq!(p.slides.len(), 1);
|
||||
assert_eq!(p.slides[0].title(), "");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_outline_strips_utf8_bom_and_keeps_plain_utf8() {
|
||||
let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n";
|
||||
let want = vec![
|
||||
("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]),
|
||||
("Second".to_string(), vec![(0, "More".to_string())]),
|
||||
];
|
||||
|
||||
let mut utf8_bom = vec![0xEF, 0xBB, 0xBF];
|
||||
utf8_bom.extend_from_slice(source.as_bytes());
|
||||
|
||||
for (label, bytes) in [("utf-8 bom", utf8_bom.as_slice()), ("utf-8 no bom", source.as_bytes())] {
|
||||
let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap();
|
||||
assert_eq!(outline_of(&p), want, "open_presentation ({label})");
|
||||
assert!(!p.slides[0].title().starts_with('\u{feff}'), "leading BOM kept ({label})");
|
||||
assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})");
|
||||
}
|
||||
|
||||
let p = crate::cmd::file::open_presentation("empty.txt", &[0xEF, 0xBB, 0xBF]).unwrap();
|
||||
assert_eq!(p.slides.len(), 1);
|
||||
assert_eq!(p.slides[0].title(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rtf_without_heading_paragraphs_opens_as_one_blank_slide() {
|
||||
let p = crate::cmd::file::open_presentation("empty.rtf", br"{\rtf1\ansi}").unwrap();
|
||||
@@ -6049,15 +6107,47 @@ fn table_cell_commands_reject_an_invalid_cell_and_name_the_registered_command()
|
||||
assert!(e.contains("table.insertColumnLeft"), "error should name the registered command: {e}");
|
||||
}
|
||||
|
||||
/// #2260 (the follow-up #1189's review named): a resize of a row or column the table doesn't
|
||||
/// have is an error, and leaves the presentation and the undo and redo history as they were.
|
||||
#[test]
|
||||
fn table_column_width_of_a_huge_column_is_ignored() {
|
||||
fn table_resize_rejects_a_row_or_column_past_the_table() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
|
||||
for keep_total in [true, false] {
|
||||
let r = s.execute("table.columnWidth", &json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": keep_total}));
|
||||
assert!(r.is_ok(), "columnWidth must ignore a huge col (keepTotal {keep_total}), got {r:?}");
|
||||
assert_eq!(table_of(&s, id).cols, vec![100.0, 100.0], "no column changes");
|
||||
// A row height undone, so there is a redo step for the rejected resizes to keep.
|
||||
s.execute("table.rowHeight", &json!({"id": id.0, "row": 0, "height": 30.0})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for (cmd, params) in [
|
||||
("table.rowHeight", json!({"id": id.0, "row": 2, "height": 50.0})),
|
||||
("table.rowHeight", json!({"id": id.0, "row": 99, "height": 50.0})),
|
||||
("table.columnWidth", json!({"id": id.0, "col": 2, "width": 50.0})),
|
||||
("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0})),
|
||||
("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0, "keepTotal": true})),
|
||||
("table.columnWidth", json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": true})),
|
||||
] {
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
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}");
|
||||
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");
|
||||
}
|
||||
// The history behaves as if they never ran: redo still brings back the row height.
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
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_in_range_still_works() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
s.execute("table.rowHeight", &json!({"id": id.0, "row": 1, "height": 50.0})).unwrap();
|
||||
s.execute("table.columnWidth", &json!({"id": id.0, "col": 1, "width": 150.0})).unwrap();
|
||||
let t = table_of(&s, id);
|
||||
assert_eq!(t.rows.get(1).map(|r| r.height), Some(50.0));
|
||||
assert_eq!(t.cols, vec![100.0, 150.0]);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 2, "one undo step each");
|
||||
}
|
||||
|
||||
/// Slides imported from an outline join the section of the slide they follow, like `slide.new`.
|
||||
@@ -7215,67 +7305,6 @@ fn invalid_slide_index_never_falls_back_to_the_selection_in_export_commands() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// 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");
|
||||
}
|
||||
|
||||
/// G6: with no sites given, shape.connect joins the sites that face each other along the
|
||||
/// dominant direction between the two shapes (a box mostly below leaves from the bottom), not
|
||||
/// "the closest pair", which for a diagonal neighbour picked a side site and crossed boxes.
|
||||
@@ -7774,6 +7803,153 @@ fn save_to_image_path_is_an_error_not_zip_bytes() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_save_paths_are_refused_and_write_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-ext-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for name in ["a.pptm", "a.ppt", "a.pot", "a.potm", "a.pps", "a.ppsm", "a.odp", "a.xml", "a.svg", "a.bmp", "a"] {
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let path = dir.join(name).to_string_lossy().to_string();
|
||||
let before = s.doc().unwrap().path.clone();
|
||||
let err = s.execute("file.saveAs", &json!({"path": path})).unwrap_err();
|
||||
assert!(err.to_string().contains("cannot save"), "{name}: {err}");
|
||||
assert!(!std::path::Path::new(&path).exists(), "{name} must not be written");
|
||||
assert_eq!(s.doc().unwrap().path, before, "{name}: the document keeps its path");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_paths_are_refused_even_with_an_explicit_format() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-ext-fmt-{}", 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("a.pptm").to_string_lossy().to_string();
|
||||
let err = s.execute("file.saveAs", &json!({"path": path, "format": "pptx"})).unwrap_err();
|
||||
assert!(err.to_string().contains("cannot save"), "{err}");
|
||||
assert!(!std::path::Path::new(&path).exists(), "the path guard wins over the explicit format");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_extensionless_save_is_refused_even_with_an_explicit_format() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-extless-{}", 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("no-extension").to_string_lossy().to_string();
|
||||
let err = s.execute("file.saveAs", &json!({"path": path, "format": "pptx"})).unwrap_err();
|
||||
assert!(err.to_string().contains("cannot save"), "{err}");
|
||||
assert!(!std::path::Path::new(&path).exists(), "the path guard wins over the explicit format");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_bytes_rejects_an_unknown_format() {
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let err = s.execute("file.saveBytes", &json!({"format": "odp"})).unwrap_err();
|
||||
assert!(err.to_string().contains("unknown save format"), "{err}");
|
||||
assert!(s.execute("file.saveBytes", &json!({"format": "deckcraft"})).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_export_paths_are_refused() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-export-ext-{}", 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("a.pptm").to_string_lossy().to_string();
|
||||
assert!(s.execute("file.export", &json!({"path": path})).is_err());
|
||||
assert!(!std::path::Path::new(&path).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensionless_export_with_an_explicit_format_still_writes() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-export-fmt-{}", 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("out").to_string_lossy().to_string();
|
||||
s.execute("file.export", &json!({"path": path, "format": "png", "slide": 0})).unwrap();
|
||||
assert!(std::path::Path::new(&path).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_paths_still_save() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-ok-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (name, magic) in [("a.pptx", b"PK".as_slice()), ("a.deckcraft", b"PK".as_slice()), ("a.txt", b"")] {
|
||||
let mut s = Session::new();
|
||||
sample::open_sample(&mut s).unwrap();
|
||||
let path = dir.join(name).to_string_lossy().to_string();
|
||||
s.execute("file.saveAs", &json!({"path": path})).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert!(!bytes.is_empty(), "{name}");
|
||||
if !magic.is_empty() {
|
||||
assert!(bytes.starts_with(magic), "{name}: not a ZIP");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_save_format_must_match_the_path() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-mismatch-{}", 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("a.pptx").to_string_lossy().to_string();
|
||||
std::fs::write(&path, b"sentinel").unwrap();
|
||||
let before = s.doc().unwrap().path.clone();
|
||||
let err = s.execute("file.saveAs", &json!({"path": path, "format": "deckcraft"})).unwrap_err();
|
||||
assert!(err.to_string().contains("does not match"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"sentinel", "the existing file is untouched");
|
||||
assert_eq!(s.doc().unwrap().path, before, "the document keeps its path");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_unsupported_destination_is_untouched() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-existing-{}", 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("a.pptm").to_string_lossy().to_string();
|
||||
std::fs::write(&path, b"sentinel").unwrap();
|
||||
let before = s.doc().unwrap().path.clone();
|
||||
let err = s.execute("file.saveAs", &json!({"path": path})).unwrap_err();
|
||||
assert!(err.to_string().contains("cannot save"), "{err}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"sentinel", "the existing file is untouched");
|
||||
assert_eq!(s.doc().unwrap().path, before, "the document keeps its path");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_txt_format_is_allowed_for_a_txt_path() {
|
||||
let dir = std::env::temp_dir().join(format!("deckcraft-save-txt-alias-{}", 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, "format": "txt"})).unwrap();
|
||||
assert!(!std::fs::read(&path).unwrap().is_empty());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `shape.connect` glues to a shape inside a group, as PowerPoint does: the connector's
|
||||
/// end is set to the grouped shape and follows it when the group moves. The glue was dropped at
|
||||
/// once (the end stayed `None`) because rerouting only looked at the slide's top-level shapes,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Standalone EMF and WMF files inserted as pictures (#2392).
|
||||
|
||||
use std::io::{Cursor, Read};
|
||||
|
||||
use craft_metafile::write::{Op, emf, wmf};
|
||||
use deckcraft_engine::Session;
|
||||
use deckcraft_engine::cmd::base64_encode;
|
||||
use deckcraft_geom::{KurboShape as _, Rect};
|
||||
use deckcraft_model::{ShapeId, ShapeKind};
|
||||
use serde_json::json;
|
||||
|
||||
/// Two solid rectangles, red at the top left and blue at the bottom right, on a 200 x 100 pt
|
||||
/// picture.
|
||||
fn two_rects() -> (Vec<Op>, Rect) {
|
||||
let fill = |r: Rect, rgb: [u8; 3]| Op::Fill { path: r.to_path(0.1), even_odd: false, rgb };
|
||||
(
|
||||
vec![fill(Rect::new(0.0, 0.0, 100.0, 50.0), [0xC7, 0x30, 0x40]), fill(Rect::new(100.0, 50.0, 200.0, 100.0), [0x20, 0x70, 0xD0])],
|
||||
Rect::new(0.0, 0.0, 200.0, 100.0),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_emf_and_wmf_files_insert_as_pictures_and_save_as_metafile_parts() {
|
||||
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, ext) in [("source.emf", emf, "emf"), ("source.wmf", wmf, "wmf")] {
|
||||
let mut s = Session::with_new();
|
||||
let rect = [200.0, 120.0, 480.0, 270.0];
|
||||
let r = s.execute("insert.picture", &json!({"data": base64_encode(&bytes), "name": name, "rect": rect})).expect(name);
|
||||
let id = ShapeId(r["id"].as_u64().expect("id") as u32);
|
||||
let doc = &s.doc().expect("doc").doc;
|
||||
let sh = doc.slides.iter().flat_map(|sl| &sl.shapes).find(|sh| sh.id == id).expect("inserted shape");
|
||||
let ShapeKind::Picture { fill } = &sh.kind else { panic!("{name} is a picture: {:?}", sh.kind) };
|
||||
let x = sh.xfrm.expect("xfrm");
|
||||
assert_eq!([x.x, x.y, x.w, x.h], rect, "{name} sits at the requested bounds");
|
||||
assert_eq!(doc.media(fill.media).expect("media").data.as_slice(), bytes.as_slice(), "{name} is embedded as given");
|
||||
|
||||
// Saved as a metafile part, and read back as the same picture.
|
||||
let pptx = deckcraft_pptx::export(doc).expect("export");
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(&pptx)).expect("zip");
|
||||
let part = z.file_names().find(|n| n.starts_with("ppt/media/") && n.ends_with(&format!(".{ext}"))).map(str::to_string);
|
||||
let part = part.unwrap_or_else(|| panic!("{name} is saved as a .{ext} part: {:?}", z.file_names().collect::<Vec<_>>()));
|
||||
let mut saved = Vec::new();
|
||||
z.by_name(&part).expect("part").read_to_end(&mut saved).expect("read");
|
||||
assert_eq!(saved, bytes, "{part} holds the file's bytes");
|
||||
let back = deckcraft_pptx::import(&pptx).expect("import");
|
||||
let reopened = back
|
||||
.slides
|
||||
.iter()
|
||||
.flat_map(|sl| &sl.shapes)
|
||||
.find(|sh| matches!(&sh.kind, ShapeKind::Picture { fill } if back.media(fill.media).is_some_and(|m| *m.data == bytes)));
|
||||
let reopened = reopened.unwrap_or_else(|| panic!("{name} reopens as a picture"));
|
||||
let x = reopened.xfrm.expect("reopened xfrm");
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
|
||||
assert!(
|
||||
near(x.x, rect[0]) && near(x.y, rect[1]) && near(x.w, rect[2]) && near(x.h, rect[3]),
|
||||
"{name} reopens at the requested bounds: {:?}",
|
||||
[x.x, x.y, x.w, x.h]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
mod chart_native;
|
||||
mod insert_metafile;
|
||||
mod show_clicks;
|
||||
|
||||
@@ -113,6 +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).
|
||||
code_page: u16,
|
||||
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
|
||||
out: Vec<(usize, String)>,
|
||||
}
|
||||
@@ -199,6 +202,7 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
|
||||
pending_skip: 0,
|
||||
skip_cont: 0,
|
||||
line: String::new(),
|
||||
code_page: 1252,
|
||||
out: vec![],
|
||||
};
|
||||
p.run(rtf);
|
||||
@@ -273,6 +277,12 @@ 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)) {
|
||||
self.code_page = cp;
|
||||
}
|
||||
}
|
||||
"tab" | "line" => self.line.push(' '),
|
||||
"uc" => self.st.uc = arg.unwrap_or(1).clamp(0, 8) as usize,
|
||||
"u" => self.unicode(i64::from(arg.unwrap_or(0))),
|
||||
@@ -294,14 +304,14 @@ impl Outline {
|
||||
self.pending_skip = self.st.uc;
|
||||
}
|
||||
|
||||
/// `\'hh`: one cp1252 byte.
|
||||
/// `\'hh`: one byte in the document's code page.
|
||||
fn hex_escape(&mut self, h: u8) {
|
||||
if self.pending_skip > 0 {
|
||||
self.pending_skip -= 1;
|
||||
return;
|
||||
}
|
||||
if !self.st.skip && h != 0 {
|
||||
self.line.push(craft_rtf::codepage::cp1252(h));
|
||||
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -621,6 +631,28 @@ 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.
|
||||
#[test]
|
||||
fn hex_escapes_decode_in_the_code_page_ansicpg_names() {
|
||||
let outline = |cpg: &str, title: &str, body: &str| {
|
||||
let rtf = format!(
|
||||
r"{{\rtf1\ansi{cpg}{{\stylesheet{{\s1 heading 1;}}{{\s2 heading 2;}}}}\pard\s1 {title}\par\pard\s2 {body}\par\pard\s1 Plain\par}}"
|
||||
);
|
||||
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
|
||||
assert_eq!(rtf_to_slides(&mut p, &rtf), 2, "{rtf}");
|
||||
crate::slides_to_outline(&p)
|
||||
};
|
||||
assert_eq!(
|
||||
outline(r"\ansicpg1250", r"\'8elu\'9dou\'e8k\'fd k\'f9\'f2", r"\'dap\'ecl \'ef\'e1belsk\'e9 \'f3dy"),
|
||||
"Žluťoučký kůň\n\tÚpěl ďábelské ódy\nPlain\n"
|
||||
);
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_heading_styles() {
|
||||
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
|
||||
|
||||
@@ -247,7 +247,11 @@ fn export_tool_lists_pdf_and_its_options() {
|
||||
assert!(formats.iter().any(|x| x == f), "format {f}: {export}");
|
||||
}
|
||||
assert_eq!(props["layout"]["enum"], json!(["slides", "notes", "handouts"]));
|
||||
assert_eq!(props["perPage"]["enum"], json!([1, 2, 3, 4, 6, 9]));
|
||||
// Gemini function declarations accept only string enums (#2211): perPage stays a plain integer
|
||||
// and the allowed values are spelled out in the description (the engine validates the set).
|
||||
assert_eq!(props["perPage"]["type"], "integer");
|
||||
assert!(props["perPage"].get("enum").is_none(), "{export}");
|
||||
assert!(props["perPage"]["description"].as_str().unwrap().contains("1, 2, 3, 4, 6 or 9"), "{export}");
|
||||
for p in ["dpi", "slides", "includeHidden", "textLayer", "frame", "paper", "orientation"] {
|
||||
assert!(props.get(p).is_some(), "{p}: {export}");
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"all": boolean("All slides (images)"),
|
||||
"scale": num("Pixels per point for images (default 2)"),
|
||||
"layout": {"type": "string", "enum": ["slides", "notes", "handouts"], "description": "PDF page layout (default slides)"},
|
||||
"perPage": {"type": "integer", "enum": [1, 2, 3, 4, 6, 9], "description": "PDF handouts: slides per page (default 6)"},
|
||||
"perPage": {"type": "integer", "description": "PDF handouts: slides per page (1, 2, 3, 4, 6 or 9; default 6)"},
|
||||
"dpi": num("PDF: raster resolution of slide artwork, 36-600 (default 200)"),
|
||||
"slides": {"type": "array", "items": {"type": "integer", "minimum": 0}, "description": "PDF and GIF: slide indices to export, in order (default all)"},
|
||||
"includeHidden": boolean("PDF and GIF: include hidden slides (default false)"),
|
||||
|
||||
@@ -990,13 +990,15 @@ fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm
|
||||
let finite = |v: f64| if v.is_finite() { v } else { 0.0 };
|
||||
let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy));
|
||||
let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs());
|
||||
let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 };
|
||||
if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) {
|
||||
let stored_rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 };
|
||||
if (45.0..135.0).contains(&stored_rot) || (225.0..315.0).contains(&stored_rot) {
|
||||
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
|
||||
std::mem::swap(&mut w, &mut h);
|
||||
x = cx - w / 2.0;
|
||||
y = cy - h / 2.0;
|
||||
}
|
||||
// A shape flipped in exactly one direction stores its angle mirrored; undo it.
|
||||
let rot = if flip_h ^ flip_v { (360.0 - stored_rot).rem_euclid(360.0) } else { stored_rot };
|
||||
Xfrm { x, y, w, h, rot, flip_h, flip_v }
|
||||
}
|
||||
|
||||
@@ -1072,4 +1074,35 @@ mod tests {
|
||||
assert_eq!(linear_angle(a), dm, "{a}");
|
||||
}
|
||||
}
|
||||
|
||||
/// [MS-ODRAW] stores the angle of a shape flipped in exactly one direction as 360° - θ.
|
||||
/// The importer must undo that before writing `a:xfrm rot` (#2407).
|
||||
#[test]
|
||||
fn a_single_flip_mirrors_the_stored_legacy_rotation_back() {
|
||||
let a = draw::Anchor { left: 0.0, top: 0.0, right: 100.0, bottom: 50.0 };
|
||||
let m = Map { sx: 1.0, sy: 1.0, ox: 0.0, oy: 0.0 };
|
||||
|
||||
// A 30° visual shape is stored as 330° with one flip.
|
||||
let h = xfrm(&a, m, 330.0, true, false);
|
||||
assert_eq!((h.rot, h.flip_h, h.flip_v), (30.0, true, false));
|
||||
let v = xfrm(&a, m, 330.0, false, true);
|
||||
assert_eq!((v.rot, v.flip_h, v.flip_v), (30.0, false, true));
|
||||
assert_eq!(xfrm(&a, m, 30.0, true, false).rot, 330.0);
|
||||
|
||||
// Both flips and no flip keep the stored angle.
|
||||
assert_eq!(xfrm(&a, m, 330.0, true, true).rot, 330.0);
|
||||
assert_eq!(xfrm(&a, m, 330.0, false, false).rot, 330.0);
|
||||
|
||||
// A 90° visual shape is stored as 270°; the box swap still follows the stored angle.
|
||||
let q = xfrm(&a, m, 270.0, true, false);
|
||||
assert_eq!((q.rot, q.w, q.h), (90.0, 50.0, 100.0));
|
||||
|
||||
// The wrap is applied before the mirror.
|
||||
assert_eq!(xfrm(&a, m, 360.0, true, false).rot, 0.0);
|
||||
assert_eq!(xfrm(&a, m, -30.0, true, false).rot, 30.0);
|
||||
|
||||
// A group's child map still applies before the flip correction.
|
||||
let g = xfrm(&a, Map { sx: 2.0, sy: 3.0, ox: 10.0, oy: 20.0 }, 330.0, true, false);
|
||||
assert_eq!((g.rot, g.x, g.y, g.w, g.h), (30.0, 10.0, 20.0, 200.0, 150.0));
|
||||
}
|
||||
}
|
||||
|
||||
+39
-15
@@ -376,18 +376,15 @@ Then wave"
|
||||
);
|
||||
}
|
||||
|
||||
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
|
||||
/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k
|
||||
/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search.
|
||||
#[test]
|
||||
fn many_character_runs_are_not_quadratic() {
|
||||
const N: usize = 640_000;
|
||||
let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
|
||||
/// A text box holding `n` one-character formatting runs (a character and a line break, alternating),
|
||||
/// as a legacy .ppt file.
|
||||
fn file_with_character_runs(n: usize) -> Vec<u8> {
|
||||
let text: String = (0..n).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect();
|
||||
let mut style = vec![];
|
||||
style.extend_from_slice(&(N as u32 + 1).to_le_bytes());
|
||||
style.extend_from_slice(&(n as u32 + 1).to_le_bytes());
|
||||
style.extend_from_slice(&0u16.to_le_bytes());
|
||||
style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields
|
||||
for _ in 0..=N {
|
||||
for _ in 0..=n {
|
||||
style.extend_from_slice(&1u32.to_le_bytes());
|
||||
style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields
|
||||
}
|
||||
@@ -398,12 +395,39 @@ fn many_character_runs_are_not_quadratic() {
|
||||
);
|
||||
let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]);
|
||||
let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None);
|
||||
let bytes = crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]);
|
||||
let t = std::time::Instant::now();
|
||||
let p = crate::import(&bytes).unwrap();
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
|
||||
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
|
||||
assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2);
|
||||
crate::cfb::build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])
|
||||
}
|
||||
|
||||
/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to
|
||||
/// scan the run starts from the beginning, so the cost grew with runs²: 640k one-character runs
|
||||
/// (about 6 MB of file) took 75 s that way in a debug build, and about 2 s with binary search.
|
||||
///
|
||||
/// The test compares two sizes in the same process instead of timing one against a fixed limit, so
|
||||
/// a slow or busy host (the FreeBSD CI VM took 20 to 31 s for the 640k file, mostly in the kernel,
|
||||
/// where a quiet one takes 2 s) slows both alike. Four times the runs take about four times as long
|
||||
/// when the work is linear and sixteen times as long when it is quadratic. Each size is the best of
|
||||
/// three imports, so a stall in one of them doesn't decide the result.
|
||||
#[test]
|
||||
fn many_character_runs_are_not_quadratic() {
|
||||
const SMALL: usize = 40_000;
|
||||
const LARGE: usize = 4 * SMALL;
|
||||
let best_of_three = |n: usize| {
|
||||
let bytes = file_with_character_runs(n);
|
||||
let mut best = std::time::Duration::MAX;
|
||||
let mut breaks = 0;
|
||||
for _ in 0..3 {
|
||||
let t = std::time::Instant::now();
|
||||
let p = crate::import(&bytes).unwrap();
|
||||
best = best.min(t.elapsed());
|
||||
let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs;
|
||||
breaks = runs.iter().filter(|r| r.kind == RunKind::Break).count();
|
||||
}
|
||||
(best, breaks)
|
||||
};
|
||||
let (small, small_breaks) = best_of_three(SMALL);
|
||||
let (large, large_breaks) = best_of_three(LARGE);
|
||||
assert_eq!((small_breaks, large_breaks), (SMALL / 2, LARGE / 2));
|
||||
assert!(large < small * 10, "{LARGE} runs took {large:?}, {SMALL} runs took {small:?}: more than 10x for 4x the runs");
|
||||
}
|
||||
|
||||
/// A slide naming a master that doesn't exist falls back to the first main master, every time. The
|
||||
|
||||
@@ -59,10 +59,6 @@ impl craft_pptx::Defaults for DeckDefaults {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn default_text_style(&self) -> craft_drawingml::text::ListStyle {
|
||||
convert::list_style_to_craft(&defaults::default_text_style())
|
||||
}
|
||||
|
||||
fn application(&self) -> &str {
|
||||
"DeckCraft"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Presentation text defaults across PPTX import, export and reopen.
|
||||
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
use craft_xml::Local;
|
||||
use deckcraft_model::{Presentation, defaults};
|
||||
|
||||
const PRESENTATION: &str = "ppt/presentation.xml";
|
||||
|
||||
fn imported_with_style(style_xml: &str) -> Presentation {
|
||||
let base = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("author fixture");
|
||||
let mut original = zip::ZipArchive::new(Cursor::new(base)).expect("open fixture package");
|
||||
let mut fixture = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..original.len() {
|
||||
let mut part = original.by_index(i).expect("package part");
|
||||
fixture.start_file(part.name(), zip::write::SimpleFileOptions::default()).expect("write package part");
|
||||
if part.name() == PRESENTATION {
|
||||
let mut xml = String::new();
|
||||
part.read_to_string(&mut xml).expect("author fixture presentation XML");
|
||||
let start = xml.find("<p:defaultTextStyle>").expect("new decks have a populated style");
|
||||
let end_tag = "</p:defaultTextStyle>";
|
||||
let end = xml.find(end_tag).expect("end of presentation text style") + end_tag.len();
|
||||
xml.replace_range(start..end, style_xml);
|
||||
fixture.write_all(xml.as_bytes()).expect("write fixture presentation XML");
|
||||
} else {
|
||||
std::io::copy(&mut part, &mut fixture).expect("copy fixture part");
|
||||
}
|
||||
}
|
||||
let bytes = fixture.finish().expect("finish fixture package").into_inner();
|
||||
deckcraft_pptx::import(&bytes).expect("import authored fixture")
|
||||
}
|
||||
|
||||
fn assert_empty_after_two_saves(mut presentation: Presentation) {
|
||||
assert!(presentation.default_text_style.is_empty(), "the imported style begins empty");
|
||||
for save in 1..=2 {
|
||||
let bytes = deckcraft_pptx::export(&presentation).expect("save PPTX");
|
||||
let mut package = zip::ZipArchive::new(Cursor::new(&bytes)).expect("open saved package");
|
||||
let mut xml = Vec::new();
|
||||
package.by_name(PRESENTATION).expect("presentation part").read_to_end(&mut xml).expect("read presentation XML");
|
||||
let document = craft_drawingml::xmlx::parse(&xml).expect("parse saved presentation XML");
|
||||
assert!(
|
||||
document.child(Local("defaultTextStyle")).is_none_or(|style| style.elements().next().is_none()),
|
||||
"save {save} must not add inherited text formatting to an empty presentation style"
|
||||
);
|
||||
presentation = deckcraft_pptx::import(&bytes).expect("reopen PPTX");
|
||||
assert!(presentation.default_text_style.is_empty(), "reopen {save} must retain the empty style");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_presentation_text_style_stays_empty_after_two_saves() {
|
||||
assert_empty_after_two_saves(imported_with_style(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_presentation_text_style_stays_empty_after_two_saves() {
|
||||
assert_empty_after_two_saves(imported_with_style("<p:defaultTextStyle/>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authored_presentation_text_styles_survive_two_saves() {
|
||||
let imported = imported_with_style(r#"<p:defaultTextStyle><a:lvl1pPr><a:defRPr kern="8800"/></a:lvl1pPr></p:defaultTextStyle>"#);
|
||||
assert_eq!(imported.default_text_style.level(0).expect("explicit level").run.kern, Some(88.0));
|
||||
let new_deck = defaults::new_presentation(None);
|
||||
assert!(!new_deck.default_text_style.is_empty());
|
||||
|
||||
for mut presentation in [imported, new_deck] {
|
||||
let expected = presentation.default_text_style.clone();
|
||||
for _ in 0..2 {
|
||||
let bytes = deckcraft_pptx::export(&presentation).expect("save authored style");
|
||||
presentation = deckcraft_pptx::import(&bytes).expect("reopen authored style");
|
||||
assert_eq!(presentation.default_text_style, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod corpus_kinds;
|
||||
mod corpus_media;
|
||||
mod corpus_style;
|
||||
mod corpus_themes;
|
||||
mod default_text_style;
|
||||
mod export_scale;
|
||||
mod fills;
|
||||
mod kept_parts;
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::{FontFace, UnicodeSegmentation};
|
||||
/// Is `family` a symbol font (characters at U+F000 + code)?
|
||||
pub(crate) fn is_symbol_font(family: &str) -> bool {
|
||||
let f = family.to_ascii_lowercase();
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett")
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett") || f.starts_with("monotype sorts")
|
||||
}
|
||||
|
||||
/// Does `face` draw the symbol-font character `c` (a U+F0xx private-use code)? Either directly at
|
||||
@@ -300,7 +300,11 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
}
|
||||
// Only the legacy symbol fonts: "Noto Sans Symbols" and the like are Unicode fonts whose
|
||||
// characters (❑ ❖) are drawn as they are. Private-use codes are mapped only when no font is named.
|
||||
if f.contains("wingdings") || f == "symbol" || (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first)) {
|
||||
if f.contains("wingdings")
|
||||
|| (f.starts_with("monotype sorts") && ((first as u32) < 0x100 || ('\u{f000}'..='\u{f0ff}').contains(&first)))
|
||||
|| f == "symbol"
|
||||
|| (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first))
|
||||
{
|
||||
let code = (first as u32) & 0xff;
|
||||
// Wingdings 2 and 3 put different shapes at the same codes.
|
||||
if f.starts_with("wingdings 2") {
|
||||
@@ -327,6 +331,8 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
return m.to_string();
|
||||
}
|
||||
let m = match code {
|
||||
0x6d if f.starts_with("monotype sorts") => '○',
|
||||
0xf0 if f.contains("wingdings") => '⇨',
|
||||
0xa7 => '▪',
|
||||
0xd8 => '➢',
|
||||
0xe8 => '➔',
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
use deckcraft_text::map_symbol_bullet;
|
||||
|
||||
#[test]
|
||||
fn monotype_sorts_m_bullet_is_open_circle() {
|
||||
assert_eq!(map_symbol_bullet("m", Some("Monotype Sorts")), "\u{25CB}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wingdings_eth_bullet_is_right_arrow() {
|
||||
assert_eq!(map_symbol_bullet("\u{f0}", Some("Wingdings")), "\u{21E8}");
|
||||
assert_eq!(map_symbol_bullet("\u{f0f0}", Some("Wingdings")), "\u{21E8}");
|
||||
}
|
||||
@@ -82,6 +82,11 @@ pub struct Show {
|
||||
notes_px: f32,
|
||||
timings: Vec<(usize, f64)>,
|
||||
last_move: f64,
|
||||
/// Leftover fraction of a discrete wheel line. High-resolution and free-spin wheels send
|
||||
/// fractions of a line, so the delta accumulates here and each whole line is one slide.
|
||||
wheel_carry: f32,
|
||||
/// A discrete wheel line was handled this frame, so the canvas tool must not turn the page too.
|
||||
wheel_taken: bool,
|
||||
pub ended: bool,
|
||||
/// The slide whose media was last started (auto-play runs once per visit).
|
||||
media_slide: Option<usize>,
|
||||
@@ -125,7 +130,16 @@ pub(crate) struct BackKey {
|
||||
struct Transition {
|
||||
/// The slide left behind, whose shapes Morph matches.
|
||||
from: Option<usize>,
|
||||
/// The time of the key press. A hidden show, which draws nothing, expires the transition
|
||||
/// from it.
|
||||
start: f64,
|
||||
/// Where the drawn transition's clock starts: the frame after the first one (see `progress`),
|
||||
/// because rendering the new slide and the transition's pictures can take longer than the
|
||||
/// whole transition (#1385). `None` until then.
|
||||
clock: Option<f64>,
|
||||
/// The first frame of the transition has been drawn: the new slide and the pictures the
|
||||
/// transition needs exist, so the time they took is not part of the transition.
|
||||
primed: bool,
|
||||
kind: String,
|
||||
option: String,
|
||||
dur: f64,
|
||||
@@ -134,6 +148,20 @@ struct Transition {
|
||||
reverse: bool,
|
||||
}
|
||||
|
||||
impl Transition {
|
||||
/// How far the transition has come at frame time `now`, from 0 to 1. The first frame is the
|
||||
/// one that renders the new slide and the transition's pictures and the second one starts the
|
||||
/// clock, so a slow render never eats the transition's duration (#1385).
|
||||
fn progress(&mut self, now: f64) -> f64 {
|
||||
if !self.primed {
|
||||
self.primed = true;
|
||||
return 0.0;
|
||||
}
|
||||
let clock = *self.clock.get_or_insert(now);
|
||||
((now - clock) / self.dur.max(0.01)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy of the show's clock origins for regressions that must not depend on wall time.
|
||||
#[cfg(test)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
@@ -209,6 +237,8 @@ impl Show {
|
||||
notes_px: NOTES_DEFAULT,
|
||||
timings: vec![],
|
||||
last_move: 0.0,
|
||||
wheel_carry: 0.0,
|
||||
wheel_taken: false,
|
||||
ended: false,
|
||||
media_slide: None,
|
||||
last_viewed: None,
|
||||
@@ -230,7 +260,7 @@ impl Show {
|
||||
.map(|t| (t.kind.clone(), t.option.clone(), t.duration_ms as f64 / 1000.0))
|
||||
.unwrap_or(("none".into(), String::new(), 0.0));
|
||||
self.trans = if kind != "none" && dur > 0.0 && !doc.show.without_animation {
|
||||
Some(Transition { from, start: now, kind, option, dur, reverse: false })
|
||||
Some(Transition { from, start: now, clock: None, primed: false, kind, option, dur, reverse: false })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -443,7 +473,7 @@ impl Show {
|
||||
// reversed Morph.
|
||||
let reverse = back && kind != "morph";
|
||||
self.trans = if kind != "none" && dur > 0.0 && !doc.show.without_animation {
|
||||
Some(Transition { from, start: now, kind, option, dur, reverse })
|
||||
Some(Transition { from, start: now, clock: None, primed: false, kind, option, dur, reverse })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -493,8 +493,8 @@ fn prepare_transition(
|
||||
store: &TextureStore<FrameKey>,
|
||||
frame: &mut PaintFrame,
|
||||
) {
|
||||
let Some(tr) = &show.trans else { return };
|
||||
let p = ((now - tr.start) / tr.dur.max(0.01)).clamp(0.0, 1.0);
|
||||
let Some(tr) = &mut show.trans else { return };
|
||||
let p = tr.progress(now);
|
||||
if p >= 1.0 {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -625,6 +625,29 @@ fn animations_start_after_the_slides_transition() {
|
||||
assert_eq!(show.clock_snapshot().step_start, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_first_frame_does_not_use_up_the_transition() {
|
||||
// #1385: the clock started at the key press, so rendering the new slide for longer than the
|
||||
// transition's duration showed the next slide with no transition at all.
|
||||
let mut s = deckcraft_engine::Session::with_new();
|
||||
s.execute("slide.new", &json!({})).unwrap();
|
||||
s.execute("transition.set", &json!({"kind": "fade", "index": 1, "duration": 500})).unwrap();
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let mut show = Show::new(&doc, 0, false, false);
|
||||
assert!(show.apply(ShowAction::Slide(1), &doc, 10.0));
|
||||
let tr = show.trans.as_mut().expect("the fade plays");
|
||||
assert!((tr.dur - 0.5).abs() < 1e-9);
|
||||
// The first frame renders for two seconds; it still shows the start of the transition.
|
||||
assert_eq!(tr.progress(10.0), 0.0);
|
||||
// The frame after it starts the clock.
|
||||
assert_eq!(tr.progress(12.0), 0.0);
|
||||
assert!((tr.progress(12.25) - 0.5).abs() < 1e-9);
|
||||
assert_eq!(tr.progress(12.5), 1.0);
|
||||
assert_eq!(tr.progress(20.0), 1.0);
|
||||
// A hidden show still expires it from the key press.
|
||||
assert_eq!(tr.start, 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_back_plays_the_left_slides_transition_reversed() {
|
||||
// #1531: Back plays the transition of the slide being left, in reverse.
|
||||
@@ -752,9 +775,18 @@ fn a_first_animation_after_or_with_previous_plays_when_the_slide_appears() {
|
||||
|
||||
/// A running show on the first of three slides, with presenter view off.
|
||||
fn show_of_three() -> egui_kittest::Harness<'static, SlideApp> {
|
||||
show_of_with_hidden(3, &[])
|
||||
}
|
||||
|
||||
/// A running show on the first of `slides`, with `hidden` slides hidden.
|
||||
fn show_of_with_hidden(slides: usize, hidden: &[usize]) -> egui_kittest::Harness<'static, SlideApp> {
|
||||
let mut session = deckcraft_engine::Session::with_new();
|
||||
session.execute("slide.new", &json!({})).unwrap();
|
||||
session.execute("slide.new", &json!({})).unwrap();
|
||||
for _ in 1..slides {
|
||||
session.execute("slide.new", &json!({})).unwrap();
|
||||
}
|
||||
for &i in hidden {
|
||||
session.execute("slide.hide", &json!({"index": i, "hidden": true})).unwrap();
|
||||
}
|
||||
let mut harness =
|
||||
harness_with(session, Services::default(), egui_kittest::Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0), |_| {});
|
||||
harness.state_mut().ui.presenter_view = false;
|
||||
@@ -801,10 +833,184 @@ fn ctrl_wheel_zooms_the_show_and_the_plain_wheel_turns_the_page() {
|
||||
assert!((show.view.zoom - fit).abs() < fit * 1e-3);
|
||||
|
||||
show_wheel(&mut h, centre, -3.0, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 1, "the plain wheel turns the page");
|
||||
// #1724: a -3.0 wheel event is three lines, so three slides (clamped to the last of three).
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 2, "the plain wheel turns the page");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1724: two discrete wheel notches inside the trackpad's old 0.35 s cooldown turn two slides.
|
||||
/// One notch is one slide; the second notch must not be dropped by a gesture gate.
|
||||
#[test]
|
||||
fn two_wheel_notches_inside_the_trackpad_cooldown_turn_two_slides() {
|
||||
let mut h = show_of_three();
|
||||
let centre = pos2(500.0, 350.0);
|
||||
let notch = |harness: &mut egui_kittest::Harness<'static, SlideApp>, steps: usize| {
|
||||
harness.input_mut().events.push(egui::Event::PointerMoved(centre));
|
||||
harness.input_mut().events.push(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
harness.run_steps(steps);
|
||||
};
|
||||
notch(&mut h, 4);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 1, "one notch turns one slide");
|
||||
notch(&mut h, 4);
|
||||
assert_eq!(
|
||||
h.state().show.as_ref().expect("still showing").state.slide,
|
||||
2,
|
||||
"a second notch inside the old trackpad cooldown still turns the next slide"
|
||||
);
|
||||
}
|
||||
|
||||
/// #1724: on the end screen a discrete wheel notch keeps the old semantics: forward exits
|
||||
/// the show, back resumes the last slide instead of jumping.
|
||||
#[test]
|
||||
fn wheel_on_the_end_screen_exits_forward_and_resumes_back() {
|
||||
let mut h = show_of_three();
|
||||
let centre = pos2(500.0, 350.0);
|
||||
let line = |harness: &mut egui_kittest::Harness<'static, SlideApp>, y: f32| {
|
||||
harness.input_mut().events.push(egui::Event::PointerMoved(centre));
|
||||
harness.input_mut().events.push(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: vec2(0.0, y),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
harness.run_steps(4);
|
||||
};
|
||||
line(&mut h, -1.0);
|
||||
line(&mut h, -1.0);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 2);
|
||||
line(&mut h, -1.0);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended, "past the last slide: the end screen");
|
||||
// Back resumes the last slide instead of jumping to the one before it.
|
||||
line(&mut h, 1.0);
|
||||
let show = h.state().show.as_ref().expect("still showing");
|
||||
assert!(!show.ended, "a backward notch leaves the end screen");
|
||||
assert_eq!(show.state.slide, 2, "it resumes the last slide");
|
||||
// Forward past the end again, then a forward notch exits.
|
||||
line(&mut h, -1.0);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended);
|
||||
line(&mut h, -1.0);
|
||||
assert!(h.state().show.is_none(), "a forward notch on the end screen exits the show");
|
||||
}
|
||||
|
||||
/// Backward from an end screen reached on a hidden tail resumes the last visible slide, not the
|
||||
/// hidden slide the show was left on.
|
||||
#[test]
|
||||
fn wheel_back_on_an_end_screen_from_a_hidden_tail_resumes_the_last_visible_slide() {
|
||||
let mut h = show_of_with_hidden(4, &[3]);
|
||||
let doc = h.state().session.active().unwrap().doc.clone();
|
||||
h.state_mut().show.as_mut().unwrap().state.goto(&doc, 3);
|
||||
h.run_steps(2);
|
||||
show_wheel(&mut h, pos2(500.0, 350.0), -1.0, egui::Modifiers::NONE);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended, "the hidden tail has no forward slide");
|
||||
show_wheel(&mut h, pos2(500.0, 350.0), 1.0, egui::Modifiers::NONE);
|
||||
let show = h.state().show.as_ref().expect("still showing");
|
||||
assert!(!show.ended, "a backward notch leaves the end screen");
|
||||
assert_eq!(show.state.slide, 2, "it resumes the last visible slide, not the hidden one");
|
||||
}
|
||||
|
||||
/// A looping show wraps a forward wheel notch from the last visible slide to the first instead
|
||||
/// of entering the end screen.
|
||||
#[test]
|
||||
fn wheel_forward_on_the_last_slide_wraps_in_a_looping_show() {
|
||||
let mut h = show_of_three();
|
||||
let st = h.state_mut().session.active_mut().unwrap();
|
||||
std::sync::Arc::make_mut(&mut st.doc).show.loop_until_esc = true;
|
||||
let centre = pos2(500.0, 350.0);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 2);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
let show = h.state().show.as_ref().expect("still showing");
|
||||
assert!(!show.ended, "the looping show does not end");
|
||||
assert_eq!(show.state.slide, 0, "it wraps to the first visible slide");
|
||||
}
|
||||
|
||||
/// The wheel turns slides through the show's visible order, so a hidden slide is skipped as
|
||||
/// ←/→ skip it instead of opening it through `ShowState::goto`.
|
||||
#[test]
|
||||
fn a_wheel_notch_skips_a_hidden_slide() {
|
||||
let mut h = show_of_with_hidden(3, &[1]);
|
||||
let centre = pos2(500.0, 350.0);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 2, "the hidden middle slide is skipped");
|
||||
show_wheel(&mut h, centre, 1.0, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 0, "back also skips it");
|
||||
}
|
||||
|
||||
/// Two notches in one frame are applied in the order they arrived: a backward then a forward
|
||||
/// notch at the first slide still moves forward (a signed net would cancel them out).
|
||||
#[test]
|
||||
fn a_backward_then_forward_notch_in_one_frame_still_moves_forward() {
|
||||
let mut h = show_of_three();
|
||||
let centre = pos2(500.0, 350.0);
|
||||
h.input_mut().events.push(egui::Event::PointerMoved(centre));
|
||||
for y in [1.0_f32, -1.0] {
|
||||
h.input_mut().events.push(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: vec2(0.0, y),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 1, "the forward notch still moves one slide");
|
||||
}
|
||||
|
||||
/// A backward notch with two lines on the end screen resumes the last slide and still steps one
|
||||
/// more back, matching the per-line contract of the ordinary-slide path.
|
||||
#[test]
|
||||
fn two_backward_lines_on_the_end_screen_reach_the_penultimate_slide() {
|
||||
let mut h = show_of_three();
|
||||
let centre = pos2(500.0, 350.0);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended, "at the end screen");
|
||||
show_wheel(&mut h, centre, 2.0, egui::Modifiers::NONE);
|
||||
let show = h.state().show.as_ref().expect("still showing");
|
||||
assert!(!show.ended, "two backward lines leave the end screen");
|
||||
assert_eq!(show.state.slide, 1, "the last slide then one more back");
|
||||
}
|
||||
|
||||
/// A hidden slide after the last visible one has no forward neighbour; a notch there still shows
|
||||
/// the end screen instead of doing nothing.
|
||||
#[test]
|
||||
fn a_forward_notch_on_a_hidden_slide_after_the_last_visible_ones_ends_the_show() {
|
||||
let mut h = show_of_with_hidden(4, &[3]);
|
||||
let doc = h.state().session.active().unwrap().doc.clone();
|
||||
h.state_mut().show.as_mut().unwrap().state.goto(&doc, 3);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 3);
|
||||
show_wheel(&mut h, pos2(500.0, 350.0), -1.0, egui::Modifiers::NONE);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended, "no visible slide ahead: the end screen");
|
||||
}
|
||||
|
||||
/// A completed forward wheel notch past the last slide reaches the end screen and then exits,
|
||||
/// the same way a trackpad flick does; a partial line still does nothing.
|
||||
#[test]
|
||||
fn a_forward_wheel_notch_past_the_last_slide_reaches_the_end_screen() {
|
||||
let mut h = show_of_three();
|
||||
let centre = pos2(500.0, 350.0);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert_eq!(h.state().show.as_ref().expect("still showing").state.slide, 2);
|
||||
// A partial line on the last slide does not end the show.
|
||||
show_wheel(&mut h, centre, -0.4, egui::Modifiers::NONE);
|
||||
assert!(!h.state().show.as_ref().expect("still showing").ended, "a partial notch does not reach the end screen");
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert!(h.state().show.as_ref().expect("still showing").ended, "a completed forward notch reaches the end screen");
|
||||
show_wheel(&mut h, centre, -1.0, egui::Modifiers::NONE);
|
||||
assert!(h.state().show.is_none(), "forward on the end screen exits the show");
|
||||
}
|
||||
|
||||
/// A zoom at the top of the letterboxed slide keeps the slide over the fitted picture, as production's zoom window
|
||||
/// stays on the slide: its top edge stays at the picture's, not pushed up to the window's.
|
||||
#[test]
|
||||
|
||||
@@ -112,6 +112,7 @@ impl CanvasTool for ShowTool<'_> {
|
||||
if !self.show.zoomed
|
||||
&& !self.show.pen
|
||||
&& !self.show.grid
|
||||
&& !self.show.wheel_taken
|
||||
&& let Some(wheel) = space.wheel()
|
||||
&& !wheel.zooms
|
||||
{
|
||||
|
||||
@@ -143,6 +143,12 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
if show.reading {
|
||||
bars::show(ui, show, p.doc, p.room, p.now);
|
||||
}
|
||||
// A discrete mouse-wheel notch turns one slide per line at once; point-based trackpad
|
||||
// gestures keep the canvas's own page turn.
|
||||
show.wheel_taken = false;
|
||||
if !show.pen && !show.zoomed {
|
||||
wheel_lines(&ctx, show, p.doc, out);
|
||||
}
|
||||
let mut media_wake = None;
|
||||
with_env(
|
||||
ui,
|
||||
@@ -220,6 +226,98 @@ fn canvas_pass(app: &mut SlideApp, ui: &mut Ui, bcx: &mut BodyCx<'_>, show: &mut
|
||||
media_wake
|
||||
}
|
||||
|
||||
/// Discrete wheel input must not share the trackpad's gesture gate. Keep every completed line in
|
||||
/// the order it arrived, including several notches in one frame, so movement at a boundary is not
|
||||
/// lost: a backward then forward notch at the first slide still moves forward. High-resolution
|
||||
/// 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) {
|
||||
// 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();
|
||||
let mut steps = Vec::new();
|
||||
let mut handled = false;
|
||||
ctx.input_mut(|input| {
|
||||
let slides = doc.slides.len();
|
||||
input.events.retain(|event| {
|
||||
let egui::Event::MouseWheel { unit, delta, modifiers, .. } = event else { return true };
|
||||
if !matches!(unit, egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page)
|
||||
|| modifiers.ctrl
|
||||
|| modifiers.command
|
||||
|| modifiers.shift
|
||||
|| !delta.y.is_finite()
|
||||
|| delta.y == 0.0
|
||||
|| delta.y.abs() < delta.x.abs()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if act {
|
||||
if show.wheel_carry * delta.y < 0.0 {
|
||||
show.wheel_carry = 0.0;
|
||||
}
|
||||
show.wheel_carry += delta.y;
|
||||
// The small slack keeps sums such as 10 × 0.1 from falling just short of a line.
|
||||
let whole = (show.wheel_carry.abs() + 1e-4).floor();
|
||||
show.wheel_carry -= whole.copysign(show.wheel_carry);
|
||||
let count = whole.min(slides as f32) as usize;
|
||||
if count > 0 {
|
||||
steps.push(if delta.y < 0.0 { count as i32 } else { -(count as i32) });
|
||||
}
|
||||
}
|
||||
handled = true;
|
||||
false
|
||||
});
|
||||
});
|
||||
show.wheel_taken = handled;
|
||||
if !handled || !act {
|
||||
return;
|
||||
}
|
||||
// Each line is applied in arrival order against the state the preceding line left.
|
||||
for by in steps {
|
||||
let count = by.unsigned_abs() as usize;
|
||||
if show.ended {
|
||||
if by > 0 {
|
||||
out.keep = false;
|
||||
break;
|
||||
}
|
||||
show.ended = false;
|
||||
// Resume the last visible slide, even when the show ended from a hidden tail.
|
||||
let Some(target) = show.state.last_index(doc) else { continue };
|
||||
out.actions.push(show.state.goto(doc, target));
|
||||
if count > 1
|
||||
&& let Some(target) = show.state.visible_step_clamped(doc, target, false, count - 1)
|
||||
{
|
||||
out.actions.push(show.state.goto(doc, target));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let forward = by > 0;
|
||||
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 => {
|
||||
// A looping show wraps from its last visible slide to the first instead of ending.
|
||||
if deckcraft_anim::looping(doc)
|
||||
&& let Some(first) = show.state.first_index(doc)
|
||||
{
|
||||
out.actions.push(show.state.goto(doc, first));
|
||||
if count > 1
|
||||
&& let Some(target) = show.state.visible_step_clamped(doc, first, true, count - 1)
|
||||
{
|
||||
out.actions.push(show.state.goto(doc, target));
|
||||
}
|
||||
} else {
|
||||
// A notch that cannot move forward shows the end screen instead of being
|
||||
// swallowed, as a trackpad flick past the last slide does.
|
||||
show.state.end();
|
||||
show.ended = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The slide's rect on screen when fitted to `rect`, as the unzoomed show draws it.
|
||||
fn fitted_picture(rect: Rect, target: &ViewTarget, zoom: &ShowZoomInputs<'_>) -> Rect {
|
||||
let mut view = CanvasView::new(rect, Point::ZERO, 1.0);
|
||||
|
||||
Reference in New Issue
Block a user