Compare commits

..
Author SHA1 Message Date
autocraft-bot[bot] f1ac9bf7cf Merge main (3a6082b4) into the pull request
I resolved the three conflicts in crates/engine/src/lib.rs and kept both

I resolved the three conflicts in crates/engine/src/lib.rs and kept both sides. The DocState field and its constructor now hold the PR's `autocorrected` and the default branch's `notes_run` and `notes_before`. In `execute`, the default branch's notes-joining logic is kept. The PR's extra "AutoCorrect" undo step is pushed only in the branch that records a normal undo entry, with `vertex_kind.clone()` as in the PR. The PR's new test `undo_takes_back_only_the_autocorrect` passes, as do the 9 notes tests, and `cargo fmt --check` is clean. I did not run clippy or the full engine test suite.
2026-12-02 19:08:25 +00:00
autocraft-bot[bot] 0b1399df94 Apply review fixes
- crates/engine/src/cmd/text/autocorrect.rs
- crates/engine/src/tests.rs
2026-11-17 09:04:28 +00:00
Luis 2359e5c066 AutoCorrect: Undo takes back only the correction (#2184)
Typing the space that set off AutoCorrect and the correction were one undo step, so Ctrl+Z removed the space too and typing it again corrected the word again. The correction (word replacement, sentence caps, ordinal superscripts) is now its own undo step on top of the typed character, as in PowerPoint.
2026-11-17 09:01:43 +01:00
21 changed files with 92 additions and 891 deletions
+7 -65
View File
@@ -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 = if rtf { String::from_utf8_lossy(bytes).into_owned() } else { decode_outline_bytes(bytes) };
let text = String::from_utf8_lossy(bytes);
let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
if rtf {
deckcraft_format::rtf::rtf_to_slides(&mut p, &text);
@@ -234,37 +234,10 @@ fn probe_clips(p: &mut Presentation) {
}
}
/// 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.
/// An outline file's text: RTF is read into the tab-indented outline, anything else as UTF-8.
pub fn outline_text(bytes: &[u8]) -> String {
if deckcraft_format::rtf::sniff_rtf(bytes) {
deckcraft_format::rtf::rtf_to_outline(&String::from_utf8_lossy(bytes))
} else {
decode_outline_bytes(bytes)
}
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() }
}
pub fn add_opened(s: &mut Session, name: &str, path: Option<String>, p: Presentation) -> usize {
@@ -399,8 +372,7 @@ 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" => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())),
_ => Err(EngineError::Other(format!("unknown save format `{format}`"))),
_ => deckcraft_format::save(doc).map_err(|e| EngineError::Other(e.to_string())),
}
}
@@ -494,27 +466,6 @@ 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)
@@ -564,13 +515,7 @@ 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 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 format = str_param(p, "format").unwrap_or(format_for_path(&path));
let bytes = save_bytes(&s.doc()?.doc, format)?;
write_file(&path, &bytes)?;
mark_saved(s, Some(path.clone()))?;
@@ -657,10 +602,7 @@ 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 = match str_param(p, "format") {
Some(f) => f.to_string(),
None => writable_format(&path)?.to_string(),
};
let format = str_param(p, "format").unwrap_or(format_for_path(&path)).to_string();
let st = s.doc()?;
let scale = finite_scale(f64_or(p, "scale", 2.0));
let transparent = bool_or(p, "transparentBackground", false);
-2
View File
@@ -279,7 +279,6 @@ 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),
@@ -301,7 +300,6 @@ 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)?;
-37
View File
@@ -73,19 +73,6 @@ 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))
@@ -188,10 +175,6 @@ 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));
@@ -261,23 +244,3 @@ 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");
}
}
+1 -67
View File
@@ -182,7 +182,7 @@ mod tests {
use deckcraft_model::ShapeId;
use serde_json::json;
use crate::cmd::{base64_decode, base64_encode};
use crate::cmd::base64_encode;
use crate::{MediaStatus, Session, UiRequest};
fn wav() -> Vec<u8> {
@@ -291,72 +291,6 @@ 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();
+2 -94
View File
@@ -501,19 +501,15 @@ 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). 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.
/// `doc` are shared; a linked item keeps its link).
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() || m.content_type.eq_ignore_ascii_case(TAGS_CONTENT_TYPE) {
let new = if m.link.is_some() {
let mut item = m.clone();
item.id = MediaId(doc.alloc_id().ok_or_else(|| bad(cmd, NO_ID_SPACE))?);
let new = item.id;
@@ -796,94 +792,6 @@ 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 },
+1 -66
View File
@@ -246,26 +246,6 @@ 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![];
@@ -281,12 +261,8 @@ fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
| deckcraft_model::ShapeKind::Media(_)
| deckcraft_model::ShapeKind::Group { .. }
);
if sh.descr.trim().is_empty() && !sh.decorative && (needs_alt || crate::icons::is_inserted_icon(sh)) {
if needs_alt && sh.descr.trim().is_empty() && !sh.decorative {
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.
@@ -1065,45 +1041,4 @@ 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));
}
}
+1 -29
View File
@@ -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.
pub(crate) fn reassign_sections(doc: &mut Presentation, moved: &[SlideId], at: usize) {
fn reassign_sections(doc: &mut Presentation, moved: &[SlideId], at: usize) {
if doc.sections.is_empty() {
return;
}
@@ -690,11 +690,6 @@ 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);
@@ -987,29 +982,6 @@ 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();
-8
View File
@@ -725,18 +725,11 @@ 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());
@@ -765,7 +758,6 @@ 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;
}
+4 -2
View File
@@ -168,9 +168,9 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
while start > 0 && line.get(start - 1).is_some_and(|c| !c.is_whitespace()) {
start -= 1;
}
// "word," and "word." also count: the punctuation was typed before the space.
// "word," and "word." also count when the text came in one piece; a typed punctuation mark already ran AutoCorrect on the word, and an Undo of that correction stays (#2184).
let mut word: String = line.get(start..word_end).map(|w| w.iter().collect()).unwrap_or_default();
if replacement(&s.prefs, &word).is_none() {
if !typing && replacement(&s.prefs, &word).is_none() {
let trimmed = word.trim_end_matches(|c: char| ".,;:!?".contains(c));
if !trimmed.is_empty() && trimmed.len() < word.len() && !word.ends_with("...") {
word_end -= word.chars().count() - trimmed.chars().count();
@@ -195,6 +195,7 @@ pub(super) fn autocorrect(s: &mut Session, typing: bool) -> Result<()> {
};
let delta = rep.chars().count() as isize - word.chars().count() as isize;
let st = s.doc_mut()?;
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
let mut d = (*st.doc).clone();
let sel = st.selection.clone();
if let Some(b) = body_mut(&mut d, &sel, &t) {
@@ -315,6 +316,7 @@ fn superscript_suffix(s: &mut Session, t: &crate::TextSel, end: usize) -> Result
if body_of(st, t).is_none_or(|body| ed::props_at(body, b).baseline.unwrap_or(0.0) > 0.0) {
return Ok(());
}
st.autocorrected = Some((st.doc.clone(), st.selection.clone()));
let mut d = (*st.doc).clone();
let sel = st.selection.clone();
if let Some(body) = body_mut(&mut d, &sel, t) {
+1 -38
View File
@@ -514,24 +514,14 @@ 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);
}
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);
}
doc.slides.remove(change.slide);
Ok(Some(change.slide.min(doc.slides.len().saturating_sub(1))))
}
}
@@ -821,33 +811,6 @@ 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();
-45
View File
@@ -12,14 +12,6 @@ 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,
@@ -218,43 +210,6 @@ 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;
+13 -1
View File
@@ -237,6 +237,9 @@ pub struct DocState {
/// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after
/// can put the typed text back.
pub auto_list: Option<cmd::text::AutoList>,
/// The presentation and selection between a typed character and the AutoCorrect it set off,
/// so the command's undo step splits in two and Undo takes back only the correction (#2184).
pub autocorrected: Option<(Arc<Presentation>, Selection)>,
/// The slide whose editor's consecutive notes changes share one undo step.
pub notes_run: Option<SlideId>,
notes_before: Option<Arc<Presentation>>,
@@ -269,6 +272,7 @@ impl DocState {
compare: None,
last_duplicate: None,
auto_list: None,
autocorrected: None,
notes_run: None,
notes_before: None,
}
@@ -729,6 +733,9 @@ impl Session {
}
if outer {
self.tool.vertex_kind = vertex_kind;
if let Some(st) = self.active_mut() {
st.autocorrected = None;
}
}
return Err(e);
}
@@ -736,6 +743,7 @@ impl Session {
if let Some(st) = self.active_mut() {
clamp_selection(st);
}
let autocorrected = if outer { self.active_mut().and_then(|st| st.autocorrected.take()) } else { None };
if let (Some((uid, old, sel)), Some(st)) = (before, self.active_mut())
&& st.uid == uid
&& !Arc::ptr_eq(&old, &st.doc)
@@ -753,8 +761,12 @@ impl Session {
}
} else {
let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone());
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind });
push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind: vertex_kind.clone() });
st.notes_before = notes_before;
// The text as typed, before AutoCorrect changed it: its own step, undone first.
if let Some((doc, selection)) = autocorrected.filter(|(doc, _)| !Arc::ptr_eq(doc, &st.doc)) {
push_undo(st, HistoryEntry { label: "AutoCorrect".into(), doc, selection, vertex_kind });
}
}
}
if spec.journal && outer {
+50 -242
View File
@@ -2779,64 +2779,6 @@ 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();
@@ -5359,6 +5301,51 @@ fn autocorrect_options_as_you_type() {
assert_eq!(s.execute("text.get", &json!({"id": title})).unwrap()["text"], "monday notes ");
}
/// #2184: Undo right after AutoCorrect takes back only the correction; the space that set it off
/// stays, and typing on does not correct the word again. A second Undo removes the space.
#[test]
fn undo_takes_back_only_the_autocorrect() {
let mut s = session();
let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0;
let text = |s: &Session| {
s.doc().unwrap().current_slide().unwrap().shapes.iter().find(|sh| sh.id.0 == title).unwrap().text.as_ref().unwrap().paragraphs[0].text()
};
s.execute("text.edit", &json!({"id": title})).unwrap();
for c in "hello ".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "Hello ");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hello ", "the correction is undone, the space stays");
assert_eq!(s.doc().unwrap().selection.text.as_ref().map(|t| t.caret), Some((0, 6)), "the caret stays after the space");
// Redo brings the correction back.
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(text(&s), "Hello ");
s.execute("edit.undo", &json!({})).unwrap();
for c in "world ".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "hello world ", "typing on leaves the word as it is");
for _ in 0.."world ".len() {
s.execute("edit.undo", &json!({})).unwrap();
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hello", "the next Undo removes the space");
// Typing that AutoCorrect leaves alone is still one step per character.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s), "hell");
// A typed comma sets AutoCorrect off too; the space after it leaves the undone word alone.
s.execute("text.selectAll", &json!({})).ok();
s.execute("text.delete", &json!({"dir": "backward"})).ok();
for c in "hello,".chars() {
s.execute("text.insert", &json!({"text": c.to_string()})).unwrap();
}
assert_eq!(text(&s), "Hello,");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("text.insert", &json!({"text": " "})).unwrap();
assert_eq!(text(&s), "hello, ", "the space after the comma leaves the undone word alone");
}
#[test]
fn autocorrect_superscripts_ordinals_as_you_type() {
let mut s = session();
@@ -6107,47 +6094,15 @@ 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_resize_rejects_a_row_or_column_past_the_table() {
fn table_column_width_of_a_huge_column_is_ignored() {
let mut s = session();
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
// 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, &params).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");
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");
}
// 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`.
@@ -7803,153 +7758,6 @@ 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,
+2 -34
View File
@@ -113,9 +113,6 @@ 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)>,
}
@@ -202,7 +199,6 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
pending_skip: 0,
skip_cont: 0,
line: String::new(),
code_page: 1252,
out: vec![],
};
p.run(rtf);
@@ -277,12 +273,6 @@ 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))),
@@ -304,14 +294,14 @@ impl Outline {
self.pending_skip = self.st.uc;
}
/// `\'hh`: one byte in the document's code page.
/// `\'hh`: one cp1252 byte.
fn hex_escape(&mut self, h: u8) {
if self.pending_skip > 0 {
self.pending_skip -= 1;
return;
}
if !self.st.skip && h != 0 {
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
self.line.push(craft_rtf::codepage::cp1252(h));
}
}
@@ -631,28 +621,6 @@ 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);
+2 -35
View File
@@ -990,15 +990,13 @@ 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 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 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 (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 }
}
@@ -1074,35 +1072,4 @@ 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));
}
}
+4
View File
@@ -59,6 +59,10 @@ 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"
}
@@ -1,75 +0,0 @@
//! 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);
}
}
}
-1
View File
@@ -9,7 +9,6 @@ mod corpus_kinds;
mod corpus_media;
mod corpus_style;
mod corpus_themes;
mod default_text_style;
mod export_scale;
mod fills;
mod kept_parts;
+2 -25
View File
@@ -125,16 +125,7 @@ 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,
@@ -143,20 +134,6 @@ 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)]
@@ -253,7 +230,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, clock: None, primed: false, kind, option, dur, reverse: false })
Some(Transition { from, start: now, kind, option, dur, reverse: false })
} else {
None
};
@@ -466,7 +443,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, clock: None, primed: false, kind, option, dur, reverse })
Some(Transition { from, start: now, kind, option, dur, reverse })
} else {
None
};
+2 -2
View File
@@ -493,8 +493,8 @@ fn prepare_transition(
store: &TextureStore<FrameKey>,
frame: &mut PaintFrame,
) {
let Some(tr) = &mut show.trans else { return };
let p = tr.progress(now);
let Some(tr) = &show.trans else { return };
let p = ((now - tr.start) / tr.dur.max(0.01)).clamp(0.0, 1.0);
if p >= 1.0 {
return;
}
-23
View File
@@ -625,29 +625,6 @@ 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.