Compare commits

..
20 changed files with 57 additions and 846 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;
}
+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;
+21 -243
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();
@@ -5859,15 +5801,30 @@ fn a_long_ink_stroke_is_extended_in_place_and_capped() {
fn double_clicking_a_capped_freeform_keeps_its_vertices() {
let mut s = session();
let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 3.0, pressure: None };
let point_cap = 16;
s.set_tool(tools::ToolKind::Shape { preset: "freeform".into() });
assert_eq!(s.tool.press_point_cap(), tools::MAX_GESTURE_POINTS);
s.tool.freeform_press_point_cap = Some(point_cap);
s.pointer(ev(tools::PointerKind::Down, 100.0, 100.0)).unwrap();
// Densely clicked vertices, each within the double-click tolerance of the last.
for i in 0..tools::MAX_GESTURE_POINTS + 10 {
// The first press counts toward the cap, so 11 of these presses add no point.
for i in 0..point_cap + 10 {
s.pointer(ev(tools::PointerKind::Down, 300.0 + i as f64 * 0.001, 100.0)).unwrap();
}
s.pointer(ev(tools::PointerKind::DoubleClick, 300.0, 100.0)).unwrap();
let st = s.doc().unwrap();
let deckcraft_model::Geom::Custom { paths } = &st.shapes().last().unwrap().geom else { panic!("no freeform") };
assert_eq!(paths[0].d.matches(" L ").count(), point_cap - 1);
}
#[test]
fn freeform_command_keeps_points_up_to_the_gesture_cap() {
let mut s = session();
// Send one point beyond the real cap to check that the command keeps as many as the tool can draw.
let points: Vec<_> = (0..=tools::MAX_GESTURE_POINTS).map(|i| [i % 500, i / 500]).collect();
let r = s.execute("shape.freeform", &json!({"points": points, "closed": false, "smooth": false})).unwrap();
let id = ShapeId(r["id"].as_u64().unwrap() as u32);
let deckcraft_model::Geom::Custom { paths } = &s.doc().unwrap().shape(id).unwrap().geom else { panic!("no freeform") };
assert_eq!(paths[0].d.matches(" L ").count(), tools::MAX_GESTURE_POINTS - 1);
}
@@ -6107,47 +6064,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 +7728,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,
+12
View File
@@ -274,6 +274,9 @@ pub struct ToolState {
pub path_closing: bool,
/// Whether the last freeform press added a vertex (it adds none at the point cap).
pub press_added_vertex: bool,
/// A smaller cap for tests that exercise freeform presses.
#[cfg(test)]
pub(crate) freeform_press_point_cap: Option<usize>,
/// The shape in Edit Points: its vertices are handles instead of the box's.
pub edit_points: Option<ShapeId>,
/// The vertex (path, index) whose control handles show in Edit Points.
@@ -310,6 +313,15 @@ impl ToolState {
pub fn drawing_freeform(&self) -> bool {
matches!(self.drag, Some(Drag::Freeform { .. }))
}
/// Most vertices freeform presses place: [`MAX_GESTURE_POINTS`], or a smaller cap a test sets.
pub(crate) fn press_point_cap(&self) -> usize {
#[cfg(test)]
if let Some(cap) = self.freeform_press_point_cap {
return cap;
}
MAX_GESTURE_POINTS
}
}
/// Handle positions in slide coordinates for a box (8 resize + rotate).
+1 -1
View File
@@ -262,7 +262,7 @@ impl Session {
self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false });
return self.finish_freeform(true);
}
self.tool.press_added_vertex = points.len() < super::MAX_GESTURE_POINTS;
self.tool.press_added_vertex = points.len() < self.tool.press_point_cap();
if self.tool.press_added_vertex {
points.push(p);
}
+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);
+1 -5
View File
@@ -247,11 +247,7 @@ 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"]));
// 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}");
assert_eq!(props["perPage"]["enum"], json!([1, 2, 3, 4, 6, 9]));
for p in ["dpi", "slides", "includeHidden", "textLayer", "frame", "paper", "orientation"] {
assert!(props.get(p).is_some(), "{p}: {export}");
}
+1 -1
View File
@@ -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", "description": "PDF handouts: slides per page (1, 2, 3, 4, 6 or 9; default 6)"},
"perPage": {"type": "integer", "enum": [1, 2, 3, 4, 6, 9], "description": "PDF handouts: slides per page (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)"),
+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;