From 460b5438c0a6262135ab5759eafa81dffe8b3a27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:18:30 -0800 Subject: [PATCH 001/136] Dialogs: a Save As goes ahead when the portal answers with a file type of another shape answer() in crates/dialogs/src/portal.rs read the portal's current_filter with zvariant's tuple conversion, which panics on a structure with fewer fields than the tuple (zvariant 5.15.1, structure.rs:382). The Save dialog's thread then ended after a file was picked, and nothing was saved. filter_label reads the label only from a structure of a string and an array of (us), the (sa(us)) type the FileChooser portal documents. A current_filter of any other shape names no file type, and the answer keeps the path. A structure with more fields than (sa(us)) used to name its file type and now names none. This carries the fix from storytold/photocraft#13490 to the code that moved here from apps/photocraft/src/portal_save.rs. --- crates/dialogs/src/portal.rs | 17 +++++++++--- crates/dialogs/src/portal/tests.rs | 42 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/dialogs/src/portal.rs b/crates/dialogs/src/portal.rs index 1c6e75b04f..f75f2223bd 100644 --- a/crates/dialogs/src/portal.rs +++ b/crates/dialogs/src/portal.rs @@ -158,13 +158,22 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = results.get("current_filter").and_then(|v| filter_label(v)); Ok(Some(Saved { path, filter })) } +/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of +/// another shape. +fn filter_label(value: &Value<'_>) -> Option { + match value { + Value::Structure(s) => match s.fields() { + [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), + _ => None, + }, + _ => None, + } +} + /// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes. // pc: apps/photocraft/src/portal_save.rs:134 file_uri_path fn file_uri_path(uri: &str) -> Option { diff --git a/crates/dialogs/src/portal/tests.rs b/crates/dialogs/src/portal/tests.rs index 18cbc07e8b..26cf0b788d 100644 --- a/crates/dialogs/src/portal/tests.rs +++ b/crates/dialogs/src/portal/tests.rs @@ -10,6 +10,48 @@ fn file_uris_become_local_paths() { assert_eq!(file_uri_path("file://host/x.png"), None); } +/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string) +/// gives the path alone; `uris` of another shape is an error. +#[trial] +fn an_answer_of_another_shape_is_not_read() { + let answer_with = |uris: Value<'_>, filter: Option>| { + let mut r = HashMap::new(); + r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); + if let Some(filter) = filter { + r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); + } + answer(0, &r) + }; + let card = || Value::from(vec!["file:///tmp/card".to_string()]); + let malformed = [ + Value::from(("PNG".to_string(),)), + Value::from(("PNG".to_string(), vec![(0u32,)])), + Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])), + Value::from((1u32, vec![(0u32, "*.png".to_string())])), + Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)), + Value::from("PNG"), + ]; + for filter in malformed { + let shape = filter.value_signature().to_string(); + assert_eq!(answer_with(card(), Some(filter)), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })), "{shape}"); + } + // The shape the portal defines is still read, and so is the one `options` sends. + let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())])); + assert_eq!(answer_with(card(), Some(png)), Ok(Some(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }))); + let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"]))); + assert_eq!(filter_label(&sent), Some("Photoshop".into())); + let malformed = [ + Value::from(vec![1u32]), + Value::from(vec![("file:///tmp/card".to_string(),)]), + Value::from(Vec::::new()), + Value::from("file:///tmp/card"), + ]; + for uris in malformed { + let shape = uris.value_signature().to_string(); + assert!(answer_with(uris, None).is_err(), "{shape}"); + } +} + /// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the /// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with. #[trial] From 5926d7ead3f1e6079b029fbc5fe388947b7f0ae4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:32:21 -0800 Subject: [PATCH 002/136] Screen: the color picker portal's answer of another shape fails the pick without a panic On Wayland the screen color picker reads the Screenshot portal's PickColor answer, whose color is a (ddd) structure. It read it with zvariant's tuple conversion, which panics inside zvariant 5.15.1 (structure.rs:382) on a structure with fewer fields than the tuple. portal_color now reads the channels only from a structure of three doubles; any other shape fails the pick with "the desktop color picker returned no color". --- crates/platform/src/screen.rs | 43 ++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 0fc52b6787..8a247ab446 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -155,6 +155,19 @@ fn picked_color(rgb: [f64; 3]) -> Result { Ok(Capture::Color(rgb.map(|v| v as f32))) } +/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> { + use zbus::zvariant::Value; + match value { + Value::Structure(s) => match s.fields() { + [Value::F64(r), Value::F64(g), Value::F64(b)] => Some([*r, *g, *b]), + _ => None, + }, + _ => None, + } +} + /// The most pixels one monitor image may hold (64 M); larger captures fail with `Failed`. pub const MAX_PIXELS: usize = 64 * 1024 * 1024; @@ -231,7 +244,10 @@ fn unpack_rgba( #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod backend { - use super::{Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, usable_scale}; + use super::{ + Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, portal_color, + usable_scale, + }; const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024; /// Length limit of the property reads, in 32-bit units. @@ -437,8 +453,7 @@ mod backend { _ => return Err(failed("the desktop color picker could not sample this screen")), } let value = values.get("color").ok_or_else(|| failed("the desktop color picker returned no color"))?; - let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(failed)?.try_into().map_err(|e: zbus::zvariant::Error| failed(e))?; - picked_color([r, g, b]) + picked_color(portal_color(value).ok_or_else(|| failed("the desktop color picker returned no color"))?) } } @@ -724,4 +739,26 @@ mod tests { assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err()); assert!(checked_stride(1, 1, usize::MAX).is_err()); } + + /// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array) + /// gives no colour; a `(ddd)` value gives its channels. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[test] + fn a_color_of_another_shape_is_not_read() { + use zbus::zvariant::Value; + let malformed = [ + Value::from((0.5f64,)), + Value::from((0.5f64, 0.25f64)), + Value::from((0.5f64, 0.25f64, 1u32)), + Value::from(("red".to_string(), 0.25f64, 0.75f64)), + Value::from((0.5f64, 0.25f64, 0.75f64, 1.0f64)), + Value::from("red"), + Value::from(vec![0.5f64, 0.25, 0.75]), + ]; + for color in malformed { + let shape = color.value_signature().to_string(); + assert_eq!(portal_color(&color), None, "{shape}"); + } + assert_eq!(portal_color(&Value::from((0.5f64, 0.25f64, 0.75f64))), Some([0.5, 0.25, 0.75])); + } } From e5c911b900b1229f1f79fa1ecf3ff5bb675f9dda Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:52:37 -0500 Subject: [PATCH 003/136] ppt-binary: read PowerPoint 95 pictures and notes (#2317, step 4) PowerPoint 95 keeps a document's pictures as Windows metafiles in a slot list inside the Environment record. A picture on a slide is a rectangle whose link record names its slot and holds its crop. Each one now reads as a picture shape in its box, with its crop and the line and fill PowerPoint 95 draws it with. The metafile becomes image/x-wmf media as stored, as the PowerPoint 97 path keeps its metafiles. A slot is read once however many shapes show it, all of them within the PowerPoint 97 path's 2 GiB budget. A picture whose slot is missing, empty or not a metafile is left out. Each slide's notes page sits inside the slide. The text of its notes placeholder becomes the slide's notes. The notes master is not read. --- crates/ppt-binary/README.md | 8 +- crates/ppt-binary/src/blip.rs | 2 +- crates/ppt-binary/src/lib.rs | 4 +- crates/ppt-binary/src/ppt95.rs | 103 ++++++-- crates/ppt-binary/src/ppt95/picture.rs | 118 +++++++++ crates/ppt-binary/src/ppt95/tests.rs | 347 +++++++++++++++++++++++-- crates/ppt-binary/src/ppt95/text.rs | 2 +- 7 files changed, 541 insertions(+), 43 deletions(-) create mode 100644 crates/ppt-binary/src/ppt95/picture.rs diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 5736b17785..ebcdabd935 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -62,7 +62,13 @@ the rectangle, rounded rectangle and ellipse take the angle the user set. A shap nothing but text is a text box. Freeforms read as custom paths through their points, in their box, with their format's fill, line and shadow, and open ones with their arrowheads. Groups read as groups of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip -a group), nested up to 32 deep. Pictures, notes and the master's text styles come later. +a group), nested up to 32 deep. Pictures read as picture shapes in their box, with their crop and +the line and fill PowerPoint 95 draws them with. PowerPoint 95 keeps every picture as a Windows +metafile, whatever was inserted; each becomes `image/x-wmf` media as stored, as the PowerPoint 97 +path keeps its metafiles, read once however many shapes show it, and all of them within the +PowerPoint 97 path's 2 GiB budget. A picture whose picture can't be read is left out. Each slide's +notes page gives the slide its notes: the text of the page's notes placeholder. The master's text +styles come later. The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: its layouts and placeholders. The file's masters then place and style the placeholders that diff --git a/crates/ppt-binary/src/blip.rs b/crates/ppt-binary/src/blip.rs index 56b6abaeca..32aa261290 100644 --- a/crates/ppt-binary/src/blip.rs +++ b/crates/ppt-binary/src/blip.rs @@ -11,7 +11,7 @@ const MAX_INFLATED: usize = 64 << 20; /// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt` /// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could. /// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0. -const MAX_TOTAL: usize = 2 << 30; +pub(crate) const MAX_TOTAL: usize = 2 << 30; // A zero or tiny budget would drop every picture without a word, and the shift above can wrap on // a 32-bit target (wasm32) without any error, so the build checks it on every target. const _: () = assert!(MAX_TOTAL >= MAX_INFLATED); diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index 8637b778af..22a52bc33d 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -10,8 +10,8 @@ //! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read //! as far as their slide size, masters with their colour schemes, backgrounds and placeholder //! boxes, and slides with their order, master, layout type, background, placeholders and text -//! boxes with formatted text, and shapes and lines with their fill, line and shadow; their -//! pictures and notes are not read yet. +//! boxes with formatted text, shapes and lines with their fill, line and shadow, freeforms, groups +//! and pictures, and their notes. //! PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 797c68e3ae..1b8afe7252 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -7,8 +7,8 @@ //! //! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the //! slides in order with their master, layout type and background, holding their placeholders, text -//! boxes, shapes, lines, freeforms and groups, with the text and its character and paragraph -//! formatting ([`text`]). +//! boxes, shapes, lines, freeforms, groups and pictures, with the text and its character and +//! paragraph formatting ([`text`]), and their notes. //! //! A page's object list (3000) holds shapes (3008), placeholders (3010, which add a 3011 atom: the //! type, the size, then the index), lines (3014), freeforms (3016) and groups (3001). A shape or @@ -41,12 +41,18 @@ //! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path //! does. //! -//! Not read yet: pictures; notes; and the master's text styles, so the levels of the default -//! master's styles stay as they are (the slide text carries its own formatting in full). +//! A picture is a shape naming one of the document's pictures, which are Windows metafiles; its +//! box is the cropped picture's ([`picture`]). A slide's notes page is a Notes record (1008) inside +//! the slide, whose notes placeholder (type 0x0E) holds the notes text ([`notes`]). +//! +//! Not read yet: the master's text styles, so the levels of the default master's styles stay as +//! they are (the slide text carries its own formatting in full). use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use craft_pptx::style::PictureFill; +use craft_pptx::text::BodyProps; use craft_pptx::{ Background, ColorRef, Defaults, Effects, Fill, Geom, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, TextBody, Xfrm, @@ -54,9 +60,11 @@ use craft_pptx::{ use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme}; use crate::record::u32_at; +use picture::{PictureRef, Pictures}; use shape::Look; use text::Env; +mod picture; mod shape; mod text; @@ -68,6 +76,7 @@ mod rt { pub const SLIDE_BOX: u32 = 1005; pub const SLIDE: u32 = 1006; pub const SLIDE_ATOM: u32 = 1007; + pub const NOTES: u32 = 1008; pub const SCHEME: u32 = 1012; pub const LAYOUT: u32 = 1015; pub const MAIN_MASTER: u32 = 1016; @@ -87,8 +96,15 @@ mod rt { pub const FREEFORM_ATOM: u32 = 3017; pub const POINTS: u32 = 3035; pub const TEXT: u32 = 4001; + pub const TEXT_BODY: u32 = 4002; + pub const TEXT_ATOM: u32 = 4003; } +/// A notes page's notes placeholder, in PowerPoint 95's numbering (3011 +0). +const NOTES_PLACEHOLDER: u8 = 0x0E; +/// The notes text type ([MS-PPT] `TextTypeEnum`), in a text atom's (4003) +0. +const NOTES_TEXT: u32 = 2; + /// "No instance". const NO_INSTANCE: u32 = 0xFFFF; /// Slides, and masters, read at most: beyond any real presentation, so a file of empty slide @@ -273,6 +289,8 @@ enum Kind { Line, /// A freeform (3016). Freeform, + /// A picture: a shape (3008) naming one of the document's pictures. + Picture(PictureRef), /// A group (3001) and its members. Group(Vec), } @@ -417,15 +435,22 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { look = shape::look(&f, scheme); } } - Some(Object { placeholder, ph, xfrm, text, geom, look, kind: Kind::Shape }) + let kind = match picture::picture_ref(r).filter(|_| !placeholder) { + Some(pic) => Kind::Picture(pic), + None => Kind::Shape, + }; + Some(Object { placeholder, ph, xfrm, text, geom, look, kind }) } -/// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its -/// text; else a shape or line that draws something. One that draws nothing is left out. A -/// placeholder of an unknown type keeps its text as a text box. -fn shape(p: &mut Presentation, o: Object) -> Option { - if let Kind::Group(members) = o.kind { - return group(p, members); +/// An object as a shape: a placeholder of a known type; a picture; a text box when it draws +/// nothing but its text; else a shape or line that draws something. One that draws nothing is left +/// out, and so is a picture whose picture can't be read. A placeholder of an unknown type keeps its +/// text as a text box. +fn shape(p: &mut Presentation, pictures: &mut Pictures, o: Object) -> Option { + match o.kind { + Kind::Group(members) => return group(p, pictures, members), + Kind::Picture(pic) => return picture(p, pictures, o.xfrm, o.geom, o.look, pic), + _ => {} } let Some(ph) = o.ph else { let text = o.text.filter(|t| !t.is_empty()); @@ -475,19 +500,39 @@ fn shape(p: &mut Presentation, o: Object) -> Option { Some(Shape { id: ShapeId(p.alloc_id()?), name: name.into(), xfrm: Some(o.xfrm), ph: Some(ph), text, ..Default::default() }) } +/// A picture in its box, drawn with its format as PowerPoint 95 draws it (a picture made by +/// inserting a file has a line, and a fill behind it, as any new shape does), showing the cropped +/// picture. +fn picture(p: &mut Presentation, pictures: &mut Pictures, xfrm: Xfrm, geom: Option, look: Look, pic: PictureRef) -> Option { + let media = pictures.media(p, pic.slot)?; + let id = p.alloc_id()?; + let Look { fill, line, shadow } = look; + Some(Shape { + id: ShapeId(id), + name: format!("Picture {id}"), + xfrm: Some(xfrm), + geom: geom.unwrap_or_else(|| Geom::Preset { name: "rect".into(), adj: vec![] }), + fill: Some(fill), + line: Some(line), + effects: shadow.map(|s| Effects { outer_shadow: Some(s), ..Default::default() }), + kind: ShapeKind::Picture { fill: PictureFill { media, crop: pic.crop, ..Default::default() } }, + ..Default::default() + }) +} + /// A group of the shapes its members are, in the box they span, which is also its child space, so /// the members keep their places on the slide. A group none of whose members draws anything is /// left out. /// /// A nested group recurses here directly, not through [`shape`], whose frame is far larger: the /// recursion is bounded by [`MAX_DEPTH`], and each level should cost the stack little. -fn group(p: &mut Presentation, members: Vec) -> Option { +fn group(p: &mut Presentation, pictures: &mut Pictures, members: Vec) -> Option { let id = p.alloc_id()?; let mut children = Vec::with_capacity(members.len()); for m in members { let s = match m.kind { - Kind::Group(inner) => group(p, inner), - _ => shape(p, m), + Kind::Group(inner) => group(p, pictures, inner), + _ => shape(p, pictures, m), }; children.extend(s); } @@ -509,6 +554,11 @@ fn group(p: &mut Presentation, members: Vec) -> Option { /// Build the presentation from a PowerPoint 95 Document container. pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { + convert_within(document, app, crate::blip::MAX_TOTAL) +} + +/// [`convert`], with all of the document's pictures together within `budget` bytes. +fn convert_within(document: &Rec, app: &dyn Defaults, budget: usize) -> Presentation { let atom = document.child(rt::DOCUMENT_ATOM); let field = |at: usize| atom.and_then(|a| a.i32(at)); let size = Size::new(page_side(field(0), 720.0), page_side(field(4), 540.0)); @@ -516,6 +566,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { p.notes_size = Size::new(page_side(field(8), 540.0), page_side(field(12), 720.0)); let env = Env::new(document); + let mut pictures = Pictures::new(document, budget); // The lists are told apart by what they hold, in whatever order they come. let (mut slides, mut masters) = (vec![], vec![]); @@ -549,7 +600,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { } continue; } - if let Some(s) = shape(&mut p, o) { + if let Some(s) = shape(&mut p, &mut pictures, o) { master.shapes.push(s); } } @@ -574,13 +625,31 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let Some(id) = p.alloc_id() else { break }; let mut shapes = vec![]; for o in Reader::page(&env, &scheme, size, &s.rec) { - shapes.extend(shape(&mut p, o)); + shapes.extend(shape(&mut p, &mut pictures, o)); } - p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, ..Default::default() })); + let notes = s.rec.child(rt::NOTES).and_then(|n| notes(&n, &env, &scheme)).unwrap_or_default(); + p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, notes, ..Default::default() })); } p } +/// The text of a slide's notes page (1008, inside the slide): its notes placeholder's, or else the +/// first text of the notes text type, in the page's own colours. The notes master, a 1008 in the +/// Document itself, isn't read: the PowerPoint 97 path doesn't import notes masters either. +fn notes(page: &Rec, env: &Env, slide_scheme: &Scheme) -> Option { + let scheme = page.child(rt::SCHEME).and_then(|s| s.child(rt::COLOR_SCHEME)).map_or(*slide_scheme, |s| scheme_of(&s)); + let is_notes = |r: &Rec| { + let kind = r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let text_type = r.child(rt::TEXT).and_then(|t| t.child(rt::TEXT_BODY)).and_then(|b| b.child(rt::TEXT_ATOM)).and_then(|a| a.u32(0)); + kind == Some(NOTES_PLACEHOLDER) || (kind.is_none() && text_type == Some(NOTES_TEXT)) + }; + let objects = page.child(rt::OBJECTS)?; + let found = objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).find(|r| is_notes(r))?; + let mut body = text::text_body(&found.child(rt::TEXT)?, env, &scheme, None, false)?; + body.body = BodyProps::default(); + Some(body) +} + /// The caller's default master, with ids above those handed out so far, wearing `scheme`. fn default_master(p: &mut Presentation, app: &dyn Defaults, size: Size, scheme: Option) -> Master { let (mut master, last) = app.master(size, p.next_id); diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs new file mode 100644 index 0000000000..016a91ffeb --- /dev/null +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -0,0 +1,118 @@ +//! PowerPoint 95 pictures, learned from files PowerPoint 95 wrote. +//! +//! The Environment (1010) holds the document's pictures in a slot list (2006), as it holds its +//! fonts and rulers: each slot is what comes before a 2017 record. A slot's picture is a 4028 +//! container holding a 4037, which holds a header (4038) and the picture itself (4033): always a +//! Windows metafile without a placeable header, whatever was inserted (a BMP, a JPEG and a PNG all +//! became metafiles drawing the bitmap). Inserting the same file again reuses its slot. +//! +//! A picture on a page is a shape (3008, a rectangle drawn with its format as any shape is) holding +//! a 4014 container: 4015, the crop (left, top, right and bottom as i32s, in ten-thousandths of the +//! picture), and 4053 → 4036, the picture's slot number. The shape's box is the cropped picture's. +//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Only the +//! left and top crops were seen set; the right and bottom are taken to follow in that order. +//! +//! The metafile is kept as it is, as `image/x-wmf` media, as the PowerPoint 97 path keeps the +//! metafiles of its blip store. Each slot is read once, the first time a shape names it, and all of +//! them together within [`crate::blip::MAX_TOTAL`] bytes, the PowerPoint 97 path's budget. + +use std::collections::HashMap; + +use craft_pptx::{MediaId, Presentation}; + +use super::Rec; +use super::text::slots; +use crate::record::u16_at; + +/// Record types. +pub(super) mod rt { + pub const ENVIRONMENT: u32 = 1010; + pub const PICTURES: u32 = 2006; + pub const PICTURE: u32 = 4028; + pub const PICTURE_BODY: u32 = 4037; + pub const METAFILE: u32 = 4033; + pub const LINK: u32 = 4014; + pub const CROP: u32 = 4015; + pub const PICTURE_LINK: u32 = 4053; + pub const PICTURE_INDEX: u32 = 4036; +} + +/// A WMF's standard header: 9 words. +const WMF_HEADER: usize = 18; +/// Crop values are ten-thousandths of the picture. +const CROP_UNIT: f64 = 10_000.0; + +/// What a shape says about its picture: the slot it names and its crop (left, top, right, bottom, +/// as fractions of the picture). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PictureRef { + pub slot: u32, + pub crop: [f64; 4], +} + +/// A shape's picture link (4014 → 4053 → 4036), with its crop. `None` for a shape that shows no +/// picture, a notes page's slide image included. +pub(super) fn picture_ref(shape: &Rec) -> Option { + let link = shape.child(rt::LINK)?; + let slot = link.child(rt::PICTURE_LINK)?.child(rt::PICTURE_INDEX)?.u32(0)?; + let mut crop = [0.0; 4]; + if let Some(c) = link.child(rt::CROP) { + for (i, v) in crop.iter_mut().enumerate() { + *v = c.i32(i * 4).map_or(0.0, |n| (f64::from(n) / CROP_UNIT).clamp(-1.0, 1.0)); + } + } + Some(PictureRef { slot, crop }) +} + +/// The document's pictures: each slot's metafile record, made media only when a shape first names +/// it, every slot at most once, and all of them within a byte budget. +pub(super) struct Pictures<'a> { + slots: Vec>>, + media: HashMap>, + budget: usize, +} + +impl<'a> Pictures<'a> { + pub(super) fn new(document: &Rec<'a>, budget: usize) -> Pictures<'a> { + let slots = document + .child(rt::ENVIRONMENT) + .and_then(|e| e.child(rt::PICTURES)) + .map(|list| slots(&list, rt::PICTURE, |p| p.child(rt::PICTURE_BODY)?.child(rt::METAFILE))) + .unwrap_or_default(); + Pictures { slots, media: HashMap::new(), budget } + } + + /// The media of the picture in `slot`. `None` for a slot that is missing or empty, whose + /// metafile can't be read, or that would pass the budget. + pub(super) fn media(&mut self, p: &mut Presentation, slot: u32) -> Option { + if let Some(m) = self.media.get(&slot) { + return *m; + } + let id = self.read(p, slot); + self.media.insert(slot, id); + id + } + + fn read(&mut self, p: &mut Presentation, slot: u32) -> Option { + let record = self.slots.get(usize::try_from(slot).ok()?).copied().flatten()?; + let bytes = metafile(record.data)?; + if bytes.len() > self.budget { + log::warn!("ppt: PowerPoint 95 pictures pass {} bytes; the rest are left out", crate::blip::MAX_TOTAL); + return None; + } + self.budget -= bytes.len(); + p.add_media(&format!("image{}.wmf", u64::from(slot) + 1), "image/x-wmf", bytes.to_vec()) + } +} + +/// A metafile record's bytes as a WMF file: a standard header (a type of 1 or 2 and a header of 9 +/// words), cut to the size the header gives when the record holds more. `None` for anything else. +fn metafile(data: &[u8]) -> Option<&[u8]> { + let (kind, words) = (u16_at(data, 0)?, u16_at(data, 2)?); + if !matches!(kind, 1 | 2) || words != 9 || data.len() < WMF_HEADER { + return None; + } + // The file's size in words. + let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2)).unwrap_or(0); + Some(data.get(..size).filter(|_| size >= WMF_HEADER).unwrap_or(data)) +} diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 9d41014c1a..4b6e27a1dc 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -3,7 +3,7 @@ #![allow(clippy::unwrap_used)] use craft_pptx::text::{Align, Bullet}; -use craft_pptx::{Background, ColorRef, Fill, Geom, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; +use craft_pptx::{Background, ColorRef, Fill, Geom, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, ShapeKind, TextBody}; use super::rt; use crate::tests::{AppDefaults, build}; @@ -66,27 +66,37 @@ struct SlideSpec { scheme: [u32; 8], /// The slide's object list. objects: Vec>, + /// Its notes page (1008). + notes: Option>, } impl SlideSpec { fn new(id: u32, layout: u32) -> SlideSpec { - SlideSpec { id, master: MASTER, layout, follow_background: true, fill: [0, 0, 0, 0], filled: true, scheme: DEFAULT, objects: vec![] } + SlideSpec { + id, + master: MASTER, + layout, + follow_background: true, + fill: [0, 0, 0, 0], + filled: true, + scheme: DEFAULT, + objects: vec![], + notes: None, + } } } fn slide(s: &SlideSpec) -> Vec { - container( - rt::SLIDE, - 0x10, - &[ - rec(rt::SLIDE_ATOM, 0, 0, &le32(&[s.id, s.master])), - slide_box(s.follow_background), - rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), - container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), - background_shape(s.fill, s.filled), - container(rt::OBJECTS, 0x14, &s.objects), - ], - ) + let mut kids = vec![rec(rt::SLIDE_ATOM, 0, 0, &le32(&[s.id, s.master])), slide_box(s.follow_background)]; + // A notes page comes after the slide box, as PowerPoint 95 writes it. + kids.extend(s.notes.clone()); + kids.extend([ + rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), + container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), + background_shape(s.fill, s.filled), + container(rt::OBJECTS, 0x14, &s.objects), + ]); + container(rt::SLIDE, 0x10, &kids) } fn master(id: u32, scheme: [u32; 8], fill: [u8; 4]) -> Vec { @@ -136,7 +146,7 @@ const WIDE_RULER: [(i32, i32); 5] = [(576, 288), (828, 648), (1044, 900), (1260, /// The Environment: fonts Times New Roman, Arial, Courier New and "Café" by slot, and the rulers: /// the body's, a plain one, an empty slot and a wide one. -fn environment() -> Vec { +fn environment(pictures: &[Vec]) -> Vec { let fonts = container( 2005, 0x19, @@ -148,7 +158,9 @@ fn environment() -> Vec { 0x18, &[ruler(BODY_RULER), slot_end(0), ruler(plain), slot_end(1), rec(2018, 0, 0, &[]), slot_end(2), ruler(WIDE_RULER), slot_end(3)], ); - container(1010, 0x15, &[rulers, fonts, container(2005, 0x1A, &[])]) + let mut kids = pictures.to_vec(); + kids.extend([rulers, fonts, container(2005, 0x1A, &[])]); + container(1010, 0x15, &kids) } /// A character run: length, font slot, size in points, style bits (1 bold, 2 italic, @@ -262,16 +274,21 @@ fn document_atom(w: u32, h: u32, slides: u32) -> Vec { /// A `PowerPoint Document` stream: root 3 holding the Document and a type-10 atom. fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec { + stream_with(atom, slides, masters, &[], &[]) +} + +/// A stream whose Environment starts with `pictures` (the 2006 list) and whose Document ends with +/// `extra` records (a notes master, say). +fn stream_with(atom: Vec, slides: &[Vec], masters: &[Vec], pictures: &[Vec], extra: &[Vec]) -> Vec { let list = |tag: u32, items: &[Vec]| { let mut kids = vec![rec(2001, 0, 0, &le32(&[items.len() as u32]))]; kids.extend_from_slice(items); container(rt::LIST, tag, &kids) }; - let document = container( - rt::DOCUMENT, - 0, - &[atom, environment(), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], - ); + let mut kids = vec![atom, environment(pictures), list(0xA, slides), list(0xB, masters)]; + kids.extend_from_slice(extra); + kids.extend([list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])]); + let document = container(rt::DOCUMENT, 0, &kids); container(rt::ROOT, 0, &[document, rec(10, 0, 0, &le32(&[1, 0x100]))]) } @@ -1491,6 +1508,241 @@ fn hostile_freeforms_and_groups_never_panic() { } } +/// A Windows metafile without a placeable header: the standard header (type 1, 9 words, version +/// 0x300, its size in words), `records`, then the end record. +fn wmf(records: &[u8]) -> Vec { + let words = (18 + records.len() + 6) / 2; + let mut b = vec![1, 0, 9, 0, 0, 3]; + b.extend_from_slice(&(words as u32).to_le_bytes()); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(records); + b.extend_from_slice(&[3, 0, 0, 0, 0, 0]); + b +} + +/// A metafile that is told apart from others by `n`: a SETWINDOWEXT of n × n. +fn wmf_n(n: u8) -> Vec { + wmf(&[5, 0, 0, 0, 0x0C, 0x02, n, 0, n, 0]) +} + +/// The document's picture list (2006): each slot's metafile record body, or an empty slot. +fn picture_list(slots: &[Option>]) -> Vec { + let mut kids = vec![]; + for (i, s) in slots.iter().enumerate() { + match s { + Some(body) => { + let header = rec(4038, 0, 0, &le32(&[0xF00, 0, 0, 12, 12])); + kids.push(container(4028, 9, &[container(4037, 0, &[header, rec(4033, 0, 0, body)])])); + kids.push(rec(4043, 0, 0, &[])); + } + None => kids.push(rec(2018, 0, 0, &[])), + } + kids.push(slot_end(i as u32)); + } + container(2006, 0x17, &kids) +} + +/// A picture on a slide: a rectangle at `bx` drawn with `f`, naming `slot`, cropped by `crop` +/// (left, top, right, bottom in ten-thousandths). +fn picture_95(bx: [i32; 4], slot: u32, crop: [i32; 4], f: Format) -> Vec { + let link = container(4014, 0x1F, &[rec(4015, 0, 0, &le32(&crop.map(|v| v as u32))), container(4053, 0, &[rec(4036, 0, 0, &le32(&[slot]))])]); + container(rt::SHAPE, 0x13, &[coded_geometry((-3i32) as u32, 0, bx, 0), format(f), link]) +} + +/// 1 in square at 1 in, 1 in: AddPicture(file, 1440, 1440, 1440, 1440). +const PICTURE_BOX: [i32; 4] = [-2304, -1584, -1728, -1008]; + +/// A deck of `slides` slide object lists over the picture list `slots`, its pictures within +/// `budget` bytes. +fn picture_deck(slides: Vec>>, slots: &[Option>], budget: usize) -> Presentation { + let s: Vec> = + slides.into_iter().enumerate().map(|(i, objects)| slide(&SlideSpec { objects, ..SlideSpec::new(0x100 + i as u32, 16) })).collect(); + let stream = stream_with(document_atom(5760, 4320, s.len() as u32), &s, &[master(MASTER, DEFAULT, [0; 4])], &[picture_list(slots)], &[]); + let document = super::document(&stream).unwrap(); + super::convert_within(&document, &AppDefaults, budget) +} + +/// A picture shape as its box, media, crop and the media's bytes. +type Pictured = ((f64, f64, f64, f64), craft_pptx::MediaId, [f64; 4], Vec); + +/// Each picture on slide `i`: its box, media, crop and the media's bytes. +fn pictures_on(p: &Presentation, i: usize) -> Vec { + p.slides[i] + .shapes + .iter() + .filter_map(|s| match &s.kind { + ShapeKind::Picture { fill } => { + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!(media.content_type, "image/x-wmf"); + Some((boxed(s), fill.media, fill.crop, media.data.to_vec())) + } + _ => None, + }) + .collect() +} + +/// A picture is a picture shape in its box, showing its slot's metafile as it is, cropped as it +/// says, drawn with its format's line and fill. +#[test] +fn pictures_show_their_metafile() { + let p = picture_deck( + vec![vec![picture_95(PICTURE_BOX, 0, [0; 4], PLAIN), picture_95([-2160, -1512, -1728, -1008], 0, [2500, 1250, 0, -500], PLAIN)]], + &[Some(wmf_n(12))], + usize::MAX, + ); + let pics = pictures_on(&p, 0); + assert_eq!(pics.len(), 2); + assert_eq!((pics[0].0, pics[0].2, &pics[0].3), ((72.0, 72.0, 72.0, 72.0), [0.0; 4], &wmf_n(12))); + assert_eq!((pics[1].0, pics[1].2), ((90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, -0.05])); + let s = &p.slides[0].shapes[0]; + assert_eq!((s.fill.clone(), s.line.clone()), (Some(Fill::solid(rgb(0, 0xCC, 0x99))), Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0)))); + assert_eq!(preset_of(s).0, "rect"); + // Through the whole import too, with the full budget. + let stream = stream_with( + document_atom(5760, 4320, 1), + &[slide(&SlideSpec { objects: vec![picture_95(PICTURE_BOX, 0, [0; 4], PLAIN)], ..SlideSpec::new(0x100, 16) })], + &[master(MASTER, DEFAULT, [0; 4])], + &[picture_list(&[Some(wmf_n(2))])], + &[], + ); + let p = import(&stream).unwrap(); + assert_eq!(pictures_on(&p, 0).iter().map(|x| x.3.clone()).collect::>(), [wmf_n(2)]); +} + +/// Pictures naming one slot share one media item, on one slide or many; each slot is its own. +#[test] +fn pictures_sharing_a_slot_share_media() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(0)], vec![pic(0)]], &[Some(wmf_n(2)), Some(wmf_n(3))], usize::MAX); + let (first, second) = (pictures_on(&p, 0), pictures_on(&p, 1)); + assert_eq!((first.len(), second.len(), p.media.len()), (3, 1, 2)); + assert_eq!((first[0].1, second[0].1), (first[2].1, first[2].1)); + assert_ne!(first[0].1, first[1].1); + assert_eq!((first[0].3.clone(), first[1].3.clone()), (wmf_n(2), wmf_n(3))); +} + +/// A picture naming a slot that is missing, empty or holds no metafile is left out; the shapes +/// beside it are kept. +#[test] +fn a_dangling_picture_is_left_out() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let slots = [Some(wmf_n(2)), None, Some(b"GIF89a, not a metafile".to_vec()), Some(vec![1, 0, 9, 0, 0, 3])]; + let p = picture_deck( + vec![vec![pic(1), pic(2), pic(3), pic(7), pic(u32::MAX), autoshape(-1, 0, [0, 0, 576, 576], 0, PLAIN), pic(0)]], + &slots, + usize::MAX, + ); + let shapes = &p.slides[0].shapes; + assert_eq!(shapes.iter().map(|s| preset_of(s).0).collect::>(), ["ellipse", "rect"]); + assert_eq!(pictures_on(&p, 0).len(), 1); +} + +/// A metafile record holding more than its header's size is cut to it; one holding less is kept +/// as it is. +#[test] +fn a_metafile_is_cut_to_its_size() { + let mut long = wmf_n(2); + long.extend_from_slice(b"trailing bytes"); + let mut short = wmf_n(3); + short.truncate(short.len() - 6); + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let p = picture_deck(vec![vec![pic(0), pic(1)]], &[Some(long), Some(short.clone())], usize::MAX); + assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [wmf_n(2), short]); +} + +/// All the pictures together keep to the budget: a picture that would pass it is left out, and a +/// slot read already costs nothing more when it is shown again. +#[test] +fn pictures_keep_to_the_budget() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let (a, b) = (wmf_n(2), wmf_n(3)); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(0)]], &[Some(a.clone()), Some(b)], a.len() + 4); + assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [a.clone(), a.clone()]); + // The full import's budget is the PowerPoint 97 path's. + assert_eq!(crate::blip::MAX_TOTAL, 2 << 30); + let p = picture_deck(vec![vec![pic(0)]], &[Some(a.clone())], a.len() - 1); + assert!(p.slides[0].shapes.is_empty() && p.media.is_empty()); +} + +/// A notes page (1008) inside a slide, its slide id in its 1009 atom, holding a slide image +/// placeholder (type 0x13, linked to the slide) and the notes placeholder (0x0E) with `text`. +fn notes_page(slide_id: u32, text: &[u8]) -> Vec { + let bx = [-1440, -2448, 1440, -288]; + let image = container(4014, 0x1F, &[rec(4015, 0, 0, &[0; 16]), container(4054, 0, &[rec(4032, 0, 0, &le32(&[slide_id]))])]); + let image = container(3010, 0x13, &[rec(3011, 0, 0, &[0x13, 0, 0, 0, 0, 0, 0, 0]), geometry(bx, 0), format(PLAIN), image]); + let body_box = [-1584, -144, 1584, 2448]; + let body = placeholder_95(0x0E, 0, 1, body_box, Some(simple_text(text, body_box, BODY))); + notes_with(slide_id, vec![image, body]) +} + +/// A notes page holding `objects`. +fn notes_with(slide_id: u32, objects: Vec>) -> Vec { + container(rt::NOTES, 0x25, &[rec(1009, 0, 0, &le32(&[slide_id])), slide_box(true), container(rt::OBJECTS, 0x14, &objects)]) +} + +/// A text container's text type (its 4003 atom's +0) set to `kind`. +fn text_typed(mut text: Vec, kind: u32) -> Vec { + let at = text.windows(4).position(|w| w == 4003u32.to_le_bytes()).unwrap(); + text[at + 16..at + 20].copy_from_slice(&kind.to_le_bytes()); + text +} + +/// Each slide's notes are its own notes page's notes placeholder's text (or, without one, the text +/// of the notes text type); the notes master's text and the slide image aren't notes, and nothing +/// on a notes page becomes a slide shape. +#[test] +fn notes_land_on_their_slide() { + let mut slides = [SlideSpec::new(0x100, 16), SlideSpec::new(0x101, 16), SlideSpec::new(0x102, 16), SlideSpec::new(0x103, 16)]; + slides[0].notes = Some(notes_page(0x100, b"First note\rsecond line")); + slides[2].notes = Some(notes_page(0x102, b"Third")); + // A notes page whose text is a plain shape of the notes text type. + let bx = [-1584, -144, 1584, 2448]; + slides[3].notes = Some(notes_with( + 0x103, + vec![shape_95(bx, Some(text_typed(simple_text(b"Typed", bx, BODY), 4))), shape_95(bx, Some(text_typed(simple_text(b"Fourth", bx, BODY), 2)))], + )); + slides[0].objects = vec![shape_95([0, 0, 576, 576], Some(simple_text(b"On the slide", [0, 0, 576, 576], BODY)))]; + let s: Vec> = slides.iter().map(slide).collect(); + let notes_master = notes_with(MASTER, vec![placeholder_95(0x05, 0, 1, bx, Some(simple_text(b"Master notes", bx, MASTER_BODY)))]); + let p = import(&stream_with(document_atom(5760, 4320, 4), &s, &[master(MASTER, DEFAULT, [0; 4])], &[], &[notes_master])).unwrap(); + assert_eq!(p.slides.iter().map(|s| s.notes.text()).collect::>(), ["First note\nsecond line", "", "Third", "Fourth"]); + assert_eq!(p.slides[0].notes.paragraphs[0].runs[0].props.size, Some(24.0)); + assert_eq!(texts(&p), ["On the slide"]); + assert!(p.slides[1..].iter().all(|s| s.shapes.is_empty())); +} + +/// Damaged pictures and notes never panic: every word of a deck of them set to hostile values (huge +/// sizes, bad slot numbers, odd types), or the deck cut anywhere. +#[test] +fn hostile_pictures_and_notes_never_panic() { + let mut s = SlideSpec::new(0x100, 16); + s.objects = vec![picture_95(PICTURE_BOX, 0, [2500, 0, -20000, i32::MAX], PLAIN), group_95(&[picture_95(PICTURE_BOX, 1, [0; 4], PLAIN)])]; + s.notes = Some(notes_page(0x100, b"Note")); + let stream = stream_with( + document_atom(5760, 4320, 1), + &[slide(&s)], + &[master(MASTER, DEFAULT, [0; 4])], + &[picture_list(&[Some(wmf_n(2)), None, Some(wmf_n(3))])], + &[], + ); + for at in (0..stream.len() - 4).step_by(2) { + for v in [0u32, 1, 2, 9, 0xFAB, 0xFB5, 0xFC4, 0x3F0, 0x7FFF_FFFF, 0xFFFF_FFFF] { + let mut d = stream.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + if let Ok(p) = import(&d) { + for s in &p.slides { + for x in s.shapes.iter().filter_map(|x| x.xfrm) { + assert!(x.w.is_finite() && x.h.is_finite()); + } + } + } + } + } + for cut in 0..stream.len() { + let _ = import(&stream[..cut]); + } +} + /// The presets of the object model's shape types 1 to 12, as PowerPoint 95 rendered them ("custom" for /// the trapezoid, which has its own outline). const SHAPE_PRESETS: [&str; 12] = @@ -1557,10 +1809,63 @@ fn check_sample(name: &str, p: &Presentation) { // The automation reported 1295, 1367.5, 4610 × 720 twips. assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); } + "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), _ => check_shape_sample(name, p), } } +/// What one PowerPoint 95 picture or notes sample shows, by its case name. +fn check_media_sample(name: &str, p: &Presentation) { + let notes: Vec = p.slides.iter().map(|s| s.notes.text()).collect(); + // Each picture on a slide: its box, media, crop, and whether it has the default black line. + let pictures = |i: usize| -> Vec<_> { + p.slides[i] + .shapes + .iter() + .map(|s| { + let ShapeKind::Picture { fill } = &s.kind else { panic!("{name}: {:?} is not a picture", s.name) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!((media.content_type.as_str(), &media.data[..4]), ("image/x-wmf", &[1, 0, 9, 0][..]), "{name}"); + assert_eq!(s.line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0)), "{name}"); + (boxed(s), fill.media, fill.crop, media.data.len()) + }) + .collect() + }; + // AddPicture(file, 1440, 1440, 1440, 1440) in twips: 1 in square at 1 in, 1 in. + let inch = (72.0, 72.0, 72.0, 72.0); + match name { + "picture" | "picwmf" | "jpeg" | "png" => { + let pics = pictures(0); + // The BMP's metafile is 128 bytes, the JPEG's and PNG's 220. + let len = if name == "jpeg" || name == "png" { 220 } else { 128 }; + assert_eq!((pics.len(), pics[0].0, pics[0].2, pics[0].3, p.media.len()), (1, inch, [0.0; 4], len, 1), "{name}"); + } + "piccrop" => { + // CropLeft 0.25 and CropTop 0.125 of the inch square: what is left of it, where it was. + let pics = pictures(0); + assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, 0.0])); + } + "twopics" => { + let pics = pictures(0); + assert_eq!(pics.iter().map(|x| (x.0, x.3)).collect::>(), [(inch, 128), ((216.0, 72.0, 144.0, 72.0), 220)]); + assert_ne!(pics[0].1, pics[1].1); + } + "picshare" => { + // One file inserted three times, on two slides: one picture. + let (first, second) = (pictures(0), pictures(1)); + assert_eq!((first.len(), second.len(), p.media.len()), (2, 1, 1)); + assert_eq!((first[0].0, first[1].0, second[0].0), (inch, (216.0, 72.0, 36.0, 36.0), inch)); + assert!(first[1].1 == first[0].1 && second[0].1 == first[0].1); + } + "notes" => assert_eq!(notes, ["Speaker note"]), + "notes2" => assert_eq!(notes, ["Note one", "Note two", ""]), + _ => {} + } + if name.starts_with("notes") { + assert!(p.slides.iter().all(|s| s.shapes.is_empty()), "{name}: the notes page's placeholders aren't slide shapes"); + } +} + /// What one PowerPoint 95 shape sample shows, by its case name. fn check_shape_sample(name: &str, p: &Presentation) { let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index d3d97dba7e..4b1d9952e9 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -83,7 +83,7 @@ impl Env { /// A slot list's entries of `kind`, read by `read`: an entry is the slot of the 2017 records /// before it. -fn slots(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option) -> Vec> { +pub(super) fn slots<'a, T>(list: &Rec<'a>, kind: u32, read: impl Fn(&Rec<'a>) -> Option) -> Vec> { let mut out = vec![]; let mut current = None; for r in list.children() { From 2958d98e8a5d6145f69aaa950e2cd1e8b83c2088 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:53:57 -0500 Subject: [PATCH 004/136] ppt-binary: check the PowerPoint 95 crop's right and bottom values A sample cropped on the right and at the bottom shows the crop record's last two values in that order, as the reader takes them; the samples check now covers it. --- crates/ppt-binary/src/ppt95/picture.rs | 4 ++-- crates/ppt-binary/src/ppt95/tests.rs | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs index 016a91ffeb..e81a4466d0 100644 --- a/crates/ppt-binary/src/ppt95/picture.rs +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -9,8 +9,8 @@ //! A picture on a page is a shape (3008, a rectangle drawn with its format as any shape is) holding //! a 4014 container: 4015, the crop (left, top, right and bottom as i32s, in ten-thousandths of the //! picture), and 4053 → 4036, the picture's slot number. The shape's box is the cropped picture's. -//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Only the -//! left and top crops were seen set; the right and bottom are taken to follow in that order. +//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Each of the +//! four crops was seen set: left and top in one file, right and bottom in another. //! //! The metafile is kept as it is, as `image/x-wmf` media, as the PowerPoint 97 path keeps the //! metafiles of its blip store. Each slot is read once, the first time a shape names it, and all of diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 4b6e27a1dc..53d31298cf 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1809,7 +1809,7 @@ fn check_sample(name: &str, p: &Presentation) { // The automation reported 1295, 1367.5, 4610 × 720 twips. assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); } - "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), + "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "piccrop2" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), _ => check_shape_sample(name, p), } } @@ -1845,6 +1845,11 @@ fn check_media_sample(name: &str, p: &Presentation) { let pics = pictures(0); assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, 0.0])); } + "piccrop2" => { + // CropRight 0.3 and CropBottom 0.05: the crop's last two values, in that order. + let pics = pictures(0); + assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (72.0, 72.0, 50.375, 68.375), [0.0, 0.0, 0.3, 0.05])); + } "twopics" => { let pics = pictures(0); assert_eq!(pics.iter().map(|x| (x.0, x.3)).collect::>(), [(inch, 128), ((216.0, 72.0, 144.0, 72.0), 220)]); From 4be518decabaaf240fd6905174ee75874441c07d Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 00:54:53 -0500 Subject: [PATCH 005/136] ppt95: the centred-title test takes this branch's environment and stream helpers --- crates/ppt-binary/src/ppt95/tests.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index c1a2428412..54dce20317 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -814,8 +814,13 @@ fn a_masters_centred_title_gives_the_title_style_its_ruler() { Some(text(b"T", &[plain(2)], &[para_run(2, false, 0, 1, 0)], 3, [0; 4], MASTER_BODY)), ); let atoms = [style_atom([LEVEL; 5], 0x13)]; - let stream = - stream_with(document_atom(5760, 4320, 0), &[], &[master_with(MASTER, DEFAULT, [0; 4], &[title])], environment_with(&[styles(&atoms)])); + let stream = stream_with( + document_atom(5760, 4320, 0), + &[], + &[master_with(MASTER, DEFAULT, [0; 4], &[title])], + environment_with(&[], &[styles(&atoms)]), + &[], + ); let t = import(&stream).unwrap().masters[0].title_style.level(0).cloned().unwrap(); // The wide ruler (slot 3): level 1 at 576 units, its first line at 288. assert_eq!((t.para.margin_left, t.para.indent), (Some(72.0), Some(-36.0))); From 8f195d860b04fca074fa9725a7eeecc8babfa614 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:15:56 -0500 Subject: [PATCH 006/136] ppt95: a notes page's notes placeholder wins over other notes text The notes came from the first object that was either the notes placeholder or text of the notes type, so a notes-type shape before the placeholder gave its text instead. The placeholder is now looked for first, and other notes text only without one. --- crates/ppt-binary/src/ppt95.rs | 10 ++++++---- crates/ppt-binary/src/ppt95/tests.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 71140e044a..88ecd68f3c 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -741,13 +741,15 @@ fn convert_within(document: &Rec, app: &dyn Defaults, budget: usize) -> Presenta /// Document itself, isn't read: the PowerPoint 97 path doesn't import notes masters either. fn notes(page: &Rec, env: &Env, slide_scheme: &Scheme) -> Option { let scheme = page.child(rt::SCHEME).and_then(|s| s.child(rt::COLOR_SCHEME)).map_or(*slide_scheme, |s| scheme_of(&s)); - let is_notes = |r: &Rec| { - let kind = r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let kind = |r: &Rec| r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let notes_text = |r: &Rec| { let text_type = r.child(rt::TEXT).and_then(|t| t.child(rt::TEXT_BODY)).and_then(|b| b.child(rt::TEXT_ATOM)).and_then(|a| a.u32(0)); - kind == Some(NOTES_PLACEHOLDER) || (kind.is_none() && text_type == Some(NOTES_TEXT)) + kind(r).is_none() && text_type == Some(NOTES_TEXT) }; let objects = page.child(rt::OBJECTS)?; - let found = objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).find(|r| is_notes(r))?; + let candidates = || objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)); + // The notes placeholder wherever it is, before any other text of the notes type. + let found = candidates().find(|r| kind(r) == Some(NOTES_PLACEHOLDER)).or_else(|| candidates().find(|r| notes_text(r)))?; let mut body = text::text_body(&found.child(rt::TEXT)?, env, &scheme, None, false)?; body.body = BodyProps::default(); Some(body) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 5e0fc61191..c5e5789e23 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2137,6 +2137,18 @@ fn notes_land_on_their_slide() { assert_eq!(p.slides[0].notes.paragraphs[0].runs[0].props.size, Some(24.0)); assert_eq!(texts(&p), ["On the slide"]); assert!(p.slides[1..].iter().all(|s| s.shapes.is_empty())); + + // Text of the notes type before the notes placeholder: the placeholder's text is the notes. + let mut spec = SlideSpec::new(0x100, 16); + spec.notes = Some(notes_with( + 0x100, + vec![ + shape_95(bx, Some(text_typed(simple_text(b"Typed first", bx, BODY), 2))), + placeholder_95(0x0E, 0, 1, bx, Some(simple_text(b"From the placeholder", bx, BODY))), + ], + )); + let p = import(&stream_of(document_atom(5760, 4320, 1), &[slide(&spec)], &[master(MASTER, DEFAULT, [0; 4])])).unwrap(); + assert_eq!(p.slides[0].notes.text(), "From the placeholder"); } /// Notes paragraphs keep their spacing and justified alignment, as a slide's do. From 70b6613f0dcb3784494b42097e3ca756728e1525 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:19:02 -0500 Subject: [PATCH 007/136] ppt95: a metafile whose header gives a size smaller than itself is not one metafile() fell back to the whole record when the header's size was smaller than the 18-byte header, so a broken header passed as a metafile. It is now refused, and its picture left out. The budget warning now gives the picture's size and the bytes left, which can be less than the 2 GiB total it named. --- crates/ppt-binary/src/ppt95/picture.rs | 16 ++++++++++++---- crates/ppt-binary/src/ppt95/tests.rs | 7 +++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs index e81a4466d0..46f34cf784 100644 --- a/crates/ppt-binary/src/ppt95/picture.rs +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -97,7 +97,11 @@ impl<'a> Pictures<'a> { let record = self.slots.get(usize::try_from(slot).ok()?).copied().flatten()?; let bytes = metafile(record.data)?; if bytes.len() > self.budget { - log::warn!("ppt: PowerPoint 95 pictures pass {} bytes; the rest are left out", crate::blip::MAX_TOTAL); + log::warn!( + "ppt: a {}-byte PowerPoint 95 picture passes the {} bytes left of the pictures' budget; it is left out", + bytes.len(), + self.budget + ); return None; } self.budget -= bytes.len(); @@ -106,13 +110,17 @@ impl<'a> Pictures<'a> { } /// A metafile record's bytes as a WMF file: a standard header (a type of 1 or 2 and a header of 9 -/// words), cut to the size the header gives when the record holds more. `None` for anything else. +/// words), cut to the size the header gives when the record holds more. `None` for anything else, +/// a header giving a size smaller than itself included. fn metafile(data: &[u8]) -> Option<&[u8]> { let (kind, words) = (u16_at(data, 0)?, u16_at(data, 2)?); if !matches!(kind, 1 | 2) || words != 9 || data.len() < WMF_HEADER { return None; } // The file's size in words. - let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2)).unwrap_or(0); - Some(data.get(..size).filter(|_| size >= WMF_HEADER).unwrap_or(data)) + let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2))?; + if size < WMF_HEADER { + return None; + } + Some(data.get(..size).unwrap_or(data)) } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index c5e5789e23..43f352d49b 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2066,7 +2066,7 @@ fn a_dangling_picture_is_left_out() { } /// A metafile record holding more than its header's size is cut to it; one holding less is kept -/// as it is. +/// as it is; one whose header gives a size smaller than the header isn't a metafile. #[test] fn a_metafile_is_cut_to_its_size() { let mut long = wmf_n(2); @@ -2074,7 +2074,10 @@ fn a_metafile_is_cut_to_its_size() { let mut short = wmf_n(3); short.truncate(short.len() - 6); let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); - let p = picture_deck(vec![vec![pic(0), pic(1)]], &[Some(long), Some(short.clone())], usize::MAX); + // A header giving a size smaller than itself: not a metafile, so its picture is left out. + let mut tiny = wmf_n(4); + tiny[6..10].copy_from_slice(&4u32.to_le_bytes()); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(2)]], &[Some(long), Some(short.clone()), Some(tiny)], usize::MAX); assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [wmf_n(2), short]); } From 92e4cab2d3265f97a436a1982d77cdbf7035ae6c Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:07:40 -0500 Subject: [PATCH 008/136] craft-ppt-binary: say unknown master placeholders are left out; match each outline to its own polygon The module doc said a placeholder of an unknown type keeps its text as a text box, which is true on slides only: the master leaves it out. check_outlines let two shapes match the same rendered polygon, so two shapes moved onto one place still passed. Each shape now takes a polygon of its own. --- crates/ppt-binary/src/ppt95.rs | 7 ++++--- crates/ppt-binary/src/ppt95/tests.rs | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 38e4c7333d..a1584bbfa4 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -37,9 +37,10 @@ //! cap. //! //! PowerPoint 95 numbers placeholders its own way: on the master 1 title, 2 body, 6 date, 7 slide -//! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. A -//! placeholder of any other type keeps its text as a text box. The master's placeholders place the -//! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path +//! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. On a +//! slide, a placeholder of any other type keeps its text as a text box; on the master it is left +//! out. The master's placeholders place the caller's default master's, and the footer row places +//! every layout's, as the PowerPoint 97 path //! does. //! //! A picture is a shape naming one of the document's pictures, which are Windows metafiles; its diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 1bd81dd20a..61f91721ee 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2808,11 +2808,13 @@ fn the_wmf_reader_stays_in_each_record() { } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a -/// straight outline matches a polygon PowerPoint 95 drew. The number of shapes checked. +/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own: two shapes +/// moved onto one place don't both match it. The number of shapes checked. fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { let polygons = wmf_polygons(wmf, p.slide_size); let Some(slide) = p.slides.first() else { return 0 }; let mut checked = 0; + let mut used = vec![false; polygons.len()]; for s in &slide.shapes { let Some(corners) = outline_corners(s) else { continue }; // A dashed line is drawn dash by dash. @@ -2821,7 +2823,9 @@ fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { } let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); let near = polygons.iter().min_by_key(|poly| poly.len().abs_diff(corners.len())); - assert!(polygons.iter().any(|poly| outline_matches(&corners, poly, width)), "{name}: {corners:?} is not drawn; nearest {near:?}"); + let hit = (0..polygons.len()).find(|&i| !used[i] && outline_matches(&corners, &polygons[i], width)); + let Some(i) = hit else { panic!("{name}: {corners:?} is not drawn, or only where another shape is; nearest {near:?}") }; + used[i] = true; checked += 1; } checked From bbd4b02c899bc3592343bdc3e09e31ca4c8486e9 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:14:39 -0500 Subject: [PATCH 009/136] craft-ppt-binary: match outlines to polygons by trying every assignment First-fit could reject shapes that do all fit: a shape that fits two polygons could take the one another shape needs. check_outlines now uses bipartite matching (match_outlines), with a test of that case and of two shapes moved onto one place. --- crates/ppt-binary/src/ppt95/tests.rs | 57 +++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 61f91721ee..6b9f56780f 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2808,13 +2808,13 @@ fn the_wmf_reader_stays_in_each_record() { } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a -/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own: two shapes -/// moved onto one place don't both match it. The number of shapes checked. +/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own +/// ([`match_outlines`]): two shapes moved onto one place don't both match it. The number of shapes +/// checked. fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { let polygons = wmf_polygons(wmf, p.slide_size); let Some(slide) = p.slides.first() else { return 0 }; - let mut checked = 0; - let mut used = vec![false; polygons.len()]; + let mut outlines = vec![]; for s in &slide.shapes { let Some(corners) = outline_corners(s) else { continue }; // A dashed line is drawn dash by dash. @@ -2823,12 +2823,51 @@ fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { } let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); let near = polygons.iter().min_by_key(|poly| poly.len().abs_diff(corners.len())); - let hit = (0..polygons.len()).find(|&i| !used[i] && outline_matches(&corners, &polygons[i], width)); - let Some(i) = hit else { panic!("{name}: {corners:?} is not drawn, or only where another shape is; nearest {near:?}") }; - used[i] = true; - checked += 1; + assert!(polygons.iter().any(|poly| outline_matches(&corners, poly, width)), "{name}: {corners:?} is not drawn; nearest {near:?}"); + outlines.push((corners, width)); } - checked + if let Err(i) = match_outlines(&outlines, &polygons) { + panic!("{name}: {:?} is drawn only where another shape is", outlines[i].0); + } + outlines.len() +} + +/// Gives each outline (its corners and line width) a polygon of its own that it matches, trying +/// every assignment rather than the first that fits, or else the first outline left without one. +fn match_outlines(outlines: &[(Vec<(f64, f64)>, f64)], polygons: &[Vec<(f64, f64)>]) -> Result<(), usize> { + let fits: Vec> = + outlines.iter().map(|(corners, width)| (0..polygons.len()).filter(|&q| outline_matches(corners, &polygons[q], *width)).collect()).collect(); + // Kuhn's algorithm: a polygon already taken is freed when its owner can move to another. + fn assign(fits: &[Vec], s: usize, seen: &mut [bool], owner: &mut [Option]) -> bool { + for &q in &fits[s] { + if std::mem::replace(&mut seen[q], true) { + continue; + } + if owner[q].is_none_or(|t| assign(fits, t, seen, owner)) { + owner[q] = Some(s); + return true; + } + } + false + } + let mut owner = vec![None; polygons.len()]; + for s in 0..outlines.len() { + if !assign(&fits, s, &mut vec![false; polygons.len()], &mut owner) { + return Err(s); + } + } + Ok(()) +} + +/// Two shapes can't both match one drawn polygon, and a polygon that fits two shapes goes to the +/// one that needs it, whatever order the polygons were drawn in. +#[test] +fn each_outline_matches_a_polygon_of_its_own() { + let rect = |x: f64| vec![(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]; + // Shapes at 100 and 102 drawn at 101 and 99: the first fits both, the second only 101. + assert_eq!(match_outlines(&[(rect(100.0), 1.0), (rect(102.0), 1.0)], &[rect(101.0), rect(99.0)]), Ok(())); + // Two shapes moved onto one place, drawn at two. + assert_eq!(match_outlines(&[(rect(0.0), 1.0), (rect(0.0), 1.0)], &[rect(0.0), rect(50.0)]), Err(1)); } /// A file holding fewer slides than its DocumentAtom counts names the missing ones by position, From d54f840b8f9d3dc24ad19d77da9cd452ad0f4846 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:17:18 -0500 Subject: [PATCH 010/136] craft-ppt-binary: check the hostile-text fixture reads before mutating it If the fixture stopped reaching the text reader, every mutated copy could fail early and the sweep would still pass. Import it whole first and check its slide text and the master's title style. --- crates/ppt-binary/src/ppt95/tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 6b9f56780f..4615c9ea70 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1039,6 +1039,11 @@ fn hostile_text_never_panics() { let level = Level { spacing: [150, -36, 20], align: 3, ..LEVEL }; let env = environment_with(&[], &[styles(&[style_atom([level; 5], 0x13), style_atom([level; 5], 0x21)])]); let stream = stream_with(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &objects)], env, &[]); + // Whole, it reaches the text reader: else every hostile copy below could fail early and pass. + let p = import(&stream).unwrap(); + assert_eq!(texts(&p), ["One\nTwo", "T"]); + let t = p.masters[0].title_style.level(0).unwrap(); + assert_eq!((t.para.line_spacing, t.para.space_before), (Some(Spacing::Pct(1.5)), Some(Spacing::Pts(36.0)))); for at in (0..stream.len() - 4).step_by(4) { for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF] { let mut d = stream.clone(); From ed647a5d49c88c3ade7486267a329ab5d5ffb485 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:35 -0800 Subject: [PATCH 011/136] Canvas: the body's tool pass carries the text the editor part pastes The framework takes a paste event out of egui's input and keeps its text for the focused component, so a canvas body that applies its editor's Edit(Paste) could only read the installed clipboard, which fails where the system clipboard can't be opened (a Wayland session where arboard finds no data-control protocol). ToolPass::pasted now holds the text the platform's paste event carried in the pass of that paste: Ctrl+V's, or the one a Paste command asks the platform for. --- crates/ui-canvas/src/canvas/mod.rs | 13 ++++++++ crates/ui-canvas/tests/it/canvas/editor.rs | 36 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9cab..ad3724c1bd 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -240,6 +240,8 @@ pub struct Canvas<'a> { settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. context_key: bool, + /// The text of the paste the editor part takes this pass, taken in `update` with its inputs. + pasted: Option>, /// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)). ease: Option, /// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional @@ -316,6 +318,7 @@ impl<'a> Canvas<'a> { snap: None, settled: None, context_key: false, + pasted: None, ease: None, follows_pointer: false, tool_regions: Vec::new(), @@ -689,6 +692,7 @@ impl<'a> Canvas<'a> { navigation: self.navigation, editor_input: self.editor_input.clone(), editor: cx.editor_handle(), + pasted: self.pasted.clone(), } } @@ -758,6 +762,11 @@ pub struct ToolPass { pub editor_input: Arc<[EditorInput]>, /// The editor part of this pass, through which the body reports its editor state; `None` without an editor. pub editor: Option, + /// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of + /// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's, + /// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the + /// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one. + pub pasted: Option>, } impl ToolPass { @@ -863,6 +872,10 @@ impl Component for Canvas<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { // Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`. self.editor_input = cx.editor_input().collect::>().into(); + self.pasted = match cx.clipboard().paste() { + crate::runtime::pending::Pending::Ready(content) => content.text.clone(), + _ => None, + }; // Left untaken: the canvas's generic context request is recorded as for a secondary click. self.context_key = cx.intents().untaken(&Intent::ContextMenu); // The canvas is no value component: it reads and writes its view's binding itself, as a container does. diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f3..4cf2f9cd83 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,7 +2,7 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; @@ -88,6 +88,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the ); } +/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`. +type PassPaste = (Vec, Option); + +/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass: +/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't +/// be opened. +#[trial] +fn a_paste_events_text_reaches_the_body_with_the_editors_paste() { + let seen: Rc>> = Rc::default(); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).show_at(ui, room, |_, body| { + let Some(pass) = tool_pass(&body.env) else { return }; + shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned))); + }); + }); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + seen.borrow_mut().clear(); + fixture.frame(vec![Event::Paste("from the platform".into())]); + fixture.frame(vec![]); + let passes = seen.take(); + let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect(); + assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}"); + for (inputs, text) in &pasted { + assert_eq!(text.as_deref(), Some("from the platform")); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}"); + } + assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}"); +} + /// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines, /// so its caret reaches the input method and no empty text is announced on the canvas's node. #[trial] From 9e1c5f75e43c84d973815bcfcaca8632d10cd03d Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Sat, 21 Nov 2026 12:20:36 +0000 Subject: [PATCH 012/136] #7171: scroll bodies offer fill-width children the view, not the bar lane Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/contract/body/hooks.rs | 9 +++++++- .../tests/it/layout/stack_widths.rs | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c6..6c96686a88 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1524,7 +1524,14 @@ impl BodyHooks<'_> { if lays_out { crate::runtime::lazy::begin(ctx, view, self.anchor.map(|anchor| anchor.child), self.glide.map(|glide| glide.child)); } - let env = run.env.derive_local(|scoped| scoped.lazy = Some(view)); + // The children fill what the view shows: the width the body was offered counts the bar's lane, so a child that + // fills the offered width would lie under the bar. + let env = run.env.derive_local(|scoped| { + scoped.lazy = Some(view); + if let Some(offered) = scoped.offered.as_mut() { + *offered = (*offered - inset.x).max(0.0); + } + }); let installed = Env::install_for(®ion_ui, env.clone()); ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out, laid_for: (inset, shows) } } diff --git a/crates/ui-widgets/tests/it/layout/stack_widths.rs b/crates/ui-widgets/tests/it/layout/stack_widths.rs index 2d6ba4bcfb..f3dd67968f 100644 --- a/crates/ui-widgets/tests/it/layout/stack_widths.rs +++ b/crates/ui-widgets/tests/it/layout/stack_widths.rs @@ -190,3 +190,26 @@ fn labelled_radios_in_a_wrapping_row_break_onto_a_new_line() { let starts = KINDS.iter().filter(|kind| (rect(kind).left() - first.left()).abs() < 0.5).count(); assert!(starts >= 2, "a radio that wraps starts its line at the row's start edge: {starts} radios do"); } + +/// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it +/// (a Print page's buttons ran under the settings column's bar). +#[trial] +fn a_fill_width_child_of_a_scrolling_stack_leaves_the_bars_lane() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let child = Cell::new(Rect::NOTHING); + let shown = Stack::new().sizing(Sizing::FillHeight).least_width(LeastWidth::Dialog).scroll(Scroll::vertical()).show(ui, |ui, _| { + for _ in 0..30 { + child.set(Button::new("Save these pages as PDF…").sizing(Sizing::FillWidth).show(ui).rect); + } + }); + if !ui.is_sizing_pass() { + out.set((shown.output.rect, child.get())); + } + }); + fixture.room(Vec2::new(1440.0, 300.0)).settle(); + let (stack, button) = seen.get(); + assert!(stack != Rect::NOTHING && button != Rect::NOTHING, "the stack showed"); + assert!(button.max.x <= stack.max.x - 4.0, "the button leaves the bar's lane: {button:?} in {stack:?}"); +} From 2cde919852d239ac996621d8037a5e8645c6fdde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:44:12 -0800 Subject: [PATCH 013/136] craft-docx: read and write the hide spelling and grammar errors settings Settings gains hide_spelling_errors and hide_grammar_errors, the per-document Hide spelling errors and Hide grammar errors options. craft-docx reads w:hideSpellingErrors and w:hideGrammaticalErrors from settings.xml, writes them after w:mirrorMargins and before w:proofState, and lists them as owned in the settings merge, so a saved file carries each one once and drops it when it is turned off. --- crates/docx/src/read/meta.rs | 2 ++ crates/docx/src/write/settings.rs | 7 ++++ crates/docx/src/write/settings_merge.rs | 2 ++ crates/docx/tests/it/settings_merge.rs | 47 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 9 +++++ 5 files changed, 67 insertions(+) diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index b9debe1fa0..a6e3c51bcb 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -24,6 +24,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a098174056..afd7d6a389 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.gutter_at_top { w.empty("w:gutterAtTop", &[]); } + // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. + if s.hide_spelling_errors { + w.empty("w:hideSpellingErrors", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index a72046e831..2e064f05ac 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -19,6 +19,8 @@ const OWNED: &[&str] = &[ "w:displayBackgroundShape", "w:mirrorMargins", "w:gutterAtTop", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index c07986795e..312564626c 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -163,3 +163,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 46faf16c36..d7689fa66d 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -170,6 +170,13 @@ pub struct Settings { /// comments and tracked changes are saved without `w:date`. #[serde(skip_serializing_if = "std::ops::Not::not")] pub remove_date_time: bool, + /// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under + /// misspelled words. Spelling & Grammar (F7) still finds them. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_spelling_errors: bool, + /// Hide grammar errors in this document only (`w:hideGrammaticalErrors`). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_grammar_errors: bool, /// The document was opened from ODF: the standard's rules that differ from Word's apply as /// it is laid out. #[serde(skip_serializing_if = "Option::is_none")] @@ -333,6 +340,8 @@ impl Default for Settings { zoom: None, remove_personal_info: false, remove_date_time: false, + hide_spelling_errors: false, + hide_grammar_errors: false, odf: None, } } From 97b202c281875d53a4dee080a394c125cbaa3aaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:22:43 -0800 Subject: [PATCH 014/136] Fit: items rank their short forms, and late ones shorten after the free items leave fit_items took every short form, last item first, before any free item left the strip. A host could not choose which items shorten first, or keep a label until the other items had gone to the overflow menu. FitItem gains two builder options: - short_order(order: u16) ranks the item's short form. Lower ranks shorten first; items of one rank shorten last item first. Every item ranks 0 by default. - short_late() keeps the item's full form until no more free items can leave. Late items then shorten in the same rank order. Items that left do not come back. Items that set neither option fit exactly as before. --- crates/behavior/src/fit.rs | 58 ++++++++++++++++++++++++++---------- crates/behavior/tests/fit.rs | 31 +++++++++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..ee52c7e4a7 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,12 +230,16 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } /// The item with a shorter form `extent` long, which it takes before any free item leaves. @@ -243,6 +247,20 @@ impl FitItem { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: short forms of a lower rank are taken first, and items of + /// one rank take theirs last item first. Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left, so the other items go to + /// the overflow menu before this one shortens. A free item with a late short form leaves in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +295,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +322,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; From 45515d18b536184b357ffdd1cce3eb84bf97525d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:29:19 -0800 Subject: [PATCH 015/136] craft-automation: ui.drag presses, moves in even steps and releases as one request A host app that serves the control channel can now run a whole drag from one request instead of composing ui.click with hold, ui.move steps and ui.release itself. - synthetic::Drag reads {from, to, button?, steps?, modifiers}. from and to are point objects {x?, y?, coordinates?, page?}, each in its own space; errors inside one name it (from.x ...). steps runs from 1 to MAX_DRAG_STEPS (200), default DRAG_STEPS (12). - Drag::inject resolves both points before it queues anything, then queues the press at from, the moves to to in even steps (the last one lands on to) and the release at to. The modifiers stay held through the release and are let go afterwards unless other input stays held, as after ui.click. - input_method dispatches ui.drag, so its reply waits for the release. - The crate README, docs/craft-framework.md and docs/porting.md list it. Tests: a drag with a document-point end presses at from, makes one move per step towards to, releases at to and leaves nothing held; a drag keeps its modifiers while a held key stays down; a drag whose end cannot be placed queues no press; bad drag params join the refused-input table. --- crates/automation/README.md | 2 +- crates/automation/src/synthetic.rs | 79 ++++++++++++++++++++++++- crates/automation/tests/it/synthetic.rs | 70 +++++++++++++++++++++- docs/craft-framework.md | 2 +- docs/porting.md | 2 +- 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..be6496ceb0 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `KeyPress`, `move_from_params` and `Drag`: the validated parameters of `ui.click`, `ui.move`, `ui.key` and `ui.drag` (a press, moves in even steps and the release, from one request), and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958c..8a2bdb184b 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, +//! `ui.release`, `ui.type`, `ui.ime` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -11,7 +11,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -33,6 +34,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -192,6 +199,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are resolved before anything is queued, so a point that cannot be placed leaves no press down. + /// When the host withdraws the rest of the gesture after its press ran, the button stays down until `ui.release`, + /// as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.resolve(map)?, self.to.resolve(map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -304,6 +376,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848dd..aa70cb1439 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,11 +1,11 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -122,6 +122,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -291,6 +337,19 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -356,6 +415,13 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "coordinates": "page"})), ("ui.move", json!({"y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 5e24eaacdc..0c87b65c8a 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1124,7 +1124,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | | `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | -| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | +| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.drag`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists | | `profiler` | Frame profiler | exists | | `screenshot` | Screenshot request queue | exists | diff --git a/docs/porting.md b/docs/porting.md index f7a03e41bd..fdd9301051 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -130,7 +130,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | | Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | -| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | +| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`, `Drag`: the checked parameters of `ui.click`, `ui.key`, `ui.move`, `ui.drag` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | | Screenshots | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer | | View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` | From 6c33621a06715619e8a82d1bc6e01ccfdbaa32fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:30:38 -0800 Subject: [PATCH 016/136] Menu bar: the output reports the width every title takes side by side craft_ui::menu::MenuBarOutput and craft_menu::MenuBarOutput gain a `natural: f32` field: the width of every title side by side with none in the "..." menu, whatever room the bar had. `titles` stays the rect of the titles drawn. A host that puts controls after the titles on the same row compares `natural` with the room it leaves the bar, and can narrow its own controls before titles fold. The field is zero while the bar shows nothing (ScreenTop), and a memoized replay keeps it. Trials: a bar in a wide and a narrow rect (craft-ui-widgets) and MenuBarUi in a wide and a narrow Stack (craft-menu) report the same natural width, equal to the titles' width when all fit and larger than the drawn titles when some fold. --- crates/menu/README.md | 4 ++- crates/menu/src/bar.rs | 12 ++++++--- crates/menu/tests/it/title_bar.rs | 30 ++++++++++++++++++++- crates/ui-widgets/src/menu/bar.rs | 14 +++++++--- crates/ui-widgets/tests/it/menu/bar.rs | 36 +++++++++++++++++++++++++- 5 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index cb82dc8f9e..307cd092ad 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by +side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that +width with the room it leaves the bar. Show it inside a `Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 4b2c81e742..9ea75cec33 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform { /// A replay at another place moves the titles' rect with the bar. impl craft_ui::runtime::Shift for MenuBarOutput { fn shifted(&self, by: &egui::RecordShift) -> Self { - MenuBarOutput { titles: by.rect(self.titles) } + MenuBarOutput { titles: by.rect(self.titles), natural: self.natural } } fn snapped(&self, to: &Self, within: f32) -> Self { - MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within) } + MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural } } } @@ -63,6 +63,9 @@ pub struct MenuBarOutput { /// The menu titles alone, without the room the bar leaves after them /// ([`craft_ui::menu::MenuBarOutput::titles`]). pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had + /// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing. + pub natural: f32, } /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top @@ -145,7 +148,7 @@ impl<'a> MenuBarUi<'a> { help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0 }) } } @@ -182,7 +185,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); } - MenuBarOutput { titles: bar.show(ui).titles } + let shown = bar.show(ui); + MenuBarOutput { titles: shown.titles, natural: shown.natural } } /// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 1e79bf5c18..15543e8d97 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,6 +1,7 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title //! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` -//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. In any room the bar +//! reports the width its titles take side by side. use std::cell::Cell; use std::rc::Rc; @@ -131,3 +132,30 @@ fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_i fixture.click(&more).settle(); assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); } + +/// The bar reports the width every title takes side by side: in a stack that holds them all it is the titles' width, +/// and in a stack too narrow for them it is the same width while the drawn titles are narrower. +#[trial] +fn the_bar_reports_the_width_every_title_takes_in_a_wide_and_a_narrow_stack() { + let mut reports = Vec::new(); + for width in [1520.0, 240.0] { + let bar = Rc::new(model()); + let seen = Rc::new(Cell::new((0.0, 0.0))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let out = Rc::clone(&out); + Stack::new().show(ui, move |ui, _| { + let shown = MenuBarUi::new(&bar).target(Target::Windows).show(ui); + out.set((shown.natural, shown.titles.width())); + }); + }); + fixture.os(Os::Windows).room(vec2(width, 600.0)).settle(); + reports.push(seen.get()); + } + let [(wide, wide_titles), (narrow, narrow_titles)] = [reports[0], reports[1]]; + assert!(wide > 0.0, "the bar reports a width"); + assert!((wide - wide_titles).abs() < 0.5, "with room for every title the natural width {wide} is the titles' width {wide_titles}"); + assert!((narrow - wide).abs() < 0.5, "a narrow bar reports the same natural width {narrow} as a wide one {wide}"); + assert!(narrow_titles < narrow, "a narrow bar draws titles {narrow_titles} narrower than its natural width {narrow}"); +} diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index c74ef97b5c..dced87415a 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -209,6 +209,10 @@ pub struct MenuBarOutput { pub open: bool, /// The titles alone (with "…" when it shows), from the first title's reading start to the last title's end. pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had: a host that places + /// controls after the titles on the same row compares it with the room it leaves the bar. Zero when the bar + /// shows nothing (`MenuPlacement::ScreenTop`). + pub natural: f32, } impl Outcome for MenuBarOutput { @@ -304,12 +308,14 @@ pub struct MenuBar<'a> { #[prop] keyboard: bool, open: bool, + /// The width of every title side by side, from this pass's measure or parts step. + natural: f32, } impl<'a> MenuBar<'a> { /// A bar named `label` with one title per menu, in reading order. pub fn new(label: impl Into