Compare commits

...
Author SHA1 Message Date
dependabot[bot] 8a0e6a1510 ci(deps): bump step-security/harden-runner
Bumps the actions group with 1 update in the / directory: [step-security/harden-runner](https://github.com/step-security/harden-runner).


Updates `step-security/harden-runner` from 2.22.4 to 2.23.0
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/v2.22.4...v2.23.0)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <[email protected]>
2026-12-01 11:34:57 +00:00
autocraft-bot[bot] 86c8111089 Merge pull request #2411 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] ce493cf0af Merge pull request #2406 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] ec62fd85d5 Merge pull request #2404 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] 2c6699ad4d Merge pull request #2368 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] 98cc22869d Merge pull request #2365 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] 6eb23b7779 Merge pull request #2309 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] 6526e3783a Merge pull request #2273 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] abc82cb4cb Merge pull request #2231 2026-12-01 08:36:32 +00:00
autocraft-bot[bot] 3a6082b4b9 Merge pull request #2212 2026-12-01 08:36:32 +00:00
MaheshDesu e00af8eea2 fix: undo the stored rotation of a singly flipped .ppt shape (#2407)
Signed-off-by: MaheshDesu <[email protected]>
2026-11-28 00:09:42 +05:30
Josias Eli Rodriguez e1ce3b95eb fix(engine): TXT outline import decodes BOM-marked UTF-16 and strips the UTF-8 BOM (#2395) 2026-11-27 07:02:47 -06:00
Josias Eli Rodriguez ca1cc70a30 RTF outline import: read \'hh bytes in the code page \ansicpg names (#2394)
An outline saved on a non-Western Windows locale names its code page with
\ansicpg (1250 for Central European, 1251 for Cyrillic, ...) and writes its
letters as \'hh bytes of that page, but every byte was read as
Windows-1252, so ť came in as a control character and č as è. The bytes
are now read in the named code page (the single-byte Windows, DOS and Mac
pages craft-rtf decodes); no \ansicpg, or an East Asian one, stays
Windows-1252.
2026-11-27 04:03:06 +00:00
cloutier 237718c81a Preserve empty PPTX presentation text styles on save (#2363) 2026-11-25 11:20:08 -05:00
cloutier 2ee3785c5e Review: report missing alt text on inserted icons 2026-11-25 08:55:18 -05:00
Josias Eli Rodriguez 5503791117 fix(engine): keep a tags part per owner when reusing slides (#2279)
slide.reuse copied every source media item through add_media, which shares
identical bytes. Tags parts (think-cell or OLE custDataLst) with the same tag
list on a master and its layouts collapsed into one media item, so the saved
PPTX had one tags part referenced by several owners and PowerPoint asked to
repair it.

copy_media now gives a tags part a fresh item under a new id, as it already
does for linked media. Every other item keeps the byte dedupe.
2026-11-21 18:57:31 +00:00
Josias Eli Rodriguez 4ca6a795d9 table: reject row and column resizes past the table (#2260)
table.rowHeight and table.columnWidth accepted a row or column the table
doesn't have (row 99 on a 2 x 2 table) and reported success. Both now return
an invalid-argument error, checked inside the edit before any change, so a
refused resize leaves the presentation and the undo and redo history as they
were. This is the follow-up #1189's review named.

The old test that expected a huge col to be ignored now expects the error.
2026-11-20 08:50:39 +00:00
Hamza 43815b285f Check Accessibility test: a picture's own spaced file name is reported 2026-11-18 19:16:33 +05:00
Hamza eec73f3396 Check Accessibility: alt text that is only a file name is reported (#2224)
Insert Picture sets a picture's alt text to its file name, so the picture counted as described
and review.accessibility said nothing, though a screen reader would read only "IMG_2041.png".
Alt text that is one word ending in a picture extension, or that is the name of the file the
picture came from, is now reported as "Alternative text is a file name", until it is
described or marked decorative.
2026-11-18 19:15:17 +05:00
Josias Eli Rodriguez 75f798124e fix(mcp): drop the integer enum from the export tool's perPage (#2211) 2026-11-17 19:06:31 -06:00
19 changed files with 504 additions and 34 deletions
+7 -7
View File
@@ -5,23 +5,23 @@ version: 'v0.0.3'
workflows:
'.github/workflows/ci.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/freebsd.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/lockfile.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/nightly-dispatch.yml': []
'.github/workflows/nightly-macos.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
'.github/workflows/notify-services.yml': []
'.github/workflows/packaging-lint.yml':
- 'actions/[email protected]'
- 'step-security/[email protected]2.4'
- 'step-security/[email protected]3.0'
'.github/workflows/release.yml': []
'.github/workflows/sonarcloud.yml': []
'.github/workflows/windows-arm64.yml': []
@@ -31,8 +31,8 @@ dependencies:
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'step-security/[email protected]2.4':
ref: 'v2.22.4'
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
'step-security/[email protected]3.0':
ref: 'v2.23.0'
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
owner_id: 88700172
repo_id: 422287306
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
CRAFT_FONTS_REF: 37827adc41fd165f9a9234ac40f94dbad353aa69
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- name: Check out craft-fonts
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
RUST_BACKTRACE: 1
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+2 -2
View File
@@ -28,7 +28,7 @@ jobs:
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
@@ -58,7 +58,7 @@ jobs:
contents: read
steps:
- name: Harden runner
uses: step-security/[email protected]2.4
uses: step-security/[email protected]3.0
with:
egress-policy: audit
- uses: actions/[email protected]
+31 -4
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 = String::from_utf8_lossy(bytes);
let text = if rtf { String::from_utf8_lossy(bytes).into_owned() } else { decode_outline_bytes(bytes) };
let mut p = defaults::blank_presentation(defaults::WIDE, Default::default(), false);
if rtf {
deckcraft_format::rtf::rtf_to_slides(&mut p, &text);
@@ -234,10 +234,37 @@ fn probe_clips(p: &mut Presentation) {
}
}
/// An outline file's text: RTF is read into the tab-indented outline, anything else as UTF-8.
/// Decode outline text bytes by BOM: `EF BB BF` strips the UTF-8 BOM, `FF FE` decodes UTF-16LE,
/// `FE FF` decodes UTF-16BE, and anything else keeps lossy UTF-8 decoding.
fn decode_outline_bytes(bytes: &[u8]) -> String {
if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
String::from_utf8_lossy(rest).into_owned()
} else if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) {
decode_utf16(rest, u16::from_le_bytes)
} else if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
decode_utf16(rest, u16::from_be_bytes)
} else {
String::from_utf8_lossy(bytes).into_owned()
}
}
fn decode_utf16(bytes: &[u8], decode: fn([u8; 2]) -> u16) -> String {
let (chunks, tail) = bytes.as_chunks::<2>();
let mut out: String = char::decode_utf16(chunks.iter().copied().map(decode)).map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER)).collect();
if !tail.is_empty() {
out.push(char::REPLACEMENT_CHARACTER);
}
out
}
/// An outline file's text: RTF is read into the tab-indented outline; plain text and Markdown
/// honour UTF-8, UTF-16LE and UTF-16BE BOMs and otherwise decode as UTF-8.
pub fn outline_text(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
if deckcraft_format::rtf::sniff_rtf(bytes) { deckcraft_format::rtf::rtf_to_outline(&text) } else { text.into_owned() }
if deckcraft_format::rtf::sniff_rtf(bytes) {
deckcraft_format::rtf::rtf_to_outline(&String::from_utf8_lossy(bytes))
} else {
decode_outline_bytes(bytes)
}
}
pub fn add_opened(s: &mut Session, name: &str, path: Option<String>, p: Presentation) -> usize {
+2
View File
@@ -279,6 +279,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result<Value> {
if rect.w < 1.0 || rect.h < 1.0 {
return Err(bad("insert.icon", "rect needs a positive width and height"));
}
let (tag, value) = crate::icons::INSERTED_ICON_TAG;
let shape = Shape {
name: icon.label.to_string(),
xfrm: Some(rect),
@@ -300,6 +301,7 @@ fn insert_icon(s: &mut Session, p: &Value) -> Result<Value> {
..Default::default()
}),
style: Some(ShapeStyle::line(SchemeSlot::Tx1)),
tags: vec![(tag.into(), value.into())],
..Default::default()
};
let id = add_shape(s, "insert.icon", shape, true)?;
+94 -2
View File
@@ -501,15 +501,19 @@ pub(crate) fn import_master(
Ok(m)
}
/// The content type of a tags part (`p:custDataLst`/`p:tags`), which belongs to exactly one owner.
const TAGS_CONTENT_TYPE: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml";
/// Copy the source media `used` into `doc` under fresh ids, once each (identical bytes already in
/// `doc` are shared; a linked item keeps its link).
/// `doc` are shared; a linked item keeps its link). A tags part is never shared: identical tag lists
/// on a master and its layouts must stay one part per owner, or PowerPoint repairs the file.
fn copy_media(cmd: &str, doc: &mut Presentation, src: &Presentation, used: &[MediaId], map: &mut HashMap<MediaId, MediaId>) -> Result<()> {
for &id in used {
if map.contains_key(&id) {
continue;
}
let Some(m) = src.media(id) else { continue };
let new = if m.link.is_some() {
let new = if m.link.is_some() || m.content_type.eq_ignore_ascii_case(TAGS_CONTENT_TYPE) {
let mut item = m.clone();
item.id = MediaId(doc.alloc_id().ok_or_else(|| bad(cmd, NO_ID_SPACE))?);
let new = item.id;
@@ -792,6 +796,94 @@ mod tests {
assert_eq!(got, want, "every reference resolves to its own copied bytes");
}
/// A tags part belongs to one owner. Identical tag lists on a master and its layouts (a
/// think-cell or OLE object on each) come over as one item per owner, never one shared item,
/// so the saved file has a part for each and PowerPoint opens it without a repair.
#[test]
fn reused_master_keeps_a_tags_part_per_owner() {
const TAGS: &str = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml";
const TAGS_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tags";
let tags = br#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:tagLst xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:tag name="THINKCELLSHAPEDONOTDELETE" val="t1"/></p:tagLst>"#.to_vec();
let mut src = defaults::new_presentation(None);
let ids: Vec<MediaId> = (0..3)
.map(|_| {
let id = MediaId(src.alloc_id().expect("id"));
src.media.push(deckcraft_model::MediaItem {
id,
name: "tag1.xml".into(),
content_type: TAGS.into(),
data: Arc::new(tags.clone()),
link: None,
});
id
})
.collect();
let object = |id: MediaId| {
Shape {
id: ShapeId(9100),
kind: ShapeKind::Opaque {
xml: r#"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="9100" name="think-cell data"/><p:cNvGraphicFramePr/><p:nvPr><p:custDataLst><p:tags r:id="rId2"/></p:custDataLst></p:nvPr></p:nvGraphicFramePr></p:graphicFrame>"#.into(),
preview: None,
label: "think-cell".into(),
parts: vec![("rId2".into(), TAGS_REL.into(), id)],
},
..Default::default()
}
};
let master = src.masters.first_mut().map(Arc::make_mut).expect("master");
assert!(master.layouts.len() >= 2, "the default master has layouts to share the tags");
master.shapes = vec![object(ids[0])];
for (layout, id) in master.layouts.iter_mut().zip(&ids[1..]) {
layout.shapes = vec![object(*id)];
}
let bytes = deckcraft_format::save(&src).expect("save");
let mut s = Session::with_new();
let own = s.edit(|doc, _| Ok(doc.add_media("tag1.xml", TAGS, tags.clone()).expect("media"))).expect("own tags");
s.execute(
"slide.reuse",
&json!({"data": super::super::base64_encode(&bytes), "name": "src.deckcraft", "slides": [0], "keepFormatting": true}),
)
.expect("reuse");
let doc = &s.doc().expect("doc").doc;
let imported = doc.masters.last().expect("imported master");
let parts = |shapes: &[Shape]| -> Vec<MediaId> {
shapes
.iter()
.filter_map(|sh| match &sh.kind {
ShapeKind::Opaque { parts, .. } => Some(parts.iter().map(|(_, _, m)| *m)),
_ => None,
})
.flatten()
.collect()
};
let mut got = parts(&imported.shapes);
for layout in imported.layouts.iter().take(2) {
got.extend(parts(&layout.shapes));
}
assert_eq!(got.len(), 3, "the master and two layouts each hold their object");
for m in &got {
let item = doc.media(*m).expect("copied tags item");
assert_eq!((item.content_type.as_str(), item.data.as_slice()), (TAGS, tags.as_slice()), "each copy keeps the tag list");
assert_ne!(*m, own, "a copied tags part is not shared with the destination's own");
}
let mut distinct = got.clone();
distinct.sort_by_key(|m| m.0);
distinct.dedup();
assert_eq!(distinct.len(), got.len(), "each owner has its own tags item: {got:?}");
let pptx = deckcraft_pptx::export(doc).expect("export");
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&pptx)).expect("zip");
let mut written = 0;
for i in 0..z.len() {
let mut f = z.by_index(i).expect("entry");
let mut body = Vec::new();
std::io::Read::read_to_end(&mut f, &mut body).expect("read");
written += usize::from(body == tags);
}
assert!(written >= 3, "the saved file has a tags part per owner, found {written}");
}
fn link_to(slide: SlideId) -> Hyperlink {
Hyperlink {
action: Action::Slide { slide },
+66 -1
View File
@@ -246,6 +246,26 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result<Value> {
Ok(json!({"slide": slide, "index": index, "text": text}))
}
/// Whether alternative text is a picture's file name and nothing else: one word ending in a
/// picture file's extension (`IMG_2041.png`, `C:\\photos\\a.JPG`), or the name of the file the
/// picture came from, which may have spaces (`Screenshot 2024 at 10.00.png`).
fn is_file_name(alt: &str, file: Option<&str>) -> bool {
const PICTURE_EXTENSIONS: [&str; 15] =
["png", "jpg", "jpeg", "jpe", "gif", "bmp", "tif", "tiff", "webp", "svg", "emf", "wmf", "heic", "avif", "ico"];
let alt = alt.trim();
let one_word = !alt.is_empty() && !alt.contains(char::is_whitespace);
(one_word && alt.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && PICTURE_EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))))
|| file.is_some_and(|f| !alt.is_empty() && f.trim().eq_ignore_ascii_case(alt))
}
/// The name of the file a picture shape's picture came from, if it has one.
fn picture_file<'a>(doc: &'a deckcraft_model::Presentation, sh: &deckcraft_model::Shape) -> Option<&'a str> {
match &sh.kind {
deckcraft_model::ShapeKind::Picture { fill } => doc.media(fill.media).map(|m| m.name.as_str()),
_ => None,
}
}
fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
let st = s.doc()?;
let mut out = vec![];
@@ -261,8 +281,12 @@ fn accessibility(s: &mut Session, _p: &Value) -> Result<Value> {
| deckcraft_model::ShapeKind::Media(_)
| deckcraft_model::ShapeKind::Group { .. }
);
if needs_alt && sh.descr.trim().is_empty() && !sh.decorative {
if sh.descr.trim().is_empty() && !sh.decorative && (needs_alt || crate::icons::is_inserted_icon(sh)) {
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Missing alternative text"}));
} else if needs_alt && !sh.decorative && is_file_name(&sh.descr, picture_file(&st.doc, sh)) {
// Insert Picture names a picture after its file, which is all a screen reader
// would then say (#2224).
out.push(json!({"slide": i, "shape": sh.id, "name": sh.name, "issue": "Alternative text is a file name"}));
}
});
// Low-contrast text against the slide background.
@@ -1041,4 +1065,45 @@ mod accessibility_contrast_tests {
assert!(!contrasts.iter().any(|issue| issue["shape"] == 6), "black control warned: {issues}");
assert!(!contrasts.iter().any(|issue| issue["shape"] == 8), "white break or spaces warned: {issues}");
}
/// #2224: Insert Picture's alt text is the file name, which says nothing; it is reported until
/// it is described or marked decorative. A description that mentions a file is fine.
#[test]
fn alt_text_that_is_a_file_name_is_reported() {
let png: Vec<u8> = vec![
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 8, 0, 0, 0, 8, 8, 2, 0, 0, 0, 75, 109, 41, 220, 0, 0, 0, 17, 73,
68, 65, 84, 120, 156, 99, 184, 163, 161, 129, 21, 49, 12, 45, 9, 0, 123, 123, 75, 1, 251, 162, 81, 240, 0, 0, 0, 0, 73, 69, 78, 68, 174,
66, 96, 130,
];
let mut s = Session::with_new();
let id = s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "IMG_2041.png"})).unwrap()["id"].clone();
let named = |s: &mut Session| {
let issues = s.execute("review.accessibility", &json!({})).unwrap();
issues.as_array().unwrap().iter().filter(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name").count()
};
assert_eq!(named(&mut s), 1);
for (text, decorative, expected) in [
("photo.JPEG", false, 1),
("C:\\Users\\me\\Pictures\\holiday.png", false, 1),
("A red square", false, 0),
("A red square, from IMG_2041.png", false, 0),
("IMG_2041.png", true, 0),
] {
s.execute("shape.altText", &json!({"text": text, "decorative": decorative, "ids": [id]})).unwrap();
assert_eq!(named(&mut s), expected, "{text:?} decorative {decorative}");
}
// A file name with spaces is reported when it is the picture's own file's.
let mut s = Session::with_new();
let id =
s.execute("insert.picture", &json!({"data": crate::cmd::base64_encode(&png), "name": "Screenshot 2024 at 10.00.png"})).unwrap()["id"]
.clone();
let issues = s.execute("review.accessibility", &json!({})).unwrap();
assert!(issues.as_array().unwrap().iter().any(|i| i["shape"] == id && i["issue"] == "Alternative text is a file name"), "{issues}");
assert!(!is_file_name("Version 2.0", None), "a version number is not a picture's extension");
assert!(!is_file_name(".png", None));
assert!(!is_file_name("A red square, from IMG_2041.png", None));
// The picture's own file name counts, spaces and all.
assert!(is_file_name("Screenshot 2024 at 10.00.png", Some("Screenshot 2024 at 10.00.png")));
assert!(!is_file_name("Screenshot 2024 at 10.00.png", None));
}
}
+8
View File
@@ -725,11 +725,18 @@ fn distribute(s: &mut Session, p: &Value, rows: bool) -> Result<Value> {
})
}
/// A row or column the table doesn't have is an error, like a malformed index (#2260): checked
/// inside the edit, so a refused resize changes nothing and adds no undo step.
fn index_in_table(cmd: &str, key: &str, i: usize, n: usize, what: &str) -> Result<()> {
if i < n { Ok(()) } else { Err(bad(cmd, format!("`{key}` {i} is out of range: the table has {n} {what}"))) }
}
fn column_width(s: &mut Session, p: &Value) -> Result<Value> {
let (_, c) = at(s, p, "table.columnWidth")?;
let w = f64_param(p, "width").ok_or_else(|| bad("table.columnWidth", "missing `width`"))?.clamp(4.0, 4000.0);
let keep_total = bool_or(p, "keepTotal", false);
with_table(s, p, "table.columnWidth", move |t| {
index_in_table("table.columnWidth", "col", c, t.n_cols(), "columns")?;
// Keeping the table's width, the column to the right gives or takes the difference (dragging
// an inner border). The last column has none: the table gets wider or narrower.
let pair = t.cols.get(c).zip(t.cols.get(c.saturating_add(1))).map(|(a, b)| a.max(0.0) + b.max(0.0)).filter(|x| x.is_finite());
@@ -758,6 +765,7 @@ fn row_height(s: &mut Session, p: &Value) -> Result<Value> {
let (r, _) = at(s, p, "table.rowHeight")?;
let h = f64_param(p, "height").ok_or_else(|| bad("table.rowHeight", "missing `height`"))?.clamp(4.0, 4000.0);
with_table(s, p, "table.rowHeight", move |t| {
index_in_table("table.rowHeight", "row", r, t.n_rows(), "rows")?;
if let Some(x) = t.rows.get_mut(r) {
x.height = h;
}
+45
View File
@@ -12,6 +12,14 @@ use deckcraft_geom::{BezPath, PathEl};
/// Design size of every icon, in path units. Lucide's viewBox is `0 0 24 24`.
pub const VIEW: f64 = 24.0;
/// Shape tag that preserves gallery icon identity in native and PPTX files.
pub(crate) const INSERTED_ICON_TAG: (&str, &str) = ("DECKCRAFT_INSERTED_ICON", "1");
pub(crate) fn is_inserted_icon(shape: &deckcraft_model::Shape) -> bool {
let (name, value) = INSERTED_ICON_TAG;
shape.tags.iter().any(|(key, tag_value)| key == name && tag_value == value)
}
/// One icon from the Insert gallery.
pub struct Icon {
pub name: &'static str,
@@ -210,6 +218,43 @@ mod tests {
assert!((width - 8.0).abs() < 0.05, "{width}");
}
#[test]
fn missing_icon_alt_text_is_reported_after_round_trips() {
let mut s = Session::with_new();
let insert_icon = |s: &mut Session| s.execute("insert.icon", &json!({"name": "star"})).unwrap()["id"].as_u64().unwrap();
let missing = insert_icon(&mut s);
let described = insert_icon(&mut s);
let decorative = insert_icon(&mut s);
let freeform = s.execute("shape.freeform", &json!({"points": [[0, 0], [20, 10], [5, 25]], "closed": true})).unwrap()["id"].as_u64().unwrap();
s.execute("shape.rename", &json!({"ids": [freeform], "name": "Star"})).unwrap();
s.execute("shape.rename", &json!({"ids": [missing], "name": "Repainted symbol"})).unwrap();
s.execute("shape.altText", &json!({"ids": [described], "text": "Five-point outline"})).unwrap();
s.execute("shape.altText", &json!({"ids": [decorative], "decorative": true})).unwrap();
let assert_alert = |s: &mut Session| {
let issues = s.execute("review.accessibility", &json!({})).unwrap();
let shapes: Vec<_> = issues
.as_array()
.unwrap()
.iter()
.filter(|issue| issue["issue"] == "Missing alternative text")
.map(|issue| issue["shape"].as_u64().unwrap())
.collect();
assert_eq!(shapes, [missing], "{issues}");
};
assert_alert(&mut s);
let doc = &s.doc().unwrap().doc;
let native = deckcraft_format::load(&deckcraft_format::save(doc).unwrap()).unwrap();
let pptx = deckcraft_pptx::import(&deckcraft_pptx::export(doc).unwrap()).unwrap();
let second_pptx = deckcraft_pptx::import(&deckcraft_pptx::export(&pptx).unwrap()).unwrap();
for doc in [native, pptx, second_pptx] {
let mut reopened = Session::new();
reopened.add_document(crate::DocState::new(doc, None, "Reopened deck".into()));
assert_alert(&mut reopened);
}
}
fn ink_in(img: &deckcraft_render::Image, x: f64, y: f64, w: f64, h: f64, scale: f64) -> usize {
let x0 = (x * scale).floor().max(0.0) as u32;
let y0 = (y * scale).floor().max(0.0) as u32;
+95 -5
View File
@@ -2779,6 +2779,64 @@ fn plain_outlines_are_unchanged() {
assert_eq!(p.slides.first().map(|s| s.title()).as_deref(), Some("# Intro"));
}
#[test]
fn txt_outline_decodes_utf16_boms() {
let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n";
let want = vec![
("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]),
("Second".to_string(), vec![(0, "More".to_string())]),
];
let mut utf16_le = vec![0xFF, 0xFE];
utf16_le.extend(source.encode_utf16().flat_map(u16::to_le_bytes));
let mut utf16_be = vec![0xFE, 0xFF];
utf16_be.extend(source.encode_utf16().flat_map(u16::to_be_bytes));
for (label, bytes) in [("utf-16le bom", utf16_le.as_slice()), ("utf-16be bom", utf16_be.as_slice())] {
let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap();
assert_eq!(outline_of(&p), want, "open_presentation ({label})");
assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})");
}
// Truncated trailing byte and unpaired surrogate in UTF-16LE replace rather than panic.
let truncated_le = [0xFF, 0xFE, b'O', 0x00, b'k', 0x00, 0x00, 0xD8, 0x42];
let p = crate::cmd::file::open_presentation("truncated.txt", &truncated_le).unwrap();
assert_eq!(p.slides.len(), 1);
assert_eq!(p.slides[0].title(), "Ok\u{FFFD}\u{FFFD}");
assert_eq!(crate::cmd::file::outline_text(&truncated_le), "Ok\u{FFFD}\u{FFFD}");
// BOM-only UTF-16 files open as one blank slide.
for bom in [&[0xFF, 0xFE][..], &[0xFE, 0xFF][..]] {
let p = crate::cmd::file::open_presentation("empty.txt", bom).unwrap();
assert_eq!(p.slides.len(), 1);
assert_eq!(p.slides[0].title(), "");
}
}
#[test]
fn txt_outline_strips_utf8_bom_and_keeps_plain_utf8() {
let source = "Intro — café\r\n\tPoint one\r\n\t\tSub point 🚀\r\nSecond\r\n\tMore\r\n";
let want = vec![
("Intro — café".to_string(), vec![(0, "Point one".to_string()), (1, "Sub point 🚀".to_string())]),
("Second".to_string(), vec![(0, "More".to_string())]),
];
let mut utf8_bom = vec![0xEF, 0xBB, 0xBF];
utf8_bom.extend_from_slice(source.as_bytes());
for (label, bytes) in [("utf-8 bom", utf8_bom.as_slice()), ("utf-8 no bom", source.as_bytes())] {
let p = crate::cmd::file::open_presentation("outline.txt", bytes).unwrap();
assert_eq!(outline_of(&p), want, "open_presentation ({label})");
assert!(!p.slides[0].title().starts_with('\u{feff}'), "leading BOM kept ({label})");
assert_eq!(crate::cmd::file::outline_text(bytes), source, "outline_text ({label})");
}
let p = crate::cmd::file::open_presentation("empty.txt", &[0xEF, 0xBB, 0xBF]).unwrap();
assert_eq!(p.slides.len(), 1);
assert_eq!(p.slides[0].title(), "");
}
#[test]
fn rtf_without_heading_paragraphs_opens_as_one_blank_slide() {
let p = crate::cmd::file::open_presentation("empty.rtf", br"{\rtf1\ansi}").unwrap();
@@ -6049,15 +6107,47 @@ fn table_cell_commands_reject_an_invalid_cell_and_name_the_registered_command()
assert!(e.contains("table.insertColumnLeft"), "error should name the registered command: {e}");
}
/// #2260 (the follow-up #1189's review named): a resize of a row or column the table doesn't
/// have is an error, and leaves the presentation and the undo and redo history as they were.
#[test]
fn table_column_width_of_a_huge_column_is_ignored() {
fn table_resize_rejects_a_row_or_column_past_the_table() {
let mut s = session();
let id = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]]));
for keep_total in [true, false] {
let r = s.execute("table.columnWidth", &json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": keep_total}));
assert!(r.is_ok(), "columnWidth must ignore a huge col (keepTotal {keep_total}), got {r:?}");
assert_eq!(table_of(&s, id).cols, vec![100.0, 100.0], "no column changes");
// A row height undone, so there is a redo step for the rejected resizes to keep.
s.execute("table.rowHeight", &json!({"id": id.0, "row": 0, "height": 30.0})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
for (cmd, params) in [
("table.rowHeight", json!({"id": id.0, "row": 2, "height": 50.0})),
("table.rowHeight", json!({"id": id.0, "row": 99, "height": 50.0})),
("table.columnWidth", json!({"id": id.0, "col": 2, "width": 50.0})),
("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0})),
("table.columnWidth", json!({"id": id.0, "col": 99, "width": 50.0, "keepTotal": true})),
("table.columnWidth", json!({"id": id.0, "col": u64::MAX, "width": 50.0, "keepTotal": true})),
] {
let doc = s.doc().unwrap().doc.clone();
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
let e = s.execute(cmd, &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");
}
// 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`.
+34 -2
View File
@@ -113,6 +113,9 @@ struct Outline {
/// non-ASCII `Token::Symbol`.
skip_cont: usize,
line: String,
/// The document's code page (`\ansicpg`), which `\'hh` bytes are in: Windows-1252 until it
/// names another single-byte one (#2394).
code_page: u16,
/// Paragraphs so far: outline level and text (empty only for an empty level-0 title).
out: Vec<(usize, String)>,
}
@@ -199,6 +202,7 @@ fn paragraphs(rtf: &str) -> Vec<(usize, String)> {
pending_skip: 0,
skip_cont: 0,
line: String::new(),
code_page: 1252,
out: vec![],
};
p.run(rtf);
@@ -273,6 +277,12 @@ impl Outline {
self.style_level = arg.filter(|a| (1..=9).contains(a) && self.headings[*a as usize]).map(|a| a as u32 - 1);
}
"li" => self.indent = i64::from(arg.unwrap_or(0)),
// A code page read a byte at a time; any other (East Asian multibyte, unknown) keeps Windows-1252.
"ansicpg" => {
if let Some(cp) = arg.and_then(|a| u16::try_from(a).ok()).filter(|cp| craft_rtf::codepage::is_byte_code_page(*cp)) {
self.code_page = cp;
}
}
"tab" | "line" => self.line.push(' '),
"uc" => self.st.uc = arg.unwrap_or(1).clamp(0, 8) as usize,
"u" => self.unicode(i64::from(arg.unwrap_or(0))),
@@ -294,14 +304,14 @@ impl Outline {
self.pending_skip = self.st.uc;
}
/// `\'hh`: one cp1252 byte.
/// `\'hh`: one byte in the document's code page.
fn hex_escape(&mut self, h: u8) {
if self.pending_skip > 0 {
self.pending_skip -= 1;
return;
}
if !self.st.skip && h != 0 {
self.line.push(craft_rtf::codepage::cp1252(h));
self.line.push(craft_rtf::codepage::code_page_byte(self.code_page, h));
}
}
@@ -621,6 +631,28 @@ mod tests {
assert_eq!(crate::slides_to_outline(&reopened), expected);
}
/// A writer on a non-Western Windows locale names its code page with `\ansicpg` and writes
/// non-ASCII letters as `\'hh` bytes of that page (#2394); `\ansicpg1252` and no `\ansicpg`
/// both stay Windows-1252.
#[test]
fn hex_escapes_decode_in_the_code_page_ansicpg_names() {
let outline = |cpg: &str, title: &str, body: &str| {
let rtf = format!(
r"{{\rtf1\ansi{cpg}{{\stylesheet{{\s1 heading 1;}}{{\s2 heading 2;}}}}\pard\s1 {title}\par\pard\s2 {body}\par\pard\s1 Plain\par}}"
);
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
assert_eq!(rtf_to_slides(&mut p, &rtf), 2, "{rtf}");
crate::slides_to_outline(&p)
};
assert_eq!(
outline(r"\ansicpg1250", r"\'8elu\'9dou\'e8k\'fd k\'f9\'f2", r"\'dap\'ecl \'ef\'e1belsk\'e9 \'f3dy"),
"Žluťoučký kůň\n\tÚpěl ďábelské ódy\nPlain\n"
);
assert_eq!(outline(r"\ansicpg1251", r"\'cf\'f0\'e8\'e2\'e5\'f2", r"\'ec\'e8\'f0"), "Привет\n\tмир\nPlain\n");
assert_eq!(outline(r"\ansicpg1252", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
assert_eq!(outline("", r"Caf\'e9", r"\'93a\'94"), "Café\n\t“a”\nPlain\n");
}
#[test]
fn export_writes_heading_styles() {
let mut p = deckcraft_model::defaults::blank_presentation(deckcraft_model::defaults::WIDE, Default::default(), false);
+5 -1
View File
@@ -247,7 +247,11 @@ fn export_tool_lists_pdf_and_its_options() {
assert!(formats.iter().any(|x| x == f), "format {f}: {export}");
}
assert_eq!(props["layout"]["enum"], json!(["slides", "notes", "handouts"]));
assert_eq!(props["perPage"]["enum"], json!([1, 2, 3, 4, 6, 9]));
// Gemini function declarations accept only string enums (#2211): perPage stays a plain integer
// and the allowed values are spelled out in the description (the engine validates the set).
assert_eq!(props["perPage"]["type"], "integer");
assert!(props["perPage"].get("enum").is_none(), "{export}");
assert!(props["perPage"]["description"].as_str().unwrap().contains("1, 2, 3, 4, 6 or 9"), "{export}");
for p in ["dpi", "slides", "includeHidden", "textLayer", "frame", "paper", "orientation"] {
assert!(props.get(p).is_some(), "{p}: {export}");
}
+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", "enum": [1, 2, 3, 4, 6, 9], "description": "PDF handouts: slides per page (default 6)"},
"perPage": {"type": "integer", "description": "PDF handouts: slides per page (1, 2, 3, 4, 6 or 9; default 6)"},
"dpi": num("PDF: raster resolution of slide artwork, 36-600 (default 200)"),
"slides": {"type": "array", "items": {"type": "integer", "minimum": 0}, "description": "PDF and GIF: slide indices to export, in order (default all)"},
"includeHidden": boolean("PDF and GIF: include hidden slides (default false)"),
+35 -2
View File
@@ -990,13 +990,15 @@ fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm
let finite = |v: f64| if v.is_finite() { v } else { 0.0 };
let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy));
let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs());
let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 };
if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) {
let stored_rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 };
if (45.0..135.0).contains(&stored_rot) || (225.0..315.0).contains(&stored_rot) {
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
std::mem::swap(&mut w, &mut h);
x = cx - w / 2.0;
y = cy - h / 2.0;
}
// A shape flipped in exactly one direction stores its angle mirrored; undo it.
let rot = if flip_h ^ flip_v { (360.0 - stored_rot).rem_euclid(360.0) } else { stored_rot };
Xfrm { x, y, w, h, rot, flip_h, flip_v }
}
@@ -1072,4 +1074,35 @@ mod tests {
assert_eq!(linear_angle(a), dm, "{a}");
}
}
/// [MS-ODRAW] stores the angle of a shape flipped in exactly one direction as 360° - θ.
/// The importer must undo that before writing `a:xfrm rot` (#2407).
#[test]
fn a_single_flip_mirrors_the_stored_legacy_rotation_back() {
let a = draw::Anchor { left: 0.0, top: 0.0, right: 100.0, bottom: 50.0 };
let m = Map { sx: 1.0, sy: 1.0, ox: 0.0, oy: 0.0 };
// A 30° visual shape is stored as 330° with one flip.
let h = xfrm(&a, m, 330.0, true, false);
assert_eq!((h.rot, h.flip_h, h.flip_v), (30.0, true, false));
let v = xfrm(&a, m, 330.0, false, true);
assert_eq!((v.rot, v.flip_h, v.flip_v), (30.0, false, true));
assert_eq!(xfrm(&a, m, 30.0, true, false).rot, 330.0);
// Both flips and no flip keep the stored angle.
assert_eq!(xfrm(&a, m, 330.0, true, true).rot, 330.0);
assert_eq!(xfrm(&a, m, 330.0, false, false).rot, 330.0);
// A 90° visual shape is stored as 270°; the box swap still follows the stored angle.
let q = xfrm(&a, m, 270.0, true, false);
assert_eq!((q.rot, q.w, q.h), (90.0, 50.0, 100.0));
// The wrap is applied before the mirror.
assert_eq!(xfrm(&a, m, 360.0, true, false).rot, 0.0);
assert_eq!(xfrm(&a, m, -30.0, true, false).rot, 30.0);
// A group's child map still applies before the flip correction.
let g = xfrm(&a, Map { sx: 2.0, sy: 3.0, ox: 10.0, oy: 20.0 }, 330.0, true, false);
assert_eq!((g.rot, g.x, g.y, g.w, g.h), (30.0, 10.0, 20.0, 200.0, 150.0));
}
}
-4
View File
@@ -59,10 +59,6 @@ impl craft_pptx::Defaults for DeckDefaults {
Default::default()
}
fn default_text_style(&self) -> craft_drawingml::text::ListStyle {
convert::list_style_to_craft(&defaults::default_text_style())
}
fn application(&self) -> &str {
"DeckCraft"
}
@@ -0,0 +1,75 @@
//! Presentation text defaults across PPTX import, export and reopen.
use std::io::{Cursor, Read, Write};
use craft_xml::Local;
use deckcraft_model::{Presentation, defaults};
const PRESENTATION: &str = "ppt/presentation.xml";
fn imported_with_style(style_xml: &str) -> Presentation {
let base = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("author fixture");
let mut original = zip::ZipArchive::new(Cursor::new(base)).expect("open fixture package");
let mut fixture = zip::ZipWriter::new(Cursor::new(Vec::new()));
for i in 0..original.len() {
let mut part = original.by_index(i).expect("package part");
fixture.start_file(part.name(), zip::write::SimpleFileOptions::default()).expect("write package part");
if part.name() == PRESENTATION {
let mut xml = String::new();
part.read_to_string(&mut xml).expect("author fixture presentation XML");
let start = xml.find("<p:defaultTextStyle>").expect("new decks have a populated style");
let end_tag = "</p:defaultTextStyle>";
let end = xml.find(end_tag).expect("end of presentation text style") + end_tag.len();
xml.replace_range(start..end, style_xml);
fixture.write_all(xml.as_bytes()).expect("write fixture presentation XML");
} else {
std::io::copy(&mut part, &mut fixture).expect("copy fixture part");
}
}
let bytes = fixture.finish().expect("finish fixture package").into_inner();
deckcraft_pptx::import(&bytes).expect("import authored fixture")
}
fn assert_empty_after_two_saves(mut presentation: Presentation) {
assert!(presentation.default_text_style.is_empty(), "the imported style begins empty");
for save in 1..=2 {
let bytes = deckcraft_pptx::export(&presentation).expect("save PPTX");
let mut package = zip::ZipArchive::new(Cursor::new(&bytes)).expect("open saved package");
let mut xml = Vec::new();
package.by_name(PRESENTATION).expect("presentation part").read_to_end(&mut xml).expect("read presentation XML");
let document = craft_drawingml::xmlx::parse(&xml).expect("parse saved presentation XML");
assert!(
document.child(Local("defaultTextStyle")).is_none_or(|style| style.elements().next().is_none()),
"save {save} must not add inherited text formatting to an empty presentation style"
);
presentation = deckcraft_pptx::import(&bytes).expect("reopen PPTX");
assert!(presentation.default_text_style.is_empty(), "reopen {save} must retain the empty style");
}
}
#[test]
fn an_absent_presentation_text_style_stays_empty_after_two_saves() {
assert_empty_after_two_saves(imported_with_style(""));
}
#[test]
fn an_empty_presentation_text_style_stays_empty_after_two_saves() {
assert_empty_after_two_saves(imported_with_style("<p:defaultTextStyle/>"));
}
#[test]
fn authored_presentation_text_styles_survive_two_saves() {
let imported = imported_with_style(r#"<p:defaultTextStyle><a:lvl1pPr><a:defRPr kern="8800"/></a:lvl1pPr></p:defaultTextStyle>"#);
assert_eq!(imported.default_text_style.level(0).expect("explicit level").run.kern, Some(88.0));
let new_deck = defaults::new_presentation(None);
assert!(!new_deck.default_text_style.is_empty());
for mut presentation in [imported, new_deck] {
let expected = presentation.default_text_style.clone();
for _ in 0..2 {
let bytes = deckcraft_pptx::export(&presentation).expect("save authored style");
presentation = deckcraft_pptx::import(&bytes).expect("reopen authored style");
assert_eq!(presentation.default_text_style, expected);
}
}
}
+1
View File
@@ -9,6 +9,7 @@ mod corpus_kinds;
mod corpus_media;
mod corpus_style;
mod corpus_themes;
mod default_text_style;
mod export_scale;
mod fills;
mod kept_parts;