mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 22:30:34 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32984c6c80 | ||
|
|
c86b62966b | ||
|
|
067a81c812 | ||
|
|
0e97d11789 | ||
|
|
196accb4b6 |
@@ -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);
|
||||
|
||||
@@ -287,8 +287,16 @@ fn current_run(s: &Session) -> RunProps {
|
||||
}
|
||||
None => {
|
||||
let Some(sh) = st.selected_shapes().first().map(|x| (*x).clone()) else { return RunProps::default() };
|
||||
let para = sh.text.as_ref().and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
|
||||
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_default();
|
||||
// A selected table reads its first selected cell (the whole table without a range: its first cell).
|
||||
let body = match &sh.kind {
|
||||
deckcraft_model::ShapeKind::Table(tb) => {
|
||||
let first = super::table::selected_range(st.selection.cells, sh.id, tb).map_or((0, 0), |(a, _)| a);
|
||||
tb.cell(first.0, first.1).map(|c| &c.text)
|
||||
}
|
||||
_ => sh.text.as_ref(),
|
||||
};
|
||||
let para = body.and_then(|t| t.paragraphs.first().cloned()).unwrap_or_default();
|
||||
let rp = para.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| para.end_props.clone());
|
||||
(sh, para, rp)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -338,7 +338,10 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => Some(sh.text.get_or_insert_with(TextBody::default)),
|
||||
};
|
||||
let Some(body) = target else { return Err(bad("text.set", "no text here (tables need `cell`)")) };
|
||||
let keep = body.paragraphs.first().and_then(|p| p.runs.first()).map(|r| r.props.clone()).unwrap_or_default();
|
||||
// The first run's formatting, or for text that is still empty the formatting its end
|
||||
// mark holds (format.* before any text lands there), so a size set before text.set survives.
|
||||
let keep =
|
||||
body.paragraphs.first().map(|p| p.runs.first().map(|r| r.props.clone()).unwrap_or_else(|| p.end_props.clone())).unwrap_or_default();
|
||||
let levels: Vec<(u8, deckcraft_model::text::ParaProps)> = body.paragraphs.iter().map(|p| (p.level, p.props.clone())).collect();
|
||||
let mut nb = TextBody::from_text(&text);
|
||||
for (i, para) in nb.paragraphs.iter_mut().enumerate() {
|
||||
@@ -353,6 +356,11 @@ pub(super) fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for r in &mut para.runs {
|
||||
r.props = keep.clone();
|
||||
}
|
||||
// The end mark keeps it too, so an empty `text` (no runs) carries the formatting to
|
||||
// the text set next.
|
||||
para.end_props = keep.clone();
|
||||
// A run emptied by stripping leading tabs would shadow the end mark for the text typed next.
|
||||
para.normalize();
|
||||
}
|
||||
body.paragraphs = nb.paragraphs;
|
||||
Ok(())
|
||||
|
||||
@@ -25,6 +25,10 @@ pub(crate) fn format_run_levels(
|
||||
// Only the levels of the paragraphs the selected range touches.
|
||||
let levels = if a == b { Vec::new() } else { master_levels(st, &t, t.ordered()) };
|
||||
edit_text(s, |body, _| {
|
||||
// A body with no paragraph has no end mark to hold the formatting of the text typed next.
|
||||
if body.paragraphs.is_empty() {
|
||||
body.paragraphs.push(Default::default());
|
||||
}
|
||||
if levels.is_empty() {
|
||||
ed::format(body, a, b, f);
|
||||
} else {
|
||||
@@ -65,6 +69,9 @@ pub(crate) fn format_run_levels(
|
||||
for (r, row) in t.rows.iter_mut().enumerate() {
|
||||
for (c, cell) in row.cells.iter_mut().enumerate() {
|
||||
if crate::cmd::table::in_range(range, r, c) {
|
||||
if cell.text.paragraphs.is_empty() {
|
||||
cell.text.paragraphs.push(Default::default());
|
||||
}
|
||||
ed::format_all(&mut cell.text, f);
|
||||
}
|
||||
}
|
||||
@@ -72,6 +79,11 @@ pub(crate) fn format_run_levels(
|
||||
}
|
||||
_ => {
|
||||
let body = sh.text.get_or_insert_with(TextBody::default);
|
||||
// Text that is still empty keeps the formatting on an end mark, so a size set
|
||||
// before the text lands survives it; a body with no paragraph has none.
|
||||
if body.paragraphs.is_empty() {
|
||||
body.paragraphs.push(Default::default());
|
||||
}
|
||||
let eff = effective.iter().find(|(i, _)| *i == id).map(|(_, e)| e);
|
||||
match eff {
|
||||
Some(eff) => {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
+23
-176
@@ -22,14 +22,6 @@ enum FlagMode {
|
||||
Num,
|
||||
}
|
||||
|
||||
/// Where a part sits in a compound.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Pos {
|
||||
First,
|
||||
Middle,
|
||||
Last,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Cond {
|
||||
Any,
|
||||
@@ -116,8 +108,6 @@ pub struct Dictionary {
|
||||
compound_begin: Option<Flag>,
|
||||
compound_middle: Option<Flag>,
|
||||
compound_end: Option<Flag>,
|
||||
/// `COMPOUNDPERMITFLAG`: an affix carrying it may sit inside a compound, not only at its ends.
|
||||
compound_permit: Option<Flag>,
|
||||
compound_min: usize,
|
||||
compound_max: usize,
|
||||
}
|
||||
@@ -177,7 +167,6 @@ impl Dictionary {
|
||||
["COMPOUNDBEGIN", f, ..] => d.compound_begin = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIDDLE", f, ..] => d.compound_middle = one_flag(Some(f), mode),
|
||||
["COMPOUNDEND", f, ..] | ["COMPOUNDLAST", f, ..] => d.compound_end = one_flag(Some(f), mode),
|
||||
["COMPOUNDPERMITFLAG", f, ..] => d.compound_permit = one_flag(Some(f), mode),
|
||||
["COMPOUNDMIN", n, ..] => d.compound_min = n.parse::<usize>().unwrap_or(3).max(1),
|
||||
["COMPOUNDWORDMAX", n, ..] => d.compound_max = n.parse().unwrap_or(0),
|
||||
["REP", n] => {
|
||||
@@ -261,26 +250,11 @@ impl Dictionary {
|
||||
self.words.get(word).is_some_and(|hs| hs.iter().any(|f| self.has(f, self.forbidden)))
|
||||
}
|
||||
|
||||
/// An affix that may only be used inside a compound (`ONLYINCOMPOUND` among its continuation
|
||||
/// flags): frami's zero suffixes that turn `Vor` into a compound's first part don't make `Vor`
|
||||
/// a word of its own (#2145).
|
||||
fn only_in_compound_affix(&self, a: &Affix) -> bool {
|
||||
self.only_in_compound.is_some_and(|o| a.cont.contains(&o))
|
||||
}
|
||||
|
||||
/// An affix that needs a further affix (`NEEDAFFIX` among its continuation flags): it can't be
|
||||
/// the last affix of a word or of a compound part.
|
||||
fn needs_another_affix(&self, a: &Affix) -> bool {
|
||||
self.need_affix.is_some_and(|n| a.cont.contains(&n))
|
||||
}
|
||||
|
||||
/// Strip suffixes from `w` (one, or two through continuation flags); `extra` flags must also be
|
||||
/// on the root, `cross` means the suffix must allow a prefix. `completed`: a prefix that needs
|
||||
/// nothing more is already on the word, so a suffix that needs another affix has it
|
||||
/// (`work/US` with `SFX S 0 s/N` makes `unworks`, not `works`).
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool, completed: bool) -> bool {
|
||||
/// on the root, `cross` means the suffix must allow a prefix.
|
||||
fn suffixed(&self, w: &[char], extra: &[Flag], cross: bool) -> bool {
|
||||
for s in &self.sfx {
|
||||
if (cross && !s.cross) || self.only_in_compound_affix(s) || (self.needs_another_affix(s) && !completed) {
|
||||
if cross && !s.cross {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_end(w, &s.add, &s.strip) else { continue };
|
||||
@@ -295,7 +269,7 @@ impl Dictionary {
|
||||
}
|
||||
// A second suffix whose continuation allows this one (`walk/A` + `ing/B`…).
|
||||
for s2 in &self.sfx {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) || self.only_in_compound_affix(s2) {
|
||||
if !s.cont.is_empty() || !s2.cont.contains(&s.flag) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem2) = strip_end(&stem, &s2.add, &s2.strip) else { continue };
|
||||
@@ -311,47 +285,24 @@ impl Dictionary {
|
||||
false
|
||||
}
|
||||
|
||||
/// A root carrying `flag`, or a root with one affix, as a compound part at `pos`.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
/// A root (or, for the last part, a suffixed root) carrying `flag`, as a compound part.
|
||||
fn compound_part(&self, part: &[char], flag: Flag, last: bool) -> bool {
|
||||
let word: String = part.iter().collect();
|
||||
let ok = self.words.get(&word).is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag)));
|
||||
ok || self.affixed_compound_part(part, flag, pos)
|
||||
ok || (last && self.suffixed_compound_end(part, flag))
|
||||
}
|
||||
|
||||
/// A compound part made of a root and one affix, as Hunspell reads them: a suffix ends the last
|
||||
/// part and a prefix starts the first; anywhere else the affix needs `COMPOUNDPERMITFLAG`.
|
||||
/// An affix that carries `NEEDAFFIX` needs a second one and doesn't count. A suffix found
|
||||
/// through the plain compound flag whose continuation flags carry `COMPOUNDEND` may only be on
|
||||
/// the last part. The compound `flag`
|
||||
/// may be on the root or among the affix's continuation flags. German frami gives many first
|
||||
/// parts their flag that way: `Vor/hij` with `SFX j 0 0/xoc` begins `Vorschlag` (#2145).
|
||||
fn affixed_compound_part(&self, w: &[char], flag: Flag, pos: Pos) -> bool {
|
||||
let permit = |a: &Affix| self.compound_permit.is_some_and(|p| a.cont.contains(&p));
|
||||
// An affix that itself needs another (`NEEDAFFIX` among its continuation flags) doesn't
|
||||
// finish a part on its own.
|
||||
let fits = |a: &Affix, stem: &[char], suffix: bool| {
|
||||
!self.needs_another_affix(a)
|
||||
// Only the last part may take a suffix found through the plain compound flag whose
|
||||
// continuation flags carry the compound end flag; the begin, middle and prefix
|
||||
// lookups don't check it, as in Hunspell.
|
||||
&& (pos == Pos::Last || !suffix || Some(flag) != self.compound || !self.compound_end.is_some_and(|e| a.cont.contains(&e)))
|
||||
&& self.words.get(&stem.iter().collect::<String>()).is_some_and(|hs| {
|
||||
hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&a.flag) && (f.contains(&flag) || a.cont.contains(&flag)))
|
||||
})
|
||||
};
|
||||
let suffixed = self
|
||||
.sfx
|
||||
.iter()
|
||||
// At the end of a compound, Hunspell refuses a suffix that adds letters and may only be
|
||||
// used inside compounds; a zero-length one is accepted.
|
||||
.filter(|s| if pos == Pos::Last { s.add.is_empty() || !self.only_in_compound_affix(s) } else { permit(s) })
|
||||
.any(|s| strip_end(w, &s.add, &s.strip).is_some_and(|stem| s.cond_ok(&stem, false) && fits(s, &stem, true)));
|
||||
suffixed
|
||||
|| self
|
||||
.pfx
|
||||
.iter()
|
||||
.filter(|p| pos == Pos::First || permit(p))
|
||||
.any(|p| strip_start(w, &p.add, &p.strip).is_some_and(|stem| p.cond_ok(&stem, true) && fits(p, &stem, false)))
|
||||
/// The last part of a compound with a suffix: the root must carry the compound `flag`.
|
||||
fn suffixed_compound_end(&self, w: &[char], flag: Flag) -> bool {
|
||||
self.sfx.iter().any(|s| {
|
||||
strip_end(w, &s.add, &s.strip).is_some_and(|stem| {
|
||||
s.cond_ok(&stem, false)
|
||||
&& self
|
||||
.words
|
||||
.get(&stem.iter().collect::<String>())
|
||||
.is_some_and(|hs| hs.iter().any(|f| !self.has(f, self.forbidden) && f.contains(&flag) && f.contains(&s.flag)))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `w` made of dictionary parts allowed in compounds (`COMPOUNDFLAG`, or the begin, middle and
|
||||
@@ -372,12 +323,11 @@ impl Dictionary {
|
||||
let role = if index == 0 { self.compound_begin } else { self.compound_middle };
|
||||
for i in min..=w.len() - min {
|
||||
let (head, rest) = w.split_at(i);
|
||||
let pos = if index == 0 { Pos::First } else { Pos::Middle };
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, pos));
|
||||
let head_ok = [self.compound, role].into_iter().flatten().any(|f| self.compound_part(head, f, false));
|
||||
if !head_ok {
|
||||
continue;
|
||||
}
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, Pos::Last)) {
|
||||
if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, true)) {
|
||||
return true;
|
||||
}
|
||||
if self.compounded(rest, index + 1, failed) {
|
||||
@@ -396,21 +346,18 @@ impl Dictionary {
|
||||
return true;
|
||||
}
|
||||
let w: Vec<char> = word.chars().collect();
|
||||
if self.suffixed(&w, &[], false, false) {
|
||||
if self.suffixed(&w, &[], false) {
|
||||
return true;
|
||||
}
|
||||
for p in &self.pfx {
|
||||
if self.only_in_compound_affix(p) {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = strip_start(&w, &p.add, &p.strip) else { continue };
|
||||
if !p.cond_ok(&stem, true) {
|
||||
continue;
|
||||
}
|
||||
if !self.needs_another_affix(p) && self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
if self.root(&stem.iter().collect::<String>(), &[p.flag], true) {
|
||||
return true;
|
||||
}
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true, !self.needs_another_affix(p)) {
|
||||
if p.cross && self.suffixed(&stem, &[p.flag], true) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1085,106 +1032,6 @@ SFX D Y 1\nSFX D 0 ed/S .\n";
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_give_compound_parts_their_flags() {
|
||||
// #2145, the way German frami builds compounds: the first and middle parts get their flags
|
||||
// from zero affixes' continuation classes, not from the root, and those roots need an affix.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDMIDDLE M\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nONLYINCOMPOUND O\nNEEDAFFIX N\n\
|
||||
COMPOUNDMIN 2\nSFX j Y 1\nSFX j 0 0/BOP .\nSFX m Y 1\nSFX m 0 0/MOP .\nPFX q Y 1\nPFX q 0 0/BO .\n\
|
||||
SFX s Y 1\nSFX s 0 e .\nSFX u Y 1\nSFX u 0 s .\nPFX v Y 1\nPFX v 0 un .\nSFX t Y 1\nSFX t 0 0/BNP .\n";
|
||||
let dic = "8\nvor/Nj\nschlag/OEs\nwerk/Njm\nzeug/OEs\nding/Nq\nhaus/Ev\ntag/Bs\ntor/t\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), dic.as_bytes());
|
||||
// First part through SFX j, middle part through SFX m (it carries the permit flag), last
|
||||
// part from its root, with or without a suffix there.
|
||||
for w in ["vorschlag", "vorschlage", "werkzeug", "werkzeuge", "vorwerkzeug", "werkhaus", "dinghaus"] {
|
||||
assert!(d.check(w), "{w}");
|
||||
}
|
||||
for w in [
|
||||
// A NEEDAFFIX or ONLYINCOMPOUND root alone, or a part with no compound flag at all.
|
||||
"vor",
|
||||
"werk",
|
||||
"schlag",
|
||||
"hausvor",
|
||||
"schlagzeug",
|
||||
// A suffix on the first part without the permit flag (s), and a prefix on a later part
|
||||
// without it (v).
|
||||
"vorschlageschlag",
|
||||
"werkunhaus",
|
||||
// tag carries B but its suffix s has no permit flag; SFX t gives B but carries NEEDAFFIX.
|
||||
"tageschlag",
|
||||
"torhaus",
|
||||
// Not words.
|
||||
"vorschlagx",
|
||||
"xvorschlag",
|
||||
] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affixes_that_need_another_or_only_live_in_compounds_follow_hunspell() {
|
||||
// Each row as Hunspell 1.7.6 reads the same dictionary: `sun/X` and `cat/S`, `SFX S` adding
|
||||
// the compound flag X and NEEDAFFIX (N) or ONLYINCOMPOUND (O).
|
||||
let dict = |sfx: &str| {
|
||||
let aff = format!("COMPOUNDFLAG X\nCOMPOUNDMIN 3\nNEEDAFFIX N\nONLYINCOMPOUND O\nSFX S Y 1\nSFX S {sfx} .\n");
|
||||
Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice())
|
||||
};
|
||||
let rows: [(&str, &[&str], &[&str]); 4] = [
|
||||
// An affix that needs another finishes neither a word nor a compound part.
|
||||
("0 s/XN", &["sun", "cat"], &["cats", "suncats", "catssun"]),
|
||||
("0 0/XN", &["sun", "cat"], &["suncat"]),
|
||||
// At the end of a compound a compound-only suffix may be empty, not add letters.
|
||||
("0 s/XO", &["sun", "cat"], &["cats", "suncats"]),
|
||||
("0 0/XO", &["sun", "cat", "suncat"], &["catsun", "suncatsun"]),
|
||||
];
|
||||
for (sfx, good, bad) in rows {
|
||||
let d = dict(sfx);
|
||||
for w in good {
|
||||
assert!(d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{sfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_completes_a_suffix_that_needs_another_affix() {
|
||||
// As Hunspell 1.7.6 reads it: `work/US`, a suffix needing another affix (N). The prefix
|
||||
// completes it (`unworks`); alone it doesn't (`works`); when both need another, neither
|
||||
// completes the other.
|
||||
for (pfx, good, bad) in
|
||||
[("0 un", &["work", "unwork", "unworks"][..], &["works"][..]), ("0 un/N", &["work"][..], &["works", "unwork", "unworks"][..])]
|
||||
{
|
||||
let aff = format!("NEEDAFFIX N\nPFX U Y 1\nPFX U {pfx} .\nSFX S Y 1\nSFX S 0 s/N .\n");
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"1\nwork/US\n".as_slice());
|
||||
for w in good {
|
||||
assert!(d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
for w in bad {
|
||||
assert!(!d.check(w), "{pfx}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_affix_carrying_the_compound_end_flag_only_ends_a_compound() {
|
||||
let aff = "COMPOUNDFLAG X\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/XEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/X\ncat/S\n".as_slice());
|
||||
assert!(d.check("suncats"));
|
||||
assert!(d.check("cats"));
|
||||
assert!(!d.check("catssun"));
|
||||
// Through the begin flag, the end flag on the suffix doesn't matter: Hunspell 1.7.6
|
||||
// accepts `catssun` here (and `cats`), and rejects `catsun`, `suncats` and `suncat`.
|
||||
let aff = "COMPOUNDBEGIN B\nCOMPOUNDEND E\nCOMPOUNDPERMITFLAG P\nCOMPOUNDMIN 3\nSFX S Y 1\nSFX S 0 s/BEP .\n";
|
||||
let d = Dictionary::parse(aff.as_bytes(), b"2\nsun/E\ncat/S\n".as_slice());
|
||||
assert!(d.check("catssun"));
|
||||
assert!(d.check("cats"));
|
||||
for w in ["catsun", "suncats", "suncat"] {
|
||||
assert!(!d.check(w), "{w}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_compound_roots_with_a_failing_ending_stay_cheap() {
|
||||
// Roots a..aaaaaaaa overlap, so many splits of "aaa…ab" reach the same (tail, part) state; unmemoized that is millions of searches.
|
||||
|
||||
+66
-242
@@ -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();
|
||||
@@ -6107,47 +6049,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, ¶ms).expect_err(&format!("{cmd} {params} should be rejected"));
|
||||
assert!(e.to_string().contains(cmd), "the error should name {cmd}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &doc), "{cmd} {params} must leave the presentation unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params} must not add an undo step");
|
||||
assert_eq!(s.doc().unwrap().history.redo.len(), redo, "{cmd} {params} must keep the redo step");
|
||||
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`.
|
||||
@@ -7305,6 +7215,67 @@ fn invalid_slide_index_never_falls_back_to_the_selection_in_export_commands() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A size (or colour, bold…) set on a shape before it has any text survives the text that is
|
||||
/// then set: text.set keeps the first run's properties, and an empty paragraph keeps them on its
|
||||
/// end mark, which is what the agent's format.size then set_text sequence relies on.
|
||||
#[test]
|
||||
fn text_set_keeps_the_formatting_of_an_empty_shape() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("format.size", &json!({"size": 30})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
s.execute("text.set", &json!({"id": id, "text": "Hello"})).unwrap();
|
||||
let props =
|
||||
|s: &Session| s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
|
||||
let run = props(&s);
|
||||
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "{run:?}");
|
||||
// Emptied and filled again: the empty paragraph's end mark carried the formatting.
|
||||
s.execute("text.set", &json!({"id": id, "text": ""})).unwrap();
|
||||
s.execute("text.set", &json!({"id": id, "text": "Again"})).unwrap();
|
||||
let run = props(&s);
|
||||
assert_eq!((run.size, run.bold), (Some(30.0), Some(true)), "after an empty text.set: {run:?}");
|
||||
}
|
||||
|
||||
/// The same while editing the text: a bold set in the text editor of a shape with an empty body
|
||||
/// (no paragraph at all) is what the next typed text gets.
|
||||
#[test]
|
||||
fn text_insert_keeps_the_formatting_set_in_an_empty_editor() {
|
||||
let mut s = session();
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 300, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.edit(|doc, sel| {
|
||||
let sh = deckcraft_model::find_shape_mut(crate::shapes_mut(doc, sel).unwrap(), deckcraft_model::ShapeId(id as u32)).unwrap();
|
||||
sh.text = Some(deckcraft_model::text::TextBody::default());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
s.execute("format.bold", &json!({"on": true})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Hi"})).unwrap();
|
||||
let run = s.doc().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().paragraphs[0].runs[0].props.clone();
|
||||
assert_eq!(run.bold, Some(true), "{run:?}");
|
||||
}
|
||||
|
||||
/// Font toggles on a selected table read the first selected cell, so the second Bold turns it off
|
||||
/// again, also for a cell whose empty text got its paragraph from the first toggle.
|
||||
#[test]
|
||||
fn bold_toggles_on_a_selected_table_cell() {
|
||||
let mut s = session();
|
||||
let id = table_at(&mut s, &[100.0, 100.0], json!([["", "b"], ["c", "d"]]));
|
||||
let bold = |s: &Session, r: usize, c: usize| {
|
||||
let st = s.doc().unwrap();
|
||||
let deckcraft_model::ShapeKind::Table(t) = &st.shape(id).unwrap().kind else { panic!("table") };
|
||||
let p = &t.cell(r, c).unwrap().text.paragraphs[0];
|
||||
p.runs.first().map_or(p.end_props.bold, |r| r.props.bold)
|
||||
};
|
||||
s.execute("table.selectCells", &json!({"id": id, "from": [0, 0], "to": [0, 1]})).unwrap();
|
||||
s.execute("format.bold", &json!({})).unwrap();
|
||||
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(true), Some(true)));
|
||||
assert_eq!(s.execute("format.state", &json!({})).unwrap()["bold"], json!(true));
|
||||
s.execute("format.bold", &json!({})).unwrap();
|
||||
assert_eq!((bold(&s, 0, 0), bold(&s, 0, 1)), (Some(false), Some(false)));
|
||||
assert_eq!(bold(&s, 1, 0), None, "cells outside the range keep their formatting");
|
||||
}
|
||||
|
||||
/// G6: with no sites given, shape.connect joins the sites that face each other along the
|
||||
/// dominant direction between the two shapes (a box mostly below leaves from the bottom), not
|
||||
/// "the closest pair", which for a diagonal neighbour picked a side site and crossed boxes.
|
||||
@@ -7803,153 +7774,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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
|
||||
@@ -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)"),
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::{FontFace, UnicodeSegmentation};
|
||||
/// Is `family` a symbol font (characters at U+F000 + code)?
|
||||
pub(crate) fn is_symbol_font(family: &str) -> bool {
|
||||
let f = family.to_ascii_lowercase();
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett") || f.starts_with("monotype sorts")
|
||||
f.starts_with("wingdings") || f == "symbol" || f.starts_with("webdings") || f.starts_with("marlett")
|
||||
}
|
||||
|
||||
/// Does `face` draw the symbol-font character `c` (a U+F0xx private-use code)? Either directly at
|
||||
@@ -300,11 +300,7 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
}
|
||||
// Only the legacy symbol fonts: "Noto Sans Symbols" and the like are Unicode fonts whose
|
||||
// characters (❑ ❖) are drawn as they are. Private-use codes are mapped only when no font is named.
|
||||
if f.contains("wingdings")
|
||||
|| (f.starts_with("monotype sorts") && ((first as u32) < 0x100 || ('\u{f000}'..='\u{f0ff}').contains(&first)))
|
||||
|| f == "symbol"
|
||||
|| (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first))
|
||||
{
|
||||
if f.contains("wingdings") || f == "symbol" || (font.is_none() && ('\u{f000}'..='\u{f0ff}').contains(&first)) {
|
||||
let code = (first as u32) & 0xff;
|
||||
// Wingdings 2 and 3 put different shapes at the same codes.
|
||||
if f.starts_with("wingdings 2") {
|
||||
@@ -331,8 +327,6 @@ pub fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
|
||||
return m.to_string();
|
||||
}
|
||||
let m = match code {
|
||||
0x6d if f.starts_with("monotype sorts") => '○',
|
||||
0xf0 if f.contains("wingdings") => '⇨',
|
||||
0xa7 => '▪',
|
||||
0xd8 => '➢',
|
||||
0xe8 => '➔',
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
use deckcraft_text::map_symbol_bullet;
|
||||
|
||||
#[test]
|
||||
fn monotype_sorts_m_bullet_is_open_circle() {
|
||||
assert_eq!(map_symbol_bullet("m", Some("Monotype Sorts")), "\u{25CB}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wingdings_eth_bullet_is_right_arrow() {
|
||||
assert_eq!(map_symbol_bullet("\u{f0}", Some("Wingdings")), "\u{21E8}");
|
||||
assert_eq!(map_symbol_bullet("\u{f0f0}", Some("Wingdings")), "\u{21E8}");
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user