From cc6773c95f1f23800c82329ec404f68868c8b22b Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:02:59 +0200 Subject: [PATCH 01/94] Use evaluated field values in the placed text so the PDF text layer shows the slide number (#1153) --- crates/render/src/placed.rs | 21 ++++++++++++++++++--- crates/render/src/tests.rs | 12 ++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/render/src/placed.rs b/crates/render/src/placed.rs index 0164f3f07..f83af46d8 100644 --- a/crates/render/src/placed.rs +++ b/crates/render/src/placed.rs @@ -2,9 +2,9 @@ //! that put real text over a raster (PDF text layer, links) and for text extraction. use deckcraft_model::resolve::{self, Ctx}; -use deckcraft_model::text::{Hyperlink, TextBody}; +use deckcraft_model::text::{Hyperlink, RunKind, TextBody}; use deckcraft_model::{Presentation, Shape, ShapeId, ShapeKind}; -use deckcraft_text::{Opts, TextLayout}; +use deckcraft_text::{Fields, Opts, TextLayout}; use kurbo::{Affine, Rect}; use crate::{SlideFields, shape_geometry, table}; @@ -162,7 +162,22 @@ fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId let r = Rect::new(x0, line.top, x1, line.bottom); out.links.push(PlacedLink { rect: m.transform_rect_bbox(r), link, shape: owner, text: true }); } - out.texts.push(PlacedText { layout, transform: m, body: body.clone() }); + // Field runs carry their saved text (`‹#›`); the layout drew their values, so the body that + // goes with it (character offsets, text layer) must hold the same values. + let mut body = body.clone(); + for para in &mut body.paragraphs { + let src = para.clone(); + for run in &mut para.runs { + if let RunKind::Field { field } = &run.kind { + let lang = resolve::run(rctx, s, &src, &run.props).lang; + if let Some(v) = fields.field_in(field, lang.as_deref()) { + run.text = v; + run.kind = RunKind::Text; + } + } + } + } + out.texts.push(PlacedText { layout, transform: m, body }); } /// The hyperlink of the model run containing character `at` of paragraph `para`. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 4ee1c889d..9987bd7c9 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2595,3 +2595,15 @@ fn empty_bullet_is_gray_only_while_editing_and_never_in_exports() { assert!(changed.iter().any(|(px, _)| px[0] == 179 && px[1] == 179 && px[2] == 179)); assert!(changed.iter().all(|(px, _)| px[0] >= 179 && px[0] == px[1] && px[1] == px[2])); } + +#[test] +fn placed_text_holds_the_field_value_not_the_saved_placeholder() { + let mut p = deck_with(vec![field_shape(Some("slidenum"), "<#>")]); + let second = p.slides[0].clone(); + p.slides.push(second); + let placed = place_slide(&p, 1); + assert_eq!(placed.texts.len(), 1); + assert_eq!(placed.texts[0].body.text(), "2"); + // The layout was drawn from the same value, so the offsets agree with the body. + assert_eq!(placed.texts[0].layout.runs.iter().map(|r| r.chars.1).max(), Some(1)); +} From 813378cc20aa0d94228bb3f700645e7d546b795d Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:08:53 +0200 Subject: [PATCH 02/94] Keep the PDF text layer aligned with line breaks, use one clock reading for raster and text layer, and test the page text (#1153) --- crates/pdf/src/lib.rs | 9 +++--- crates/pdf/src/tests.rs | 61 ++++++++++++++++++++++++++++++++++--- crates/render/src/lib.rs | 2 +- crates/render/src/placed.rs | 30 ++++++++++-------- crates/render/src/tests.rs | 9 ++++++ 5 files changed, 89 insertions(+), 22 deletions(-) diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 22dc42d36..cc5d5e56a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -299,7 +299,7 @@ pub fn master_text_pieces(pres: &Presentation, m: &deckcraft_model::Master, pape .body .paragraphs .get(run.para) - .map(|p| p.runs.iter().map(|r| r.text.as_str()).collect::()) + .map(|p| p.runs.iter().map(|r| r.content()).collect::()) .unwrap_or_default() .chars() .skip(run.chars.0) @@ -440,7 +440,8 @@ impl Exporter<'_> { let k = b.width() / sw; // Raster at the requested dpi relative to the box size on paper. let scale = (b.width() / 72.0 * self.opts.dpi.clamp(36.0, 600.0)) / sw; - let ropts = RenderOpts { scale, threads: 4, ..Default::default() }; + // One clock reading for the raster and the text layer, so a date field cannot differ between them. + let ropts = RenderOpts { scale, threads: 4, now: deckcraft_text::datetime::DateTime::now_local(), ..Default::default() }; // Two rasters per slide: the backdrop (background, master and layout graphics) is the same // on every slide that shares its layout, so the writer stores it once, and the slide's own // shapes draw over it (#845). @@ -476,7 +477,7 @@ impl Exporter<'_> { } if self.opts.text_layer { let view = Affine::translate((b.x0, b.y0)) * Affine::scale(k); - for pt in deckcraft_render::place_slide(pres, i).texts { + for pt in deckcraft_render::place_slide_with(pres, i, &ropts).texts { self.text_layer(s, &pt, view, false)?; } let _ = sh; @@ -494,7 +495,7 @@ impl Exporter<'_> { .body .paragraphs .get(run.para) - .map(|p| p.runs.iter().map(|r| r.text.as_str()).collect::()) + .map(|p| p.runs.iter().map(|r| r.content()).collect::()) .unwrap_or_default() .chars() .skip(run.chars.0) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2bc5c41ac..fd1839377 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -200,8 +200,6 @@ fn unembeddable_font_returns_error_instead_of_a_pdf_missing_text() { #[cfg_attr(not(target_arch = "wasm32"), test)] fn supported_unicode_is_shaped_and_recovered_from_the_page_text_layer() { use deckcraft_model::{Shape, ShapeId, Xfrm}; - use hayro_syntax::content::ops::TypedInstruction; - use hayro_syntax::object::{Dict, Object, Stream}; let text = "Café Ελληνικά Привет"; let face = FontDb::global().face("Ubuntu", "Regular"); @@ -223,8 +221,17 @@ fn supported_unicode_is_shaped_and_recovered_from_the_page_text_layer() { assert!(runs.iter().all(|run| run.face.family == "Ubuntu" && !run.glyphs.is_empty() && run.glyphs.iter().all(|glyph| glyph.0 != 0))); let bytes = export(&p, &opts(PageLayout::Slides)).unwrap(); - let pdf = hayro_syntax::Pdf::new(bytes.clone()).unwrap(); - let page = &pdf.pages()[0]; + assert_eq!(page_text(&bytes, 0), text); +} + +/// The text of page `index`, read the way a PDF reader does: the content stream's text-showing +/// operators decoded through the page font's ToUnicode map. +fn page_text(bytes: &[u8], index: usize) -> String { + use hayro_syntax::content::ops::TypedInstruction; + use hayro_syntax::object::{Dict, Object, Stream}; + + let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).unwrap(); + let page = &pdf.pages()[index]; let resources = page.raw().get::>(b"Resources").unwrap(); let fonts = resources.get::>(b"Font").unwrap(); assert_eq!(fonts.len(), 1); @@ -275,7 +282,51 @@ fn supported_unicode_is_shaped_and_recovered_from_the_page_text_layer() { _ => {} } } - assert_eq!(extracted, text); + extracted +} + +fn ubuntu_runs(runs: Vec) -> TextBody { + let paragraph = deckcraft_model::text::Paragraph { runs, ..Default::default() }; + let mut body = TextBody { paragraphs: vec![paragraph], ..Default::default() }; + for run in &mut body.paragraphs[0].runs { + run.props.font = Some("Ubuntu".into()); + run.props.size = Some(20.0); + } + body +} + +fn deck_with_body(n: usize, body: TextBody) -> Presentation { + use deckcraft_model::{Shape, ShapeId, Xfrm}; + let mut p = deck(n); + for slide in &mut p.slides { + Arc::make_mut(slide).shapes = + vec![Shape { id: ShapeId(9001), xfrm: Some(Xfrm::new(20.0, 20.0, 920.0, 100.0)), text: Some(body.clone()), ..Default::default() }]; + } + p +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn slide_number_field_is_recovered_from_the_page_text_layer() { + use deckcraft_model::text::{Run, RunKind}; + let mut field = Run::new("<#>"); + field.kind = RunKind::Field { field: "slidenum".into() }; + let p = deck_with_body(3, ubuntu_runs(vec![Run::new("Page "), field])); + let bytes = export(&p, &opts(PageLayout::Slides)).unwrap(); + for (i, want) in ["Page 1", "Page 2", "Page 3"].into_iter().enumerate() { + assert_eq!(page_text(&bytes, i), want); + } +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn line_break_keeps_the_text_layer_aligned_with_the_layout() { + use deckcraft_model::text::{Run, RunKind}; + let mut brk = Run::new(""); + brk.kind = RunKind::Break; + let p = deck_with_body(1, ubuntu_runs(vec![Run::new("one"), brk, Run::new("two")])); + let bytes = export(&p, &opts(PageLayout::Slides)).unwrap(); + assert_eq!(page_text(&bytes, 0), "onetwo"); } /// Notes pages and handouts print on the chosen paper, landscape included, with every slide box diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index cf124a9f6..722162721 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -53,7 +53,7 @@ pub use extent::{Region, TILE, layout_extent, pasteboard_region, slide_extent}; pub use images::{decode as decode_image, gif_frame}; pub use morph_path::PathMorph; pub use morph_text::TextMorph; -pub use placed::{Placed, PlacedLink, PlacedShape, PlacedText, place_master_texts, place_slide, text_outline}; +pub use placed::{Placed, PlacedLink, PlacedShape, PlacedText, place_master_texts, place_slide, place_slide_with, text_outline}; pub use table::cell_body as table_cell_body; pub use table::cell_rects as table_cell_rects; pub use table::row_heights as table_row_heights; diff --git a/crates/render/src/placed.rs b/crates/render/src/placed.rs index f83af46d8..2081b2400 100644 --- a/crates/render/src/placed.rs +++ b/crates/render/src/placed.rs @@ -52,10 +52,16 @@ pub struct Placed { /// Text and links of slide `index` (master and layout graphics first, as rendered). pub fn place_slide(pres: &Presentation, index: usize) -> Placed { + place_slide_with(pres, index, &crate::RenderOpts::default()) +} + +/// [`place_slide`] with the render options the slide was drawn with, so date fields take the same +/// date and time as the raster (`opts.now`). +pub fn place_slide_with(pres: &Presentation, index: usize, opts: &crate::RenderOpts) -> Placed { let mut out = Placed::default(); let Some(slide) = pres.slides.get(index) else { return out }; let Some(rctx) = Ctx::for_slide(pres, slide) else { return out }; - let fields = SlideFields::new(pres.slide_number(index), pres.header_footer.footer_text.clone(), &crate::RenderOpts::default()); + let fields = SlideFields::new(pres.slide_number(index), pres.header_footer.footer_text.clone(), opts); let (show_layout, show_master) = resolve::show_master_shapes(slide, rctx.layout); if show_master { let mctx = Ctx::for_master(pres, rctx.master); @@ -164,20 +170,20 @@ fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId } // Field runs carry their saved text (`‹#›`); the layout drew their values, so the body that // goes with it (character offsets, text layer) must hold the same values. - let mut body = body.clone(); - for para in &mut body.paragraphs { - let src = para.clone(); - for run in &mut para.runs { - if let RunKind::Field { field } = &run.kind { - let lang = resolve::run(rctx, s, &src, &run.props).lang; - if let Some(v) = fields.field_in(field, lang.as_deref()) { - run.text = v; - run.kind = RunKind::Text; - } + let mut placed = body.clone(); + for (pi, para) in body.paragraphs.iter().enumerate() { + for (ri, run) in para.runs.iter().enumerate() { + let RunKind::Field { field } = &run.kind else { continue }; + let lang = resolve::run(rctx, s, para, &run.props).lang; + if let Some(v) = fields.field_in(field, lang.as_deref()) + && let Some(out_run) = placed.paragraphs.get_mut(pi).and_then(|p| p.runs.get_mut(ri)) + { + out_run.text = v; + out_run.kind = RunKind::Text; } } } - out.texts.push(PlacedText { layout, transform: m, body }); + out.texts.push(PlacedText { layout, transform: m, body: placed }); } /// The hyperlink of the model run containing character `at` of paragraph `para`. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9987bd7c9..b9011f999 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2607,3 +2607,12 @@ fn placed_text_holds_the_field_value_not_the_saved_placeholder() { // The layout was drawn from the same value, so the offsets agree with the body. assert_eq!(placed.texts[0].layout.runs.iter().map(|r| r.chars.1).max(), Some(1)); } + +#[test] +fn placed_text_takes_its_date_from_the_given_render_options() { + use deckcraft_text::datetime::DateTime; + let p = deck_with(vec![field_shape(Some("datetime1"), "1/1/2000")]); + let at = |now: DateTime| place_slide_with(&p, 0, &RenderOpts { now: Some(now), ..Default::default() }); + assert_eq!(at(DateTime::new(2026, 10, 9, 20, 5, 7)).texts[0].body.text(), "10/9/2026"); + assert_eq!(at(DateTime::new(2027, 3, 4, 0, 0, 0)).texts[0].body.text(), "3/4/2027"); +} From d8936f94af1dd1a9a9c72cb626c5a0062ed19abb Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:58:38 +0100 Subject: [PATCH 03/94] Keep whole character after a backslash in RTF outline import Found while testing crates/format/src/rtf.rs:301-326 (symbol / text, reached via escape) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/format/src/rtf.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/format/src/rtf.rs b/crates/format/src/rtf.rs index 4800aba26..b546a832f 100644 --- a/crates/format/src/rtf.rs +++ b/crates/format/src/rtf.rs @@ -299,7 +299,8 @@ impl Outline<'_> { /// A one-character control symbol (`\\`, `\{`, `\~`, ...). fn symbol(&mut self, n: u8) { - self.i += 1; + let c = self.rtf.get(self.i..).and_then(|r| r.chars().next()); + self.i = advance(self.rtf, self.i, 1); if self.st.skip { return; } @@ -308,6 +309,7 @@ impl Outline<'_> { b'~' => self.line.push('\u{a0}'), b'_' => self.line.push('\u{2011}'), b'\n' | b'\r' => self.flush(), + _ if !n.is_ascii() => self.line.extend(c), _ => {} } } @@ -419,6 +421,11 @@ mod tests { assert_eq!(rtf_to_outline(r"{\rtf1 x\u-70000?y\par}"), "x\u{ee90}y\n"); } + #[test] + fn multibyte_control_symbol_keeps_character_and_following_text() { + assert_eq!(rtf_to_outline("{\\rtf1 A\\éB\\par}"), "AéB\n"); + } + /// `\\_` is RTF's non-breaking hyphen: a visible character, not markup. #[test] fn non_breaking_hyphen_is_kept() { From 6303166a1816693d7dfa7b04263cee61daf062fa Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:58:27 -0500 Subject: [PATCH 04/94] [PP1] show.setup showMediaControls survives a pptx save and reopen PowerPoint stores Show media controls as the p14:showMediaCtrls extension inside p:showPr (uri {2FDB2607-...}); absent means shown. Write it when hidden, read it back. Co-Authored-By: Claude Sonnet 5.5 --- crates/pptx/src/read.rs | 1 + crates/pptx/src/write.rs | 8 ++++++++ crates/pptx/tests/it/roundtrip.rs | 9 +++++++++ 3 files changed, 18 insertions(+) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 917aa9277..2df349cb7 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -1283,6 +1283,7 @@ fn read_show(sp: &El, shows: &HashMap) -> ShowSettings { without_narration: sp.bool("showNarration") == Some(false), without_animation: sp.bool("showAnimation") == Some(false), use_timings: sp.bool("useTimings").unwrap_or(true), + show_media_controls: sp.find("showMediaCtrls").and_then(|e| e.bool("val")).unwrap_or(true), ..Default::default() }; if sp.child("browse").is_some() { diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 5d3e60e92..37cf5cd7d 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -1181,6 +1181,14 @@ fn pres_props_xml(p: &Presentation) -> Vec { w.open0("p:penClr"); w.val("a:srgbClr", s.pen_color.hex()); w.close("p:penClr"); + if !s.show_media_controls { + // "Show media controls" is PowerPoint's p14 extension; absent means shown. + w.open0("p:extLst"); + w.open("p:ext", A::new().a("uri", "{2FDB2607-1784-4EEB-B798-7EB5836EED8A}")); + w.empty("p14:showMediaCtrls", A::new().a("xmlns:p14", NS_P14).a("val", 0)); + w.close("p:ext"); + w.close("p:extLst"); + } w.close("p:showPr"); w.close("p:presentationPr"); w.finish() diff --git a/crates/pptx/tests/it/roundtrip.rs b/crates/pptx/tests/it/roundtrip.rs index 370cc9a9f..c61e6e433 100644 --- a/crates/pptx/tests/it/roundtrip.rs +++ b/crates/pptx/tests/it/roundtrip.rs @@ -1969,3 +1969,12 @@ fn default_durations_match_powerpoint() { assert_eq!(a.4, ms, "{effect}"); } } + +/// Show media controls is PowerPoint's `p14:showMediaCtrls` extension inside `p:showPr`. +#[test] +fn hidden_media_controls_survive_save_and_reopen() { + let mut p = Presentation::default(); + p.show.show_media_controls = false; + assert!(!round(&p).show.show_media_controls); + assert!(round(&Presentation::default()).show.show_media_controls); +} From cbb0c484459af252620ef0ad9c928cde586290a0 Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo Date: Sun, 1 Nov 2026 22:19:06 +0100 Subject: [PATCH 05/94] Fix OS clipboard: enable eframe's clipboard feature dropped in the egui 0.37 migration Since #1350 (v0.11.1) the desktop build listed eframe features without `clipboard`, so egui-winit simulated a clipboard inside the app: Ctrl+V never read text or pictures from other apps, and Ctrl+C of text (sent out as HTML through arboard) never reached egui's clipboard, so Ctrl+V pasted nothing or stale text. The context menu kept working because it only uses the session clipboard. Turn the feature back on. On native Wayland, egui-winit owns the clipboard through winit's data device (text and PNG); leave the X11-only arboard pasteboard (HTML, pictures) off there so copies are claimed on the Wayland selection. Regression tests guard the feature list and the Wayland switch. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 102 +++++++++++++++++++++++++++++++++++-- ROADMAP.md | 4 +- apps/deckcraft/Cargo.toml | 4 +- apps/deckcraft/src/main.rs | 41 +++++++++++++-- docs/gaps.md | 5 +- docs/parity-checklist.md | 4 +- 6 files changed, 144 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 408e99948..2e7f72a5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -565,18 +565,42 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.5", + "tracing", +] + [[package]] name = "calloop-wayland-source" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" dependencies = [ - "calloop", + "calloop 0.13.0", "rustix 0.38.44", "wayland-backend", "wayland-client", ] +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.5", + "wayland-backend", + "wayland-client", +] + [[package]] name = "cast" version = "0.3.0" @@ -1507,13 +1531,16 @@ dependencies = [ "block2 0.6.2", "bytemuck", "egui", + "image", "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "objc2-ui-kit 0.3.2", + "parking_lot", "profiling", "raw-window-handle", + "smithay-clipboard", "web-time", "webbrowser", "windows-sys 0.61.2", @@ -4403,8 +4430,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" dependencies = [ "bitflags 2.13.2", - "calloop", - "calloop-wayland-source", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", "cursor-icon", "libc", "log", @@ -4421,6 +4448,44 @@ dependencies = [ "xkeysym", ] +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + [[package]] name = "smol_str" version = "0.2.2" @@ -4928,6 +4993,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -5370,6 +5436,32 @@ dependencies = [ "wayland-scanner", ] +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + [[package]] name = "wayland-protocols-plasma" version = "0.3.12" @@ -5980,7 +6072,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "bytemuck", - "calloop", + "calloop 0.13.0", "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", @@ -6001,7 +6093,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", - "smithay-client-toolkit", + "smithay-client-toolkit 0.19.2", "smol_str", "tracing", "unicode-segmentation", diff --git a/ROADMAP.md b/ROADMAP.md index f92554c14..6255c9421 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (print-preview tests use egui's emitted URL, and macOS removes its previews before exit; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** major (fix for a workflow-breaking regression: Ctrl+C/X/V use the system clipboard again, broken for all text and objects from 0.11.1 to 0.14.1; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (progress log: read-only `slide.actions` lists shape and table text actions; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: Set Up Slide Show ▸ Keep mouse cursor visible, #1445; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (progress log: dragging several selected slides moves them all; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -148,6 +148,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows | | 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits | | 2026-10-30 | `slide.actions` lists shape click and hover actions and text-run hyperlinks (including table cells and grouped shapes) for audit; listing never runs an action. The UI pane is a follow-up | | 2026-10-29 | Slide Show: going back to the previous slide plays the transition of the slide being left, reversed, as PowerPoint does, instead of the previous slide's own entrance transition (#1531); a jump (Go to Slide, links) still plays the target slide's transition | @@ -318,6 +319,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| +| 2026-11-01 | major | Workflow-breaking regression fixed: the desktop build uses the system clipboard again (eframe `clipboard` feature) | | 2026-10-30 | trivial | Progress log: read-only slide action inspection; parity scores unchanged | | 2026-10-29 | trivial | Progress log: going back in the slide show reverses the left slide's transition (#1531). Scores and milestone names unchanged | | 2026-10-29 | trivial | Progress log: the Picture Styles row leaves room for Crop and Size (#1232). Scores and milestone names unchanged | diff --git a/apps/deckcraft/Cargo.toml b/apps/deckcraft/Cargo.toml index b336a8433..5b4afbb83 100644 --- a/apps/deckcraft/Cargo.toml +++ b/apps/deckcraft/Cargo.toml @@ -14,7 +14,9 @@ workspace = true deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } deckcraft-media = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "links", "wayland", "x11"] } +# `clipboard` is the OS clipboard (Ctrl+C/X/V with other apps). Without it egui simulates one inside +# the app; the egui 0.37 migration (#1350) dropped it from this list. +eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "links", "wayland", "x11"] } egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true } diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index ad3f820fa..2798c2d71 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -103,7 +103,13 @@ fn save_prefs(app: &SlideApp) { } } -fn services() -> Services { +/// The desktop services. `native_wayland`: the window is a Wayland client (not Xwayland). +fn services(native_wayland: bool) -> Services { + // On native Wayland, egui-winit owns the clipboard through winit's data device, which carries + // text and PNG but no HTML. `pasteboard` (arboard, built for X11 only) would put a copy on the + // Xwayland selection instead and skip egui's Wayland claim, so Ctrl+V would read something + // else. There, text goes through egui and pictures arrive as `PasteImage` events. + let pasteboard = !native_wayland; Services { pick_open: Some(Box::new(|purpose: &str| { let d = rfd::FileDialog::new(); @@ -126,9 +132,9 @@ fn services() -> Services { pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))), read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), - clipboard_image: Some(Box::new(pasteboard::image_png)), - clipboard_html: Some(Box::new(pasteboard::html)), - clipboard_set_html: Some(Box::new(pasteboard::set_html)), + clipboard_image: pasteboard.then(|| Box::new(pasteboard::image_png) as Box Option>>), + clipboard_html: pasteboard.then(|| Box::new(pasteboard::html) as Box Option>), + clipboard_set_html: pasteboard.then(|| Box::new(pasteboard::set_html) as Box bool>), // Media is mixed and clocked by the output device; `DECKCRAFT_NO_AUDIO` plays silently. audio_out: std::env::var_os("DECKCRAFT_NO_AUDIO") .is_none() @@ -247,6 +253,11 @@ fn main() -> eframe::Result { false } }; + // `Default` lets winit choose, and winit takes Wayland whenever `WAYLAND_DISPLAY` is set. + #[cfg(all(unix, not(target_os = "macos")))] + let native_wayland = !x11 && std::env::var_os("WAYLAND_DISPLAY").is_some_and(|w| !w.is_empty()); + #[cfg(not(all(unix, not(target_os = "macos"))))] + let native_wayland = false; #[cfg(all(unix, not(target_os = "macos")))] if x11 { options.event_loop_builder = Some(Box::new(|b| { @@ -268,7 +279,7 @@ fn main() -> eframe::Result { options, Box::new(move |cc| { deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx); - let mut app = SlideApp::new(Session::new(), services()); + let mut app = SlideApp::new(Session::new(), services(native_wayland)); load_prefs(&mut app); app.enable_update_checks(); // AutoRecover: reopen what a previous run left unsaved, then keep it current. @@ -335,6 +346,26 @@ mod tests { assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}"); } + /// The egui 0.37 migration (#1350) left `clipboard` out of eframe's features. egui then + /// simulated a clipboard inside the app: nothing pasted from other apps, and Ctrl+C/Ctrl+V + /// lost text that went out as HTML. Keep the OS clipboard on. + #[test] + fn eframe_uses_the_os_clipboard() { + let manifest = include_str!("../Cargo.toml"); + let eframe = manifest.lines().find(|l| l.starts_with("eframe = ")).unwrap_or_default(); + assert!(eframe.contains("\"clipboard\""), "eframe must enable the OS clipboard: {eframe}"); + } + + /// On native Wayland, the X11-only pasteboard would bypass egui's Wayland clipboard; elsewhere + /// it carries HTML and pictures beside egui's text. + #[test] + fn the_pasteboard_stays_off_native_wayland() { + let s = services(true); + assert!(s.clipboard_html.is_none() && s.clipboard_set_html.is_none() && s.clipboard_image.is_none()); + let s = services(false); + assert!(s.clipboard_html.is_some() && s.clipboard_set_html.is_some() && s.clipboard_image.is_some()); + } + #[test] fn help_exits_instead_of_opening_a_file() { assert!(matches!(startup(None, ["--help".to_string()]), Startup::Help)); diff --git a/docs/gaps.md b/docs/gaps.md index 29edfd573..75a92355b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where DeckCraft falls short of PowerPoint -> **Last reviewed:** 2026-10-30 · **Last updated:** 2026-10-30 · **Change:** minor (slide-show hit testing follows each shape’s own animation state; scale and rotation covered; previous: trivial, AutoFormat lists run independently of Replace text as you type; previous: minor, slide-show click targets follow animated shapes and text links; previous: minor, Animation Pane ▸ Play From; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: soak tests, PPTX corpus, comment threads (#70), embedded fonts, SmartArt Text Pane, Animation Pane timeline, Hunspell spelling, thesaurus, AutoCorrect, 14 new dialogs, pen pressure and trackpad gestures; duplicated entries and headers folded; previous: minor, 3-D bevel, camera and face lighting rendered) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-30 · **Last updated:** 2026-11-01 · **Change:** major (workflow-breaking regression fixed: Ctrl+C/X/V use the system clipboard again; #1414 to re-test on Windows; previous: minor, slide-show hit testing follows each shape’s own animation state; scale and rotation covered; previous: trivial, AutoFormat lists run independently of Replace text as you type; previous: minor, slide-show click targets follow animated shapes and text links; previous: minor, Animation Pane ▸ Play From; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: soak tests, PPTX corpus, comment threads (#70), embedded fonts, SmartArt Text Pane, Animation Pane timeline, Hunspell spelling, thesaurus, AutoCorrect, 14 new dialogs, pen pressure and trackpad gestures; duplicated entries and headers folded; previous: minor, 3-D bevel, camera and face lighting rendered) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) Every known shortfall, one entry each, ranked by how much it stops someone who presents with PowerPoint from switching. This is the work list: pick from the top. Numbers are summarized in @@ -161,7 +161,7 @@ Detail in [file-format-parity.md](file-format-parity.md). - **Estimate:** 3–5 h. **Beta blocker.** ### Image paste fails on Windows (#1414) -- **Evidence:** #53 is closed (PR #88 pastes an image-only clipboard as a picture); #1414 (Ctrl+V fails to paste external images on Windows) is open. Linux was not re-checked after #53 closed. +- **Evidence:** #53 is closed (PR #88 pastes an image-only clipboard as a picture); #1414 (Ctrl+V fails to paste external images on Windows) is open. From the egui 0.37 migration (#1350, v0.11.1) to 0.14.1 the desktop build left out eframe's `clipboard` feature, so egui simulated a clipboard inside the app and Ctrl+V never read the system clipboard on any platform. Fixed 2026-11-01. #1414 may have the same cause: re-test on Windows. - **Impact:** copy-paste of screenshots is a core workflow. - **Estimate:** 2–4 h. **Beta blocker.** @@ -368,6 +368,7 @@ Detail in [localization-parity.md](localization-parity.md). | Date | Change | Summary | |---|---|---| +| 2026-11-01 | major | Workflow-breaking regression: image paste entry: the OS clipboard was off from #1350 to 0.14.1; Linux re-checked, Windows #1414 to re-test | | 2026-10-30 | minor | Slide-show click targets use each shape’s own animation state; scale and rotation test added | | 2026-10-28 | trivial | Automatic lists now run independently of Replace text as you type; proofing gap description updated | | 2026-10-27 | minor | Refreshed against merged PRs: removed the Morph alignment entry (#67 merged 2026-10-14); #77 (animation rewind, PR #83) is fixed, leaving #74 in the round-trip gap; #75 was closed unmerged, so #60 stays open with no fix PR; #53 is closed and the image-paste gap is now Windows #1414; Reuse Slides (#1103) and Compare reject (#850) noted in the smaller rows; the duplicate header line is gone | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 0c0d3ec60..9a9094780 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -36,7 +36,7 @@ The summary between ` | Automation (✱) | 100% | | Platforms (✱) | 67% | -Open P0 items: Contextual tabs (Shape Format, Picture Format, Table Design/Layout, Chart Design), Export to PDF (slides, notes pages, handouts; text layer, links, bookmarks; vector artwork pending), Format Shape pane, Font, size, bold, italic, underline, strikethrough (only Regular/Bold/Italic faces, #69), Edit chart data, Crop (and crop to shape, aspect ratio), Paste image from clipboard (fails on Windows, #1414; Linux not re-checked), Audio/video playback in the show (WMA/WMV not decodable yet), Animation pane (reorder, timing), Presenter view (notes, next slide, timer), macOS, Windows, Linux builds. +Open P0 items: Contextual tabs (Shape Format, Picture Format, Table Design/Layout, Chart Design), Export to PDF (slides, notes pages, handouts; text layer, links, bookmarks; vector artwork pending), Format Shape pane, Font, size, bold, italic, underline, strikethrough (only Regular/Bold/Italic faces, #69), Edit chart data, Crop (and crop to shape, aspect ratio), Paste image from clipboard (fails on Windows, #1414, re-test after the 2026-11-01 OS-clipboard fix), Audio/video playback in the show (WMA/WMV not decodable yet), Animation pane (reorder, timing), Presenter view (notes, next slide, timer), macOS, Windows, Linux builds. ## Rows @@ -187,7 +187,7 @@ Open P0 items: Contextual tabs (Shape Format, Picture Format, Table Design/Layou | Pictures | Picture styles and borders | P1 | D | | Pictures | Change / reset picture | P1 | D | | Pictures | Compress pictures | P2 | D | -| Pictures | Paste image from clipboard (fails on Windows, #1414; Linux not re-checked) | P0 | P | +| Pictures | Paste image from clipboard (fails on Windows, #1414, re-test after the 2026-11-01 OS-clipboard fix) | P0 | P | | Pictures | Insert screenshot | P2 | M | | Media | Insert audio (any common format) | P0 | D | | Media | Insert video | P1 | D | From e1cfe8516e444af9357d5ea135f9b067de0bc70e Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo Date: Sun, 1 Nov 2026 22:29:43 +0100 Subject: [PATCH 06/94] Paste and duplicate keep a placeholder's inherited look A placeholder copied or duplicated on a slide became a regular shape by clearing `ph`, which also dropped everything it inherited from its layout and master: the title's 44 pt heading font, the body's bullets and indent levels, autofit and the box. Without `ph` the text fell back to the presentation's default style (18 pt, no bullets), on Ctrl+V and the context menu alike. `resolve::detach_placeholder` makes the inherited box, fill, line, effects, body properties and every level's text style the shape's own before `ph` is cleared. Theme references stay references, so the default paste still follows the destination theme. Copy (so Cut and pasting into another deck work after the source is gone) and Duplicate use it. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 3 +- crates/engine/src/cmd/edit.rs | 15 ++++++- crates/engine/src/tests.rs | 85 +++++++++++++++++++++++++++++++++++ crates/model/src/resolve.rs | 39 ++++++++++++++++ 4 files changed, 140 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6255c9421..fd17b3a1c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** major (fix for a workflow-breaking regression: Ctrl+C/X/V use the system clipboard again, broken for all text and objects from 0.11.1 to 0.14.1; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** major (fix for a workflow-breaking regression: Ctrl+C/X/V use the system clipboard again, broken for all text and objects from 0.11.1 to 0.14.1; pasted and duplicated placeholders keep their look; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-30 · **Change:** trivial (progress log: read-only `slide.actions` lists shape and table text actions; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-27 · **Change:** trivial (progress log: Set Up Slide Show ▸ Keep mouse cursor visible, #1445; stage and scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-26 · **Change:** trivial (progress log: dragging several selected slides moves them all; previous: trivial, progress log: Edit Points handle drags with Shift, Ctrl/Cmd or Alt/Option set the point type; previous: trivial, progress log: scroll bars on the zoomed slide pane, #1157; previous: minor, native chart payloads stored in bounded ZIP members; previous: major, community PR wave 2026-10-14: ~60 landed items in the progress log, among them the Font, Paragraph, Photo Album, theme colour and font and Date and Time dialogs, presenter and show controls, the SmartArt Text Pane and PPTX corpus slices; breadth 84% after `cargo xtask parity`, ready stays ~55%, stage stays alpha; duplicated rows and headers folded; previous: minor, hours to ~95% per audience added) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -148,6 +148,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-01 | Copy, Cut, Paste and Duplicate of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text | | 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows | | 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits | | 2026-10-30 | `slide.actions` lists shape click and hover actions and text-run hyperlinks (including table cells and grouped shapes) for audit; listing never runs an action. The UI pane is a follow-up | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f084c6225..9674bb8ad 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -120,6 +120,13 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result { }) }) .collect(); + // A placeholder pastes on a slide as a regular shape; it keeps the look it inherited here. + let mut shapes = shapes; + if st.selection.target == crate::Target::Slides + && let Some(ctx) = st.current_slide().and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(&st.doc, sl)) + { + shapes.iter_mut().for_each(|sh| deckcraft_model::resolve::detach_placeholder(&ctx, sh)); + } let mids = crate::media_refs::shapes_media(&shapes); let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect(); let plain = shapes.iter().filter_map(|x| x.text.as_ref().map(|t| t.text())).collect::>().join("\n"); @@ -340,7 +347,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { x.x += off; x.y += off; } - // A pasted placeholder becomes a regular shape keeping its look. + // A pasted placeholder becomes a regular shape; copying gave it its look. if sh.ph.is_some() && sel.target == crate::Target::Slides { sh.ph = None; } @@ -533,6 +540,12 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { let mut copies: Vec = list.iter().filter(|x| ids.contains(&x.id)).cloned().collect(); let sources: Vec = copies.iter().map(|c| c.id).collect(); let boxes: Vec<_> = copies.iter().map(|c| xfrm_of(doc, sel, c)).collect(); + // A duplicated placeholder becomes a regular shape that keeps the look it inherited. + if sel.target == crate::Target::Slides + && let Some(ctx) = doc.slides.get(sel.slide).and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(doc, sl)) + { + copies.iter_mut().for_each(|c| deckcraft_model::resolve::detach_placeholder(&ctx, c)); + } // Duplicating the copies of the last Duplicate again repeats how far they were moved // since (#966); anything else gets the usual offset. let (dx, dy) = last diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a687de95c..eec43cc4a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -214,6 +214,91 @@ fn clipboard_copy_paste_shapes_and_slides() { assert!(s.doc().unwrap().doc.validate().is_empty()); } +/// The resolved look of every paragraph and run of shape `id` on the current slide: size, font, +/// colour, bold, bullet, indent, alignment, and the box's insets and anchor. +fn resolved_look(s: &Session, id: ShapeId) -> String { + use deckcraft_model::resolve; + let st = s.doc().unwrap(); + let slide = st.current_slide().unwrap(); + let ctx = resolve::Ctx::for_slide(&st.doc, slide).unwrap(); + let sh = st.shape(id).unwrap(); + let t = sh.text.as_ref().unwrap(); + let b = resolve::body(&ctx, sh); + let mut out = format!("body {:?} {:?} {:?}\n", b.anchor, b.inset_l, b.autofit); + for p in &t.paragraphs { + let pp = resolve::para(&ctx, sh, p); + out += &format!("para {:?} {:?} {:?} {:?}\n", pp.align, pp.margin_left, pp.indent, pp.bullet); + for r in &p.runs { + let rp = resolve::run(&ctx, sh, p, &r.props); + out += &format!(" run {:?} {:?} {:?} {:?}\n", rp.size, rp.font, rp.bold, rp.fill); + } + } + out +} + +/// A placeholder pasted or duplicated on a slide becomes a regular shape, and keeps the look its +/// layout and master gave it: the title's size and font, the body's bullets and indents. Before, +/// the copy fell back to the master's other-text style (18 pt, no bullets). +#[test] +fn a_pasted_or_duplicated_placeholder_keeps_its_inherited_look() { + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let phs: Vec = s.doc().unwrap().current_slide().unwrap().shapes.iter().filter(|x| x.ph.is_some()).map(|x| x.id).collect(); + assert!(phs.len() >= 2, "a title and a body placeholder"); + for (k, id) in phs.iter().enumerate() { + s.execute("text.set", &json!({"id": id.0, "text": format!("Placeholder {k}\nSecond line")})).unwrap(); + } + for id in phs { + let want = resolved_look(&s, id); + for cmd in ["paste", "duplicate"] { + s.execute("selection.select", &json!({"id": id.0})).unwrap(); + if cmd == "paste" { + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + } else { + s.execute("edit.duplicate", &json!({})).unwrap(); + } + let copy = s.doc().unwrap().selection.shapes[0]; + assert_ne!(copy, id); + assert!(s.doc().unwrap().shape(copy).unwrap().ph.is_none(), "{cmd}: the copy is a regular shape"); + assert_eq!(resolved_look(&s, copy), want, "{cmd} of placeholder {}", id.0); + } + } + assert!(s.doc().unwrap().doc.validate().is_empty()); +} + +/// The same on every text placeholder of the sample deck (titles, bulleted bodies, subtitles). +#[test] +fn sample_placeholders_paste_with_their_look() { + let mut s = Session::new(); + crate::sample::open_sample(&mut s).unwrap(); + let slides = s.doc().unwrap().doc.slides.len(); + let mut checked = 0; + for i in 0..slides { + s.execute("slide.go", &json!({"index": i})).unwrap(); + let phs: Vec = s + .doc() + .unwrap() + .current_slide() + .unwrap() + .shapes + .iter() + .filter(|x| x.ph.is_some() && x.text.as_ref().is_some_and(|t| !t.is_empty())) + .map(|x| x.id) + .collect(); + for id in phs { + let want = resolved_look(&s, id); + s.execute("selection.select", &json!({"id": id.0})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_eq!(resolved_look(&s, copy), want, "slide {i}, placeholder {}", id.0); + checked += 1; + } + } + assert!(checked >= 3, "the sample has text placeholders ({checked})"); +} + #[test] fn pasted_shapes_get_the_next_automatic_name() { let mut s = session(); diff --git a/crates/model/src/resolve.rs b/crates/model/src/resolve.rs index 8d87229f3..8cf87582d 100644 --- a/crates/model/src/resolve.rs +++ b/crates/model/src/resolve.rs @@ -218,6 +218,45 @@ pub fn effects(ctx: &Ctx, shape: &Shape) -> (Option, Option) { (None, None) } +/// Turn a placeholder into a regular shape that looks the same: what it inherited from its layout +/// and master placeholders (position, fill, line, effects, style, body properties and the text +/// style of every outline level, the master's title or body style included) becomes its own, and +/// `ph` is cleared. A shape that is not a placeholder is left as it is. +/// +/// Theme references (`+mj-lt`, scheme colours) stay references, so the copy still follows the +/// destination theme, as PowerPoint's default paste does. +pub fn detach_placeholder(ctx: &Ctx, shape: &mut Shape) { + if shape.ph.is_none() { + return; + } + let (lp, mp) = parents(ctx, shape); + let parents = [lp, mp].into_iter().flatten(); + shape.xfrm = Some(xfrm(ctx, shape)); + if shape.fill.is_none() && shape.style.is_none() { + shape.fill = parents.clone().find_map(|s| s.fill.clone()); + } + if shape.style.is_none() { + shape.style = parents.clone().find_map(|s| s.style.clone()); + } + if shape.effects.is_none() { + shape.effects = parents.clone().find_map(|s| s.effects.clone()); + } + let mut line = shape.line.clone(); + for p in parents.filter_map(|s| s.line.as_ref()) { + line.get_or_insert_with(Line::default).inherit(p); + } + shape.line = line; + if shape.text.is_some() { + let body = body(ctx, shape); + let levels: Vec> = (0..9).map(|l| Some(level_style(ctx, shape, l))).collect(); + if let Some(t) = shape.text.as_mut() { + t.body = body; + t.list_style = ListStyle { levels }; + } + } + shape.ph = None; +} + /// Body properties with defaults filled in. pub fn body(ctx: &Ctx, shape: &Shape) -> BodyProps { let (lp, mp) = parents(ctx, shape); From f006b5d8cef8ed499f14a16f58510b2dd0aaa7ef Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo Date: Sun, 1 Nov 2026 22:38:05 +0100 Subject: [PATCH 07/94] Ctrl+V pastes a picture copied in a browser, not its link A browser's Copy Image puts the picture on the clipboard together with text that only names it (the address and alt text, or Firefox's UTF-16 text/x-moz-url read as UTF-8) and an HTML fragment. Ctrl+V only looked for a picture when the text was empty, so it pasted a text box with the link. When the text or HTML only names a picture, paste the picture; with no picture on the clipboard the link still pastes as text. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/app/clipboard.rs | 46 +++++++++++++++++++++++++++++ crates/ui-egui/src/app/keys.rs | 6 ++-- crates/ui-egui/src/tests.rs | 44 +++++++++++++++++++++++++++ docs/gaps.md | 2 +- 5 files changed, 96 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index fd17b3a1c..42ccd19dc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -148,6 +148,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-01 | Ctrl+V of a picture copied in a browser (Copy Image) pastes the picture, not a text box with its link and alt text; the link still pastes as text when no picture came with it | | 2026-11-01 | Copy, Cut, Paste and Duplicate of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text | | 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows | | 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits | diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 19fd48bf1..f6003dd04 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -11,6 +11,52 @@ pub(crate) fn system_clipboard_text(t: &str) -> String { if t.is_empty() { OBJECTS_MARKER.to_string() } else { t.to_string() } } +/// Whether pasted `text` (and the clipboard's `html`) only name a picture that is on the clipboard +/// too, as a browser's Copy Image leaves them: the picture's address, perhaps followed by its alt +/// text, or HTML that is a lone ``. Then Ctrl+V pastes the picture, as PowerPoint does. +/// Text with NULs is UTF-16 read as UTF-8 (Firefox's `text/x-moz-url`), never words to keep. +pub(crate) fn names_a_picture(text: &str, html: Option<&str>) -> bool { + if text.contains('\0') { + return true; + } + if let Some(h) = html + && h.to_ascii_lowercase().contains("`/`"); + } else if rest.starts_with('<') { + i = skip_to(">"); + } else { + let end = rest.find('<').map_or(html.len(), |e| i + e); + out.push_str(&html[i..end]); + i = end; + } + } + out.replace(" ", " ") +} + impl SlideApp { /// Offer the copy or cut on the system clipboard. /// diff --git a/crates/ui-egui/src/app/keys.rs b/crates/ui-egui/src/app/keys.rs index d6903e82d..7523308c0 100644 --- a/crates/ui-egui/src/app/keys.rs +++ b/crates/ui-egui/src/app/keys.rs @@ -152,8 +152,10 @@ impl SlideApp { // Text keeps its HTML (bold, italic, underline) when the host can read it. let html = self.services.clipboard_html.as_mut().and_then(|f| f()).filter(|h| !h.is_empty()); // egui 0.37 sends `PasteImage` directly; the services fallback stays for - // integrations that still send an empty `Paste`. Never insert twice. - let img = if text.is_empty() && !pasted_image_event { self.services.clipboard_image.as_mut().and_then(|f| f()) } else { None }; + // integrations that still send an empty `Paste`, and for a browser's Copy + // Image, whose text is only the picture's link. Never insert twice. + let wants_picture = text.is_empty() || super::clipboard::names_a_picture(&text, html.as_deref()); + let img = if wants_picture && !pasted_image_event { self.services.clipboard_image.as_mut().and_then(|f| f()) } else { None }; let revision = self.session.active().map(|d| d.revision); let r = match img { Some(png) => self diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 98f3b85c7..47192ad36 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -378,6 +378,50 @@ fn title_bar_export_opens_the_export_dialog() { assert_eq!(harness.state().dialog.as_ref().map(|d| d.id.as_str()), Some("export")); } +/// A browser's Copy Image puts the picture on the clipboard with text that only names it: the +/// address (and the alt text), and an `` fragment as HTML. Ctrl+V pastes the picture, as +/// PowerPoint does, instead of a text box with the link. Without a picture the link pastes as text. +#[test] +fn ctrl_v_pastes_the_picture_a_browser_copied_not_its_link() { + let url = "https://github.com/storytold/deckcraft/raw/main/assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png"; + let caption = format!("{url}\nDeckCraft icon: a presentation screen with a bar chart on an orange tile"); + for (text, html, with_picture, pictures_after) in [ + (caption.clone(), Some(format!("\"DeckCraft")), true, 1), + (url.to_string(), None, true, 1), + // Firefox's text/x-moz-url is UTF-16; read as UTF-8 it carries NULs. + (url.chars().flat_map(|c| [c, '\0']).collect(), None, true, 1), + (url.to_string(), None, false, 0), + ("See https://example.com for the photos".to_string(), None, true, 0), + ] { + let session = Session::with_new(); + let png = { + let d = session.active().unwrap(); + deckcraft_engine::cmd::file::render_png(&d.doc, 0, 0.1, false).0 + }; + let services = Services { + clipboard_image: Some(Box::new(move || with_picture.then(|| png.clone()))), + clipboard_html: Some(Box::new(move || html.clone())), + ..Default::default() + }; + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SlideApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + SlideApp::new(session, services), + ); + harness.run_steps(2); + let shapes_before = harness.state().session.active().unwrap().doc.slides[0].shapes.len(); + harness.event(egui::Event::Paste(text.clone())); + harness.run_steps(2); + let d = harness.state().session.active().unwrap(); + let shapes = &d.doc.slides[0].shapes; + let pictures = shapes.iter().filter(|s| matches!(s.kind, deckcraft_model::ShapeKind::Picture { .. })).count(); + assert_eq!(pictures, pictures_after, "{text:?}"); + assert_eq!(shapes.len(), shapes_before + 1, "one shape, picture or text, for {text:?}"); + } +} + /// #53: Ctrl+V did nothing for an image-only clipboard: egui-winit sends no Paste event for it and /// swallows the key press, so only the V release reaches the app. #[test] diff --git a/docs/gaps.md b/docs/gaps.md index 75a92355b..27c7ef7c7 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -161,7 +161,7 @@ Detail in [file-format-parity.md](file-format-parity.md). - **Estimate:** 3–5 h. **Beta blocker.** ### Image paste fails on Windows (#1414) -- **Evidence:** #53 is closed (PR #88 pastes an image-only clipboard as a picture); #1414 (Ctrl+V fails to paste external images on Windows) is open. From the egui 0.37 migration (#1350, v0.11.1) to 0.14.1 the desktop build left out eframe's `clipboard` feature, so egui simulated a clipboard inside the app and Ctrl+V never read the system clipboard on any platform. Fixed 2026-11-01. #1414 may have the same cause: re-test on Windows. +- **Evidence:** #53 is closed (PR #88 pastes an image-only clipboard as a picture); #1414 (Ctrl+V fails to paste external images on Windows) is open. From the egui 0.37 migration (#1350, v0.11.1) to 0.14.1 the desktop build left out eframe's `clipboard` feature, so egui simulated a clipboard inside the app and Ctrl+V never read the system clipboard on any platform. Fixed 2026-11-01, as is a browser's Copy Image on Linux, which pasted its link because Ctrl+V preferred any text over the picture. #1414 may have either cause: re-test on Windows. - **Impact:** copy-paste of screenshots is a core workflow. - **Estimate:** 2–4 h. **Beta blocker.** From 1192e5ef3076f7df1b239e2f4a14645ec53186b8 Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo Date: Sun, 1 Nov 2026 23:06:09 +0100 Subject: [PATCH 08/94] Detached placeholders follow each property's style precedence Review follow-up (CodeRabbit on #1658): - Text levels are resolved before the copy's style changes. A master placeholder's font reference reached the copy's text (body font in an accent colour for a title) although the original ignores it: text only takes the shape's or the layout placeholder's font reference. - Fill, line and effects come from where `resolve::fill`, `resolve::line` and `resolve::effects` take them: the first shape in the chain with an explicit value or a style. A layout's (or the slide's own) style no longer loses to an explicit fill, line or effect on the master. The copy gets one style whose references each come from the shape that supplied that property; unused references are neutral. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 100 ++++++++++++++++++++++++++++++++++++ crates/model/src/resolve.rs | 71 ++++++++++++++++--------- 2 files changed, 147 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eec43cc4a..26fb7b9cf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -267,6 +267,106 @@ fn a_pasted_or_duplicated_placeholder_keeps_its_inherited_look() { assert!(s.doc().unwrap().doc.validate().is_empty()); } +/// The resolved fill, line and effects of shape `id` on the current slide, with their style colours. +fn resolved_box(s: &Session, id: ShapeId) -> String { + use deckcraft_model::resolve; + let st = s.doc().unwrap(); + let ctx = resolve::Ctx::for_slide(&st.doc, st.current_slide().unwrap()).unwrap(); + let sh = st.shape(id).unwrap(); + format!("{:?}\n{:?}\n{:?}", resolve::fill(&ctx, sh), resolve::line(&ctx, sh), resolve::effects(&ctx, sh)) +} + +/// Edit the title placeholders the current slide's title inherits from: its layout's and its +/// master's. Returns the slide title's id. +fn edit_title_parents( + s: &mut Session, + layout: impl FnOnce(&mut deckcraft_model::Shape), + master: impl FnOnce(&mut deckcraft_model::Shape), +) -> ShapeId { + let st = s.doc_mut().unwrap(); + let slide = st.current_slide().unwrap().clone(); + let title = slide.shapes.iter().find(|x| x.ph_type().is_some_and(|k| k.is_title())).unwrap().id; + let doc = std::sync::Arc::make_mut(&mut st.doc); + let m = std::sync::Arc::make_mut(&mut doc.masters[0]); + let lay = m.layouts.iter_mut().find(|l| l.id == slide.layout).unwrap(); + layout(lay.shapes.iter_mut().find(|x| x.ph_type().is_some_and(|k| k.is_title())).unwrap()); + master(m.shapes.iter_mut().find(|x| x.ph_type().is_some_and(|k| k.is_title())).unwrap()); + title +} + +/// A copied placeholder takes each of fill, line and effects from where the original does: a +/// style on the layout's placeholder (or on the slide's own) wins over an explicit value on the +/// master's, as `resolve::fill`, `resolve::line` and `resolve::effects` decide. +#[test] +fn a_pasted_placeholder_keeps_the_style_precedence_of_its_box() { + use deckcraft_color::SchemeSlot; + use deckcraft_model::{ColorRef, Effects, Fill, Line, ShapeStyle}; + for style_on_slide in [false, true] { + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let style = ShapeStyle { + line_ref: (1, ColorRef::scheme(SchemeSlot::Accent2)), + fill_ref: (1, ColorRef::scheme(SchemeSlot::Accent1)), + effect_ref: (0, ColorRef::scheme(SchemeSlot::Accent3)), + font_ref: ("minor".into(), None), + }; + let layout_style = (!style_on_slide).then(|| style.clone()); + let title = edit_title_parents( + &mut s, + |l| l.style = layout_style, + |m| { + m.fill = Some(Fill::solid(ColorRef::scheme(SchemeSlot::Accent4))); + m.line = Some(Line::solid(ColorRef::scheme(SchemeSlot::Accent5), 20.0)); + m.effects = Some(Effects { soft_edge: Some(5.0), ..Default::default() }); + }, + ); + if style_on_slide { + s.edit(|doc, sel| { + let list = crate::shapes_mut(doc, sel).unwrap(); + list.iter_mut().find(|x| x.id == title).unwrap().style = Some(style.clone()); + Ok(()) + }) + .unwrap(); + } + s.execute("text.set", &json!({"id": title.0, "text": "Styled title"})).unwrap(); + let want = (resolved_box(&s, title), resolved_look(&s, title)); + s.execute("selection.select", &json!({"id": title.0})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_eq!((resolved_box(&s, copy), resolved_look(&s, copy)), want, "style on the slide: {style_on_slide}"); + } +} + +/// The master's placeholder style never reaches the copy's text: the original's text ignores it +/// (only the shape's or the layout's font reference counts), so the copy must too. +#[test] +fn a_pasted_placeholder_ignores_the_masters_font_reference() { + use deckcraft_color::SchemeSlot; + use deckcraft_model::{ColorRef, ShapeStyle}; + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let title = edit_title_parents( + &mut s, + |l| l.style = None, + |m| { + m.style = Some(ShapeStyle { + line_ref: (0, ColorRef::scheme(SchemeSlot::Accent2)), + fill_ref: (0, ColorRef::scheme(SchemeSlot::Accent1)), + effect_ref: (0, ColorRef::scheme(SchemeSlot::Accent3)), + font_ref: ("minor".into(), Some(ColorRef::scheme(SchemeSlot::Accent6))), + }) + }, + ); + s.execute("text.set", &json!({"id": title.0, "text": "Title"})).unwrap(); + let want = (resolved_box(&s, title), resolved_look(&s, title)); + assert!(want.1.contains("+mj-lt"), "the title draws in the heading font: {}", want.1); + s.execute("selection.select", &json!({"id": title.0})).unwrap(); + s.execute("edit.duplicate", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_eq!((resolved_box(&s, copy), resolved_look(&s, copy)), want); +} + /// The same on every text placeholder of the sample deck (titles, bulleted bodies, subtitles). #[test] fn sample_placeholders_paste_with_their_look() { diff --git a/crates/model/src/resolve.rs b/crates/model/src/resolve.rs index 8cf87582d..5f1651de9 100644 --- a/crates/model/src/resolve.rs +++ b/crates/model/src/resolve.rs @@ -4,7 +4,7 @@ use deckcraft_color::{ColorScheme, Rgba, SchemeSlot}; use deckcraft_geom::Xfrm; -use crate::style::{ColorRef, Effects, Fill, Line}; +use crate::style::{ColorRef, Effects, Fill, Line, ShapeStyle}; use crate::text::{Anchor, AutoFit, BodyProps, LevelStyle, ListStyle, ParaProps, RunProps}; use crate::{Background, Layout, Master, PhType, Presentation, Shape, Slide}; @@ -229,30 +229,53 @@ pub fn detach_placeholder(ctx: &Ctx, shape: &mut Shape) { if shape.ph.is_none() { return; } - let (lp, mp) = parents(ctx, shape); - let parents = [lp, mp].into_iter().flatten(); - shape.xfrm = Some(xfrm(ctx, shape)); - if shape.fill.is_none() && shape.style.is_none() { - shape.fill = parents.clone().find_map(|s| s.fill.clone()); - } - if shape.style.is_none() { - shape.style = parents.clone().find_map(|s| s.style.clone()); - } - if shape.effects.is_none() { - shape.effects = parents.clone().find_map(|s| s.effects.clone()); - } - let mut line = shape.line.clone(); - for p in parents.filter_map(|s| s.line.as_ref()) { - line.get_or_insert_with(Line::default).inherit(p); - } - shape.line = line; - if shape.text.is_some() { - let body = body(ctx, shape); - let levels: Vec> = (0..9).map(|l| Some(level_style(ctx, shape, l))).collect(); - if let Some(t) = shape.text.as_mut() { - t.body = body; - t.list_style = ListStyle { levels }; + // The text first: `level_style` reads the shape's own style, which changes below. + let text = shape.text.as_ref().map(|_| (body(ctx, shape), (0..9).map(|l| Some(level_style(ctx, shape, l))).collect::>())); + let own = shape.clone(); + let (lp, mp) = parents(ctx, &own); + let chain = [Some(&own), lp, mp].into_iter().flatten(); + + // Each property comes from where `fill`, `line` and `effects` take it: the first shape in the + // chain with an explicit value or a style. Lines merge explicit values up to the first styled + // shape, whose style line fills the rest. + let fill_src = chain.clone().find(|s| s.fill.is_some() || s.style.is_some()); + let effects_src = chain.clone().find(|s| s.effects.is_some() || s.style.is_some()); + let mut line = None; + let mut line_src = None; + for s in chain.clone() { + if let Some(l) = &s.line { + line.get_or_insert_with(Line::default).inherit(l); } + if s.style.is_some() { + line_src = Some(s); + break; + } + } + // Text takes its font reference from the shape's style or its layout placeholder's (a table's + // from its own only), never the master's. + let table = matches!(own.kind, crate::ShapeKind::Table(_)); + let font_src = own.style.as_ref().or(lp.filter(|_| !table).and_then(|s| s.style.as_ref())); + + // One style for the copy, each reference taken from the shape that supplied that property. A + // property with an explicit value ignores its reference, except a gradient without stops, + // which takes them from its own shape's style; a neutral reference (index 0) adds nothing. + let style_of = |s: Option<&Shape>| s.and_then(|s| s.style.clone()); + let neutral = (0, ColorRef::scheme(SchemeSlot::Tx1)); + let style = chain.clone().any(|s| s.style.is_some()).then(|| ShapeStyle { + fill_ref: style_of(fill_src).map_or_else(|| neutral.clone(), |st| st.fill_ref), + line_ref: style_of(line_src).map_or_else(|| neutral.clone(), |st| st.line_ref), + effect_ref: style_of(effects_src).map_or_else(|| neutral.clone(), |st| st.effect_ref), + font_ref: font_src.map_or_else(|| ("none".into(), None), |st| st.font_ref.clone()), + }); + + shape.xfrm = Some(xfrm(ctx, &own)); + shape.fill = fill_src.and_then(|s| s.fill.clone()); + shape.effects = effects_src.and_then(|s| s.effects.clone()); + shape.line = line; + shape.style = style; + if let (Some(t), Some((body, levels))) = (shape.text.as_mut(), text) { + t.body = body; + t.list_style = ListStyle { levels }; } shape.ph = None; } From b9eaaeb23b011b7a1e96568a4101f6d0d3cc13b9 Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:03:02 -0600 Subject: [PATCH 09/94] Test: hidden media controls are written as PowerPoint's p14 extension The round trip now also checks the written presProps.xml: inside p:showPr, the extension uri and p14:showMediaCtrls with its namespace declared on the element; the default writes nothing. Co-Authored-By: Claude Opus 5.5 --- crates/pptx/tests/it/roundtrip.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/pptx/tests/it/roundtrip.rs b/crates/pptx/tests/it/roundtrip.rs index c61e6e433..521956a06 100644 --- a/crates/pptx/tests/it/roundtrip.rs +++ b/crates/pptx/tests/it/roundtrip.rs @@ -1970,11 +1970,30 @@ fn default_durations_match_powerpoint() { } } -/// Show media controls is PowerPoint's `p14:showMediaCtrls` extension inside `p:showPr`. +/// Show media controls is PowerPoint's `p14:showMediaCtrls` extension inside `p:showPr`: off is +/// written there, under its extension uri and with the p14 namespace declared on the element; +/// on (the default) writes nothing. #[test] fn hidden_media_controls_survive_save_and_reopen() { + let props = |p: &Presentation| { + let bytes = deckcraft_pptx::export(p).expect("export"); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("zip"); + let mut x = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("ppt/presProps.xml").expect("presProps"), &mut x).expect("read"); + x + }; let mut p = Presentation::default(); p.show.show_media_controls = false; + let xml = props(&p); + let show = xml.split("").next()).expect("p:showPr"); + assert!( + show.contains( + "" + ), + "{xml}" + ); assert!(!round(&p).show.show_media_controls); - assert!(round(&Presentation::default()).show.show_media_controls); + let default = Presentation::default(); + assert!(!props(&default).contains("showMediaCtrls")); + assert!(round(&default).show.show_media_controls); } From 32f069eb84dcbe4a454c191f9aa22214f1974399 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 13:44:00 -0500 Subject: [PATCH 10/94] AV1, HEVC: count repeated-frame outputs incrementally and drop inherited entry-point storage (#1763) * av1: count repeated-frame outputs as they are added * hevc: give each slice segment its own entry-point list instead of keeping the copied one's allocation --- crates/av1/src/decoder.rs | 5 ++++- crates/hevc/src/slice.rs | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/av1/src/decoder.rs b/crates/av1/src/decoder.rs index 43abce22b..d463493a1 100644 --- a/crates/av1/src/decoder.rs +++ b/crates/av1/src/decoder.rs @@ -425,6 +425,8 @@ impl Decoder { fn parse_obus(&mut self, data: &[u8], out: &mut Vec<(Output, usize, u32)>) -> Result<()> { let mut tu = 0usize; + // Repeated-frame outputs in `out`, counted as they are added rather than recounted per OBU. + let mut existing = out.iter().filter(|(o, _, _)| matches!(o, Output::Existing { .. })).count(); let mut pos = 0; while pos < data.len() { let obu = parse_obu_unit(data, pos)?; @@ -444,9 +446,10 @@ impl Decoder { } OBU_FRAME_HEADER_T | OBU_REDUNDANT_FRAME_HEADER_T | OBU_FRAME_T => { if let Some(o) = self.frame_obu(&obu)? { - if out.iter().filter(|(o, _, _)| matches!(o, Output::Existing { .. })).count() >= 32 { + if existing >= 32 { return Err(Error::Invalid("too many frame outputs in chunk")); } + existing += usize::from(matches!(o, Output::Existing { .. })); out.push((o, tu, spatial_id)); } } diff --git a/crates/hevc/src/slice.rs b/crates/hevc/src/slice.rs index aadf6159f..3d6233fb6 100644 --- a/crates/hevc/src/slice.rs +++ b/crates/hevc/src/slice.rs @@ -326,7 +326,9 @@ impl SliceHeader { /// entry_point_offset list (tiles / wavefront substreams). fn parse_entry_points(&mut self, r: &mut BitReader, pps: &Pps, sps: &Sps) -> Result<()> { - self.entry_points.clear(); + // A fresh list, not `clear()`: a dependent segment starts as a copy of its independent + // segment's header, and clearing would keep that copy's allocation for every segment. + self.entry_points = Vec::new(); if pps.tiles_enabled || pps.entropy_coding_sync { let n = r.read_ue()?; ensure!(n <= sps.pic_width_in_ctbs() * sps.pic_height_in_ctbs(), "num_entry_point_offsets out of range"); From 1eec8b266cbab49efdb5aecb8fa46a9b574688d6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:14:24 -0500 Subject: [PATCH 11/94] model: group box charts and stack sums in one pass, share hierarchy labels, cap number formats (#1760) --- crates/model/src/chart.rs | 123 +++++++++++++++++++++++++++---------- crates/model/src/numfmt.rs | 13 ++++ 2 files changed, 102 insertions(+), 34 deletions(-) diff --git a/crates/model/src/chart.rs b/crates/model/src/chart.rs index 1b300359c..9cebb5a2f 100644 --- a/crates/model/src/chart.rs +++ b/crates/model/src/chart.rs @@ -758,17 +758,20 @@ impl Chart { } fn stacked_value_range(&self, n: usize) -> (f64, f64) { - let mut lo: f64 = 0.0; - let mut hi: f64 = 0.0; - for i in 0..n { - let (mut p, mut m) = (0.0, 0.0); - for s in &self.series { - let v = s.values.get(i).copied().flatten().unwrap_or(0.0); - if v >= 0.0 { p += v } else { m += v } + // Sums per category, from the values the series hold (an absent one adds nothing). + let (mut pos, mut neg) = (vec![0.0f64; n], vec![0.0f64; n]); + for s in &self.series { + for (i, v) in s.values.iter().enumerate().take(n) { + let v = v.unwrap_or(0.0); + if v >= 0.0 { + pos[i] += v; + } else { + neg[i] += v; + } } - hi = hi.max(p); - lo = lo.min(m); } + let hi = pos.iter().fold(0.0f64, |a, &p| a.max(p)); + let lo = neg.iter().fold(0.0f64, |a, &m| a.min(m)); (lo, hi) } @@ -1348,40 +1351,50 @@ impl Chart { /// The box chart's groups (distinct category labels in order of appearance; one unnamed /// group without categories) and, per series, each group's summary (None when it has no /// points). + /// + /// Each value is put in its group's bucket once (groups are found by name in a map), and the + /// series x groups result is held to [`MAX_BOX_CELLS`]: groups past it are left out. pub fn box_groups(&self) -> (Vec, Vec>>) { + let max_groups = (MAX_BOX_CELLS / self.series.len().max(1)).max(1); let mut groups: Vec = Vec::new(); + let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); for c in &self.categories { - if !groups.contains(c) { + if !index.contains_key(c.as_str()) && groups.len() < max_groups { + index.insert(c, groups.len()); groups.push(c.clone()); } } if groups.is_empty() { groups.push(String::new()); + index.insert("", 0); } + // A value past the categories belongs to the unnamed group, when there is one. + let past_end = index.get("").copied(); let stats = self .series .iter() .map(|s| { - groups - .iter() - .map(|g| { - let pts: Vec = s - .values - .iter() - .enumerate() - .filter(|(i, _)| self.categories.get(*i).map_or(g.is_empty() || self.categories.is_empty(), |c| c == g)) - .filter_map(|(_, v)| *v) - .filter(|v| v.is_finite()) - .collect(); - box_stats_by(pts, self.inclusive_quartiles) - }) - .collect() + let mut buckets: Vec> = vec![Vec::new(); groups.len()]; + for (i, v) in s.values.iter().enumerate() { + let Some(v) = v.filter(|v| v.is_finite()) else { continue }; + let g = match self.categories.get(i) { + Some(c) => index.get(c.as_str()).copied(), + None => past_end, + }; + if let Some(b) = g.and_then(|g| buckets.get_mut(g)) { + b.push(v); + } + } + buckets.into_iter().map(|pts| box_stats_by(pts, self.inclusive_quartiles)).collect() }) .collect(); (groups, stats) } } +/// Most series x group summaries [`Chart::box_groups`] makes. +pub const MAX_BOX_CELLS: usize = 1_000_000; + /// Widens the (min, max) extent `ext` to include `v`. fn widen(ext: &mut (f64, f64), v: f64) { ext.0 = ext.0.min(v); @@ -1454,33 +1467,41 @@ impl Chart { let n = self.categories.len().max(s.values.len()); let levels: Vec<&Vec> = self.category_levels.iter().take(MAX_LEVELS).collect(); // Each leaf's path from the top level down, blanks filled from the row above. - let mut last: Vec = vec![String::new(); levels.len()]; - let paths: Vec> = (0..n) + // Labels are shared, not copied: an outer label given once stands for every leaf under it. + use std::rc::Rc; + let empty: Rc = Rc::from(""); + let mut last: Vec> = vec![empty.clone(); levels.len()]; + let paths: Vec>> = (0..n) .map(|i| { let mut path = Vec::with_capacity(levels.len() + 1); for (d, lv) in levels.iter().enumerate().rev() { let l = lv.get(i).map(|x| x.trim()).unwrap_or(""); if !l.is_empty() { - last[d] = l.to_string(); + last[d] = Rc::from(l); // A new outer label starts fresh inner groups. for inner in last.iter_mut().take(d) { - inner.clear(); + *inner = empty.clone(); } } path.push(last[d].clone()); } - path.push(self.categories.get(i).cloned().unwrap_or_default()); + path.push(self.categories.get(i).map_or_else(|| empty.clone(), |c| Rc::from(c.as_str()))); path }) .collect(); let value = |i: usize| s.values.get(i).copied().flatten().filter(|v| v.is_finite()).unwrap_or(0.0).max(0.0); - fn build(rows: &[(usize, &[String])], value: &dyn Fn(usize) -> f64) -> Vec { + fn build(rows: &[(usize, &[std::rc::Rc])], value: &dyn Fn(usize) -> f64) -> Vec { let mut out: Vec = Vec::new(); let mut i = 0; while i < rows.len() { let (idx, path) = rows[i]; if path.len() <= 1 { - out.push(TreeNode { name: path.first().cloned().unwrap_or_default(), value: value(idx), leaf: Some(idx), children: vec![] }); + out.push(TreeNode { + name: path.first().map(|p| p.to_string()).unwrap_or_default(), + value: value(idx), + leaf: Some(idx), + children: vec![], + }); i += 1; continue; } @@ -1489,14 +1510,14 @@ impl Chart { while j < rows.len() && rows[j].1.len() > 1 && &rows[j].1[0] == head { j += 1; } - let sub: Vec<(usize, &[String])> = rows[i..j].iter().map(|(k, p)| (*k, &p[1..])).collect(); + let sub: Vec<(usize, &[std::rc::Rc])> = rows[i..j].iter().map(|(k, p)| (*k, &p[1..])).collect(); let children = build(&sub, value); - out.push(TreeNode { name: head.clone(), value: children.iter().map(|c| c.value).sum(), leaf: None, children }); + out.push(TreeNode { name: head.to_string(), value: children.iter().map(|c| c.value).sum(), leaf: None, children }); i = j; } out } - let rows: Vec<(usize, &[String])> = paths.iter().enumerate().map(|(i, p)| (i, p.as_slice())).collect(); + let rows: Vec<(usize, &[Rc])> = paths.iter().enumerate().map(|(i, p)| (i, p.as_slice())).collect(); build(&rows, &value) } } @@ -1607,6 +1628,40 @@ mod chartex_tests { assert!(c.category_tree().iter().all(|n| n.leaf.is_some())); } + #[test] + fn large_box_hierarchy_and_stacked_charts_take_linear_work() { + // 50,000 distinct categories in one series: grouped through a map, one pass. + let n = 50_000; + let mut c = Chart::sample(ChartType::BoxWhisker); + c.series.truncate(1); + c.categories = (0..n).map(|i| format!("g{i}")).collect(); + c.series[0].values = (0..n).map(|i| Some(i as f64)).collect(); + let (groups, stats) = c.box_groups(); + assert_eq!((groups.len(), stats[0].len()), (n, n)); + assert!(stats[0].iter().all(Option::is_some)); + // 2,000 series cap the groups so the result stays within MAX_BOX_CELLS. + c.series = vec![c.series[0].clone(); 2000]; + let (groups, stats) = c.box_groups(); + assert_eq!(groups.len(), MAX_BOX_CELLS / 2000); + assert!(stats.iter().all(|s| s.len() == groups.len())); + // One long outer label over 50,000 leaves is shared, not copied per leaf. + let mut t = Chart::sample(ChartType::Treemap); + t.series.truncate(1); + t.categories = (0..n).map(|i| format!("c{i}")).collect(); + t.series[0].values = (0..n).map(|_| Some(1.0)).collect(); + let mut outer = vec![String::new(); n]; + outer[0] = "o".repeat(1 << 16); + t.category_levels = vec![outer]; + let tree = t.category_tree(); + assert_eq!(tree.len(), 1); + assert_eq!(tree[0].children.len(), n); + // Stacked sums over many sparse series. + let mut st = Chart::sample(ChartType::StackedBar); + st.categories = (0..n).map(|i| i.to_string()).collect(); + st.series = (0..2000).map(|k| Series { values: vec![Some(1.0); if k == 0 { n } else { 1 }], ..Default::default() }).collect(); + assert!(st.value_range().1 >= 2000.0, "{:?}", st.value_range()); + } + #[test] fn box_groups_follow_category_labels() { let c = Chart::sample(ChartType::BoxWhisker); diff --git a/crates/model/src/numfmt.rs b/crates/model/src/numfmt.rs index 5d9f2b587..b5db9667c 100644 --- a/crates/model/src/numfmt.rs +++ b/crates/model/src/numfmt.rs @@ -143,9 +143,14 @@ fn group(digits: &str, sep: char) -> String { out } +/// Longest number format applied, as in Excel (255 characters); a longer one formats as +/// General, so a chart cannot make every label expand a huge format. +pub const MAX_CODE_LEN: usize = 255; + /// `v` formatted with the Excel number format `code` in language `lang` (axis labels: the text /// section of a format doesn't apply). pub fn format(code: &str, v: f64, lang: Option<&str>) -> String { + let code = if code.len() > MAX_CODE_LEN * 4 || code.chars().count() > MAX_CODE_LEN { "General" } else { code }; let (sep, dec) = marks(lang); if !v.is_finite() { return String::new(); @@ -299,6 +304,14 @@ mod tests { const RUB: &str = r#"_-* #\ ##0\ "₽"_-;\-* #\ ##0\ "₽"_-;_-* "-"??\ "₽"_-;_-@_-"#; + #[test] + fn an_overlong_format_is_general() { + let code = "0".repeat(100_000); + assert_eq!(format(&code, 12.5, None), format("General", 12.5, None)); + let ok = "0".repeat(MAX_CODE_LEN); + assert_eq!(format(&ok, 7.0, None).len(), MAX_CODE_LEN); + } + #[test] fn scientific_subnormal() { assert_eq!(format("0.00E+00", 5e-324, None), "4.94E-324"); From 19dceffd0bf3cbc79f9aaaf23fe3e05932fb434d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 14:38:07 -0500 Subject: [PATCH 12/94] pptx: index media, layouts, sections and table styles on export (#1761) --- crates/pptx/src/tables.rs | 19 +++++++++----- crates/pptx/src/write.rs | 39 +++++++++++++++++++++++----- crates/pptx/src/write/dml.rs | 6 ++--- crates/pptx/src/write/shapes.rs | 8 +++--- crates/pptx/src/write/timing.rs | 2 +- crates/pptx/tests/it/export_scale.rs | 31 ++++++++++++++++++++++ crates/pptx/tests/it/main.rs | 1 + 7 files changed, 85 insertions(+), 21 deletions(-) create mode 100644 crates/pptx/tests/it/export_scale.rs diff --git a/crates/pptx/src/tables.rs b/crates/pptx/src/tables.rs index 67d25d624..2f627796a 100644 --- a/crates/pptx/src/tables.rs +++ b/crates/pptx/src/tables.rs @@ -210,13 +210,20 @@ pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableSt let mut w = W::new(); w.open("a:tblStyleLst", A::new().a("xmlns:a", NS_A).a("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}")); let names = deckcraft_model::table::table_styles(); - let mut done: Vec<&str> = vec![]; + // Indexes instead of scans: written ids (as given and ASCII lower-case), and the file's + // definitions by lower-case id (the first wins). + let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); + let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); + let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); + for d in defs { + def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); + } for s in used { - if done.contains(&s.as_str()) { + if !done.insert(s.as_str()) { continue; } - done.push(s); - if let Some(d) = defs.iter().find(|d| d.id.eq_ignore_ascii_case(s)) + done_lower.insert(s.to_ascii_lowercase()); + if let Some(d) = def_of.get(&s.to_ascii_lowercase()) && crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) { w.raw(&d.raw); @@ -231,11 +238,11 @@ pub fn table_styles_xml(used: &[String], defs: &[deckcraft_model::table::TableSt } // Styles the file defined but no table uses still belong to the deck. for d in defs { - if done.iter().any(|s| s.eq_ignore_ascii_case(&d.id)) { + if done_lower.contains(&d.id.to_ascii_lowercase()) { continue; } if crate::xml::parse(d.raw.as_bytes()).is_ok_and(|x| x.root.is("tblStyle")) { - done.push(&d.id); + done_lower.insert(d.id.to_ascii_lowercase()); w.raw(&d.raw); } } diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 5d3e60e92..3d80adef1 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -53,6 +53,8 @@ pub struct Exp<'a> { pub p: &'a Presentation, pub pkg: PackageOut, media_parts: HashMap, + /// Each media id's item in `p.media` (the first with the id, as `Presentation::media`). + media_at: HashMap, n_image: u32, n_media: u32, n_chart: u32, @@ -63,6 +65,8 @@ pub struct Exp<'a> { n_kept: u32, pub slide_parts: HashMap, pub table_styles: Vec, + /// The ids in `table_styles`, for checking membership without a scan. + pub table_style_set: std::collections::HashSet, placeholder: Option, } @@ -119,12 +123,17 @@ fn ext_for(content_type: &str, name: &str, data: &[u8]) -> String { if !e.is_empty() && e.len() <= 5 && e.chars().all(|c| c.is_ascii_alphanumeric()) { e } else { "bin".into() } } -impl Exp<'_> { +impl<'a> Exp<'a> { + /// The media item `id`, found through the index rather than a scan of every item. + pub fn media(&self, id: MediaId) -> Option<&'a deckcraft_model::MediaItem> { + let p: &'a Presentation = self.p; + self.media_at.get(&id).and_then(|&i| p.media.get(i)) + } fn media_part(&mut self, id: MediaId) -> Option { if let Some(p) = self.media_parts.get(&id) { return Some(p.clone()); } - let m = self.p.media(id)?; + let m = self.media(id)?; if m.data.is_empty() { return None; } @@ -147,7 +156,7 @@ impl Exp<'_> { } /// A relationship from `o` to a media item (embedded part, or external link). pub fn media_rel(&mut self, o: &mut Out, id: MediaId, kind: &str) -> Option { - let m = self.p.media(id)?; + let m = self.media(id)?; if m.data.is_empty() { let link = m.link.clone()?; return Some(o.rels.add(kind, &link, true)); @@ -156,7 +165,7 @@ impl Exp<'_> { Some(o.rels.add(kind, &opc::relative(&o.name, &part), false)) } pub fn media_rel_new(&mut self, o: &mut Out, id: MediaId, kind: &str) -> Option { - let m = self.p.media(id)?; + let m = self.media(id)?; if m.data.is_empty() { return None; } @@ -489,7 +498,8 @@ fn valid_date(s: &str) -> bool { /// A copy of the presentation with every slide pointing at a layout that exists. fn sanitized(p: &Presentation) -> std::borrow::Cow<'_, Presentation> { let mut need = p.masters.is_empty() || p.masters.iter().any(|m| m.layouts.is_empty()); - need |= p.slides.iter().any(|s| p.layout(s.layout).is_none()); + let layouts: std::collections::HashSet<_> = p.masters.iter().flat_map(|m| m.layouts.iter().map(|l| l.id)).collect(); + need |= p.slides.iter().any(|s| !layouts.contains(&s.layout)); if !need { return std::borrow::Cow::Borrowed(p); } @@ -532,6 +542,13 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { p, pkg: PackageOut::default(), media_parts: HashMap::new(), + media_at: { + let mut m = HashMap::new(); + for (i, item) in p.media.iter().enumerate() { + m.entry(item.id).or_insert(i); + } + m + }, n_image: 0, n_media: 0, n_chart: 0, @@ -541,6 +558,7 @@ pub fn export(p: &Presentation, main_ct: &str) -> Result, PptxError> { n_kept: 0, slide_parts: HashMap::new(), table_styles: vec![], + table_style_set: Default::default(), placeholder: None, }; for (i, s) in p.slides.iter().enumerate() { @@ -959,9 +977,16 @@ fn section_slides(p: &Presentation) -> Vec<(String, Vec)> { if out.is_empty() { return out; } + // Each slide's first section, found once: a section may name a slide many times. + let mut first: HashMap = HashMap::new(); + for (k, sec) in p.sections.iter().enumerate() { + for id in &sec.slides { + first.entry(*id).or_insert(k); + } + } let mut cur = 0usize; for (i, s) in p.slides.iter().enumerate() { - if let Some(k) = p.sections.iter().position(|sec| sec.slides.contains(&s.id)) + if let Some(&k) = first.get(&s.id) && k >= cur { cur = k; @@ -1027,7 +1052,7 @@ fn write_embedded_fonts(x: &mut Exp, o: &mut Out) -> Vec { if let Some(rid) = seen_part.get(&id) { return Some(rid.clone()); } - let m = x.p.media(id)?; + let m = x.media(id)?; if m.data.is_empty() || m.data.len() > 32 * 1024 * 1024 { return None; } diff --git a/crates/pptx/src/write/dml.rs b/crates/pptx/src/write/dml.rs index 6f99323c4..85041596b 100644 --- a/crates/pptx/src/write/dml.rs +++ b/crates/pptx/src/write/dml.rs @@ -100,7 +100,7 @@ pub fn fill(w: &mut W, x: &mut Exp, o: &mut Out, f: &Fill) { pub fn blip_fill(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, pf: &PictureFill) { // An image that lives outside the package is a linked picture: `a:blip` names it through // `r:link`; `r:embed` may only reference a part inside the package. - let linked = x.p.media(pf.media).is_some_and(|m| m.data.is_empty() && m.link.is_some()); + let linked = x.media(pf.media).is_some_and(|m| m.data.is_empty() && m.link.is_some()); let rid = x.media_rel(o, pf.media, "image").unwrap_or_else(|| x.placeholder_rel(o)); w.open(tag, A::new().a("rotWithShape", if pf.upright { "0" } else { "1" })); let adj = &pf.adjust; @@ -449,7 +449,7 @@ pub fn hyperlink(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, h: &Hyperlink) return; }; w.open(tag, attrs); - let name = x.p.media(sound_id).map(|m| sound_label(&m.name)).unwrap_or_else(|| "sound.wav".into()); + let name = x.media(sound_id).map(|m| sound_label(&m.name)).unwrap_or_else(|| "sound.wav".into()); w.empty("a:snd", A::new().a("r:embed", sound_rid).a("name", name)); w.close(tag); } @@ -601,7 +601,7 @@ pub fn ppr(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, level: Option, p: Some(Bullet::Picture { media }) => match x.media_rel(o, *media, "image") { Some(rid) => { w.open0("a:buBlip"); - let a = if x.p.media(*media).is_some_and(|m| m.data.is_empty() && m.link.is_some()) { + let a = if x.media(*media).is_some_and(|m| m.data.is_empty() && m.link.is_some()) { A::new().a("r:link", &rid) } else { A::new().a("r:embed", &rid) diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index 717f95ea1..3a9ba82d3 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -446,7 +446,7 @@ pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth } fn model_rel(x: &mut Exp, o: &mut Out, media: deckcraft_model::MediaId) -> Option { - if x.p.media(media).is_none_or(|m| m.data.is_empty()) { + if x.media(media).is_none_or(|m| m.data.is_empty()) { return None; } x.media_rel(o, media, crate::opc::RT_MODEL3D) @@ -479,7 +479,7 @@ fn write_model( return; }; let id = cx.id_for(s); - let poster = poster.filter(|p| x.p.media(*p).is_some_and(|m| !m.data.is_empty())); + let poster = poster.filter(|p| x.media(*p).is_some_and(|m| !m.data.is_empty())); let Some(poster) = poster else { write_model_part(w, x, o, id, s, &rid); return; @@ -700,7 +700,7 @@ fn table(w: &mut W, x: &mut Exp, o: &mut Out, t: &Table) { t.normalize(); w.open0("a:tbl"); let (guid, _) = crate::tables::guid_for_style(&t.style); - if !x.table_styles.contains(&t.style) { + if x.table_style_set.insert(t.style.clone()) { x.table_styles.push(t.style.clone()); } w.open( @@ -884,7 +884,7 @@ fn opaque( p.name = label.to_string(); } match preview { - Some(m) if x.p.media(m).is_some() => { + Some(m) if x.media(m).is_some() => { p.kind = ShapeKind::Picture { fill: deckcraft_model::style::PictureFill { media: m, ..Default::default() } }; p.ph = None; shape_with_id(w, x, o, cx, &p, id); diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs index 0f3dc8ee2..f2f3f2736 100644 --- a/crates/pptx/src/write/timing.rs +++ b/crates/pptx/src/write/timing.rs @@ -16,7 +16,7 @@ pub fn transition(w: &mut W, x: &mut Exp, o: &mut Out, t: &Transition) { 601..=900 => "med", _ => "slow", }; - let sound = t.sound.and_then(|m| x.media_rel(o, m, "audio").map(|r| (r, x.p.media(m).map(|i| i.name.clone()).unwrap_or_default()))); + let sound = t.sound.and_then(|m| x.media_rel(o, m, "audio").map(|r| (r, x.media(m).map(|i| i.name.clone()).unwrap_or_default()))); let snd = |w: &mut W| { if let Some((r, name)) = &sound { w.open0("p:sndAc"); diff --git a/crates/pptx/tests/it/export_scale.rs b/crates/pptx/tests/it/export_scale.rs new file mode 100644 index 000000000..80e06b1d1 --- /dev/null +++ b/crates/pptx/tests/it/export_scale.rs @@ -0,0 +1,31 @@ +//! Export looks media, layouts, sections and table styles up by id: a deck with many of each and +//! many references to the last ones exports in time linear in its size. + +use std::sync::Arc; + +use deckcraft_model::style::PictureFill; +use deckcraft_model::{Section, Shape, ShapeId, ShapeKind, defaults}; + +#[test] +fn many_media_sections_and_table_styles_export() { + let mut p = defaults::new_presentation(None); + // 5,000 media items; 5,000 pictures of the last one. + let mut last = None; + for i in 0..5_000u32 { + last = p.add_media(&format!("m{i}.png"), "image/png", i.to_le_bytes().to_vec()); + } + let last = last.unwrap(); + let pic = |k: u32| Shape { + id: ShapeId(100_000 + k), + kind: ShapeKind::Picture { fill: PictureFill { media: last, ..Default::default() } }, + ..Default::default() + }; + Arc::make_mut(&mut p.slides[0]).shapes = (0..5_000).map(pic).collect(); + // A section naming the slide 50,000 times, after 2,000 empty sections. + let id = p.slides[0].id; + p.sections = (0..2_000).map(|i| Section { name: format!("s{i}"), slides: vec![] }).collect(); + p.sections.push(Section { name: "last".into(), slides: vec![id; 50_000] }); + let bytes = deckcraft_pptx::export(&p).expect("export"); + let q = deckcraft_pptx::import(&bytes).expect("import"); + assert_eq!(q.slides[0].shapes.iter().filter(|s| matches!(s.kind, ShapeKind::Picture { .. })).count(), 5_000); +} diff --git a/crates/pptx/tests/it/main.rs b/crates/pptx/tests/it/main.rs index 71a8d377b..3f2026c66 100644 --- a/crates/pptx/tests/it/main.rs +++ b/crates/pptx/tests/it/main.rs @@ -9,6 +9,7 @@ mod corpus_kinds; mod corpus_media; mod corpus_style; mod corpus_themes; +mod export_scale; mod fills; mod kept_parts; mod locks; From 54e24ab86884239a5d2208fe2c16c2cfd5cfea3d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:36:05 -0500 Subject: [PATCH 13/94] Review: replace each whole word in one pass (#1793) --- crates/engine/src/cmd/review.rs | 60 ++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index 6a18db56f..92637741f 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -421,23 +421,30 @@ fn add_to_dictionary(_s: &mut Session, p: &Value) -> Result { /// Replace whole-word `from` with `to` in `text`; how many were replaced. fn replace_word(text: &mut String, from: &str, to: &str, all: bool) -> usize { let is_word = |c: char| c.is_alphanumeric() || c == '\'' || c == '’'; - let mut n = 0; - let mut at = 0; + // The result is built in one pass; the text is not edited in place for every match. + let mut out = String::new(); + let (mut n, mut at, mut copied) = (0, 0, 0); while let Some(i) = text.get(at..).and_then(|t| t.find(from)).map(|i| i + at) { let end = i + from.len(); - let before = text.get(..i).and_then(|t| t.chars().next_back()).is_some_and(is_word); + // The character before the match as the edited text would have it. + let before = text.get(copied..i).and_then(|t| t.chars().next_back()).or_else(|| out.chars().next_back()).is_some_and(is_word); let after = text.get(end..).and_then(|t| t.chars().next()).is_some_and(is_word); if before || after { at = end; continue; } - text.replace_range(i..end, to); + out.push_str(text.get(copied..i).unwrap_or_default()); + out.push_str(to); n += 1; - at = i + to.len(); + (at, copied) = (end, end); if !all { break; } } + if n > 0 { + out.push_str(text.get(copied..).unwrap_or_default()); + *text = out; + } n } @@ -764,6 +771,49 @@ fn end_compare(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod tests { + /// The replacement as it ran before: edited in place for every match. + fn replace_word_in_place(text: &mut String, from: &str, to: &str, all: bool) -> usize { + let is_word = |c: char| c.is_alphanumeric() || c == '\'' || c == '’'; + let mut n = 0; + let mut at = 0; + while let Some(i) = text.get(at..).and_then(|t| t.find(from)).map(|i| i + at) { + let end = i + from.len(); + let before = text.get(..i).and_then(|t| t.chars().next_back()).is_some_and(is_word); + let after = text.get(end..).and_then(|t| t.chars().next()).is_some_and(is_word); + if before || after { + at = end; + continue; + } + text.replace_range(i..end, to); + n += 1; + at = i + to.len(); + if !all { + break; + } + } + n + } + + #[test] + fn replace_word_matches_the_in_place_version() { + let cases = [ + ("a a b a", "a", "x", true), + ("aa a. a", "a", "bb", true), + ("a-a -a-", "-", "ab", true), + ("foo. foo.", "foo.", "", true), + ("it's it", "it", "so", true), + ("x.x. x.", "x.", "y", true), + ("a a a", "a", "b", false), + ("none", "z", "q", true), + ("é é", "é", "e", true), + ]; + for (text, from, to, all) in cases { + let (mut a, mut b) = (text.to_string(), text.to_string()); + let (na, nb) = (replace_word(&mut a, from, to, all), replace_word_in_place(&mut b, from, to, all)); + assert_eq!((na, a), (nb, b), "{text:?} {from:?} -> {to:?}"); + } + } + use super::*; use serde_json::json; From 0107186cee878b399ddbd0eac27899db3cabfd00 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:46:09 -0500 Subject: [PATCH 14/94] Engine: check the temporary file's path against the write root (#1792) --- crates/engine/src/io.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 38f4de8d2..9a98f62a0 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -48,6 +48,8 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { // A short fixed-size name: appending to the target's name could exceed the file name limit. let tmp_name = format!(".deckcraft.{}.{}.saving", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed)); let tmp = target_path.with_file_name(tmp_name); + // The sibling must pass the same check: when `path` is the write root itself it lands outside. + crate::file_access::check_write(&tmp.to_string_lossy())?; match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { Ok(f) => break (tmp, f), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempts < 16 => attempts += 1, @@ -135,4 +137,16 @@ mod tests { let _ = std::fs::remove_file(&file); } + + #[test] + fn write_file_to_the_write_root_itself_creates_no_sibling_outside_it() { + let base = std::env::temp_dir().join(format!("deckcraft_io_root_test_{}", std::process::id())); + let root = base.join("root"); + std::fs::create_dir_all(&root).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[], std::slice::from_ref(&root)).unwrap().unwrap(); + let res = crate::file_access::confine(Some(&roots), || write_file(root.to_str().unwrap(), b"x")); + assert!(res.unwrap_err().contains("outside the write root")); + assert_eq!(std::fs::read_dir(&base).unwrap().count(), 1, "only the root is there"); + let _ = std::fs::remove_dir_all(&base); + } } From 42108d0ee75ac621d8849938be744be47e06c17c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:53:44 -0500 Subject: [PATCH 15/94] PPTX export: index animation targets, cache build roles, serialize run properties once per text run (#1788) * PPTX export: index animation targets, cache a paragraph's build roles, serialize run properties once per text run * address review: warn once when a by-paragraph build is truncated --- crates/pptx/src/write/dml.rs | 14 +++++++++-- crates/pptx/src/write/timing.rs | 44 ++++++++++++++++++++++++++++++--- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/crates/pptx/src/write/dml.rs b/crates/pptx/src/write/dml.rs index 85041596b..8acc648d0 100644 --- a/crates/pptx/src/write/dml.rs +++ b/crates/pptx/src/write/dml.rs @@ -762,17 +762,27 @@ pub fn text_body(w: &mut W, x: &mut Exp, o: &mut Out, tag: &str, tb: &TextBody, } fn run_text(w: &mut W, x: &mut Exp, o: &mut Out, text: &str, props: &RunProps) { + // The run's properties are the same for every piece and line break: serialize them once. + let mut rpr_xml: Option = None; + let mut put_rpr = |w: &mut W| match &rpr_xml { + Some(xml) => w.s.push_str(xml), + None => { + let start = w.s.len(); + rpr(w, x, o, "a:rPr", props); + rpr_xml = Some(w.s[start..].to_string()); + } + }; for (i, piece) in text.split(['\n', '\u{b}']).enumerate() { if i > 0 { w.open0("a:br"); - rpr(w, x, o, "a:rPr", props); + put_rpr(w); w.close("a:br"); } if piece.is_empty() && i > 0 { continue; } w.open0("a:r"); - rpr(w, x, o, "a:rPr", props); + put_rpr(w); w.elt("a:t", piece); w.close("a:r"); } diff --git a/crates/pptx/src/write/timing.rs b/crates/pptx/src/write/timing.rs index f2f3f2736..6376e3ca0 100644 --- a/crates/pptx/src/write/timing.rs +++ b/crates/pptx/src/write/timing.rs @@ -1,7 +1,7 @@ //! Transitions and the animation timing tree. use deckcraft_model::anim::{AnimClass, AnimStart, Animation, BuildRole, TextBuild, Transition, build_filled, paragraph_build_roles}; -use deckcraft_model::{Shape, ShapeId, ShapeKind, find_shape}; +use deckcraft_model::{Shape, ShapeId, ShapeKind}; use super::shapes::IdMap; use super::{Exp, Out}; @@ -577,6 +577,21 @@ fn click_pars(w: &mut W, x: &mut Exp, ids: &mut Ids, clicks: &Groups, interactiv } } +/// Most effects one slide's timing writes; animations past it are left out. +const MAX_EFFECTS: usize = 100_000; + +/// The shapes of the tree by id, the first in document order for a repeated id (as `find_shape` +/// finds it), so each animation resolves its shape without a tree walk. +fn shape_index<'a>(shapes: &'a [Shape], depth: usize, out: &mut std::collections::HashMap) { + if depth > 64 { + return; + } + for s in shapes { + out.entry(s.id).or_insert(s); + shape_index(s.children(), depth + 1, out); + } +} + /// Write `p:timing` for a slide's animations. pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idmap: &IdMap) { let mut grp_count: std::collections::HashMap = Default::default(); @@ -585,16 +600,31 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm let mut bld: Vec<(u32, u32, bool)> = vec![]; // The last paragraph effect written: (shape, class, trigger, grpId). let mut prev_para: Option<(ShapeId, AnimClass, Option, u32)> = None; + let mut by_id = std::collections::HashMap::new(); + shape_index(shapes, 0, &mut by_id); + let mut roles_of: std::collections::HashMap> = Default::default(); + let mut effect_count = 0usize; + let mut warned = false; for a in anims.iter().take(10_000) { + if effect_count >= MAX_EFFECTS { + if !warned { + log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out"); + } + break; + } let Some(spid) = idmap.get(a.shape) else { log::warn!("pptx: animation on missing shape {} skipped", a.shape); continue; }; - let Some(shape) = find_shape(shapes, a.shape) else { continue }; + let Some(&shape) = by_id.get(&a.shape) else { continue }; let text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.is_some(); let is_text_sp = matches!(shape.kind, ShapeKind::Shape) && shape.text.as_ref().is_some_and(|t| !t.is_empty()); let text = shape.text.as_ref().filter(|_| a.text_build == TextBuild::ByParagraph && is_text_sp); - let roles = text.map(paragraph_build_roles).unwrap_or_default(); + let no_roles = Vec::new(); + let roles = match text { + Some(t) => roles_of.entry(a.shape).or_insert_with(|| paragraph_build_roles(t)), + None => &no_roles, + }; let by_para = roles.contains(&BuildRole::Top); // PowerPoint keeps a shape's consecutive paragraph effects in one build (`grpId`) marked // `build="p"`; the reader turns them back into a by-paragraph build only if that plays them @@ -632,11 +662,19 @@ pub fn timing(w: &mut W, x: &mut Exp, anims: &[Animation], shapes: &[Shape], idm _ => continue, }; let Ok(pi) = u32::try_from(i) else { break }; + if effect_count + effs.len() >= MAX_EFFECTS { + if !warned { + log::warn!("pptx: more than {MAX_EFFECTS} animation effects; the rest are left out"); + warned = true; + } + break; + } effs.push(Eff { a, spid, start, paragraph: Some(pi), grp }); } } else { effs.push(Eff { a, spid, start: a.start, paragraph: a.paragraph, grp }); } + effect_count += effs.len(); if text_sp && !joins { bld.push((spid, grp, by_para || para_effect)); } From b7d57bacab02c2b8d2d69903337ae681f931e58d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 3 Nov 2026 19:54:06 -0500 Subject: [PATCH 16/94] Text edit: splice inserted paragraphs once and paste runs without rescanning (#1787) --- crates/model/src/edit.rs | 149 +++++++++++++++++++++++++++++++++------ 1 file changed, 128 insertions(+), 21 deletions(-) diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs index 3e21e3bf8..8f79d9c4c 100644 --- a/crates/model/src/edit.rs +++ b/crates/model/src/edit.rs @@ -78,45 +78,57 @@ pub fn insert(body: &mut TextBody, pos: Pos, text: &str, props: Option if body.paragraphs.is_empty() { body.paragraphs.push(Paragraph::default()); } - let (mut pi, mut ch) = clamp(body, pos); - let props = props.unwrap_or_else(|| props_at(body, (pi, ch))); + let (pi0, mut ch) = clamp(body, pos); + let props = props.unwrap_or_else(|| props_at(body, (pi0, ch))); let text = text.replace("\r\n", "\n").replace('\r', "\n"); + // Work on the paragraph being edited apart from the body, so each new paragraph is pushed to a + // list and the body's vector is spliced once instead of shifted for every `\n`. + let Some(slot) = body.paragraphs.get_mut(pi0) else { return (pi0, ch) }; + let mut cur = std::mem::take(slot); + let mut done: Vec = Vec::new(); let mut first = true; for part in text.split('\n') { if !first { - // Split paragraph pi at ch. - let Some(p) = body.paragraphs.get_mut(pi) else { break }; - let idx = split_at(p, ch); - let tail: Vec = p.runs.drain(idx..).collect(); - let newp = - Paragraph { level: p.level, props: p.props.clone(), runs: tail, def_props: p.def_props.clone(), end_props: p.end_props.clone() }; - p.end_props = props.clone(); - body.paragraphs.insert(pi + 1, newp); - pi += 1; + // Split the current paragraph at ch. + let idx = split_at(&mut cur, ch); + let tail: Vec = cur.runs.drain(idx..).collect(); + let newp = Paragraph { + level: cur.level, + props: cur.props.clone(), + runs: tail, + def_props: cur.def_props.clone(), + end_props: cur.end_props.clone(), + }; + cur.end_props = props.clone(); + done.push(std::mem::replace(&mut cur, newp)); ch = 0; } first = false; + // The run index just after the last insertion: the next one lands there with no rescan. + let mut next: Option = None; for (k, seg) in part.split('\u{b}').enumerate() { - let Some(p) = body.paragraphs.get_mut(pi) else { break }; if k > 0 { - let idx = split_at(p, ch); - p.runs.insert(idx, Run { text: String::new(), props: props.clone(), kind: RunKind::Break }); + let idx = next.unwrap_or_else(|| split_at(&mut cur, ch)); + cur.runs.insert(idx, Run { text: String::new(), props: props.clone(), kind: RunKind::Break }); ch += 1; + next = Some(idx + 1); } if seg.is_empty() { continue; } - let idx = split_at(p, ch); - p.runs.insert(idx, Run::with(seg, props.clone())); + let idx = next.unwrap_or_else(|| split_at(&mut cur, ch)); + cur.runs.insert(idx, Run::with(seg, props.clone())); ch += seg.chars().count(); + next = Some(idx + 1); } - if let Some(p) = body.paragraphs.get_mut(pi) { - p.normalize(); - if p.runs.is_empty() { - p.end_props = props.clone(); - } + cur.normalize(); + if cur.runs.is_empty() { + cur.end_props = props.clone(); } } + let pi = pi0 + done.len(); + done.push(cur); + body.paragraphs.splice(pi0..=pi0, done); (pi, ch) } @@ -252,8 +264,16 @@ pub fn slice(body: &TextBody, a: Pos, b: Pos) -> TextBody { /// Insert a formatted body at `pos` (paste): first paragraph merges into the current one. pub fn insert_body(body: &mut TextBody, pos: Pos, src: &TextBody) -> Pos { let mut caret = clamp(body, pos); + // Plain text runs go straight in at the run index after the previous one and the paragraph is + // normalized once, not rescanned and merged for every source run. + let mut next: Option = None; + let mut dirty = false; for (k, sp) in src.paragraphs.iter().enumerate() { if k > 0 { + if let (true, Some(p)) = (dirty, body.paragraphs.get_mut(caret.0)) { + p.normalize(); + } + (next, dirty) = (None, false); caret = insert(body, caret, "\n", None); if let Some(p) = body.paragraphs.get_mut(caret.0) { p.level = sp.level; @@ -261,6 +281,22 @@ pub fn insert_body(body: &mut TextBody, pos: Pos, src: &TextBody) -> Pos { } } for r in &sp.runs { + if r.kind == RunKind::Text + && !r.text.is_empty() + && !r.text.contains(['\n', '\r', '\u{b}']) + && let Some(p) = body.paragraphs.get_mut(caret.0) + { + let idx = next.unwrap_or_else(|| split_at(p, caret.1)); + p.runs.insert(idx, Run::with(&r.text, r.props.clone())); + caret.1 += r.text.chars().count(); + (next, dirty) = (Some(idx + 1), true); + continue; + } + // Anything else takes the general path, after the pending runs are merged. + if let (true, Some(p)) = (dirty, body.paragraphs.get_mut(caret.0)) { + p.normalize(); + } + (next, dirty) = (None, false); match r.kind { RunKind::Text => caret = insert(body, caret, &r.text, Some(r.props.clone())), RunKind::Break => caret = insert(body, caret, "\u{b}", Some(r.props.clone())), @@ -274,6 +310,9 @@ pub fn insert_body(body: &mut TextBody, pos: Pos, src: &TextBody) -> Pos { } } } + if let (true, Some(p)) = (dirty, body.paragraphs.get_mut(caret.0)) { + p.normalize(); + } caret } @@ -568,6 +607,74 @@ mod tests { assert_eq!(caret, (0, 5)); } + /// The paste as it ran before the fast path: one `insert` (and normalize) per source run. + fn insert_body_by_runs(body: &mut TextBody, pos: Pos, src: &TextBody) -> Pos { + let mut caret = clamp(body, pos); + for (k, sp) in src.paragraphs.iter().enumerate() { + if k > 0 { + caret = insert(body, caret, "\n", None); + if let Some(p) = body.paragraphs.get_mut(caret.0) { + p.level = sp.level; + p.props = sp.props.clone(); + } + } + for r in &sp.runs { + match r.kind { + RunKind::Text => caret = insert(body, caret, &r.text, Some(r.props.clone())), + RunKind::Break => caret = insert(body, caret, "\u{b}", Some(r.props.clone())), + _ => { + if let Some(p) = body.paragraphs.get_mut(caret.0) { + let idx = split_at(p, caret.1); + p.runs.insert(idx, r.clone()); + caret.1 += r.char_len(); + } + } + } + } + } + caret + } + + #[test] + fn paste_matches_inserting_run_by_run() { + let bold = |t: &str| Run::with(t, RunProps { bold: Some(true), ..Default::default() }); + let mut src = body(""); + src.paragraphs = vec![ + Paragraph { + runs: vec![Run::with("ab", RunProps::default()), Run::with("cd", RunProps::default()), bold("ef"), bold("g")], + ..Default::default() + }, + Paragraph { + runs: vec![ + bold("h"), + Run { text: String::new(), props: RunProps::default(), kind: RunKind::Break }, + Run::with("i", RunProps::default()), + ], + level: 1, + ..Default::default() + }, + Paragraph { runs: vec![Run::with("jk", RunProps::default())], ..Default::default() }, + ]; + for at in [0, 1, 3, 6] { + let mut dest = body("XYZabc"); + format(&mut dest, (0, 2), (0, 4), &|p| p.italic = Some(true)); + let mut want = dest.clone(); + let want_caret = insert_body_by_runs(&mut want, (0, at), &src); + let caret = insert_body(&mut dest, (0, at), &src); + assert_eq!(caret, want_caret, "caret at {at}"); + assert_eq!(format!("{:?}", dest.paragraphs), format!("{:?}", want.paragraphs), "paste at {at}"); + } + } + + #[test] + fn multiline_insert_splits_into_paragraphs() { + let mut b = body("abcd"); + let c = insert(&mut b, (0, 2), "x\ny\u{b}z\n\nw", None); + assert_eq!(c, (3, 1)); + let texts: Vec = b.paragraphs.iter().map(Paragraph::text).collect(); + assert_eq!(texts, ["abx", "y\u{b}z", "", "wcd"]); + } + #[test] fn words_and_moves() { let b = body("Hello brave world"); From d5471bccf063ec1a4a3b664db7369bfcaea033f5 Mon Sep 17 00:00:00 2001 From: brad Date: Tue, 3 Nov 2026 18:24:57 -0600 Subject: [PATCH 17/94] Web: open and save through a framing page (?host=parent) A same-origin page that frames DeckCraft's web build with ?host=parent sends a file with deckcraft:open and gets every save back as deckcraft:save {name, saveAs, bytes} instead of a download, with deckcraft:ready, deckcraft:dirty and deckcraft:failed, as GridCraft, WordCraft and PdfCraft do. Without ?host=parent nothing changes. Save follows the desktop app. Every file from the page opens through file.adopt like File > Open on the desktop; a presentation sent with a presentation name keeps that name as its file, so Save (Ctrl+S, the File tab, the Close prompt or the command palette) writes it back under that name and format with saveAs: false. Anything else (no name, an outline, a damaged file opened as a repaired copy, a dropped file) is untitled, and its first Save is a new .deckcraft with saveAs: true, as is Save As. Exports and Print are copies (saveAs: false). Host mode starts with an empty presentation that gives way to the first file while untouched, &author= signs comments, and the URL flags are read as whole parameters so a free-text author can't set ?show. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- ROADMAP.md | 3 + apps/deckcraft-web/Cargo.toml | 2 +- apps/deckcraft-web/src/host.rs | 192 +++++++++++++++++++++++++ apps/deckcraft-web/src/main.rs | 7 +- apps/deckcraft-web/src/web.rs | 57 +++++++- crates/engine/src/cmd/file.rs | 16 ++- crates/ui-egui/src/app/commands.rs | 5 + crates/ui-egui/src/app/files.rs | 76 ++++++++++ crates/ui-egui/src/backstage.rs | 3 +- crates/ui-egui/src/backstage/info.rs | 14 +- crates/ui-egui/src/backstage/tests.rs | 29 ++++ crates/ui-egui/src/dialogs/body.rs | 5 +- crates/ui-egui/src/host_save_tests.rs | 198 ++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/services.rs | 13 ++ packaging/web/README.md | 67 ++++++++- 16 files changed, 672 insertions(+), 20 deletions(-) create mode 100644 apps/deckcraft-web/src/host.rs create mode 100644 crates/ui-egui/src/host_save_tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 9315be8a6..c254c0d1f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,6 +2,7 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (progress log: web `?host=parent` bridge opens and saves through a same-origin framing page; scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -150,6 +151,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop | | 2026-11-02 | Native and PPTX saves retain optional table right-to-left direction, including explicit false and omission; two-save round-trip tests keep labeled columns in order | | 2026-11-02 | Text runs preserve alternate-language metadata independently from the main language through native and PPTX saves | | 2026-11-02 | Picture compression measures displayed dimensions through nested group transforms; checklist score unchanged | @@ -332,6 +334,7 @@ app's JSON control channel (`deckcraft --control PORT`). |---|---|---| | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | | 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged | +| 2026-11-03 | trivial | Progress log: web `?host=parent` bridge to a framing page; scores unchanged | | 2026-11-02 | trivial | File › About replaces Account; product links, credits and appearance retained | | 2026-11-02 | trivial | Progress log: tiled picture fills keep their size in scaled groups. Scores and milestone names unchanged | | 2026-10-31 | trivial | No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged | diff --git a/apps/deckcraft-web/Cargo.toml b/apps/deckcraft-web/Cargo.toml index 541985e5b..ca04d5be9 100644 --- a/apps/deckcraft-web/Cargo.toml +++ b/apps/deckcraft-web/Cargo.toml @@ -27,4 +27,4 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "MessageEvent", "Event", "EventTarget"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "MessageEvent", "Event", "EventTarget", "UrlSearchParams"] } diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs new file mode 100644 index 000000000..85c357a12 --- /dev/null +++ b/apps/deckcraft-web/src/host.rs @@ -0,0 +1,192 @@ +//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed +//! DeckCraft in an `<iframe>` and keep its files (a Nextcloud app, a personal file server). The +//! same messages as GridCraft's, WordCraft's and PdfCraft's bridges; each is a plain object with a +//! `type`: +//! +//! - `deckcraft:ready` (to the parent): `{ version }`, sent once the app is running and +//! listening; send a file now. +//! - `deckcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or +//! `Uint8Array`, name a bare file name. It opens like a file picked with File › Open on the +//! desktop: a presentation sent with its name (.pptx, .potx, .ppsx, .deckcraft) has that name +//! as its file, so Save goes back to it; an outline (.txt, .md, .rtf), a file without a name and +//! a damaged file open untitled. +//! - `deckcraft:save` (to the parent): `{ name, saveAs, bytes }` (a transferred `ArrayBuffer`) for +//! every file DeckCraft would otherwise download. The parent stores it and reports failures +//! itself. `saveAs` says whether the file becomes the presentation's file: +//! - Save: `false`. It writes the opened file under its own name and format (a .pptx stays a +//! .pptx), as the desktop app does. A name the parent never sent (an untitled presentation, an +//! outline, a file sent without a name, a repaired copy of a damaged file, a file the user +//! picked or dropped) is a new file: `true`, as for Save As, named `<title>.deckcraft` as +//! Save suggests on the desktop. +//! - Save As (File › Save As as .pptx or .deckcraft, Ctrl+Shift+S): `true`. The presentation is +//! now that file; the next Save sends its name with `false`. +//! - Export (PDF, pictures, outline, GIF, handouts, a Save As type that isn't a presentation) +//! and Print: `false`. They are copies; the presentation's file stays the same. +//! - `deckcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away. +//! - `deckcraft:failed` (to the parent): `{ error }` when the app couldn't start. +//! +//! Only the parent window on the page's own origin is heard or answered. In host mode the app +//! starts with an empty presentation instead of the sample, which gives way to the first file the +//! parent sends; the parent guards leaving the page, and `?author=` names the user for comments. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +use deckcraft_ui_egui::{Services, SlideApp}; +use wasm_bindgen::JsCast as _; +use wasm_bindgen::JsValue; +use wasm_bindgen::closure::Closure; + +/// The longest user name taken from `?author=` (the preferences' own limit). +const MAX_AUTHOR_CHARS: usize = 256; + +#[derive(Clone)] +pub struct Bridge { + window: web_sys::Window, + parent: web_sys::Window, + origin: String, + /// Files the parent sent (the name, if it sent one), waiting for the next frame. + opened: Rc<RefCell<Vec<(Option<String>, Vec<u8>)>>>, + /// The unsaved-changes state last reported to the parent. + reported: Rc<Cell<Option<bool>>>, +} + +impl Bridge { + /// `None` when the page isn't framed (there is no parent to talk to), or when the parent is + /// on another origin: messages only go to this origin, so the browser would drop every save + /// without an error while the presentation showed as saved. + pub fn new() -> Option<Self> { + let window = web_sys::window()?; + let parent = window.parent().ok().flatten()?; + if js_sys::Object::is(&parent, &window) { + return None; + } + let origin = window.location().origin().ok()?; + // An opaque origin (a `file://` page in some browsers) can't be a `postMessage` target. + if origin == "null" { + return None; + } + // Reading another origin's location throws, which is `None` too. + if parent.location().origin().ok()? != origin { + return None; + } + Some(Self { window, parent, origin, opened: Rc::default(), reported: Rc::default() }) + } + + /// Hand saved and exported files to the parent instead of downloading them, and hear the + /// files it sends. + pub fn connect(&self, services: &mut Services, ctx: egui::Context) { + self.listen(ctx); + let bridge = self.clone(); + services.host_save = Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| bridge.post_save(name, bytes, save_as))); + // Exports and Print are copies. + let bridge = self.clone(); + services.download = Some(Box::new(move |name: &str, bytes: &[u8]| { + if let Err(e) = bridge.post_save(name, bytes, false) { + log::error!("couldn't hand {name} to the page: {e}"); + } + })); + } + + /// `?author=`: the host's name for the user signs new comments. + pub fn set_author(app: &mut SlideApp, author: &str) { + let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect(); + if !author.is_empty() { + app.session.prefs.author = author; + } + } + + pub fn post_ready(&self) { + self.send(&[("type", "deckcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]); + } + + /// The app couldn't start (no WebGPU or WebGL2, for example): let the parent say so. + pub fn post_failed(&self, error: &str) { + self.send(&[("type", "deckcraft:failed".into()), ("error", error.into())]); + } + + /// Before each frame: open the files the parent sent. + pub fn open_files(&self, app: &mut SlideApp) { + let opened = std::mem::take(&mut *self.opened.borrow_mut()); + for (name, bytes) in opened { + app.open_from_host(name.as_deref(), &bytes); + } + } + + /// After each frame: tell the parent when unsaved changes appear or go away. + pub fn report_dirty(&self, app: &SlideApp) { + let dirty = app.session.documents().iter().any(|d| d.is_dirty()); + if self.reported.get() != Some(dirty) && self.send(&[("type", "deckcraft:dirty".into()), ("dirty", dirty.into())]) { + self.reported.set(Some(dirty)); + } + } + + fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> { + let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()); + let buffer = js_sys::Uint8Array::from(bytes).buffer(); + let message = message(&[ + ("type", "deckcraft:save".into()), + ("name", name.as_str().into()), + ("saveAs", save_as.into()), + ("bytes", buffer.clone().into()), + ]) + .ok_or_else(|| "couldn't build the message".to_string())?; + self.parent + .post_message_with_transfer(&message, &self.origin, &js_sys::Array::of1(&buffer)) + .map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}"))) + } + + /// Hear `deckcraft:open` from the parent and queue the file for the next frame. + fn listen(&self, ctx: egui::Context) { + let parent = self.parent.clone(); + let origin = self.origin.clone(); + let opened = self.opened.clone(); + let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| { + if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) { + return; + } + let data = event.data(); + if string(&data, "type").as_deref() != Some("deckcraft:open") { + return; + } + // No name is no file: the presentation opens untitled, never under an invented name. + let name = string(&data, "name").filter(|n| !n.trim().is_empty()); + let Some(bytes) = bytes(&data) else { return }; + opened.borrow_mut().push((name, bytes)); + ctx.request_repaint(); + }); + if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() { + // The listener lives as long as the page. + on_message.forget(); + } + } + + /// Post a message to the parent; false if it couldn't be sent. + fn send(&self, fields: &[(&str, JsValue)]) -> bool { + message(fields).is_some_and(|m| self.parent.post_message(&m, &self.origin).is_ok()) + } +} + +fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> { + let m = js_sys::Object::new(); + for (key, value) in fields { + js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?; + } + Some(m) +} + +fn string(data: &JsValue, key: &str) -> Option<String> { + js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string() +} + +/// `bytes` as an `ArrayBuffer` or `Uint8Array`. +fn bytes(data: &JsValue) -> Option<Vec<u8>> { + let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?; + if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() { + Some(array.to_vec()) + } else if bytes.is_instance_of::<js_sys::ArrayBuffer>() { + Some(js_sys::Uint8Array::new(&bytes).to_vec()) + } else { + None + } +} diff --git a/apps/deckcraft-web/src/main.rs b/apps/deckcraft-web/src/main.rs index 2ce622e9a..8fe335eb8 100644 --- a/apps/deckcraft-web/src/main.rs +++ b/apps/deckcraft-web/src/main.rs @@ -9,15 +9,20 @@ //! - File → Open and Insert → Pictures/Audio/Video use the browser file picker; bytes arrive //! asynchronously through `Services::inbox`, applied to the document, slide and operation //! that started the pick (a dismissed picker or a closed document drops the file); -//! - Save and Export trigger a browser download; +//! - Save and Export trigger a browser download (or go to the framing page with `?host=parent`); //! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox; //! - preferences are not persisted. //! //! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?blank` starts with an //! empty presentation instead of the sample deck; `?show` starts the slide show. +//! `?host=parent` (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the +//! presentation to open and stores what DeckCraft saves (`host`), and `&author=` names the user +//! for comments. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +#[cfg(target_arch = "wasm32")] +mod host; #[cfg(target_arch = "wasm32")] mod presenter; #[cfg(target_arch = "wasm32")] diff --git a/apps/deckcraft-web/src/web.rs b/apps/deckcraft-web/src/web.rs index a385d44c8..67f5157c5 100644 --- a/apps/deckcraft-web/src/web.rs +++ b/apps/deckcraft-web/src/web.rs @@ -24,8 +24,16 @@ pub fn start() { log::error!("missing <canvas id=\"{CANVAS_ID}\">"); return; }; + // `?host=parent`: a same-origin page framing DeckCraft opens presentations in it and + // stores what it saves (`host`). The presenter popup is never the framed page. + let host = query_param("host").as_deref() == Some("parent") && crate::presenter::token().is_none(); + let bridge = if host { crate::host::Bridge::new() } else { None }; + if host && bridge.is_none() { + log::warn!("?host=parent needs a framing page on the same origin; saves download instead"); + } + let app_bridge = bridge.clone(); let mut options = eframe::WebOptions::default(); - if query().contains("webgl") + if query_has("webgl") && let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.instance_descriptor.backends = eframe::wgpu::Backends::GL; @@ -44,22 +52,38 @@ pub fn start() { return Ok(Box::new(presenter) as Box<dyn eframe::App>); } let inbox: Inbox = Inbox::default(); - let mut app = SlideApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone())); - let q = query(); - if !q.contains("blank") { + let mut services = services(inbox.clone(), cc.egui_ctx.clone()); + if let Some(bridge) = &app_bridge { + bridge.connect(&mut services, cc.egui_ctx.clone()); + } + let mut app = SlideApp::new(Session::new(), services); + // In host mode the parent sends the presentation to edit; no sample meanwhile. + if app_bridge.is_none() && !query_has("blank") { if let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) { log::error!("sample deck: {e}"); } } else if let Err(e) = app.run("file.new", serde_json::json!({})) { log::error!("new presentation: {e}"); } - if q.contains("show") { + if query_has("show") { app.start_show(0, false); } - Ok(Box::new(WebShell { app, inbox })) + if app_bridge.is_some() + && let Some(author) = query_param("author") + { + crate::host::Bridge::set_author(&mut app, &author); + } + Ok(Box::new(WebShell { app, inbox, bridge: app_bridge })) }), ) .await; + // Ready only once the runner is up: starting can still fail after the app is made. + if let Some(bridge) = &bridge { + match &result { + Ok(()) => bridge.post_ready(), + Err(e) => bridge.post_failed(&format!("{e:?}")), + } + } if let Some(el) = document.get_element_by_id(LOADING_ID) { match result { Ok(()) => el.remove(), @@ -73,17 +97,36 @@ fn query() -> String { web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default() } +fn query_param(key: &str) -> Option<String> { + web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key) +} + +/// Whether the URL has the flag `key` (`?show`, `&blank=1`). A whole parameter, never a substring: +/// `?author=` is free text. +fn query_has(key: &str) -> bool { + web_sys::UrlSearchParams::new_with_str(&query()).is_ok_and(|q| q.has(key)) +} + /// Wraps the app to read dropped files asynchronously (browsers can't read them synchronously) /// and feed them through the inbox. struct WebShell { app: SlideApp, inbox: Inbox, + /// The parent page that keeps the files (`?host=parent`). + bridge: Option<crate::host::Bridge>, } impl eframe::App for WebShell { - /// Delegate one eframe logic pass to the wrapped application. + /// Delegate one eframe logic pass to the wrapped application, opening the files the parent + /// page sent first and telling it about unsaved changes after. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + if let Some(bridge) = &self.bridge { + bridge.open_files(&mut self.app); + } self.app.logic(ctx); + if let Some(bridge) = &self.bridge { + bridge.report_dirty(&self.app); + } if self.app.show.is_none() && let Some(host) = self.app.services.presenter.as_mut() { diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8943eb9a3..e750977d9 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -253,8 +253,15 @@ pub struct LoadedFile { #[cfg(not(target_arch = "wasm32"))] pub fn read_presentation_file(path: &str) -> Result<LoadedFile> { let bytes = crate::io::read_file(path).map_err(EngineError::Other)?; - let (doc, damaged) = open_checked(path, &bytes)?; - let native = deckcraft_format::sniff(&bytes) || deckcraft_pptx::sniff(&bytes); + loaded_file(path, &bytes) +} + +/// Parse `bytes` as the presentation file `path`, as [`read_presentation_file`] does after +/// reading it. The web host bridge uses it for a file its page sent, which then saves back to +/// that name like a file opened on the desktop. +pub fn loaded_file(path: &str, bytes: &[u8]) -> Result<LoadedFile> { + let (doc, damaged) = open_checked(path, bytes)?; + let native = deckcraft_format::sniff(bytes) || deckcraft_pptx::sniff(bytes); Ok(LoadedFile { path: path.to_string(), doc, native, damaged }) } @@ -469,7 +476,10 @@ pub fn format_for_path(path: &str) -> &'static str { } } -fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> { +/// The active presentation is saved as it is now: no unsaved changes, and `path` (when given) +/// becomes its file. `file.save` calls it after writing; the web host bridge calls it once the +/// page has the bytes. +pub fn mark_saved(s: &mut Session, path: Option<String>) -> Result<()> { let st = s.doc_mut()?; st.saved_doc = st.doc.clone(); if path.is_some() { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 0f7781a84..718b95ace 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -20,6 +20,11 @@ impl SlideApp { pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> { let r = if UI_COMMANDS.iter().any(|c| c.0 == id) { self.run_ui(id, ¶ms) + } else if id == "file.save" && self.services.host_save.is_some() && params.get("path").is_none() { + // A page that keeps the files (`?host=parent`): Save by id (the command palette) goes + // to the page like Ctrl+S. The engine would write to the presentation's path, which a + // browser can't. + self.save_to_host(None).map(|name| json!({"path": name})) } else { self.session.execute(id, ¶ms).map_err(|e| e.to_string()) }; diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1e846e0db..c1c6198b4 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -462,6 +462,8 @@ impl SlideApp { Err(e) => self.set_status(e.to_string()), } } + } else if self.services.host_save.is_some() { + let _ = self.save_to_host(Some(ext)); } else if let Some(dl) = self.services.download.as_mut() && let Some(d) = self.session.active() { @@ -487,6 +489,10 @@ impl SlideApp { } pub fn save(&mut self) { + if self.services.host_save.is_some() { + let _ = self.save_to_host(None); + return; + } if self.session.active().and_then(|d| d.path.clone()).is_some() { match self.session.execute("file.save", &json!({})) { Ok(_) => self.set_status("Saved"), @@ -497,6 +503,76 @@ impl SlideApp { } } + /// Saves to the page that keeps the files ([`Services::host_save`](crate::Services::host_save)). + /// Save (`ext` `None`) writes the presentation's own file (the one the page sent, or the + /// last one saved there) in that file's format, as the desktop app does; a presentation with + /// no file of its own is a new `.deckcraft` file, the name Save suggests on the desktop. Save + /// As (`pptx`, `deckcraft`) is a new file named after the presentation. Once the page has the + /// bytes, the presentation is saved and that name is its file. Returns the name, or why it + /// wasn't saved (also shown in the status bar). + pub(super) fn save_to_host(&mut self, ext: Option<&str>) -> Result<String, String> { + use deckcraft_engine::cmd::file::{format_for_path, mark_saved, save_bytes}; + let Some(d) = self.session.active() else { return Err("no presentation is open".into()) }; + let own = d.path.as_deref().and_then(|p| std::path::Path::new(p).file_name()).map(|n| n.to_string_lossy().to_string()); + let (name, save_as) = match (ext, own) { + (None, Some(own)) => (own, false), + (ext, _) => (format!("{}.{}", d.title(), ext.unwrap_or("deckcraft")), true), + }; + let saved = save_bytes(&d.doc, format_for_path(&name)).map_err(|e| e.to_string()).and_then(|bytes| { + let host = self.services.host_save.as_mut().ok_or("no page to save to")?; + host(&name, &bytes, save_as).map_err(|e| format!("Couldn't save {name}: {e}"))?; + mark_saved(&mut self.session, Some(name.clone())).map_err(|e| e.to_string()) + }); + match saved { + Ok(()) => { + self.set_status(format!("Saved {name}")); + Ok(name) + } + Err(e) => { + self.set_status(e.clone()); + Err(e) + } + } + } + + /// A file the page that keeps the files sent (`?host=parent`), with the name it sent, if any. + /// It opens as File › Open opens it on the desktop: a presentation as itself, an outline + /// (.txt, .md, .rtf) as a new untitled presentation. The name is the presentation's file only + /// when the page sent one with a presentation extension and the file is an intact + /// presentation, so Save hands it back under that name and format; anything else (no name, an + /// outline, a damaged file opened as a repaired copy) is untitled, and its first Save is a new + /// file. An untouched untitled presentation that was the only one open (the blank one the page + /// starts with) gives way to the presentation that opened. + pub fn open_from_host(&mut self, name: Option<&str>, bytes: &[u8]) { + let blank = match self.session.documents() { + [d] if d.path.is_none() && !d.is_dirty() => Some(d.uid), + _ => None, + }; + let before = self.session.documents().len(); + let shown = name.unwrap_or("Presentation"); + let named = name.is_some_and(|n| is_presentation_name(&n.to_ascii_lowercase())); + let opened = deckcraft_engine::cmd::file::loaded_file(shown, bytes).and_then(|mut f| { + // `file.adopt` keeps the path only for a native file; a name the page didn't send + // for a presentation must not become one. + f.native &= named; + let token = self.session.stage_loaded(f); + self.session.execute("file.adopt", &json!({"path": shown, "token": token})) + }); + if let Err(e) = opened { + self.notify(e.to_string()); + } + self.drain_requests(); + if self.session.documents().len() > before + && let Some(opened) = self.session.active().map(|d| d.uid) + && let Some(i) = self.session.documents().iter().position(|d| Some(d.uid) == blank) + { + self.session.close_document(i); + if let Some(i) = self.session.documents().iter().position(|d| d.uid == opened) { + self.session.set_active(i); + } + } + } + /// Act on requests commands left for the UI. pub(super) fn drain_requests(&mut self) { for r in std::mem::take(&mut self.session.ui_requests) { diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 0fec08a52..814669728 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -249,7 +249,8 @@ fn act(app: &mut SlideApp, nav: Nav, current: Page) -> Option<Page> { match nav { Nav::Page(p) => Some(p), Nav::Save => { - let web = app.services.pick_save.is_none() && app.services.download.is_some(); + // A page that keeps the files (`host_save`) saves as the desktop does. + let web = app.services.pick_save.is_none() && app.services.download.is_some() && app.services.host_save.is_none(); let has_path = app.session.active().is_some_and(|d| d.path.is_some()); if !has_path && !web { // A presentation that was never saved goes to Save As first, as in PowerPoint. diff --git a/crates/ui-egui/src/backstage/info.rs b/crates/ui-egui/src/backstage/info.rs index 0dce74741..27c0cec6d 100644 --- a/crates/ui-egui/src/backstage/info.rs +++ b/crates/ui-egui/src/backstage/info.rs @@ -166,10 +166,20 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out: }) .response .widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, "Save as type")); - let web = app.services.pick_save.is_none(); + // A page that keeps the files (`host_save`) saves; plain web downloads. + let web = app.services.pick_save.is_none() && app.services.host_save.is_none(); let label = if web { "Download" } else { "Save" }; let save = ui.add(egui::Button::new(RichText::new(label).color(t.accent_text)).fill(t.accent).min_size(vec2(84.0, 26.0))); - if save.on_hover_text(if web { "Download the file" } else { "Choose where to save" }).clicked() { + if save + .on_hover_text(if web { + "Download the file" + } else if app.services.host_save.is_some() { + "Save to the page" + } else { + "Choose where to save" + }) + .clicked() + { let fmt = bs.file_type; let done = if matches!(fmt, "pptx" | "deckcraft") { let before = app.session.active().map(|d| (d.path.clone(), d.is_dirty())); diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index e6aa048ac..205a5522c 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -393,6 +393,35 @@ fn ctrl_w_asks_before_closing_unsaved_changes() { assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("close")); } +/// Framed by a page that keeps the files (`?host=parent`), the Close prompt's Save is a real save: +/// when the page doesn't get the file the presentation stays open with its changes, and when it +/// does the presentation closes. (A plain browser download closes either way.) +#[test] +fn host_close_prompt_keeps_the_presentation_when_the_save_fails() { + for fail in [true, false] { + let services = Services { + host_save: Some(Box::new(move |_: &str, _: &[u8], _: bool| if fail { Err("the page is gone".into()) } else { Ok(()) })), + download: Some(Box::new(|_: &str, _: &[u8]| {})), + ..Default::default() + }; + let mut h = harness(SlideApp::new(Session::with_new(), services)); + h.state_mut().run("slide.new", json!({})).unwrap(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::W); + h.run_steps(3); + assert_eq!(h.state().dialog.as_ref().map(|d| d.id.as_str()), Some("close")); + // Enter is the prompt's Save. + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().dialog.is_none(), "fail={fail}"); + let open = h.state().session.documents().len(); + assert_eq!(open, usize::from(fail), "fail={fail}: open presentations"); + if fail { + assert!(h.state().session.active().unwrap().is_dirty()); + } + } +} + /// Info shows the presentation's counts and properties, and edits them through file.properties. #[test] fn info_shows_and_edits_the_properties() { diff --git a/crates/ui-egui/src/dialogs/body.rs b/crates/ui-egui/src/dialogs/body.rs index cb1a879e9..932cd469a 100644 --- a/crates/ui-egui/src/dialogs/body.rs +++ b/crates/ui-egui/src/dialogs/body.rs @@ -339,8 +339,9 @@ fn dlg_close(app: &mut SlideApp, ui: &mut Ui, _d: &mut Dialog) -> bool { let save = ui.add(egui::Button::new(egui::RichText::new("Save").color(t.accent_text)).fill(t.accent).min_size(vec2(72.0, 24.0))); if save.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) { app.save(); - // In the browser a save is a download: the presentation stays "unsaved". - let web = app.services.pick_save.is_none() && app.services.download.is_some(); + // In the browser a save is a download: the presentation stays "unsaved". A page + // that keeps the files saves it for real, so a failed save keeps it open. + let web = app.services.pick_save.is_none() && app.services.download.is_some() && app.services.host_save.is_none(); if web || app.session.active().is_some_and(|d| !d.is_dirty()) { run(app, "file.close", json!({})); } diff --git a/crates/ui-egui/src/host_save_tests.rs b/crates/ui-egui/src/host_save_tests.rs new file mode 100644 index 000000000..8b9b03c08 --- /dev/null +++ b/crates/ui-egui/src/host_save_tests.rs @@ -0,0 +1,198 @@ +//! The web build framed by a page that keeps the files (`?host=parent`): what Save, Save As, +//! the exports and Print hand that page, under which name, and whether it is a new file. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::json; + +use super::{Services, SlideApp}; +use crate::Session; + +/// What the page was handed: (name, Save As, bytes). +type Got = Rc<RefCell<Vec<(String, bool, Vec<u8>)>>>; + +/// The web app inside such a page, with `host_save` and `download` pointed at it as the bridge +/// does; `fail` makes every save miss the page. +fn host_app(fail: bool) -> (SlideApp, Got) { + let got: Got = Rc::default(); + let (saves, downloads) = (got.clone(), got.clone()); + let services = Services { + host_save: Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| { + if fail { + return Err("the page is gone".into()); + } + saves.borrow_mut().push((name.to_string(), save_as, bytes.to_vec())); + Ok(()) + })), + download: Some(Box::new(move |name: &str, bytes: &[u8]| downloads.borrow_mut().push((name.to_string(), false, bytes.to_vec())))), + ..Default::default() + }; + // The page starts with a blank presentation, as the web shell does in host mode. + (SlideApp::new(Session::with_new(), services), got) +} + +/// A .pptx with `slides` slides, as the page would send it. +fn pptx(slides: usize) -> Vec<u8> { + let mut s = Session::with_new(); + while s.doc().unwrap().doc.slides.len() < slides { + s.execute("slide.new", &json!({})).unwrap(); + } + deckcraft_engine::cmd::file::save_bytes(&s.doc().unwrap().doc, "pptx").unwrap() +} + +fn edit(app: &mut SlideApp) { + app.session.execute("slide.new", &json!({})).unwrap(); + assert!(app.session.active().unwrap().is_dirty()); +} + +fn calls(got: &Got) -> Vec<(String, bool)> { + got.borrow().iter().map(|(n, s, _)| (n.clone(), *s)).collect() +} + +fn path(app: &SlideApp) -> Option<String> { + app.session.active().and_then(|d| d.path.clone()) +} + +/// The bug this prevents: Save of a .pptx the page sent came back as `<name>.deckcraft`. Save +/// now hands the page the opened file under its own name and format, not as a new file; Save As +/// says it is a new file and becomes the file the next Save writes. +#[test] +fn host_saves_go_back_to_the_opened_file() { + let (mut app, got) = host_app(false); + app.open_from_host(Some("Lecture 3.pptx"), &pptx(2)); + assert_eq!(app.session.documents().len(), 1, "the untouched blank presentation gave way"); + edit(&mut app); + app.save(); + assert!(!app.session.active().unwrap().is_dirty()); + edit(&mut app); + app.save_as_dialog("deckcraft"); + assert!(!app.session.active().unwrap().is_dirty()); + edit(&mut app); + app.save(); + let names = [("Lecture 3.pptx", false), ("Lecture 3.deckcraft", true), ("Lecture 3.deckcraft", false)]; + assert_eq!(calls(&got), names.map(|(n, s)| (n.to_string(), s))); + // The first save is a .pptx that reopens with the edit in it. + let first = got.borrow()[0].2.clone(); + assert!(first.windows(20).any(|w| w == b"ppt/presentation.xml"), "Save writes PowerPoint, not .deckcraft"); + let reopened = deckcraft_engine::cmd::file::loaded_file("Lecture 3.pptx", &first).unwrap(); + assert_eq!(reopened.doc.slides.len(), 3); +} + +/// A presentation the page never sent is a new file, as Save As: the page must not overwrite a +/// file of the same name. The next Save goes back to it. +#[test] +fn host_save_of_an_untitled_presentation_is_save_as() { + let (mut app, got) = host_app(false); + let name = format!("{}.deckcraft", app.session.active().unwrap().title()); + edit(&mut app); + app.save(); + edit(&mut app); + app.save(); + assert_eq!(calls(&got), [(name.clone(), true), (name, false)]); +} + +/// A presentation the user dropped (or picked with File › Open) didn't come from the page, so +/// its name isn't one the page holds: Save makes a new file. +#[test] +fn a_file_the_page_never_sent_saves_as_a_new_file() { + let (mut app, got) = host_app(false); + app.open_or_insert_bytes("dropped.pptx", &pptx(1)); + app.save(); + assert_eq!(calls(&got), [("dropped.deckcraft".to_string(), true)]); +} + +/// Exports and Print are copies: named after the presentation, not a new file, and the +/// presentation keeps its own file and its unsaved changes. +#[test] +fn host_exports_and_print_are_copies() { + let (mut app, got) = host_app(false); + app.open_from_host(Some("deck.pptx"), &pptx(1)); + edit(&mut app); + assert!(app.export_as("pdf", json!({}))); + assert!(app.print_pdf(json!({}))); + assert_eq!(calls(&got), [("deck.pdf".to_string(), false), ("deck.pdf".to_string(), false)]); + assert!(app.session.active().unwrap().is_dirty()); + assert_eq!(path(&app).as_deref(), Some("deck.pptx")); +} + +/// The page not getting the file is a failed save: the presentation keeps its changes. +#[test] +fn a_host_save_that_fails_leaves_the_presentation_unsaved() { + let (mut app, _) = host_app(true); + app.open_from_host(Some("deck.pptx"), &pptx(1)); + edit(&mut app); + app.save(); + assert!(app.session.active().unwrap().is_dirty()); + assert!(app.status.as_ref().is_some_and(|(m, _)| m.contains("Couldn't save deck.pptx"))); +} + +/// Only an untouched start presentation gives way: one with changes stays open beside the file. +#[test] +fn an_edited_start_presentation_stays_open() { + let (mut app, _) = host_app(false); + edit(&mut app); + app.open_from_host(Some("deck.pptx"), &pptx(1)); + assert_eq!(app.session.documents().len(), 2); + assert_eq!(path(&app).as_deref(), Some("deck.pptx")); +} + +/// The command palette runs `file.save` by id. With a file of its own the engine would write to +/// that path, which a browser can't; in host mode it goes to the page like Ctrl+S. +#[test] +fn palette_save_goes_to_the_page() { + let (mut app, got) = host_app(false); + app.open_from_host(Some("deck.pptx"), &pptx(1)); + edit(&mut app); + let r = app.run("file.save", json!({})).unwrap(); + assert_eq!(r["path"], "deck.pptx"); + assert_eq!(calls(&got), [("deck.pptx".to_string(), false)]); + assert!(!app.session.active().unwrap().is_dirty()); +} + +/// A file the page sent without a name, or with a name that isn't a presentation's, has no file +/// of its own: Save is a new `.deckcraft`, never an overwrite of an invented `Presentation.pptx`. +#[test] +fn a_file_sent_without_a_presentation_name_saves_as_a_new_file() { + for (name, saved) in [(None, "Presentation.deckcraft"), (Some("Talk"), "Talk.deckcraft")] { + let (mut app, got) = host_app(false); + app.open_from_host(name, &pptx(2)); + assert_eq!(app.session.documents().len(), 1, "{name:?}"); + assert_eq!(app.session.active().unwrap().doc.slides.len(), 2, "{name:?}"); + assert_eq!(path(&app), None, "{name:?}"); + app.save(); + assert_eq!(calls(&got), [(saved.to_string(), true)], "{name:?}"); + } +} + +/// An outline from the page opens as a new untitled presentation, as File › Open does on the +/// desktop: the blank start presentation gives way, and Save is a new file. +#[test] +fn an_outline_from_the_page_opens_as_a_new_presentation() { + let (mut app, got) = host_app(false); + app.open_from_host(Some("notes.md"), b"# One\n\n# Two\n\n# Three\n"); + assert_eq!(app.session.documents().len(), 1); + assert_eq!(app.session.active().unwrap().doc.slides.len(), 3); + assert_eq!(path(&app), None); + app.save(); + assert_eq!(calls(&got), [("notes.deckcraft".to_string(), true)]); +} + +/// A damaged file from the page opens as an untitled "(Repaired)" copy, so Save is a new file +/// and can't overwrite the page's original with the emptied media. +#[test] +fn a_damaged_file_from_the_page_saves_as_a_new_repaired_file() { + let mut p = deckcraft_model::Presentation::default(); + p.add_media("a.png", "image/png", b"PICTURE-BYTES-0123456789".to_vec()); + let mut bad = deckcraft_engine::cmd::file::save_bytes(&p, "deckcraft").unwrap(); + // Pictures are stored as they are, so flipping a byte breaks the entry's CRC. + let at = bad.windows(13).position(|w| w == b"PICTURE-BYTES").unwrap(); + bad[at] ^= 0xff; + let (mut app, got) = host_app(false); + app.open_from_host(Some("talk.deckcraft"), &bad); + assert_eq!(path(&app), None); + assert!(app.session.active().unwrap().title().ends_with("(Repaired)")); + app.save(); + assert_eq!(calls(&got), [("talk (Repaired).deckcraft".to_string(), true)]); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5f624d9c0..0f0e664f8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -72,7 +72,7 @@ pub use panels::notes; pub use panels::selpane; pub use panels::thumbs; pub use ribbon::qat; -pub use services::{DownloadFn, Inbox, InboxEvent, InboxFile, OpenAsyncFn, PickFn, ReadFn, Services, WriteFn}; +pub use services::{DownloadFn, HostSaveFn, Inbox, InboxEvent, InboxFile, OpenAsyncFn, PickFn, ReadFn, Services, WriteFn}; use state::{FilePlace, FilePurpose, ImeDescriptorKey, ImeDestination, ImeTerminalStamp}; pub use state::{RECENT_MAX, UiState, ViewMode, ZOOM_RANGE}; @@ -487,5 +487,8 @@ mod datetime_tests; #[cfg(test)] mod inbox_tests; +#[cfg(test)] +mod host_save_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index fc8eb5d96..b6f8a0f50 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -11,6 +11,10 @@ pub type OpenAsyncFn = Box<dyn FnMut(&str, u64)>; pub type DownloadFn = Box<dyn FnMut(&str, &[u8])>; +/// [`Services::host_save`]: `(file name, bytes, save_as)`. An error means the page didn't get +/// the file, and the save failed. +pub type HostSaveFn = Box<dyn FnMut(&str, &[u8], bool) -> Result<(), String>>; + /// A file the host finished reading for the request `id` from [`SlideApp::begin_external_file`]. #[derive(Clone, Debug)] pub struct InboxFile { @@ -49,6 +53,15 @@ pub struct Services { pub open_async: Option<OpenAsyncFn>, /// Hand bytes to the user as a named file (browser download). pub download: Option<DownloadFn>, + /// Web, framed by a page that keeps the files (`?host=parent`): Save and Save As hand the + /// presentation to that page instead of downloading it, with whether it is a new file + /// ([`HostSaveFn`]). Save writes a presentation the page sent back under its own name and + /// format, as the desktop app writes back to the file it opened; a presentation the page + /// never sent (an untitled one, a repaired copy) goes as a new `.deckcraft` file, as Save + /// suggests on the desktop. Save As (.pptx or .deckcraft) is always a new file. Either way the + /// presentation is then that file, and the next Save goes to it. Exports and Print still go + /// through `download`, which the host also points at the page: they are copies. + pub host_save: Option<HostSaveFn>, pub inbox: Option<Inbox>, /// Image on the system clipboard (PNG bytes), when the host can read one. pub clipboard_image: Option<Box<dyn FnMut() -> Option<Vec<u8>>>>, diff --git a/packaging/web/README.md b/packaging/web/README.md index 3b4f9a231..e9622f5aa 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -65,12 +65,74 @@ Local test: `python3 -m http.server 8765` inside the folder, then open http://lo - The app fills the iframe and follows its size, so size the iframe and not the app. - Keyboard shortcuts go to the iframe after the user clicks into it, as with any embedded app. - **Cross-origin embeds** work. The web build keeps no preferences between visits; it starts - with the sample deck (or `?blank`) every time. + with the sample deck (or `?blank`) every time. Opening and saving through the page + (`?host=parent`, below) needs the same origin. - **Sandboxed iframes** need at least `sandbox="allow-scripts allow-same-origin allow-downloads allow-popups"`. Without `allow-downloads`, Save and Export (browser - downloads) are blocked. + downloads) are blocked. With `?host=parent`, `allow-scripts allow-same-origin` is enough for + opening and saving (without `allow-same-origin` the frame's origin is `null` and there is no + bridge), and `allow-downloads` isn't needed. - Don't send `X-Frame-Options: DENY` or a `frame-ancestors` CSP that excludes the embedding page. +## Opening and saving through the page (`?host=parent`) + +A page that keeps the files itself (a Nextcloud app, a file server) can frame DeckCraft with +`?host=parent` on the iframe `src`, hand it a presentation and take back what it saves, instead of +the user downloading. GridCraft, WordCraft and PdfCraft have the same bridge with their own prefix. +The page and DeckCraft must be on the **same origin**: DeckCraft only hears and answers its parent +window on its own origin, and without one it downloads as usual. + +Messages are plain objects with a `type`: + +| Message | Direction | Fields | +|---|---|---| +| `deckcraft:ready` | to the page | `version`. The app runs and listens: send the file now. | +| `deckcraft:open` | from the page | `name` (a bare file name, such as `Talk.pptx`), `bytes` (`ArrayBuffer` or `Uint8Array`). Opens like File › Open: a presentation (.pptx, .potx, .ppsx, .deckcraft) has that name as its file; an outline (.txt, .md, .rtf), a file sent without a name and a damaged file open untitled. | +| `deckcraft:save` | to the page | `name`, `saveAs`, `bytes` (a transferred `ArrayBuffer`), for every file DeckCraft would otherwise download. The page stores it. | +| `deckcraft:dirty` | to the page | `dirty`, whenever unsaved changes appear or go away. | +| `deckcraft:failed` | to the page | `error`, when the app couldn't start (no WebGPU or WebGL2). | + +`saveAs` says whether the file becomes the presentation's file, as on the desktop: + +- **Save** sends the file the page sent, under its own name and format (`Talk.pptx` comes back + as `Talk.pptx`), with `saveAs: false`. DeckCraft keeps only the part after the last `/`, so + `docs/Talk.pptx` also comes back as `Talk.pptx`. A presentation that has no file the page sent + (a new one, an outline, a file sent without a name, a file the user dropped, a repaired copy of + a damaged file) is a new file with `saveAs: true`: Ctrl+S names it `<title>.deckcraft` as Save + suggests on the desktop, and File › Save opens the Save As page first, as on the desktop. +- **Save As** (.pptx or .deckcraft) sends `saveAs: true`. The presentation is now that file; the + next Save sends its name with `saveAs: false`. +- **Exports and Print** (PDF, handouts, pictures, outline, GIF) send `saveAs: false` and are + copies: the presentation keeps its file and its unsaved changes. + +`saveAs: false` doesn't mean "safe to overwrite": an export is `false` under a name the page may +already hold (`Talk.pdf`, or `Talk.pptx` exported from a presentation that is now +`Talk.deckcraft`). Replace a file without asking only when the name is the one the page sent, or +the name of the last `saveAs: true` file it stored for this presentation; ask for anything else. +DeckCraft doesn't learn the name the page finally stores a Save As under, so a page that renames +on a conflict should map later Saves of the old name itself. + +In host mode DeckCraft starts with an empty presentation instead of the sample, and the first +presentation the page sends takes its place. The page guards leaving itself (DeckCraft adds no +guard of its own), and `&author=Name` signs the user's comments. + +```html +<iframe id="deck" src="/deckcraft/?host=parent&author=Ada" style="width: 100%; height: 720px; border: 0;"></iframe> +<script> + const frame = document.getElementById("deck"); + addEventListener("message", async (e) => { + if (e.origin !== location.origin || e.source !== frame.contentWindow) return; + if (e.data.type === "deckcraft:ready") { + const bytes = await (await fetch("/files/Talk.pptx")).arrayBuffer(); + frame.contentWindow.postMessage({ type: "deckcraft:open", name: "Talk.pptx", bytes }, location.origin, [bytes]); + } else if (e.data.type === "deckcraft:save") { + // Store e.data.bytes as e.data.name. Replace silently only when !e.data.saveAs and the name + // is the one sent (or the last saveAs file stored); ask before replacing anything else. + } + }); +</script> +``` + ## Renderer selection and fallback flags DeckCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to @@ -82,6 +144,7 @@ DeckCraft renders with wgpu. It uses **WebGPU** when the browser has it and fall | `?webgl` | Force the WebGL2 backend (useful when a WebGPU driver misbehaves) | | `?blank` | Start with an empty presentation instead of the sample deck | | `?show` | Start the slide show immediately (kiosk/embedded decks) | +| `?host=parent` | Open and save through the framing page ([above](#opening-and-saving-through-the-page-hostparent)); `&author=` names the user | For example: `<iframe src="https://example.com/deckcraft/?webgl" ...>`. From a72a5167d0fddf51a4b915e8a08e0d028ea8b72f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 19:59:29 -0500 Subject: [PATCH 18/94] Morph: pick the next curve to split from a heap, not a full scan (#1782) --- crates/geom/src/morph.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/geom/src/morph.rs b/crates/geom/src/morph.rs index 411da5f93..154db5e87 100644 --- a/crates/geom/src/morph.rs +++ b/crates/geom/src/morph.rs @@ -126,6 +126,21 @@ fn split_curve(c: &[Point], n: usize, out: &mut Vec<Point>) { out.extend([p1, p2, p3]); } +/// A piece length ordered totally, so it can sit in a heap. +#[derive(PartialEq)] +struct Share(f64); +impl Eq for Share {} +impl PartialOrd for Share { + fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(o)) + } +} +impl Ord for Share { + fn cmp(&self, o: &Self) -> std::cmp::Ordering { + self.0.total_cmp(&o.0) + } +} + /// Brings a contour to `n` curves. Unlike manim (which splits every curve equally often), the extra /// splits go to the longest pieces, so a long side gets more points than a short one. fn refine(c: &Contour, n: usize) -> Contour { @@ -136,11 +151,15 @@ fn refine(c: &Contour, n: usize) -> Contour { let curves: Vec<&[Point]> = (0..have).filter_map(|k| c.pts.get(3 * k..3 * k + 4)).collect(); let len: Vec<f64> = curves.iter().map(|q| curve_length(q) + 1e-9).collect(); let mut parts = vec![1usize; curves.len()]; + // The curve with the longest piece gets the next split (the lowest index on a tie); a heap keeps + // this O(n log n) instead of rescanning every curve for each split. + let mut heap: std::collections::BinaryHeap<(Share, std::cmp::Reverse<usize>)> = + len.iter().enumerate().map(|(k, l)| (Share(*l), std::cmp::Reverse(k))).collect(); for _ in 0..n - have { - let share = |k: usize| len.get(k).copied().unwrap_or(0.0) / parts.get(k).copied().unwrap_or(1) as f64; - let best = (1..curves.len()).fold(0, |b, k| if share(k) > share(b) { k } else { b }); + let Some((_, std::cmp::Reverse(best))) = heap.pop() else { break }; if let Some(p) = parts.get_mut(best) { *p += 1; + heap.push((Share(len.get(best).copied().unwrap_or(0.0) / *p as f64), std::cmp::Reverse(best))); } } let mut out = Vec::with_capacity(1 + 3 * n); @@ -420,6 +439,16 @@ mod tests { assert_eq!(contours(&to_path(&cs)), cs); } + #[test] + fn refine_many_curves_finishes_at_the_asked_count() { + let mut c = Contour { closed: false, pts: vec![Point::ZERO] }; + for i in 1..=20_000 { + line_to(&mut c.pts, Point::new(f64::from(i), f64::from(i % 7))); + } + let r = refine(&c, 40_000); + assert_eq!(r.curves(), 40_000); + } + #[test] fn refine_splits_the_longest_curves_and_keeps_the_shape() { let c = Contour { closed: false, pts: vec![Point::ZERO, Point::new(1.0, 0.0), Point::new(2.0, 0.0), Point::new(3.0, 0.0)] }; From 0233d2906424f024a89041f1f95c28c89eca20d9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 19:59:51 -0500 Subject: [PATCH 19/94] Spelling: bound a word's language and index results by offset (#1767) * engine: bound a word's language and index spelling results by offset * engine: pass the test run's text by value --- crates/engine/src/spell.rs | 50 ++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/spell.rs b/crates/engine/src/spell.rs index 2dda5c6f4..0eeaa6757 100644 --- a/crates/engine/src/spell.rs +++ b/crates/engine/src/spell.rs @@ -700,15 +700,29 @@ pub struct Word { pub repeated: Option<usize>, } +/// Longest language tag a word is checked in. BCP 47 tags in documents are a few bytes; a longer +/// value from a file is no language we have a dictionary for, and copying it into every word of +/// a paragraph would multiply it. +const MAX_LANG_LEN: usize = 64; + /// The words of `p`, each with its run's language (`lang` on the run, else `default`). Words /// with digits are skipped; apostrophes inside a word belong to it; hyphenated words are checked -/// part by part. +/// part by part. A language over [`MAX_LANG_LEN`] counts as none. pub fn paragraph_words(p: &deckcraft_model::Paragraph, default: &str) -> Vec<Word> { let mut chars: Vec<(char, usize)> = vec![]; for (ri, r) in p.runs.iter().enumerate() { chars.extend(r.content().chars().map(|c| (c, ri))); } - let lang_of = |ri: usize| p.runs.get(ri).and_then(|r| r.props.lang.clone()).filter(|l| !l.is_empty()).unwrap_or_else(|| default.to_string()); + let default = if default.len() > MAX_LANG_LEN { "" } else { default }; + let lang_of = |ri: usize| { + p.runs + .get(ri) + .and_then(|r| r.props.lang.as_deref()) + .filter(|l| !l.is_empty()) + .map(|l| if l.len() > MAX_LANG_LEN { "" } else { l }) + .unwrap_or(default) + .to_string() + }; // Combining marks (decomposed accents) belong to the letter before them. let inside = |c: char| c.is_alphanumeric() || deckcraft_model::words::is_combining_mark(c) || c == '\'' || c == '’' || c == '-'; let mut out = vec![]; @@ -791,15 +805,18 @@ pub fn misspelt(p: &deckcraft_model::Paragraph, default: &str, ignore: &[String] .chain(repeated(p, default)) .collect::<Vec<_>>() .into_iter() - .fold(vec![], |mut v: Vec<Word>, w| { + .fold((vec![], HashMap::new()), |(mut v, mut at): (Vec<Word>, HashMap<usize, usize>), w| { // A repeated misspelt word is reported once, as repeated. - if let Some(i) = v.iter().position(|x| x.start == w.start) { - v[i] = w; - } else { - v.push(w); + match at.get(&w.start).and_then(|&i| v.get_mut(i)) { + Some(x) => *x = w, + None => { + at.insert(w.start, v.len()); + v.push(w); + } } - v + (v, at) }) + .0 } /// Use `d` for `lang` from now on in this process (a dictionary the app loaded itself). @@ -953,6 +970,23 @@ SFX D Y 1\nSFX D 0 ed/S .\n"; assert_eq!(w, vec!["check", "done"]); } + #[test] + fn a_long_paragraph_with_a_huge_language_is_checked_in_linear_work() { + use deckcraft_model::{Paragraph, Run, RunProps}; + // 100,000 copies of one word under a 1 MB language value: every word after the first is + // a repeat, and no word carries a copy of the value. + let lang = "x".repeat(1 << 20); + let p = + Paragraph { runs: vec![Run::with("the ".repeat(100_000), RunProps { lang: Some(lang), ..Default::default() })], ..Default::default() }; + let words = paragraph_words(&p, "en-US"); + assert_eq!(words.len(), 100_000); + assert!(words.iter().all(|w| w.lang.is_empty())); + let bad = misspelt(&p, "en-US", &[]); + assert_eq!(bad.len(), 99_999); + assert!(bad.iter().all(|w| w.repeated.is_some())); + assert!(paragraph_words(&Paragraph::new("word"), &"y".repeat(100)).iter().all(|w| w.lang.is_empty())); + } + #[test] fn long_and_numeric_flags_and_latin1() { let d = Dictionary::parse(b"FLAG long\nSFX Aa Y 1\nSFX Aa 0 s .\n", b"1\ncat/Aa\n"); From 872cdbf33136545699bdfa280dbbebbb6cbd9557 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:04:49 -0500 Subject: [PATCH 20/94] pptx: take nested math text once and check an object's part for relationships once (#1762) --- crates/pptx/src/read.rs | 5 +++++ crates/pptx/src/read/dml.rs | 31 ++++++++++++++++++++++++++----- crates/pptx/src/read/shapes.rs | 3 ++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 288e497f8..2056d53d7 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -46,6 +46,9 @@ pub struct Imp<'a> { pub tag_bytes: usize, /// The tag budget ran out and the warning was given. pub tags_capped: bool, + /// Whether a part has relationships of its own, by normalized part name: looked up once + /// however many embedded objects point at the part. + pub has_rels: HashMap<String, bool>, } impl Imp<'_> { @@ -446,6 +449,7 @@ pub fn import_theme(bytes: &[u8]) -> Result<(deckcraft_model::theme::Theme, Vec< tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + has_rels: HashMap::new(), }; let part = Part::new(&pkg, &theme_path, &doc); let theme = theme::read_theme(&mut imp, &part, &doc.root); @@ -487,6 +491,7 @@ pub fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec<String>), PptxE tags_by_part: HashMap::new(), tag_bytes: 0, tags_capped: false, + has_rels: HashMap::new(), }; // Slide ids first so hyperlinks anywhere can point at slides. let slide_ids = register_slides(&mut imp, &docs, &slide_entries, &mut lost_slides); diff --git a/crates/pptx/src/read/dml.rs b/crates/pptx/src/read/dml.rs index 2d82fa36a..c8902e4c7 100644 --- a/crates/pptx/src/read/dml.rs +++ b/crates/pptx/src/read/dml.rs @@ -664,12 +664,22 @@ fn push_text_runs(para: &mut Paragraph, props: RunProps, text: &str) { /// Appends an Office Math (a14:m) run: its plain text and its OMML. fn push_math_run(para: &mut Paragraph, part: &Part, e: &El) { if para.runs.len() < MAX_PARAGRAPH_RUNS { - let mut text = String::new(); - let mut ts = vec![]; - e.find_all("t", &mut ts); - for t in ts { - text.push_str(&t.text()); + // The text of the outermost `t` elements: a `t` nested in another is already part of + // the outer one's text, and taking it again would copy it once per nesting level. + fn outer_t(e: &El, depth: usize, text: &mut String) { + if depth > crate::xml::MAX_DEPTH { + return; + } + for c in e.elements() { + if c.is("t") { + text.push_str(&c.text()); + } else { + outer_t(c, depth + 1, text); + } + } } + let mut text = String::new(); + outer_t(e, 0, &mut text); let omml = e.elements().map(|c| part.keep_inner(c)).collect::<String>(); para.runs.push(Run { text, props: RunProps::default(), kind: RunKind::Math { omml } }); } @@ -714,6 +724,17 @@ mod tests { use super::*; use crate::xml::parse; + #[test] + fn nested_math_text_is_taken_once() { + // 200 `m:t` nested in each other around one word: the word, not 200 copies of it. + let x = format!(r#"<a14:m xmlns:a14="a" xmlns:m="m"><m:oMath>{}word{}</m:oMath></a14:m>"#, "<m:t>".repeat(200), "</m:t>".repeat(200)); + let d = parse(x.as_bytes()).unwrap(); + let part = Part { name: "ppt/slides/slide1.xml".into(), rels: Default::default(), ns: vec![], inner_ns: vec![] }; + let mut para = Paragraph::default(); + push_math_run(&mut para, &part, &d.root); + assert_eq!(para.runs[0].text, "word"); + } + #[test] fn colors_and_transforms() { let d = parse( diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index b3e3d48e6..3230db100 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -475,7 +475,8 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S .into_iter() .map(|id| { let rel = part.rels.get(&id).filter(|r| !r.external)?; - if !imp.pkg.rels(&rel.target).items.is_empty() { + let pkg = imp.pkg; + if *imp.has_rels.entry(crate::opc::norm(&rel.target)).or_insert_with(|| !pkg.rels(&rel.target).items.is_empty()) { return None; } let (kind, target) = (rel.ty.clone(), rel.target.clone()); From d2a8be197d1e5674f6fcf2193e38f8a97898380a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:05:11 -0500 Subject: [PATCH 21/94] geom: measure each follow band once when mapping warped lines (#1758) --- crates/geom/src/warp.rs | 28 +++++++++++++++++++--------- crates/geom/src/warp/tests.rs | 17 +++++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index d3035d512..81376d7d7 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -928,11 +928,25 @@ impl Warp { k_fill = 1.0; } zoom = zoom.max(k_fill); + // Per band, measured once: its widest line and its first and last lines' baselines. + let mut stats: Vec<Option<(f64, f64, f64)>> = vec![None; nb]; + for (l, &b) in lines.iter().zip(&band_of) { + let w = l.extent.1 - l.extent.0; + if let Some(slot) = stats.get_mut(b) { + match slot { + Some((widest, _, last)) => { + *widest = widest.max(w); + *last = l.ref_y; + } + None => *slot = Some((0.0f64.max(w), l.ref_y, l.ref_y)), + } + } + } let mut maps = Vec::with_capacity(n); let mut offsets = Vec::new(); for (i, l) in lines.iter().enumerate() { let b = band_of.get(i).copied().unwrap_or(0); - let in_band = |j: &usize| band_of.get(*j) == Some(&b); + let band = stats.get(b).copied().flatten(); match self.bands.get(b) { Some(Band::Fill { .. }) | None => { let (y0, y1) = band_y.get(b).copied().flatten().unwrap_or((0.0, 1.0)); @@ -941,16 +955,12 @@ impl Warp { } Some(Band::Follow { path, anchor }) => { let len = path.length(); - let widest = (0..n).filter(in_band).filter_map(|j| lines.get(j)).map(|l| l.extent.1 - l.extent.0).fold(0.0, f64::max); + let widest = band.map_or(0.0, |s| s.0); let k = if widest > len && widest > 1e-9 { len / widest } else { 1.0 }; - let members: Vec<&WarpLine> = (0..n).filter(in_band).filter_map(|j| lines.get(j)).collect(); let ref_y = match anchor { - LineAnchor::Last => members.last().map(|l| l.ref_y), - LineAnchor::First => members.first().map(|l| l.ref_y), - LineAnchor::Middle => match (members.first(), members.last()) { - (Some(a), Some(z)) => Some((a.ref_y + z.ref_y) / 2.0), - _ => None, - }, + LineAnchor::Last => band.map(|s| s.2), + LineAnchor::First => band.map(|s| s.1), + LineAnchor::Middle => band.map(|s| (s.1 + s.2) / 2.0), } .unwrap_or(l.ref_y); // Lines off the guide run on a parallel curve at their natural length. diff --git a/crates/geom/src/warp/tests.rs b/crates/geom/src/warp/tests.rs index c85b2b0ae..c4aa1bbd0 100644 --- a/crates/geom/src/warp/tests.rs +++ b/crates/geom/src/warp/tests.rs @@ -319,3 +319,20 @@ fn arch_and_inflate_handles_follow_the_pointer() { assert!(more > adjust_defaults("textInflate")[0], "{more}"); assert!((more - 20_000.0).abs() < 1.0, "{more}"); } + +#[test] +fn many_lines_on_a_follow_band_are_mapped_from_one_measurement() { + // 50,000 lines on an arch: each line's scale and anchor come from the band measured once. + let w = warp("textArchUp", &[], rect()).unwrap(); + let inner = Rect::new(7.2, 3.6, W - 7.2, H - 3.6); + let lines: Vec<WarpLine> = (0..50_000) + .map(|i| { + let y = i as f64 * 0.01; + WarpLine { ink: Some(Rect::new(190.0, y, 230.0, y + 1.0)), extent: (190.0, 230.0), ref_y: y + 1.0 } + }) + .collect(); + let m = w.mapper(&lines, inner); + // The last line sits on the arc, as with two lines. + let last = lines.len() - 1; + assert!(m.map(last, Point::new(210.0, lines[last].ref_y)).y.abs() < 0.05); +} From 65d5c28512a4fb452e6d99d6d265eacfdb29bcc5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:05:32 -0500 Subject: [PATCH 22/94] Text: sort a paragraph's tab stops once and find the next by binary search (#1757) * text: sort a paragraph's tab stops once and find the next by binary search * address review: skip the tab-stop lookup for a NaN position --- crates/text/src/breaking.rs | 41 ++++++++++++++++++++++++++----------- crates/text/src/tests.rs | 10 +++++++++ 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/crates/text/src/breaking.rs b/crates/text/src/breaking.rs index bb764b64c..9a6028876 100644 --- a/crates/text/src/breaking.rs +++ b/crates/text/src/breaking.rs @@ -260,12 +260,15 @@ pub(crate) struct Tab { align: TabAlign, } +/// The paragraph's tab stops in position order (a stop at no finite position is left out), so +/// [`tab_advance`] finds the next one by binary search instead of a scan per tab. pub(crate) fn tabs_of(props: &ParaProps) -> Vec<Tab> { - props + let mut tabs: Vec<Tab> = props .tabs .as_ref() .map(|t| { t.iter() + .filter(|s| s.pos.is_finite()) .map(|s| Tab { pos: s.pos, align: match s.align.as_str() { @@ -277,7 +280,9 @@ pub(crate) fn tabs_of(props: &ParaProps) -> Vec<Tab> { }) .collect() }) - .unwrap_or_default() + .unwrap_or_default(); + tabs.sort_by(|a, b| a.pos.total_cmp(&b.pos)); + tabs } /// Width of the text after the tab at cell `i` up to the next tab or line break, and the width of @@ -301,18 +306,30 @@ pub(crate) fn tab_segment(cells: &[Cell], i: usize) -> (f64, f64) { /// (`seg`: its width, and its width before the decimal point) as the stop aligns it but never /// moving back, as PowerPoint does; past the last stop, to the next default stop. pub(crate) fn tab_advance(x: f64, stops: &[Tab], default_tab: f64, seg: (f64, f64)) -> f64 { - for s in stops { - if s.pos > x + 0.5 { - let to = s.pos - x; - return match s.align { - TabAlign::Left => to, - TabAlign::Right => (to - seg.0).max(0.0), - TabAlign::Center => (to - seg.0 / 2.0).max(0.0), - TabAlign::Decimal => (to - seg.1).max(0.0), - }; - } + // `stops` is in position order (`tabs_of`): the next stop is the first past x. + // A NaN `x` (a NaN spacing upstream) skips the lookup and takes the finite default-stop path. + if let Some(s) = stops.get(stops.partition_point(|s| s.pos <= x + 0.5)).filter(|_| !x.is_nan()) { + let to = s.pos - x; + return match s.align { + TabAlign::Left => to, + TabAlign::Right => (to - seg.0).max(0.0), + TabAlign::Center => (to - seg.0 / 2.0).max(0.0), + TabAlign::Decimal => (to - seg.1).max(0.0), + }; } let d = if default_tab > 1.0 { default_tab } else { 72.0 }; let next = ((x / d).floor() + 1.0) * d; (next - x).max(1.0) } + +#[cfg(test)] +mod tab_tests { + use super::*; + + #[test] + fn a_nan_position_takes_the_finite_default_stop() { + let stops = [Tab { pos: 100.0, align: TabAlign::Left }]; + assert!(tab_advance(f64::NAN, &stops, 72.0, (0.0, 0.0)).is_finite()); + assert_eq!(tab_advance(10.0, &stops, 72.0, (0.0, 0.0)), 90.0); + } +} diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 7dbdbe4f0..a747af045 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1416,6 +1416,16 @@ fn tab_stops_align_the_text_after_them() { assert!((l.lines[0].edges[4].0 - x0(&l) - 72.0).abs() < 0.01); } +#[test] +fn many_tabs_over_many_stops_lay_out_by_position() { + // 20,000 stops given out of order, and 2,000 tabs: each tab finds the next stop by position. + let mut stops: Vec<(f64, &str)> = (1..=20_000).rev().map(|k| (k as f64 * 0.05 + 30.0, "l")).collect(); + stops.push((f64::NAN, "l")); + let text = "a\t".repeat(2_000); + let l = tabbed(&text, &stops, 1.0e6); + assert!((l.lines[0].edges[2].0 - l.inner.x0 - 30.05).abs() < 0.01, "{:?}", &l.lines[0].edges[..3]); +} + #[test] fn a_tab_past_the_end_moves_to_the_next_line() { // PowerPoint: "abcdefghij\tk\tl\tm…" in a narrow box puts the tab that doesn't fit on the next From c6b7de43bc4e69d8a654156bdc7c8c4c47d5508a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:05:53 -0500 Subject: [PATCH 23/94] engine: use sets for slide-range expansion, added slide selection and repeated-word offsets (#1756) --- crates/engine/src/cmd/file.rs | 13 ++++++++++++- crates/engine/src/cmd/review.rs | 2 +- crates/engine/src/cmd/slide.rs | 3 ++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8943eb9a3..4f8580c86 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -397,6 +397,7 @@ pub fn pdf_options(p: &Value, count: usize) -> Result<deckcraft_pdf::PdfOptions> pub fn parse_slide_range(text: &str, count: usize) -> Result<Vec<usize>> { let invalid = || bad("file.export", format!("“{text}” isn't a valid slide range: use numbers and ranges such as 1-3, 5")); let mut out: Vec<usize> = vec![]; + let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new(); for part in text.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { let (a, b) = match part.split_once('-') { Some((a, b)) => (a.trim(), b.trim()), @@ -412,7 +413,7 @@ pub fn parse_slide_range(text: &str, count: usize) -> Result<Vec<usize>> { return Err(bad("file.export", format!("the presentation has {count} slides; “{part}” is outside them"))); } for i in lo - 1..hi { - if !out.contains(&i) { + if seen.insert(i) { out.push(i); } } @@ -776,6 +777,16 @@ mod tests { use super::{parse_slide_range, write_file}; + #[test] + fn broad_and_repeated_slide_ranges_expand_once() { + // 200 copies of a 100,000-slide range: each index once, in order, without a scan per index. + let text = vec!["1-100000"; 200].join(","); + let v = parse_slide_range(&text, 100_000).unwrap(); + assert_eq!(v.len(), 100_000); + assert!(v.windows(2).all(|w| w[0] < w[1])); + assert_eq!(parse_slide_range("3, 1-3, 2", 3).unwrap(), vec![2, 0, 1]); + } + #[test] fn slide_range_rejects_plus_sign() { assert!(parse_slide_range("+2", 3).is_err()); diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index 92637741f..47cf1ff24 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -367,7 +367,7 @@ fn spelling(s: &mut Session, p: &Value) -> Result<Value> { } out.push(v); } - let rep: Vec<usize> = crate::spell::repeated(para, &default).iter().map(|w| w.start).collect(); + let rep: std::collections::HashSet<usize> = crate::spell::repeated(para, &default).iter().map(|w| w.start).collect(); for w in crate::spell::paragraph_words(para, &default) { if ignore.contains(&w.text.to_lowercase()) || rep.contains(&w.start) { continue; diff --git a/crates/engine/src/cmd/slide.rs b/crates/engine/src/cmd/slide.rs index 198f1bc6c..f15cf32fa 100644 --- a/crates/engine/src/cmd/slide.rs +++ b/crates/engine/src/cmd/slide.rs @@ -408,8 +408,9 @@ fn select_slides(s: &mut Session, p: &Value) -> Result<Value> { }; s.select(|doc, sel| { if add { + let mut have: std::collections::HashSet<_> = sel.slides.iter().copied().collect(); for i in &ids { - if !sel.slides.contains(i) { + if have.insert(*i) { sel.slides.push(*i); } } From f5511d93b60ab0e1803fca825c97b079d56d2462 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:12:03 -0500 Subject: [PATCH 24/94] Compare: index slide, shape and media lookups and compare each picture pair once (#1752) * engine: index review.compare lookups and compare each picture pair once * engine: keep the compare test's inserted slides empty --- crates/engine/src/compare.rs | 130 ++++++++++++++++++++++++++++++----- 1 file changed, 112 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/compare.rs b/crates/engine/src/compare.rs index bf8ccf4ac..cb89d08f5 100644 --- a/crates/engine/src/compare.rs +++ b/crates/engine/src/compare.rs @@ -121,9 +121,10 @@ pub fn diff(cur: &Presentation, rev: &Presentation, by_position: bool) -> Vec<Ch let cur_matched: HashSet<usize> = pairs.iter().map(|p| p.0).collect(); let rev_matched: HashSet<usize> = pairs.iter().map(|p| p.1).collect(); let mut out = vec![]; + let mut media = Media::new(cur, rev); for (i, j) in &pairs { let (Some(a), Some(b)) = (cur.slides.get(*i), rev.slides.get(*j)) else { continue }; - let details = slide_details(cur, a, rev, b); + let details = slide_details(cur, a, rev, b, &mut media); if !details.is_empty() { out.push(Change { kind: ChangeKind::Changed, slide: *i, number: i.saturating_add(1), only_in: None, revised: Some(*j), details }); } @@ -140,10 +141,18 @@ pub fn diff(cur: &Presentation, rev: &Presentation, by_position: bool) -> Vec<Ch }); } } + // Each revised slide's open match (the first pair naming it). + let mut rev_to_cur: HashMap<usize, usize> = HashMap::new(); + for p in &pairs { + rev_to_cur.entry(p.1).or_insert(p.0); + } + // After the open slide that matches the nearest matched revised slide before it. + let mut at = 0; for (j, s) in rev.slides.iter().enumerate() { + if let Some(i) = rev_to_cur.get(&j) { + at = i + 1; + } if !rev_matched.contains(&j) { - // After the open slide that matches the revised slide before it. - let at = (0..j).rev().find_map(|k| pairs.iter().find(|p| p.1 == k).map(|p| p.0 + 1)).unwrap_or(0); out.push(Change { kind: ChangeKind::Inserted, slide: at, @@ -174,8 +183,34 @@ fn shape_label(s: &Shape) -> String { if s.name.trim().is_empty() { format!("Shape {}", s.id.0) } else { s.name.clone() } } -fn media_bytes(p: &Presentation, id: MediaId) -> Option<&[u8]> { - p.media(id).map(|m| m.data.as_slice()) +/// Both decks' media bytes by id, and which picture pairs were already compared: a deck can +/// show one picture many times, and its bytes are compared once per pair. +struct Media<'a> { + cur: HashMap<MediaId, &'a [u8]>, + rev: HashMap<MediaId, &'a [u8]>, + same: HashMap<(MediaId, MediaId), bool>, +} + +impl<'a> Media<'a> { + fn new(cur: &'a Presentation, rev: &'a Presentation) -> Self { + // The first item with an id wins, as in `Presentation::media`. + let index = |p: &'a Presentation| { + let mut m = HashMap::new(); + for x in &p.media { + m.entry(x.id).or_insert(x.data.as_slice()); + } + m + }; + Media { cur: index(cur), rev: index(rev), same: HashMap::new() } + } + /// Whether the pictures (by media id, `None` for a shape that is not a picture) differ. + fn differ(&mut self, a: Option<MediaId>, b: Option<MediaId>) -> bool { + let (ba, bb) = (a.and_then(|x| self.cur.get(&x)), b.and_then(|y| self.rev.get(&y))); + match (a, b) { + (Some(x), Some(y)) if ba.is_some() && bb.is_some() => !*self.same.entry((x, y)).or_insert_with(|| ba == bb), + _ => ba.is_some() || bb.is_some(), + } + } } /// A shape without its ids (shape and media), for comparing across decks. @@ -204,7 +239,7 @@ fn turn(ctx: Option<&Ctx>, s: &Shape) -> (f64, bool, bool) { drawn_box(ctx, s).map_or((0.0, false, false), |x| (x.rot, x.flip_h, x.flip_v)) } -fn shape_details(cp: &Presentation, ca: Option<&Ctx>, a: &Shape, rp: &Presentation, cb: Option<&Ctx>, b: &Shape, out: &mut Vec<String>) { +fn shape_details(ca: Option<&Ctx>, a: &Shape, cb: Option<&Ctx>, b: &Shape, media: &mut Media, out: &mut Vec<String>) { let label = shape_label(b); let text = |s: &Shape| s.text.as_ref().map(|t| t.text()).unwrap_or_default(); let mut what = vec![]; @@ -234,11 +269,11 @@ fn shape_details(cp: &Presentation, ca: Option<&Ctx>, a: &Shape, rp: &Presentati if a.fill != b.fill || a.line != b.line || a.style != b.style || a.effects != b.effects { what.push("formatting"); } - let pic = |p: &Presentation, s: &Shape| match &s.kind { - ShapeKind::Picture { fill } => media_bytes(p, fill.media).map(|b| b.to_vec()), + let pic = |s: &Shape| match &s.kind { + ShapeKind::Picture { fill } => Some(fill.media), _ => None, }; - if pic(cp, a) != pic(rp, b) { + if media.differ(pic(a), pic(b)) { what.push("picture"); } // Anything the checks above do not cover (alt text, hidden, a link…) is reported too, also @@ -265,21 +300,32 @@ fn shape_details(cp: &Presentation, ca: Option<&Ctx>, a: &Shape, rp: &Presentati } } -fn slide_details(cp: &Presentation, a: &Slide, rp: &Presentation, b: &Slide) -> Vec<String> { +fn slide_details(cp: &Presentation, a: &Slide, rp: &Presentation, b: &Slide, media: &mut Media) -> Vec<String> { let mut out = vec![]; let mut used: HashSet<usize> = HashSet::new(); let (ca, cb) = (Ctx::for_slide(cp, a), Ctx::for_slide(rp, b)); + // The revised shapes by id (first wins) and by name (in order, with a cursor past used ones). + let mut by_id: HashMap<ShapeId, usize> = HashMap::new(); + let mut by_name: HashMap<&str, (Vec<usize>, usize)> = HashMap::new(); + for (k, x) in b.shapes.iter().enumerate() { + by_id.entry(x.id).or_insert(k); + if !x.name.is_empty() { + by_name.entry(x.name.as_str()).or_default().0.push(k); + } + } for sa in &a.shapes { - let k = b - .shapes - .iter() - .position(|x| x.id == sa.id) - .or_else(|| b.shapes.iter().enumerate().position(|(k, x)| !used.contains(&k) && x.name == sa.name && !x.name.is_empty())); + let k = by_id.get(&sa.id).copied().or_else(|| { + let (ks, next) = by_name.get_mut(sa.name.as_str())?; + while ks.get(*next).is_some_and(|k| used.contains(k)) { + *next += 1; + } + ks.get(*next).copied() + }); match k { Some(k) if !used.contains(&k) => { used.insert(k); if let Some(sb) = b.shapes.get(k) { - shape_details(cp, ca.as_ref(), sa, rp, cb.as_ref(), sb, &mut out); + shape_details(ca.as_ref(), sa, cb.as_ref(), sb, media, &mut out); } } _ => out.push(format!("{} deleted (only in the deck)", shape_label(sa))), @@ -334,19 +380,34 @@ pub fn adopt(doc: &mut Presentation, rev: &Presentation, slide: &Slide, replacin let mut sl = slide.clone(); // Media. let mut media_map: HashMap<MediaId, MediaId> = HashMap::new(); + // Both decks' media by id (the first item with an id wins, as in `Presentation::media`), + // looked up once per reference instead of searched. + let mut rev_at: HashMap<MediaId, usize> = HashMap::new(); + for (i, m) in rev.media.iter().enumerate() { + rev_at.entry(m.id).or_insert(i); + } + let mut doc_at: HashMap<MediaId, usize> = HashMap::new(); + for (i, m) in doc.media.iter().enumerate() { + doc_at.entry(m.id).or_insert(i); + } for id in crate::media_refs::slide_media(&sl) { - let Some(m) = rev.media(id) else { continue }; - match doc.media(id) { + let Some(m) = rev_at.get(&id).and_then(|&i| rev.media.get(i)) else { continue }; + match doc_at.get(&id).and_then(|&i| doc.media.get(i)) { Some(x) if x.data == m.data => {} None => { // Keeps the revision's id, so later ids must start past it. + doc_at.insert(id, doc.media.len()); doc.media.push(m.clone()); doc.next_id = doc.next_id.max(id.0); } Some(_) => { + let before = doc.media.len(); let new = doc .add_media(&m.name, &m.content_type, m.data.as_ref().clone()) .ok_or_else(|| crate::cmd::bad("review.accept", crate::cmd::NO_ID_SPACE))?; + if doc.media.len() > before { + doc_at.entry(new).or_insert(before); + } media_map.insert(id, new); } } @@ -519,6 +580,39 @@ mod tests { assert_eq!(s.doc().unwrap().doc.slides.len(), n, "comparing alone changes nothing"); } + #[test] + fn many_inserted_slides_and_same_named_pictures_compare_by_index() { + use std::sync::Arc; + + use deckcraft_model::style::PictureFill; + use deckcraft_model::{Shape, ShapeId, ShapeKind, SlideId, defaults}; + + // One slide of 3,000 pictures of one image, all named "Box"; the revision has the same + // pictures under other ids (matched by name, in order) and 3,000 slides inserted after it. + let mut cur = defaults::new_presentation(None); + let img = cur.add_media("a.png", "image/png", vec![7; 4096]).unwrap(); + let mut rev = cur.clone(); + let pic = |id: u32| Shape { + id: ShapeId(id), + name: "Box".into(), + xfrm: Some(deckcraft_model::Xfrm::new(10.0, 10.0, 50.0, 50.0)), + kind: ShapeKind::Picture { fill: PictureFill { media: img, ..Default::default() } }, + ..Default::default() + }; + Arc::make_mut(&mut cur.slides[0]).shapes = (0..3000).map(|k| pic(100_000 + k)).collect(); + Arc::make_mut(&mut rev.slides[0]).shapes = (0..3000).map(|k| pic(200_000 + k)).collect(); + let mut base = (*rev.slides[0]).clone(); + base.shapes.clear(); + for k in 0..3000 { + let mut s = base.clone(); + s.id = SlideId(300_000 + k); + rev.slides.push(Arc::new(s)); + } + let changes = super::diff(&cur, &rev, false); + assert_eq!(changes.len(), 3000, "only the inserted slides differ"); + assert!(changes.iter().all(|c| c.kind == super::ChangeKind::Inserted && c.slide == 1)); + } + /// A deck with one slide: a table whose cell has a picture fill, a picture background and a /// transition sound. `tag` starts the bytes of each. fn media_deck(tag: &str) -> deckcraft_model::Presentation { From 3c3d504eb15243a6517d1a1d8b841082a2edef9b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:12:24 -0500 Subject: [PATCH 25/94] PPTX: read a notes or comments part for the first slide that names it (#1741) * pptx: read a notes or comments part for the first slide that names it * address review: keep modern-comments precedence for already-owned parts --- crates/pptx/src/read.rs | 37 +++++++++++++++++-------------- crates/pptx/tests/it/comments.rs | 27 ++++++++++++++++++++++ crates/pptx/tests/it/malformed.rs | 31 ++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 17 deletions(-) diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index 2056d53d7..4ee3c4d32 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -668,52 +668,55 @@ fn read_slides( let pkg = imp.pkg; let fallback_layout = p.masters.first().and_then(|m| m.layouts.first()).map(|l| l.id).unwrap_or_default(); let mut file_slide_ids: HashMap<u32, SlideId> = HashMap::new(); - let mut notes_by_target: HashMap<String, TextBody> = HashMap::new(); + // A notes or comments part belongs to one slide; one shared by many must not be read (and + // copied) once per slide that names it. + let mut owned_parts: HashSet<String> = HashSet::new(); for (file_id, path, id) in slide_ids { let Some(doc) = docs.get(&opc::norm(path)) else { continue }; let part = Part::new(pkg, path, doc); let layout = part.rels.first_of("slideLayout").and_then(|r| layout_by_part.get(&opc::norm(&r.target)).copied()).unwrap_or(fallback_layout); let mut slide = read_slide(imp, &part, doc, *id, layout); - if let Some(notes) = slide_notes(imp, &part, &mut notes_by_target) { + if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) { slide.notes = notes; } - read_slide_comments(pkg, pres_part, &part, &mut slide); + read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts); file_slide_ids.insert(*file_id, *id); p.slides.push(Arc::new(slide)); } file_slide_ids } -/// The slide's notes text, read once per notes part. -fn slide_notes(imp: &mut Imp, part: &Part, cache: &mut HashMap<String, TextBody>) -> Option<TextBody> { +/// The slide's notes text. A notes part is the notes of the first slide that names it. +fn slide_notes(imp: &mut Imp, part: &Part, owned: &mut HashSet<String>) -> Option<TextBody> { let n = part.rels.first_of("notesSlide")?; - let key = opc::norm(&n.target); - if let Some(cached) = cache.get(&key) { - return Some(cached.clone()); + if !owned.insert(opc::norm(&n.target)) { + log::warn!("pptx: notes part {} is named by more than one slide; kept on the first", n.target); + return None; } let pkg = imp.pkg; let nd = load(pkg, &n.target)?; let np = Part::new(pkg, &n.target, &nd); - let notes = read_notes(imp, &np, &nd.root); - cache.insert(key, notes.clone()); - Some(notes) + Some(read_notes(imp, &np, &nd.root)) } /// Comments. A modern part and the legacy part can describe the same threads (PowerPoint /// writes both): the modern one wins, its flattened legacy copy is skipped. -fn read_slide_comments(pkg: &Package, pres_part: &Part, part: &Part, slide: &mut Slide) { - let mut parts: Vec<(Doc, bool)> = vec![]; +/// Each comments part is read once, for the first slide that names it. +fn read_slide_comments(pkg: &Package, pres_part: &Part, part: &Part, slide: &mut Slide, owned: &mut HashSet<String>) { + let mut parts: Vec<(Doc, bool, bool)> = vec![]; for c in part.rels.all_of("comments") { + // An already-owned part is not re-read, but its kind still decides modern precedence. + let fresh = owned.insert(opc::norm(&c.target)); if let Some(cd) = pkg.xml(&c.target) { // The content type names the modern part; a package that types it only through a // Default entry instead of an Override is still modern when its root is p188. let modern = pkg.content_type(&c.target).as_deref() == Some(crate::write::CT_COMMENTS_MODERN) || cd.root.prefix() == "p188"; - parts.push((cd, modern)); + parts.push((cd, modern, fresh)); } } - let has_modern = parts.iter().any(|(_, m)| *m); - for (cd, modern) in parts { - if has_modern && !modern { + let has_modern = parts.iter().any(|(_, m, _)| *m); + for (cd, modern, fresh) in parts { + if !fresh || (has_modern && !modern) { continue; } slide.comments.extend(read_comments(pkg, pres_part, &cd.root, modern)); diff --git a/crates/pptx/tests/it/comments.rs b/crates/pptx/tests/it/comments.rs index 9713b0f42..9b0e85bde 100644 --- a/crates/pptx/tests/it/comments.rs +++ b/crates/pptx/tests/it/comments.rs @@ -146,6 +146,33 @@ fn comments_on_several_slides_round_trip() { assert_eq!(q.slides[2].comments[0].text, "Slide three"); } +/// A slide that names a modern part another slide already owns, plus its own legacy part, must +/// not import the legacy copy: modern precedence holds even when the modern part is not re-read. +#[test] +fn owned_modern_part_still_suppresses_later_legacy() { + let mut p = deck(); + let layout = p.slides[0].layout; + let s2 = defaults::new_slide(&mut p, layout).expect("slide"); + p.slides.push(Arc::new(s2)); + Arc::make_mut(&mut p.slides[1]).comments = vec![Comment { author: "Cara".into(), text: "Slide two".into(), ..Default::default() }]; + let bytes = deckcraft_pptx::export(&p).expect("export"); + let rels2 = part(&bytes, "ppt/slides/_rels/slide2.xml.rels").replace("modernComment2.xml", "modernComment1.xml"); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).expect("zip"); + let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for i in 0..z.len() { + let mut f = z.by_index(i).expect("entry"); + out.start_file(f.name(), zip::write::SimpleFileOptions::default()).expect("start"); + if f.name() == "ppt/slides/_rels/slide2.xml.rels" { + std::io::Write::write_all(&mut out, rels2.as_bytes()).expect("write"); + } else { + std::io::copy(&mut f, &mut out).expect("copy"); + } + } + let q = deckcraft_pptx::import(&out.finish().expect("finish").into_inner()).expect("import"); + assert_eq!(q.slides[0].comments.len(), 2); + assert!(q.slides[1].comments.is_empty(), "{:?}", q.slides[1].comments); +} + /// A legacy-only package (what older tools read and write) still imports: 1/8 pt positions, /// flattened replies. #[test] diff --git a/crates/pptx/tests/it/malformed.rs b/crates/pptx/tests/it/malformed.rs index 774a5ee92..a07493486 100644 --- a/crates/pptx/tests/it/malformed.rs +++ b/crates/pptx/tests/it/malformed.rs @@ -287,3 +287,34 @@ fn unreadable_slide_is_reported() { assert_eq!(lost, vec!["ppt/slides/slide2.xml".to_string()]); assert_eq!(deckcraft_pptx::import(&broken).expect("import").slides.len(), 1); } + +/// Many slides naming one notes part: it is read for the first slide only, not copied onto every +/// slide that names it. +#[test] +fn a_shared_notes_part_is_read_once() { + use std::sync::Arc; + let mut p = defaults::new_presentation(None); + let layout = p.slides[0].layout; + for _ in 0..3 { + let s = defaults::new_slide(&mut p, layout).expect("slide"); + p.slides.push(Arc::new(s)); + } + for (i, s) in p.slides.iter_mut().enumerate() { + Arc::make_mut(s).notes = deckcraft_model::text::TextBody::from_text(&format!("notes {i}")); + } + let mut es = entries(&deckcraft_pptx::export(&p).expect("export")); + for (n, d) in es.iter_mut() { + if n.starts_with("ppt/slides/_rels/") { + let x = String::from_utf8(d.clone()).expect("utf8"); + let x = x + .replace("notesSlide2.xml", "notesSlide1.xml") + .replace("notesSlide3.xml", "notesSlide1.xml") + .replace("notesSlide4.xml", "notesSlide1.xml"); + *d = x.into_bytes(); + } + } + let q = deckcraft_pptx::import(&rezip(&es)).expect("import"); + assert_eq!(q.slides.len(), 4); + assert_eq!(q.slides[0].notes.text(), "notes 0"); + assert!(q.slides[1..].iter().all(|s| s.notes.text().is_empty()), "a shared notes part is not copied"); +} From 996bb42ff51a5f0d513fde4bd3a25512474009e5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:12:47 -0500 Subject: [PATCH 26/94] pptx: index relationships by id on read and by target on write (#1739) --- crates/pptx/src/opc.rs | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/crates/pptx/src/opc.rs b/crates/pptx/src/opc.rs index 20a53bcb0..459a7334c 100644 --- a/crates/pptx/src/opc.rs +++ b/crates/pptx/src/opc.rs @@ -171,6 +171,7 @@ fn rels_of(doc: &xml::Doc, part: &str) -> Rels { let external = r.attr("TargetMode").is_some_and(|m| m.eq_ignore_ascii_case("external")); let target_raw = target.to_string(); let target = if external { target_raw.clone() } else { resolve(&base, target) }; + out.by_id.entry(id.to_string()).or_insert(out.items.len()); out.items.push(Rel { id: id.to_string(), kind: ty.rsplit('/').next().unwrap_or(ty).to_string(), @@ -211,11 +212,13 @@ pub struct Rel { #[derive(Clone, Debug, Default)] pub struct Rels { pub items: Vec<Rel>, + /// Id → index of its first relationship in `items`. + by_id: HashMap<String, usize>, } impl Rels { pub fn get(&self, id: &str) -> Option<&Rel> { - self.items.iter().find(|r| r.id == id) + self.by_id.get(id).and_then(|&i| self.items.get(i)) } pub fn target(&self, id: &str) -> Option<&str> { self.get(id).map(|r| r.target.as_str()) @@ -339,23 +342,29 @@ pub fn relative(from: &str, to: &str) -> String { #[derive(Default)] pub struct RelsOut { pub items: Vec<(String, String, String, bool)>, + /// (type, target, external) → id of the relationship [`RelsOut::add`] made for it. + added: HashMap<(String, String, bool), String>, } impl RelsOut { /// Add (or reuse) a relationship; `kind` is a full type URI or a suffix of the standard base. pub fn add(&mut self, kind: &str, target: &str, external: bool) -> String { let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") }; - if let Some((id, ..)) = self.items.iter().find(|(_, t, tg, e)| *t == ty && tg == target && *e == external) { + let key = (ty, target.to_string(), external); + if let Some(id) = self.added.get(&key) { return id.clone(); } let id = format!("rId{}", self.items.len() + 1); - self.items.push((id.clone(), ty, target.to_string(), external)); + self.items.push((id.clone(), key.0.clone(), key.1.clone(), external)); + self.added.insert(key, id.clone()); id } /// Always add a new relationship even if an identical one exists. pub fn add_new(&mut self, kind: &str, target: &str, external: bool) -> String { let ty = if kind.starts_with("http") { kind.to_string() } else { format!("{RT_BASE}{kind}") }; let id = format!("rId{}", self.items.len() + 1); + // `add` reuses the first relationship for a target, whichever call made it. + self.added.entry((ty.clone(), target.to_string(), external)).or_insert_with(|| id.clone()); self.items.push((id.clone(), ty, target.to_string(), external)); id } @@ -500,6 +509,27 @@ mod tests { assert!(p.get("e").is_some()); } + #[test] + fn many_relationships_are_found_by_index_and_first_id_wins() { + let n = 50_000; + let mut x = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#); + for i in 0..n { + x.push_str(&format!(r#"<Relationship Id="rId{i}" Type="{RT_BASE}image" Target="../media/image{i}.png"/>"#)); + } + x.push_str(&format!(r#"<Relationship Id="rId0" Type="{RT_BASE}image" Target="../media/dup.png"/></Relationships>"#)); + let rels = rels_from_bytes(x.as_bytes(), "ppt/slides/slide1.xml"); + assert_eq!(rels.target("rId0"), Some("ppt/media/image0.png"), "the first of a repeated id wins"); + assert!((0..n).all(|i| rels.target(&format!("rId{i}")) == Some(&*format!("ppt/media/image{i}.png")))); + + let mut out = RelsOut::default(); + let ids: Vec<String> = (0..n).map(|i| out.add("hyperlink", &format!("https://example.com/{i}"), true)).collect(); + assert_eq!(out.add("hyperlink", "https://example.com/7", true), ids[7], "an identical target reuses its id"); + assert_eq!(out.add("hyperlink", "https://example.com/7", false), format!("rId{}", n + 1), "internal is distinct"); + let fresh = out.add_new("image", "../media/a.png", false); + assert_ne!(out.add_new("image", "../media/a.png", false), fresh); + assert_eq!(out.add("image", "../media/a.png", false), fresh, "add reuses the first add_new made"); + } + #[test] fn backslash_zip_entry_names_are_found() { let z = zip_of(&[("PPT\\Slides\\Slide1.xml", 3)]); From f5fbadde63b4f34efd292932d4ecbbe8b54fdae8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:38:10 -0500 Subject: [PATCH 27/94] Render: evict the least recently used animation instead of clearing the GIF cache (#1802) --- crates/render/src/images.rs | 50 ++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 0e86be8ce..59a274b14 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -37,7 +37,8 @@ struct Cache { bad_order: VecDeque<usize>, bad_bytes: usize, /// GIFs by bytes address and adjustments (`None`: not animated); the bytes stay alive with them. - anims: HashMap<(usize, u64), (Arc<Vec<u8>>, Option<Arc<Anim>>)>, + /// Decoded animations by (bytes, adjustments), each with the clock of its last use. + anims: HashMap<(usize, u64), (Arc<Vec<u8>>, Option<Arc<Anim>>, u64)>, } /// Longest side, total decoded size and frame count kept for one animated GIF; the largest canvas @@ -432,16 +433,33 @@ fn anim(bytes: &Arc<Vec<u8>>, adj: &PictureAdjust) -> Option<Arc<Anim>> { return None; } let key = (Arc::as_ptr(bytes) as usize, adjust_key(adj)); - if let Some(a) = with(|c| c.anims.get(&key).map(|e| e.1.clone())) { + let hit = with(|c| { + c.clock += 1; + let clock = c.clock; + c.anims.get_mut(&key).map(|e| { + e.2 = clock; + e.1.clone() + }) + }); + if let Some(a) = hit { return a; } let a = decode_anim(bytes, adj).map(Arc::new); with(|c| { - let held: usize = c.anims.values().filter_map(|e| e.1.as_ref()).map(|a| a.bytes()).sum(); - if held + a.as_ref().map_or(0, |a| a.bytes()) > GIF_CACHE_BUDGET || c.anims.len() >= 64 { - c.anims.clear(); + // Make room by dropping the least recently used animations, not every one of them, so a + // slide whose animations overflow the cache does not decode all of them again each frame. + let new = a.as_ref().map_or(0, |a| a.bytes()); + loop { + let held: usize = c.anims.values().filter_map(|e| e.1.as_ref()).map(|a| a.bytes()).sum(); + if held + new <= GIF_CACHE_BUDGET && c.anims.len() < 64 { + break; + } + let Some(oldest) = c.anims.iter().min_by_key(|(_, e)| e.2).map(|(k, _)| *k) else { break }; + c.anims.remove(&oldest); } - c.anims.insert(key, (bytes.clone(), a.clone())); + c.clock += 1; + let clock = c.clock; + c.anims.insert(key, (bytes.clone(), a.clone(), clock)); }); a } @@ -535,6 +553,26 @@ mod tests { out.into_inner() } + /// A two-frame GIF whose first pixel is `n`, so each one has its own bytes. + fn gif(n: u8) -> Arc<Vec<u8>> { + use image::codecs::gif::GifEncoder; + let frame = |c: u8| image::Frame::new(image::RgbaImage::from_pixel(2, 2, image::Rgba([n, c, 0, 255]))); + let mut out = Vec::new(); + GifEncoder::new(&mut out).encode_frames([frame(0), frame(255)]).expect("encode"); + Arc::new(out) + } + + #[test] + fn a_full_animation_cache_drops_the_oldest_entry_not_all_of_them() { + let adj = PictureAdjust::default(); + let gifs: Vec<_> = (0..70).map(gif).collect(); + for g in &gifs { + assert!(anim(g, &adj).is_some()); + } + let (len, newest) = with(|c| (c.anims.len(), c.anims.contains_key(&(Arc::as_ptr(&gifs[69]) as usize, adjust_key(&adj))))); + assert!(newest && len >= 32, "{len} cached"); + } + #[test] fn rgba_conversion_is_refused_past_the_cap() { let png = grey_png(100, 50); From 2dfb07f2c478ba1c09922aadee74c1cecb53dcdb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:38:31 -0500 Subject: [PATCH 28/94] Thumbnails: index section starts once (#1800) --- crates/ui-egui/src/panels/thumbs.rs | 40 ++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/thumbs.rs b/crates/ui-egui/src/panels/thumbs.rs index 15bf9d373..946391c35 100644 --- a/crates/ui-egui/src/panels/thumbs.rs +++ b/crates/ui-egui/src/panels/thumbs.rs @@ -112,6 +112,21 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { } } +/// Slide index -> the first section starting there, built once instead of searched per slide. +fn section_starts(doc: &deckcraft_model::Presentation) -> std::collections::HashMap<usize, usize> { + let mut index_of = std::collections::HashMap::new(); + for (i, s) in doc.slides.iter().enumerate() { + index_of.entry(s.id).or_insert(i); + } + let mut starts = std::collections::HashMap::new(); + for (si, s) in doc.sections.iter().enumerate() { + if let Some(&i) = s.slides.first().and_then(|id| index_of.get(id)) { + starts.entry(i).or_insert(si); + } + } + starts +} + /// Render the scrollable thumbnail list, scrolling the current slide into view when it changes. fn list(app: &mut SlideApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); @@ -135,11 +150,10 @@ fn list(app: &mut SlideApp, ui: &mut Ui) { let ppp = ui.ctx().pixels_per_point(); let mut budget = 3u32; let mut rects = vec![]; - let section_starts: Vec<(usize, usize)> = - doc.sections.iter().enumerate().filter_map(|(si, s)| s.slides.first().and_then(|id| doc.slide_index(*id)).map(|i| (i, si))).collect(); + let section_starts = section_starts(&doc); let mut need_more = false; for i in 0..doc.slides.len() { - if let Some((_, si)) = section_starts.iter().find(|(start, _)| *start == i) + if let Some(si) = section_starts.get(&i) && let Some(sec) = doc.sections.get(*si) { ui.add_space(4.0); @@ -434,6 +448,26 @@ mod tests { h } + #[test] + fn section_starts_map_each_first_slide_to_its_first_section() { + let mut s = Session::with_new(); + for _ in 0..3 { + s.execute("slide.new", &json!({})).unwrap(); + } + let mut doc = (*s.active().unwrap().doc).clone(); + let ids: Vec<_> = doc.slides.iter().map(|sl| sl.id).collect(); + doc.sections = vec![ + deckcraft_model::Section { name: "a".into(), slides: vec![ids[0], ids[1]] }, + deckcraft_model::Section { name: "dup".into(), slides: vec![ids[0]] }, + deckcraft_model::Section { name: "c".into(), slides: vec![ids[2]] }, + deckcraft_model::Section { name: "empty".into(), slides: vec![] }, + ]; + let starts = section_starts(&doc); + assert_eq!(starts.get(&0), Some(&0), "the first section starting at a slide wins"); + assert_eq!(starts.get(&2), Some(&2)); + assert_eq!(starts.len(), 2); + } + /// Vertical scroll offset of the thumbnail pane, as recorded each frame by `show`. fn thumbs_scroll(h: &Harness<'_, SlideApp>) -> f32 { h.state().ui.thumbs_scroll From 9d59fa96d3651c9404f1c11c11e47df1fc3062cd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:38:53 -0500 Subject: [PATCH 29/94] Text, morph: share a run's gradient between glyph runs, match morph tokens by text (#1784) --- crates/render/src/morph_text.rs | 32 ++++++++++++++++++++++---------- crates/text/src/run.rs | 2 +- crates/text/src/style.rs | 4 ++-- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/render/src/morph_text.rs b/crates/render/src/morph_text.rs index 391ec0ba3..19c83cdb2 100644 --- a/crates/render/src/morph_text.rs +++ b/crates/render/src/morph_text.rs @@ -76,16 +76,12 @@ fn tokens(l: &TextLayout, chars: bool) -> (Vec<Token>, Vec<(usize, usize)>) { /// For each token of `b`, the token of `a` with the same text, in reading order, each used once. fn matches(a: &[Token], b: &[Token]) -> Vec<Option<usize>> { - let mut used = vec![false; a.len()]; - b.iter() - .map(|tb| { - let i = a.iter().enumerate().position(|(i, ta)| !used.get(i).copied().unwrap_or(true) && ta.key == tb.key)?; - if let Some(u) = used.get_mut(i) { - *u = true; - } - Some(i) - }) - .collect() + // Unused tokens of `a` by text, in reading order, so each lookup is a pop rather than a scan. + let mut free: std::collections::HashMap<&str, std::collections::VecDeque<usize>> = std::collections::HashMap::new(); + for (i, ta) in a.iter().enumerate() { + free.entry(ta.key.as_str()).or_default().push_back(i); + } + b.iter().map(|tb| free.get_mut(tb.key.as_str())?.pop_front()).collect() } fn layout(ctx: &Ctx, s: &Shape, x: Xfrm, fields: &dyn Fields) -> Option<TextLayout> { @@ -228,3 +224,19 @@ pub(crate) fn draw( pub(crate) fn token_keys(l: &TextLayout, chars: bool) -> Vec<String> { tokens(l, chars).0.into_iter().map(|t| t.key).collect() } + +#[cfg(test)] +mod match_tests { + use super::*; + + fn tok(k: &str) -> Token { + Token { key: k.into(), glyphs: Vec::new(), origin: Point::ZERO, run: 0 } + } + + #[test] + fn each_source_token_is_used_once_in_reading_order() { + let a: Vec<Token> = ["a", "b", "a"].map(tok).into(); + let b: Vec<Token> = ["a", "a", "a", "b", "c"].map(tok).into(); + assert_eq!(matches(&a, &b), vec![Some(0), Some(2), None, Some(1), None]); + } +} diff --git a/crates/text/src/run.rs b/crates/text/src/run.rs index d7e9dbeea..56e6ead7c 100644 --- a/crates/text/src/run.rs +++ b/crates/text/src/run.rs @@ -22,7 +22,7 @@ pub struct GlyphRun { pub link: bool, /// Opacity of the fill on top of `color`'s own alpha (0 for no fill). pub alpha: f64, - pub gradient: Option<deckcraft_model::style::Gradient>, + pub gradient: Option<std::sync::Arc<deckcraft_model::style::Gradient>>, /// Shadow and glow behind the glyphs (`a:rPr/a:effectLst`). pub effects: Option<RunEffects>, /// East Asian vertical text (`eaVert`): each glyph stands upright, turned a quarter turn diff --git a/crates/text/src/style.rs b/crates/text/src/style.rs index e1289c520..b61359faf 100644 --- a/crates/text/src/style.rs +++ b/crates/text/src/style.rs @@ -46,7 +46,7 @@ pub(crate) struct Style { pub(crate) highlight: Option<Rgba>, pub(crate) outline: Option<(Rgba, f64)>, pub(crate) link: bool, - pub(crate) gradient: Option<deckcraft_model::style::Gradient>, + pub(crate) gradient: Option<std::sync::Arc<deckcraft_model::style::Gradient>>, pub(crate) effects: Option<RunEffects>, /// "Regular", "Bold"… for the slot and fallback faces. pub(crate) style_name: &'static str, @@ -136,7 +136,7 @@ pub(crate) fn make_style(ctx: &Ctx, r: &RunProps, scale: f64, prompt: Option<Rgb for s in &mut g.stops { s.color = deckcraft_model::ColorRef::rgb(ctx.color(&s.color, None)); } - (g.stops.first().map(|s| ctx.color(&s.color, None)).unwrap_or(Rgba::BLACK), 1.0, Some(g)) + (g.stops.first().map(|s| ctx.color(&s.color, None)).unwrap_or(Rgba::BLACK), 1.0, Some(std::sync::Arc::new(g))) } Some(Fill::None) => (Rgba::TRANSPARENT, 0.0, None), _ => (resolve::text_color(ctx, r), 1.0, None), From a790fdbc2080e524b2ea5f7e18eda4cc3e787598 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:39:14 -0500 Subject: [PATCH 30/94] Render: find a glyph's line by bisection for gradient and WordArt text (#1783) --- crates/render/src/text_draw.rs | 112 ++++++++++++++++++++++++++++++++- crates/render/src/warp.rs | 10 +-- 2 files changed, 115 insertions(+), 7 deletions(-) diff --git a/crates/render/src/text_draw.rs b/crates/render/src/text_draw.rs index 3fe96d694..d2400f19f 100644 --- a/crates/render/src/text_draw.rs +++ b/crates/render/src/text_draw.rs @@ -105,6 +105,7 @@ pub fn draw_layout(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, tr: pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, tr: Rect, m: Affine, paras: &[(usize, ParaState)]) { let para = |i: usize| paras.iter().find(|(p, _)| *p == i).map(|(_, s)| *s).unwrap_or_default(); let m = text_transform(m, tr, l.rotation); + let lines_of = LineIndex::new(l); let deco = |ctx: &mut RenderContext, d: &deckcraft_text::Deco| { let ps = para(d.para); if !ps.visible || ps.opacity <= 0.001 { @@ -144,7 +145,7 @@ pub fn draw_layout_with(ctx: &mut RenderContext, l: &deckcraft_text::TextLayout, draw_glyph(ctx, run, *gid, at, ps.opacity); continue; }; - let li = line_at(l, run.para, *y); + let li = lines_of.line_at(run.para, *y); if !grads.iter().any(|(i, _)| *i == li) { let scheme = deckcraft_color::ColorScheme { name: String::new(), colors: [Rgba::BLACK; 12] }; let stops = g.stops.iter().map(|s| (s.pos, s.color.resolve(&scheme, None))).collect(); @@ -191,8 +192,78 @@ pub(crate) fn fill_deco(ctx: &mut RenderContext, d: &deckcraft_text::Deco) { } } -/// The line of paragraph `para` holding a glyph on baseline `y` (the nearest baseline). -fn line_at(l: &deckcraft_text::TextLayout, para: usize, y: f64) -> usize { +/// Finds the line of a paragraph holding a glyph on baseline `y` without scanning the paragraph's +/// lines for every glyph. A paragraph whose lines are ordered top to bottom (every layout the text +/// crate produces) is searched by bisection; any other falls back to a scan with the same answer. +pub(crate) struct LineIndex<'a> { + l: &'a deckcraft_text::TextLayout, + /// Per paragraph: its lines' tops, bottoms and baselines all rise with the line index. + ordered: Vec<bool>, +} + +impl<'a> LineIndex<'a> { + pub(crate) fn new(l: &'a deckcraft_text::TextLayout) -> Self { + let ordered = l + .para_lines + .iter() + .map(|&(first, count)| { + let end = first.saturating_add(count).min(l.lines.len()); + l.lines.get(first..end).is_some_and(|ls| { + ls.iter().all(|a| a.top <= a.bottom) + && ls.windows(2).all(|w| w[0].top <= w[1].top && w[0].bottom <= w[1].bottom && w[0].baseline <= w[1].baseline) + }) + }) + .collect(); + LineIndex { l, ordered } + } + + /// The nearest line baseline to `y` among `lines` (the first of equals), as an index into `lines`. + fn nearest(lines: &[deckcraft_text::LineInfo], y: f64) -> Option<usize> { + let i = lines.partition_point(|li| li.baseline < y); + let best = match (i.checked_sub(1), lines.get(i)) { + (Some(p), Some(n)) => { + if (lines[p].baseline - y).abs() <= (n.baseline - y).abs() { + p + } else { + i + } + } + (Some(p), None) => p, + (None, Some(_)) => i, + (None, None) => return None, + }; + let b = lines[best].baseline; + Some(lines.partition_point(|li| li.baseline < b)) + } + + /// The paragraph's lines when they are ordered, with the index of the first. + fn ordered_lines(&self, para: usize) -> Option<(usize, &[deckcraft_text::LineInfo])> { + let &(first, count) = self.l.para_lines.get(para)?; + let end = first.saturating_add(count).min(self.l.lines.len()); + (self.ordered[para] && first < end).then(|| (first, &self.l.lines[first..end])) + } + + /// The line of paragraph `para` holding a glyph on baseline `y` (the nearest baseline). + pub(crate) fn line_at(&self, para: usize, y: f64) -> usize { + if let Some((first, ls)) = self.ordered_lines(para) { + return Self::nearest(ls, y).map_or(0, |i| first + i); + } + line_at_scan(self.l, para, y) + } + + /// The first line of paragraph `para` whose box holds `y`, else the nearest baseline's line. + pub(crate) fn line_of(&self, para: usize, y: f64) -> Option<usize> { + let Some((first, ls)) = self.ordered_lines(para) else { return crate::warp::line_of_scan(self.l, para, y) }; + let i = ls.partition_point(|li| li.bottom + 0.01 < y); + if ls.get(i).is_some_and(|li| y >= li.top - 0.01) { + return Some(first + i); + } + Self::nearest(ls, y).map(|i| first + i) + } +} + +/// The line of paragraph `para` holding a glyph on baseline `y` (the nearest baseline), by scanning. +fn line_at_scan(l: &deckcraft_text::TextLayout, para: usize, y: f64) -> usize { if let Some(&(first, count)) = l.para_lines.get(para) { if count == 0 { return 0; @@ -318,3 +389,38 @@ fn draw_glyph_with( ctx.stroke_path(&path); } } + +#[cfg(test)] +mod line_index_tests { + use super::*; + use deckcraft_text::{LineInfo, TextLayout}; + + fn layout(ordered: bool) -> TextLayout { + let line = |para, top: f64| LineInfo { para, top, baseline: top + 8.0, bottom: top + 10.0, ..Default::default() }; + let mut lines: Vec<LineInfo> = (0..40).map(|i| line(usize::from(i >= 25), f64::from(i) * 10.0)).collect(); + if !ordered { + lines.swap(3, 7); + } + TextLayout { lines, para_lines: vec![(0, 25), (25, 15)], ..Default::default() } + } + + #[test] + fn bisection_matches_the_scan() { + for ordered in [true, false] { + let l = layout(ordered); + let idx = LineIndex::new(l_ref(&l)); + assert_eq!(idx.ordered, vec![ordered, true]); + for para in 0..2 { + for k in -20..450 { + let y = f64::from(k) * 0.9; + assert_eq!(idx.line_at(para, y), line_at_scan(&l, para, y), "line_at {para} {y}"); + assert_eq!(idx.line_of(para, y), crate::warp::line_of_scan(&l, para, y), "line_of {para} {y}"); + } + } + } + } + + fn l_ref(l: &TextLayout) -> &TextLayout { + l + } +} diff --git a/crates/render/src/warp.rs b/crates/render/src/warp.rs index 58caa2ead..72fcbbbe5 100644 --- a/crates/render/src/warp.rs +++ b/crates/render/src/warp.rs @@ -9,13 +9,14 @@ use deckcraft_text::{GlyphRun, TextLayout}; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; use vello_cpu::{RenderContext, peniko}; +use crate::text_draw::LineIndex; use crate::{ParaState, color, glyph, scale_of, text_transform}; /// Most points one warped glyph may have (a hostile size or zoom can't explode the work). const MAX_POINTS: usize = 40_000; -/// The line of `l` a glyph of paragraph `para` on baseline `y` belongs to. -fn line_of(l: &TextLayout, para: usize, y: f64) -> Option<usize> { +/// The line of `l` a glyph of paragraph `para` on baseline `y` belongs to, by scanning. +pub(crate) fn line_of_scan(l: &TextLayout, para: usize, y: f64) -> Option<usize> { if let Some(&(first, count)) = l.para_lines.get(para) { if count == 0 { return None; @@ -110,6 +111,7 @@ pub(crate) fn draw(ctx: &mut RenderContext, l: &TextLayout, tr: Rect, m: Affine, let para = |i: usize| paras.iter().find(|(p, _)| *p == i).map(|(_, s)| *s).unwrap_or_default(); let m = text_transform(m, tr, l.rotation); let n = l.lines.len(); + let lines_of = LineIndex::new(l); let mut ink: Vec<Option<Rect>> = vec![None; n]; let mut off: Vec<Option<f64>> = vec![None; n]; let mut items: Vec<Item> = Vec::new(); @@ -117,7 +119,7 @@ pub(crate) fn draw(ctx: &mut RenderContext, l: &TextLayout, tr: Rect, m: Affine, let k = run.size / run.face.upem.max(1.0); let skew = if run.fake_italic { Affine::new([1.0, 0.0, -0.2, 1.0, 0.0, 0.0]) } else { Affine::IDENTITY }; for (gid, x, y) in &run.glyphs { - let Some(li) = line_of(l, run.para, *y) else { continue }; + let Some(li) = lines_of.line_of(run.para, *y) else { continue }; if let Some(o) = off.get_mut(li) { *o = Some(o.map_or(ref_offset(run), |v| v.max(ref_offset(run)))); } @@ -156,7 +158,7 @@ pub(crate) fn draw(ctx: &mut RenderContext, l: &TextLayout, tr: Rect, m: Affine, return; } let y = (d.rect.y0 + d.rect.y1) / 2.0; - let Some(li) = line_of(l, d.para, y) else { return }; + let Some(li) = lines_of.line_of(d.para, y) else { return }; ctx.set_transform(m * Affine::translate(ps.offset)); ctx.set_paint(color(d.color, ps.opacity)); for r in d.pieces() { From 69c91bb2651b80a71b4a3bba55ccba17fd4e9485 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:39:36 -0500 Subject: [PATCH 31/94] Render: index table style, skip list, chart point fills and waterfall bars; count each dash (#1774) * render: look up a table's style once, keep the skip list as a set, count each dash * render: index chart point fills, scatter x presence and waterfall bars once per chart --- crates/render/src/chart.rs | 33 +++++++++++++++++++++++++-------- crates/render/src/placed.rs | 4 +++- crates/render/src/renderer.rs | 28 +++++++++++++++++++++++++++- crates/render/src/stroke.rs | 3 ++- crates/render/src/tests_wild.rs | 33 +++++++++++++++++++++++++++++++++ 5 files changed, 90 insertions(+), 11 deletions(-) diff --git a/crates/render/src/chart.rs b/crates/render/src/chart.rs index d13f65223..53794987a 100644 --- a/crates/render/src/chart.rs +++ b/crates/render/src/chart.rs @@ -1,5 +1,7 @@ //! Charts: title, plot area with axes and gridlines, series marks, legend. +use std::collections::HashMap; + use deckcraft_color::{ColorTransform, Rgba, SchemeSlot}; use deckcraft_model::Shape; use deckcraft_model::chart::{Chart, ChartType, TrendlineType, axis_scale}; @@ -85,9 +87,9 @@ fn bar_outline(ctx: &Ctx, s: &deckcraft_model::chart::Series) -> Option<(Rgba, f /// Paint of one bar: a `<c:dPt>` fill wins, and a single-series chart that varies colours by point uses one accent per point /// (not waterfalls, which are never read from a `<c:barChart>`). Pattern fills draw as patterns and /// `a:noFill` leaves the bar empty, as in PowerPoint. -fn bar_paint(ctx: &Ctx, c: &Chart, si: usize, pi: usize, s: &deckcraft_model::chart::Series) -> Paint { - if let Some((_, f)) = s.point_fills.iter().find(|(k, _)| *k == pi) { - return paint_of(ctx, Some(f), series_fill(ctx, c, si, Some(s))); +fn bar_paint(ctx: &Ctx, c: &Chart, si: usize, pi: usize, s: &deckcraft_model::chart::Series, fills: Option<&HashMap<usize, &Fill>>) -> Paint { + if let Some(f) = fills.and_then(|m| m.get(&pi)) { + return paint_of(ctx, Some(*f), series_fill(ctx, c, si, Some(s))); } if c.vary_colors && c.series.len() == 1 && s.fill.is_none() && c.kind != ChartType::Waterfall { return Paint::Color(series_color(ctx, c, pi)); @@ -883,6 +885,8 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { let col = if area_kind { series_fill(rctx, c, si, Some(s)) } else { series_line(rctx, c, si, s) }; let series_stats = s.error_bars.as_ref().map(|_| deckcraft_model::chart::SeriesStats::of(&s.values)); let mut pts = vec![]; + // Whether the series has any x value, found once rather than per point. + let any_x = s.x_values.iter().flatten().next().is_some(); for i in 0..ncat { let Some(v) = s.values.get(i).copied().flatten() else { continue }; let v = if stacked { @@ -896,11 +900,11 @@ fn draw_lines(ctx: &mut RenderContext, draw: &mut LineDrawing<'_, '_>) { }; let x = match kind { ChartType::Scatter | ChartType::Bubble => { - match (s.x_values.get(i).copied().flatten().and_then(to_x), s.x_values.iter().flatten().next()) { + match (s.x_values.get(i).copied().flatten().and_then(to_x), any_x) { (Some(x), _) => x, // No x values at all: the points are numbered 1, 2, 3... - (None, None) => to_x(i as f64 + 1.0).unwrap_or(plot.x0 + band * (slot(i) + 0.5)), - (None, Some(_)) => continue, + (None, false) => to_x(i as f64 + 1.0).unwrap_or(plot.x0 + band * (slot(i) + 0.5)), + (None, true) => continue, } } _ => plot.x0 + band * (slot(i) + 0.5), @@ -970,6 +974,19 @@ fn draw_bars(ctx: &mut RenderContext, draw: &BarDrawing<'_, '_>) -> Vec<(f64, f6 let group = bar + step * (n - 1.0); // Error bars need each series' mean and spread: worked out once, not per point. let stats: Vec<deckcraft_model::chart::SeriesStats> = bars.iter().map(|(_, s)| deckcraft_model::chart::SeriesStats::of(&s.values)).collect(); + // Each series' per-point fills by point (the first for a point wins), not searched per bar. + let point_fills: Vec<HashMap<usize, &Fill>> = bars + .iter() + .map(|(_, s)| { + let mut m = HashMap::new(); + for (k, f) in &s.point_fills { + m.entry(*k).or_insert(f); + } + m + }) + .collect(); + // A waterfall's running bars, worked out once for all its categories. + let waterfall_bars = if waterfall { c.waterfall_bars() } else { Vec::new() }; for i in 0..ncat { let mut pos_acc = 0.0; let mut neg_acc = 0.0; @@ -983,7 +1000,7 @@ fn draw_bars(ctx: &mut RenderContext, draw: &BarDrawing<'_, '_>) -> Vec<(f64, f6 let v = s.values.get(i).copied().flatten().unwrap_or(0.0) / total; let start = band * slot(i) + (band - group) / 2.0 + if stacked { 0.0 } else { step * bi as f64 }; let (a, b) = if waterfall { - c.waterfall_bars().get(i).copied().unwrap_or_default() + waterfall_bars.get(i).copied().unwrap_or_default() } else if stacked { if v >= 0.0 { let r = (pos_acc, pos_acc + v); @@ -1015,7 +1032,7 @@ fn draw_bars(ctx: &mut RenderContext, draw: &BarDrawing<'_, '_>) -> Vec<(f64, f6 }; Paint::Color(series_color(rctx, c, slot)) } else { - bar_paint(rctx, c, *si, i, s) + bar_paint(rctx, c, *si, i, s, point_fills.get(bi)) }; fill_with(ctx, &paint, r.abs(), m); if !waterfall && let Some((oc, ow)) = bar_outline(rctx, s).filter(|o| o.1 > 0.0) { diff --git a/crates/render/src/placed.rs b/crates/render/src/placed.rs index 4dc9e1082..2af8152be 100644 --- a/crates/render/src/placed.rs +++ b/crates/render/src/placed.rs @@ -131,9 +131,11 @@ fn place(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, s: &Shape, parent: } ShapeKind::Table(t) => { // Cell text, laid out exactly as the table draws it. + // The table's style is looked up once, not once per cell. + let def = table::resolve_style(rctx, t); for (r, c, rect) in table::cell_rects(t, &table::row_heights(rctx, t, fields)) { let Some(cell) = t.cell(r, c).filter(|cell| !cell.text.is_empty()) else { continue }; - let body = table::cell_body(rctx, t, r, c, cell); + let body = table::cell_body_with_def(rctx, def, t, r, c, cell); let tmp = Shape::table_cell(body.clone()); place_text(out, rctx, fields, s.id, &tmp, &body, rect, m); } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index e7cd5ff35..0b66b30e6 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -33,6 +33,10 @@ pub struct Renderer { /// Visits spent on outer-shadow silhouette passes, kept apart so they cannot use up the budget /// of the normal drawing that follows. shadow_work: usize, + /// `RenderOpts::skip` as a set, with the slice (address, length) it was built from: the + /// slice can be as long as the slide, and is tested for every shape drawn. Forgotten when a + /// frame starts, so another frame's slice at the same address is never mistaken for it. + skip: Option<(usize, usize, std::collections::HashSet<ShapeId>)>, } impl Default for Renderer { @@ -48,6 +52,7 @@ impl Default for Renderer { in_shadow_pass: false, render_work: 0, shadow_work: 0, + skip: None, } } } @@ -163,6 +168,7 @@ impl Renderer { pub(crate) fn slide(&mut self, pres: &Presentation, slide: &Slide, index: usize, opts: &RenderOpts) -> Image { self.render_work = 0; self.shadow_work = 0; + self.skip = None; self.in_shadow_pass = false; let (mut ctx, w, h, view) = Self::canvas(pres, opts, needs_filters(pres, slide)); let f = Frame { pres, opts, fields: Self::fields(pres, index, opts) }; @@ -178,6 +184,7 @@ impl Renderer { pub(crate) fn slide_part(&mut self, pres: &Presentation, slide: &Slide, index: usize, part: SlidePart, opts: &RenderOpts) -> Image { self.render_work = 0; self.shadow_work = 0; + self.skip = None; self.in_shadow_pass = false; let (mut ctx, w, h, view) = Self::canvas(pres, opts, needs_filters(pres, slide)); let f = Frame { pres, opts, fields: Self::fields(pres, index, opts) }; @@ -212,6 +219,7 @@ impl Renderer { let mix = if mix.is_finite() { mix.clamp(0.0, 1.0) } else { 1.0 }; self.render_work = 0; self.shadow_work = 0; + self.skip = None; self.in_shadow_pass = false; let (mut ctx, w, h, view) = Self::canvas(pres, opts, needs_filters(pres, old.0) || needs_filters(pres, new.0)); let (Some(co), Some(cn)) = (Ctx::for_slide(pres, old.0), Ctx::for_slide(pres, new.0)) else { return self.finish(ctx, w, h) }; @@ -260,6 +268,7 @@ impl Renderer { pub(crate) fn layout(&mut self, pres: &Presentation, mi: usize, li: Option<usize>, opts: &RenderOpts) -> Image { self.render_work = 0; self.shadow_work = 0; + self.skip = None; self.in_shadow_pass = false; let (w, h) = output_size(pres, opts); let mut ctx = RenderContext::new_with(w, h, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); @@ -393,8 +402,25 @@ impl Renderer { geo } + /// Whether `id` is in `skip`, looked up in a set built once per frame and slice. + fn skipped(&mut self, skip: &[ShapeId], id: ShapeId) -> bool { + if skip.is_empty() { + return false; + } + let key = (skip.as_ptr() as usize, skip.len()); + match &self.skip { + Some((p, n, set)) if (*p, *n) == key => set.contains(&id), + _ => { + let set: std::collections::HashSet<ShapeId> = skip.iter().copied().collect(); + let hit = set.contains(&id); + self.skip = Some((key.0, key.1, set)); + hit + } + } + } + fn shape_at(&mut self, ctx: &mut RenderContext, f: &Frame, rctx: &Ctx, s: &Shape, parent: Affine, depth: usize) { - if depth > 32 || (s.hidden && !f.opts.show_hidden) || f.opts.skip.contains(&s.id) { + if depth > 32 || (s.hidden && !f.opts.show_hidden) || self.skipped(f.opts.skip, s.id) { return; } let work = if self.in_shadow_pass { &mut self.shadow_work } else { &mut self.render_work }; diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index 8310cf0c9..fc1403f6b 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -191,7 +191,8 @@ pub(crate) fn limit_dash_count(path: &BezPath, pat: Vec<f64>) -> Vec<f64> { return pat; } let len: f64 = path.segments().map(|s| s.arclen(1e-2)).sum(); - let dashes = len / period; + // Every dash of the pattern counts, not each repeat of it: a custom pattern can hold many. + let dashes = len / period * pat.len().div_ceil(2) as f64; if !len.is_finite() { return vec![]; } diff --git a/crates/render/src/tests_wild.rs b/crates/render/src/tests_wild.rs index fb25c7f0b..2da29cb37 100644 --- a/crates/render/src/tests_wild.rs +++ b/crates/render/src/tests_wild.rs @@ -990,4 +990,37 @@ fn a_tiny_dash_on_a_huge_shape_draws_without_running_out_of_memory() { p.line_to((4.0e6, 0.0)); let pat = limit_dash_count(&p, vec![1.0, 1.0]); assert!((4.0e6 / (pat[0] + pat[1]) - MAX_DASHES).abs() < 1.0, "{pat:?}"); + // A custom pattern of 1,000 dashes counts each of them: the limit is on dashes drawn. + let pat = limit_dash_count(&p, vec![1.0; 2000]); + let period: f64 = pat.iter().sum(); + assert!((4.0e6 / period * 1000.0 - MAX_DASHES).abs() < 1.0, "{}", period); +} + +/// A bar chart with 20,000 points, each with its own fill, and a sparse scatter of the same size: +/// the per-point fills and the scatter's "has any x" are looked up, not searched per point. +#[test] +fn many_point_fills_and_sparse_scatter_x_render() { + use deckcraft_model::ShapeKind; + use deckcraft_model::chart::{Chart, ChartType}; + use deckcraft_model::style::Fill; + let n = 20_000; + let chart = |kind: ChartType| { + let mut c = Chart::sample(kind); + c.series.truncate(1); + c.categories = (0..n).map(|i| i.to_string()).collect(); + c.series[0].values = (0..n).map(|i| Some(i as f64)).collect(); + c + }; + let mut bars = chart(ChartType::Column); + bars.series[0].point_fills = (0..n).rev().map(|i| (i, Fill::solid(ColorRef::rgb(Rgba::rgb(200, 0, 0))))).collect(); + let mut scatter = chart(ChartType::Scatter); + scatter.series[0].x_values = (0..n).map(|i| (i + 1 == n).then_some(1.0)).collect(); + let shape = |id: u32, c: Chart| Shape { + id: ShapeId(id), + xfrm: Some(Xfrm::new(10.0, 10.0, 400.0, 300.0)), + kind: ShapeKind::Chart(Box::new(c)), + ..Default::default() + }; + let img = render(vec![shape(2, bars), shape(3, scatter)]); + assert!(img.width > 0); } From 23ac4f7efdbd1e538bd9a7869584d4adeb9039b0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 3 Nov 2026 20:39:57 -0500 Subject: [PATCH 32/94] Fonts: bound font-controlled work in enumeration, outlines and carets (#1701) * Fonts: bound font-controlled work in enumeration, outlines and carets An embedded font could make each lookup do far more than real fonts need: - enumerating a collection read up to 256 faces times 1024 named instances, each then built with its own shaper; now 4096 per file across all faces, with a set for the duplicate-style check instead of a scan; - composite and VARC glyphs could expand one dense outline without limit, and the outline cache only counted entries; outlines now stop at 32768 path elements (drawing nothing past it) and the cache is also bounded by the elements it holds; - the 64-caret limit applied after filtering, so a ligature lookup could read every caret record; it now applies to the records read. * address review: bound thread-local glyph cache by path elements --- crates/fonts/src/fallback.rs | 7 +- crates/fonts/src/fontdb.rs | 159 +++++++++++++++++++++++++++++---- crates/render/src/text_draw.rs | 18 ++-- 3 files changed, 161 insertions(+), 23 deletions(-) diff --git a/crates/fonts/src/fallback.rs b/crates/fonts/src/fallback.rs index de4b2b0a6..8d54453f8 100644 --- a/crates/fonts/src/fallback.rs +++ b/crates/fonts/src/fallback.rs @@ -227,6 +227,9 @@ impl FontDb { } } +/// Most caret records read for one ligature glyph. +const MAX_LIGATURE_CARETS: usize = 64; + /// Caret positions inside a ligature glyph from GDEF `LigCaretList`, in font units from the /// glyph's origin (sorted ascending). Empty when the font has none for `gid`. pub fn ligature_carets(face: &FontFace, gid: u32) -> Vec<i32> { @@ -236,9 +239,12 @@ pub fn ligature_carets(face: &FontFace, gid: u32) -> Vec<i32> { let Ok(cov) = list.coverage() else { return Vec::new() }; let Some(idx) = cov.get(skrifa::GlyphId::new(gid)) else { return Vec::new() }; let Ok(lig) = list.lig_glyphs().get(idx as usize) else { return Vec::new() }; + // The limit applies to the records read, not to the carets kept: a font can list thousands of + // records it then has to be read through for every ligature laid out. let mut out: Vec<i32> = lig .caret_values() .iter() + .take(MAX_LIGATURE_CARETS) .filter_map(|cv| cv.ok()) .filter_map(|cv| match cv { skrifa::raw::tables::gdef::CaretValue::Format1(f) => Some(f.coordinate() as i32), @@ -246,7 +252,6 @@ pub fn ligature_carets(face: &FontFace, gid: u32) -> Vec<i32> { // Format 2 is a contour point index; outlines aren't consulted here. skrifa::raw::tables::gdef::CaretValue::Format2(_) => None, }) - .take(64) .collect(); out.sort_unstable(); out diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index 2e2f35299..c1db0b356 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -368,7 +368,7 @@ struct CatalogEntry { /// Process-wide font database. pub struct FontDb { faces: RwLock<Vec<Arc<FontFace>>>, - outlines: Mutex<HashMap<(u32, u32), Arc<BezPath>>>, + outlines: Mutex<OutlineCache>, #[cfg(not(target_arch = "wasm32"))] catalog: RwLock<Vec<CatalogEntry>>, /// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]). @@ -439,6 +439,38 @@ const SYSTEM_FALLBACKS: &[&str] = &[ static NEXT_ID: AtomicU32 = AtomicU32::new(1); const OUTLINE_CACHE_MAX: usize = 50_000; +/// Most path elements one glyph outline may expand to. Composite and `VARC` glyphs can draw a +/// shared outline many times over; a glyph past this draws nothing rather than holding megabytes. +const MAX_OUTLINE_ELEMENTS: usize = 1 << 15; +/// Most path elements the outline cache holds across all glyphs (about 230 MB at most) before it +/// starts over: distinct glyph ids can each expand one dense outline. +const OUTLINE_CACHE_MAX_ELEMENTS: usize = 1 << 22; + +/// Glyph outlines by (face, glyph), with the path elements they hold. +#[derive(Default)] +struct OutlineCache { + paths: HashMap<(u32, u32), Arc<BezPath>>, + elements: usize, +} + +impl OutlineCache { + fn get(&self, key: &(u32, u32)) -> Option<Arc<BezPath>> { + self.paths.get(key).cloned() + } + + fn insert(&mut self, key: (u32, u32), path: Arc<BezPath>) { + let n = path.elements().len(); + if let Some(old) = self.paths.remove(&key) { + self.elements = self.elements.saturating_sub(old.elements().len()); + } + if self.paths.len() >= OUTLINE_CACHE_MAX || self.elements.saturating_add(n) > OUTLINE_CACHE_MAX_ELEMENTS { + self.paths.clear(); + self.elements = 0; + } + self.paths.insert(key, path); + self.elements = self.elements.saturating_add(n); + } +} fn name(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Option<String> { ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(|s| s.to_string()).filter(|s| !s.is_empty())) @@ -694,6 +726,10 @@ const MAX_COLLECTION_FACES: u32 = 256; const MAX_COLLECTION_ENTRIES_SCANNED: u32 = 16_384; /// Maximum named instances read from a single face. const MAX_NAMED_INSTANCES_PER_FACE: usize = 1024; +/// Maximum faces (named instances counted separately) enumerated from one font file, across all +/// of a collection's faces: the per-collection and per-face limits multiply, and each face found +/// is then built with its own shaper. +const MAX_ENUMERATED_FACES: usize = 4096; fn distinct_face_indices(entries: impl IntoIterator<Item = (u32, u32)>) -> Vec<u32> { let mut offsets = std::collections::HashSet::new(); @@ -730,21 +766,30 @@ fn enumerate_faces(data: &[u8]) -> Vec<Found> { Err(_) => Vec::new(), }; let mut out = Vec::new(); + // Named instances read and plain faces kept, across the whole file. + let mut budget = MAX_ENUMERATED_FACES; for i in indices { + if budget == 0 { + break; + } let Ok(f) = skrifa::FontRef::from_index(data, i) else { continue }; let Some((family, style)) = face_names(&f) else { continue }; let axes = f.axes(); let mut named = Vec::new(); + let mut seen = std::collections::HashSet::new(); let instances = f.named_instances(); for ni in instances.iter().take(capped_named_instance_count(instances.len())) { + let Some(left) = budget.checked_sub(1) else { break }; + budget = left; let Some(style) = name(&f, &[ni.subfamily_name_id()]) else { continue }; - if named.iter().any(|(_, s, _): &(u32, String, _)| s.eq_ignore_ascii_case(&style)) { + if !seen.insert(style.to_ascii_lowercase()) { continue; } let coords: Vec<([u8; 4], f32)> = axes.iter().zip(ni.user_coords()).map(|(a, v)| (a.tag().to_be_bytes(), v)).collect(); named.push((i, style, coords)); } if named.is_empty() { + budget = budget.saturating_sub(1); out.push((i, family, style, Vec::new())); } else { out.extend(named.into_iter().map(|(i, s, c)| (i, family.clone(), s, c))); @@ -905,7 +950,7 @@ impl FontDb { } Self { faces: RwLock::new(faces), - outlines: Mutex::new(HashMap::new()), + outlines: Mutex::new(OutlineCache::default()), #[cfg(not(target_arch = "wasm32"))] catalog: RwLock::new(Vec::new()), font_dirs, @@ -1513,41 +1558,72 @@ impl FontDb { pub fn outline(&self, face: &FontFace, gid: u32) -> Arc<BezPath> { let key = (face.id, gid); if let Some(p) = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key) { - return p.clone(); + return p; } - let mut pen = FlipPen(BezPath::new()); + let mut pen = FlipPen::new(MAX_OUTLINE_ELEMENTS); if let Some(f) = face.skrifa() && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid)) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); } - let p = Arc::new(pen.0); - let mut cache = self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if cache.len() >= OUTLINE_CACHE_MAX { - cache.clear(); - } - cache.insert(key, p.clone()); + let p = Arc::new(pen.finish()); + self.outlines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(key, p.clone()); p } } -struct FlipPen(BezPath); +/// Collects a glyph outline, y flipped, up to `limit` path elements. Past the limit it ignores +/// what follows and [`FlipPen::finish`] gives an empty path: a cut-off outline would fill wrongly. +struct FlipPen { + path: BezPath, + limit: usize, + over: bool, +} + +impl FlipPen { + fn new(limit: usize) -> Self { + FlipPen { path: BezPath::new(), limit, over: false } + } + + /// Room for one more element? + fn room(&mut self) -> bool { + if !self.over && self.path.elements().len() >= self.limit { + self.over = true; + self.path = BezPath::new(); + } + !self.over + } + + fn finish(self) -> BezPath { + if self.over { BezPath::new() } else { self.path } + } +} impl OutlinePen for FlipPen { fn move_to(&mut self, x: f32, y: f32) { - self.0.move_to((x as f64, -y as f64)); + if self.room() { + self.path.move_to((x as f64, -y as f64)); + } } fn line_to(&mut self, x: f32, y: f32) { - self.0.line_to((x as f64, -y as f64)); + if self.room() { + self.path.line_to((x as f64, -y as f64)); + } } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { - self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); + if self.room() { + self.path.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); + } } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { - self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); + if self.room() { + self.path.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); + } } fn close(&mut self) { - self.0.close_path(); + if self.room() { + self.path.close_path(); + } } } @@ -1575,6 +1651,55 @@ mod font_dir_tests { assert_eq!(capped_named_instance_count(MAX_NAMED_INSTANCES_PER_FACE + 1), MAX_NAMED_INSTANCES_PER_FACE); } + #[test] + fn faces_of_one_file_are_bounded_across_the_collection() { + // The per-collection and per-face limits together would allow far more. + assert!((MAX_COLLECTION_FACES as usize) * MAX_NAMED_INSTANCES_PER_FACE > 16 * MAX_ENUMERATED_FACES); + for data in bundled() { + assert!(enumerate_faces(data).len() <= MAX_ENUMERATED_FACES); + } + } + + #[test] + fn an_outline_past_the_element_limit_draws_nothing() { + let mut pen = FlipPen::new(8); + pen.move_to(0.0, 0.0); + pen.line_to(1.0, 1.0); + pen.close(); + assert_eq!(pen.finish().elements().len(), 3); + // A shared outline drawn over and over (composite and VARC glyphs). + let mut pen = FlipPen::new(8); + for i in 0..1_000_000 { + pen.move_to(0.0, 0.0); + pen.line_to(i as f32, 1.0); + pen.close(); + } + assert_eq!(pen.path.elements().len(), 0); + assert!(pen.finish().elements().is_empty()); + } + + #[test] + fn outline_cache_is_bounded_by_elements() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + for i in 1..MAX_OUTLINE_ELEMENTS { + path.line_to((i as f64, 0.0)); + } + let path = Arc::new(path); + let mut cache = OutlineCache::default(); + let glyphs = 4 * OUTLINE_CACHE_MAX_ELEMENTS / MAX_OUTLINE_ELEMENTS; + for gid in 0..glyphs as u32 { + cache.insert((1, gid), path.clone()); + assert!(cache.elements <= OUTLINE_CACHE_MAX_ELEMENTS); + assert_eq!(cache.elements, cache.paths.values().map(|p| p.elements().len()).sum::<usize>()); + } + assert!(cache.get(&(1, glyphs as u32 - 1)).is_some()); + // Replacing an entry does not count it twice. + let before = cache.elements; + cache.insert((1, glyphs as u32 - 1), path.clone()); + assert_eq!(cache.elements, before); + } + #[test] fn xdg_data_dirs_contribute_their_fonts_folders() { let home = Path::new("/home/ann"); diff --git a/crates/render/src/text_draw.rs b/crates/render/src/text_draw.rs index d2400f19f..d9788a4a9 100644 --- a/crates/render/src/text_draw.rs +++ b/crates/render/src/text_draw.rs @@ -35,22 +35,30 @@ pub(crate) fn prompt_body(rctx: &Ctx, s: &Shape, kind: PhType) -> TextBody { t } +/// Most path elements this thread's glyph cache retains. Its entries are shared with the font +/// cache, but they stay alive here after that cache evicts them, so they are bounded by elements. +const GLYPH_CACHE_MAX_ELEMENTS: usize = 1 << 22; + thread_local! { - static GLYPH_CACHE: std::cell::RefCell<HashMap<(u32, u32), Arc<BezPath>>> = std::cell::RefCell::new(HashMap::new()); + /// The cached outlines, and the path elements they hold. + static GLYPH_CACHE: std::cell::RefCell<(HashMap<(u32, u32), Arc<BezPath>>, usize)> = std::cell::RefCell::new((HashMap::new(), 0)); } pub(crate) fn glyph(face: &deckcraft_fonts::FontFace, gid: u32) -> Arc<BezPath> { let key = (face.id(), gid); - if let Some(p) = GLYPH_CACHE.with(|c| c.borrow().get(&key).cloned()) { + if let Some(p) = GLYPH_CACHE.with(|c| c.borrow().0.get(&key).cloned()) { return p; } let p = FontDb::global().outline(face, gid); GLYPH_CACHE.with(|c| { let mut c = c.borrow_mut(); - if c.len() > 200_000 { - c.clear(); + let n = p.elements().len(); + if c.0.len() > 200_000 || c.1.saturating_add(n) > GLYPH_CACHE_MAX_ELEMENTS { + c.0.clear(); + c.1 = 0; } - c.insert(key, p.clone()); + c.1 += n; + c.0.insert(key, p.clone()); }); p } From 6eaae2bd8c29316e59d6bbbf601726c2bccdaae3 Mon Sep 17 00:00:00 2001 From: brad <bradprin@live.com> Date: Tue, 3 Nov 2026 23:26:50 -0600 Subject: [PATCH 33/94] Web: only the page's first file replaces the start deck; close Save As after a same-name save A file the page sent without a name opens untitled and unchanged, like the empty start presentation, so the page's next file closed it. Host mode now records the start presentation (start_for_host) and only the first file that opens takes its place, as packaging/web/README.md says. Save As > Save under the presentation's own name changed neither the path nor the dirty flag, so the Save As page stayed open and a second click sent the file again. The page now also compares the revision, which every save bumps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- apps/deckcraft-web/src/web.rs | 6 +++++- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/files.rs | 25 +++++++++++++++-------- crates/ui-egui/src/backstage/info.rs | 7 +++++-- crates/ui-egui/src/backstage/tests.rs | 29 +++++++++++++++++++++++++++ crates/ui-egui/src/host_save_tests.rs | 19 ++++++++++++++++-- crates/ui-egui/src/lib.rs | 3 +++ packaging/web/README.md | 5 +++-- 8 files changed, 80 insertions(+), 15 deletions(-) diff --git a/apps/deckcraft-web/src/web.rs b/apps/deckcraft-web/src/web.rs index 67f5157c5..7720b605c 100644 --- a/apps/deckcraft-web/src/web.rs +++ b/apps/deckcraft-web/src/web.rs @@ -58,7 +58,11 @@ pub fn start() { } let mut app = SlideApp::new(Session::new(), services); // In host mode the parent sends the presentation to edit; no sample meanwhile. - if app_bridge.is_none() && !query_has("blank") { + if app_bridge.is_some() { + if let Err(e) = app.start_for_host() { + log::error!("new presentation: {e}"); + } + } else if !query_has("blank") { if let Err(e) = deckcraft_engine::sample::open_sample(&mut app.session) { log::error!("sample deck: {e}"); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7c9c373ab..178ab24ba 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -106,6 +106,7 @@ impl SlideApp { twisting: false, next_file_id: 1, pending_files: Vec::new(), + host_start: None, ime_tracker: egui::ime_context::ImeContextTracker::new(), ime_pending: None, ime_frame_viewport: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index c1c6198b4..3ec59202e 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -541,13 +541,11 @@ impl SlideApp { /// when the page sent one with a presentation extension and the file is an intact /// presentation, so Save hands it back under that name and format; anything else (no name, an /// outline, a damaged file opened as a repaired copy) is untitled, and its first Save is a new - /// file. An untouched untitled presentation that was the only one open (the blank one the page - /// starts with) gives way to the presentation that opened. + /// file. The first presentation that opens takes the place of the empty one host mode started + /// with ([`Self::start_for_host`]), if that one is still open, untitled and unchanged; later + /// files open beside the others. pub fn open_from_host(&mut self, name: Option<&str>, bytes: &[u8]) { - let blank = match self.session.documents() { - [d] if d.path.is_none() && !d.is_dirty() => Some(d.uid), - _ => None, - }; + let blank = self.host_start.filter(|&uid| self.session.documents().iter().any(|d| d.uid == uid && d.path.is_none() && !d.is_dirty())); let before = self.session.documents().len(); let shown = name.unwrap_or("Presentation"); let named = name.is_some_and(|n| is_presentation_name(&n.to_ascii_lowercase())); @@ -562,8 +560,11 @@ impl SlideApp { self.notify(e.to_string()); } self.drain_requests(); - if self.session.documents().len() > before - && let Some(opened) = self.session.active().map(|d| d.uid) + if self.session.documents().len() <= before { + return; + } + self.host_start = None; + if let Some(opened) = self.session.active().map(|d| d.uid) && let Some(i) = self.session.documents().iter().position(|d| Some(d.uid) == blank) { self.session.close_document(i); @@ -573,6 +574,14 @@ impl SlideApp { } } + /// Host mode (`?host=parent`) starts with an empty presentation instead of the sample, for + /// the first file the page sends to take its place ([`Self::open_from_host`]). + pub fn start_for_host(&mut self) -> Result<(), String> { + self.run("file.new", json!({}))?; + self.host_start = self.session.active().map(|d| d.uid); + Ok(()) + } + /// Act on requests commands left for the UI. pub(super) fn drain_requests(&mut self) { for r in std::mem::take(&mut self.session.ui_requests) { diff --git a/crates/ui-egui/src/backstage/info.rs b/crates/ui-egui/src/backstage/info.rs index 27c0cec6d..3ddbda1a3 100644 --- a/crates/ui-egui/src/backstage/info.rs +++ b/crates/ui-egui/src/backstage/info.rs @@ -182,9 +182,12 @@ pub(super) fn save_as(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, out: { let fmt = bs.file_type; let done = if matches!(fmt, "pptx" | "deckcraft") { - let before = app.session.active().map(|d| (d.path.clone(), d.is_dirty())); + // A save bumps the revision, also one under the same name that leaves the path + // and the dirty flag as they were; a cancelled dialog or a failed save doesn't. + let snapshot = |app: &SlideApp| app.session.active().map(|d| (d.path.clone(), d.is_dirty(), d.revision)); + let before = snapshot(app); app.save_as_dialog(fmt); - web || app.session.active().map(|d| (d.path.clone(), d.is_dirty())) != before + web || snapshot(app) != before } else { app.export_as(fmt, json!({})) }; diff --git a/crates/ui-egui/src/backstage/tests.rs b/crates/ui-egui/src/backstage/tests.rs index 205a5522c..a21cd3cff 100644 --- a/crates/ui-egui/src/backstage/tests.rs +++ b/crates/ui-egui/src/backstage/tests.rs @@ -422,6 +422,35 @@ fn host_close_prompt_keeps_the_presentation_when_the_save_fails() { } } +/// Framed by a page that keeps the files, Save As › Save under the presentation's own name goes +/// back to the slide once the page has the file. The bug this prevents: that save leaves the +/// file and the dirty flag as they were, so the Save As page stayed open and a second click sent +/// the file again. +#[test] +fn host_save_as_under_the_same_name_returns_to_the_slide() { + let got: Rc<RefCell<Vec<(String, bool)>>> = Default::default(); + let saves = got.clone(); + let services = Services { + host_save: Some(Box::new(move |name: &str, _: &[u8], save_as: bool| { + saves.borrow_mut().push((name.to_string(), save_as)); + Ok(()) + })), + download: Some(Box::new(|_: &str, _: &[u8]| {})), + ..Default::default() + }; + let mut app = SlideApp::new(Session::new(), services); + app.start_for_host().unwrap(); + let deck = deckcraft_engine::cmd::file::save_bytes(&Session::with_new().doc().unwrap().doc, "pptx").unwrap(); + app.open_from_host(Some("deck.pptx"), &deck); + let mut h = harness(app); + h.state_mut().run("app.backstage", json!({"page": "saveAs"})).unwrap(); + h.run_steps(3); + click_on_page(&h, "Save"); + h.run_steps(3); + assert_eq!(*got.borrow(), [("deck.pptx".to_string(), true)]); + assert!(h.state().backstage.is_none(), "the save returns to the slide"); +} + /// Info shows the presentation's counts and properties, and edits them through file.properties. #[test] fn info_shows_and_edits_the_properties() { diff --git a/crates/ui-egui/src/host_save_tests.rs b/crates/ui-egui/src/host_save_tests.rs index 8b9b03c08..78fad53ef 100644 --- a/crates/ui-egui/src/host_save_tests.rs +++ b/crates/ui-egui/src/host_save_tests.rs @@ -29,8 +29,10 @@ fn host_app(fail: bool) -> (SlideApp, Got) { download: Some(Box::new(move |name: &str, bytes: &[u8]| downloads.borrow_mut().push((name.to_string(), false, bytes.to_vec())))), ..Default::default() }; - // The page starts with a blank presentation, as the web shell does in host mode. - (SlideApp::new(Session::with_new(), services), got) + // Host mode starts as the web shell starts it: an empty presentation for the page's file. + let mut app = SlideApp::new(Session::new(), services); + app.start_for_host().unwrap(); + (app, got) } /// A .pptx with `slides` slides, as the page would send it. @@ -138,6 +140,19 @@ fn an_edited_start_presentation_stays_open() { assert_eq!(path(&app).as_deref(), Some("deck.pptx")); } +/// Only the first file from the page takes the start presentation's place. The bug this +/// prevents: a file sent without a name opens untitled and unchanged, as the start presentation +/// is, so the page's next file closed it. +#[test] +fn only_the_first_file_from_the_page_replaces_the_start_presentation() { + let (mut app, _) = host_app(false); + app.open_from_host(None, &pptx(2)); + app.open_from_host(Some("deck.pptx"), &pptx(3)); + let slides: Vec<usize> = app.session.documents().iter().map(|d| d.doc.slides.len()).collect(); + assert_eq!(slides, [2, 3], "the file sent without a name stays open beside the next one"); + assert_eq!(path(&app).as_deref(), Some("deck.pptx")); +} + /// The command palette runs `file.save` by id. With a file of its own the engine would write to /// that path, which a browser can't; in host mode it goes to the page like Ctrl+S. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0f0e664f8..08fcc2391 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -335,6 +335,9 @@ pub struct SlideApp { next_file_id: u64, /// Picks and drops whose bytes have not arrived yet. pending_files: Vec<PendingFile>, + /// The empty presentation host mode starts with ([`SlideApp::start_for_host`]), until the + /// first file the page sends takes its place. + host_start: Option<u64>, /// Owner/generation/cause bookkeeping for the canvas text IME producer. ime_tracker: egui::ime_context::ImeContextTracker, /// Canvas IME geometry for this pass: the caret while editing, or the selected shape. diff --git a/packaging/web/README.md b/packaging/web/README.md index e9622f5aa..1e96279c0 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -113,8 +113,9 @@ DeckCraft doesn't learn the name the page finally stores a Save As under, so a p on a conflict should map later Saves of the old name itself. In host mode DeckCraft starts with an empty presentation instead of the sample, and the first -presentation the page sends takes its place. The page guards leaving itself (DeckCraft adds no -guard of its own), and `&author=Name` signs the user's comments. +presentation the page sends takes its place unless the user has changed it; later ones open +beside it. The page guards leaving itself (DeckCraft adds no guard of its own), and +`&author=Name` signs the user's comments. ```html <iframe id="deck" src="/deckcraft/?host=parent&author=Ada" style="width: 100%; height: 720px; border: 0;"></iframe> From 50187449c20d58d8b014a3eb04b967ef3cc687b2 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:52:46 +0100 Subject: [PATCH 34/94] Render tests: import place_slide_with so the date test compiles (#1153) --- crates/render/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 05306f66c..540a8500a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1,7 +1,7 @@ use super::{ Ctx, Fields, Fill, Image, Opts, PathMorph, Point, RENDERER, Rect, Region, RenderOpts, Renderer, Rgba, ShapeState, SlideFields, TextMorph, crop_dest, dpi_for_scale, gif_frame, image_dpi, images, morph_path, morph_text, needs_filters, parse_path, pasteboard_region, place_slide, - render_blend, render_shapes, render_slide, render_slide_drawn, slide_extent, text_transform, + place_slide_with, render_blend, render_shapes, render_slide, render_slide_drawn, slide_extent, text_transform, }; use deckcraft_model::chart::{ChartType, Trendline, TrendlineType}; use deckcraft_model::style::ColorRef; From 51d19baa0cbe35f259bf5e24e38f1f59b2b2ef2c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 4 Nov 2026 13:56:48 -0500 Subject: [PATCH 35/94] Ogg, xtask: check packet ranges against the source first; stats skips directory links (#1796) --- crates/ogg/src/lib.rs | 5 +++++ crates/ogg/src/tests.rs | 10 ++++++++++ xtask/src/stats.rs | 8 +++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/ogg/src/lib.rs b/crates/ogg/src/lib.rs index 77c081d52..719c96698 100644 --- a/crates/ogg/src/lib.rs +++ b/crates/ogg/src/lib.rs @@ -415,6 +415,11 @@ impl CaptureScanner { } fn read_parts(src: &(impl ByteSource + ?Sized), parts: &[(u64, u32)]) -> Result<Vec<u8>> { + // Ranges come from a scan of some source; check them against this one before sizing a buffer. + let len = src.len(); + if parts.iter().any(|&(o, n)| o.checked_add(u64::from(n)).is_none_or(|end| end > len)) { + return Err(Error::Invalid("packet range lies outside the source".into())); + } let mut v = Vec::with_capacity(parts.iter().map(|p| p.1 as usize).sum()); for &(o, n) in parts { let a = v.len(); diff --git a/crates/ogg/src/tests.rs b/crates/ogg/src/tests.rs index 480c1cda2..8f9673089 100644 --- a/crates/ogg/src/tests.rs +++ b/crates/ogg/src/tests.rs @@ -274,3 +274,13 @@ fn a_budget_too_small_to_search_is_spent() { let f = opus_file(6, 312, 0); assert_eq!(scanner.find(&f, 0, f.len() as u64).unwrap(), None); } + +#[test] +fn read_packet_checks_its_ranges_against_the_source_before_allocating() { + let f = opus_file(10, 312, 500); + let o = open(&f).unwrap(); + let s = o.stream_of(Codec::Opus).unwrap(); + // The last packet lies past the end of a source cut short: an error, not a read of missing bytes. + let short = &f[..f.len() / 2]; + assert!(matches!(o.read_packet(&short, s, 9), Err(Error::Invalid(_)))); +} diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index f40b1300a..20cd5725f 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -18,7 +18,13 @@ fn walk(dir: &Path, c: &mut Counts) { let p = e.path(); let name = e.file_name(); let name = name.to_string_lossy(); - if p.is_dir() { + // `file_type` does not follow links, so a directory link is not walked (and aliases are + // not counted twice). + let Ok(kind) = e.file_type() else { continue }; + if kind.is_symlink() { + continue; + } + if kind.is_dir() { // Nested fuzz workspaces and build output are not part of the crate. if name != "target" && name != "fuzz" && !name.starts_with('.') { walk(&p, c); From 07dc2210a1554b8186624e88b383bcc8bc0c9b19 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 4 Nov 2026 14:09:46 -0500 Subject: [PATCH 36/94] Repair: bound the notes page size like a slide (#1832) --- crates/format/src/lib.rs | 5 +++++ crates/format/src/tests.rs | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 6f345e11c..97caafdb3 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -247,6 +247,11 @@ pub fn repair(p: &mut Presentation) { if !(p.notes_size.width.is_finite() && p.notes_size.width > 0.0 && p.notes_size.height.is_finite() && p.notes_size.height > 0.0) { p.notes_size = Presentation::default().notes_size; } + // A notes page is bounded like a slide: canvas and handout drawing scale with it. + p.notes_size = deckcraft_model::Size::new( + p.notes_size.width.clamp(*SLIDE_SIDE.start(), *SLIDE_SIDE.end()), + p.notes_size.height.clamp(*SLIDE_SIDE.start(), *SLIDE_SIDE.end()), + ); sane_numbers(p); } diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index aa692d03f..ccda612f0 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -451,6 +451,13 @@ fn degenerate_slide_sizes_are_repaired() { } } +#[test] +fn repair_bounds_the_notes_page_size() { + let mut p = Presentation { notes_size: deckcraft_model::Size::new(1e12, 0.01), ..Default::default() }; + repair(&mut p); + assert_eq!((p.notes_size.width, p.notes_size.height), (4032.0, 72.0)); +} + /// A file whose slide size is null, a string or missing a side (written by hand or by /// another tool; NaN is also saved as null) opens with the default size rather than failing /// as damaged. From 80f784d21011dc71bfe20abe0bbc144e1713fae9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 4 Nov 2026 14:36:13 -0500 Subject: [PATCH 37/94] Fonts: ignore variation tags the font has no axis for (#1795) --- crates/fonts/src/fontdb.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index c1db0b356..19f190445 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -1260,9 +1260,8 @@ impl FontDb { fn instance(&self, family: &str, style: &str) -> Option<Arc<FontFace>> { let open = style.find('{')?; let base = self.find(family, style[..open].trim())?; - if base.skrifa().is_none_or(|f| f.axes().is_empty()) { - return Some(base); - } + let Some(font) = base.skrifa().filter(|f| !f.axes().is_empty()) else { return Some(base) }; + let axis_tags: Vec<[u8; 4]> = font.axes().iter().map(|a| a.tag().to_be_bytes()).collect(); let mut coords = base.coords.clone(); for kv in style[open + 1..].trim_end_matches('}').split(',') { let (k, v) = kv.split_once(':')?; @@ -1272,6 +1271,11 @@ impl FontDb { return None; } let tag = [k[0], k[1], k[2], k[3]]; + // A tag the font has no axis for changes nothing; keeping it would grow the list with + // every distinct tag in the style text. + if !axis_tags.contains(&tag) { + continue; + } match coords.iter_mut().find(|(t, _)| *t == tag) { Some(c) => c.1 = v, None => coords.push((tag, v)), From 9d36b5931cf93b36605eb5c8173260a2a346ccf5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:15:59 +0100 Subject: [PATCH 38/94] Ogg: include recovered tail packets in Opus duration (#1862) * Ogg: include recovered tail packets in Opus duration Keep the existing missing-granule recovery cursor in step with the packet ends it assigns. Add a regression for a partially and entirely unanchored stream; existing valid end-trimming coverage remains unchanged. Validation: rustc --edition=2024 --test crates/ogg/src/lib.rs: all 12 tests pass. Scoped rustfmt check passes. Full cargo --offline xtask ci is blocked before build by the uncached pinned egui checkout. * Ogg: record recovery duration correction --- ROADMAP.md | 4 ++++ crates/ogg/src/lib.rs | 1 + crates/ogg/src/tests.rs | 21 +++++++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 9315be8a6..37ef74b55 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,6 +2,8 @@ **Stage: alpha** · next: beta, ~20 points and ~120–210 h away +> **Last reviewed:** 2026-11-04 · **Last updated:** 2026-11-04 · **Change:** trivial (Ogg Opus recovery includes trailing packets without granules in its reported duration; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) + > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** trivial (community PR wave 10: PPTX and native saves keep table cell centred anchoring, text overflow, compatible line spacing, normalised character height, Thai distributed alignment, RTL table direction, alternate run language and reflection transforms; imported effects placed by parent time-node delays; Reuse Slides fits the destination size and brings custom table styles; deleted slides leave custom shows; merged shapes drop their animations; Compress Pictures measures grouped pictures at displayed size; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-02 · **Change:** trivial (File › About replaces Account; product links, credits and appearance retained; parity scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) > **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-01 · **Change:** trivial (locked No Fill and no-outline click-through regression coverage added; No Fill hit-testing follows resolved fill instead of the presence of a style (#1621); scores unchanged) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) @@ -150,6 +152,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | What landed | |---|---| +| 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | | 2026-11-02 | Native and PPTX saves retain optional table right-to-left direction, including explicit false and omission; two-save round-trip tests keep labeled columns in order | | 2026-11-02 | Text runs preserve alternate-language metadata independently from the main language through native and PPTX saves | | 2026-11-02 | Picture compression measures displayed dimensions through nested group transforms; checklist score unchanged | @@ -330,6 +333,7 @@ app's JSON control channel (`deckcraft --control PORT`). | Date | Change | Summary | |---|---|---| +| 2026-11-04 | trivial | Ogg Opus recovery duration includes its recovered tail; parity scores unchanged | | 2026-11-02 | trivial | Progress log: run alternate-language metadata round-trips through native and PPTX formats; product parity scores unchanged | | 2026-11-03 | trivial | Reuse Slides brings referenced custom table styles along; scores unchanged | | 2026-11-02 | trivial | File › About replaces Account; product links, credits and appearance retained | diff --git a/crates/ogg/src/lib.rs b/crates/ogg/src/lib.rs index 719c96698..0261ee0e6 100644 --- a/crates/ogg/src/lib.rs +++ b/crates/ogg/src/lib.rs @@ -513,6 +513,7 @@ impl OpusTiming { c = timing_add(c, i64::from(durations[k]))?; ends[k] = Some(c); } + cursor = Some(c); break; } let Some(g) = stream.packets[j].granule else { break }; diff --git a/crates/ogg/src/tests.rs b/crates/ogg/src/tests.rs index 8f9673089..728e618bd 100644 --- a/crates/ogg/src/tests.rs +++ b/crates/ogg/src/tests.rs @@ -183,6 +183,27 @@ fn opus_toc_durations() { assert_eq!(opus_packet_samples([0xF8, 0], 0), None); } +#[test] +fn opus_timing_includes_packets_after_the_last_known_granule() { + let f = opus_file(6, 312, 0); + let o = open(&f).unwrap(); + let mut stream = o.streams[0].clone(); + // Missing granules on complete-packet pages are non-conforming. The existing recovery + // fallback still assigns their packet positions; total must include the same samples. + stream.packets.last_mut().unwrap().granule = None; + let timing = OpusTiming::of(&stream, 312).unwrap(); + assert_eq!(timing.starts, vec![-312, 648, 1608, 2568, 3528, 4488]); + assert_eq!(timing.total, 6 * 960 - 312); + + // With no usable granule, every complete packet still contributes its TOC duration. + for packet in &mut stream.packets { + packet.granule = None; + } + let timing = OpusTiming::of(&stream, 312).unwrap(); + assert_eq!(timing.starts, vec![-312, 648, 1608, 2568, 3528, 4488]); + assert_eq!(timing.total, 6 * 960 - 312); +} + #[test] fn opus_timing_rejects_a_granule_that_overflows() { let packet = |granule: i64| Stream { From d6cc51e07a5cea0043778624f9f1445e1abe9a91 Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo <s.schott-verdugo@fz-juelich.de> Date: Wed, 4 Nov 2026 21:43:33 +0100 Subject: [PATCH 39/94] Alt+drag detaches placeholders; Slide Master view pastes them as placeholders Review follow-up on #1658: - The drag duplicate cleared `ph` without detaching, so a title or body dragged off with Alt lost its size and bullets. Copy, Duplicate and the drag now share `detach_on_slide`. - Detaching at copy time turned a slide placeholder pasted in Slide Master view into a regular shape. The clipboard keeps the originals, and a paste there takes them, so it stays a placeholder as before this PR. Keep Source Formatting bakes them too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- ROADMAP.md | 2 +- crates/engine/src/cmd/edit.rs | 43 ++++++++++++++-------- crates/engine/src/lib.rs | 3 ++ crates/engine/src/tests.rs | 57 +++++++++++++++++++++++++++++ crates/engine/src/tools/geometry.rs | 1 + 5 files changed, 89 insertions(+), 17 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index bb42939ac..db6929860 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -164,7 +164,7 @@ app's JSON control channel (`deckcraft --control PORT`). | 2026-11-03 | Reuse Slides brings along referenced custom table styles, including grouped tables, and remaps conflicting style ids without changing destination tables | | 2026-11-02 | Tiled picture fills in groups: a tile (`a:blipFill` with `a:tile`) keeps its size, offset and anchor in slide points whatever the group's child-coordinate scale, uniform or stretched unevenly, nested or flipped (also a group's own tile fill passed to its members, and a picture shape's own tile, with its shadow and reflection), and tiles with `rotWithShape="0"` keep their size in points at any zoom, as PowerPoint draws them (measured on its own PNG export of a synthetic probe deck: every grouped case within ~3/255 of the ungrouped control's own difference from PowerPoint, which is ~13/255 from resampling). Before, a group whose child space was ~1800 times smaller than its box showed one flat texel of the texture (a Venn diagram with paper-textured circles and a hatched intersection) | | 2026-11-01 | Ctrl+V of a picture copied in a browser (Copy Image) pastes the picture, not a text box with its link and alt text; the link still pastes as text when no picture came with it | -| 2026-11-01 | Copy, Cut, Paste and Duplicate of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text | +| 2026-11-01 | Copy, Cut, Paste, Duplicate and Alt+drag of a title, body or other placeholder on a slide keep its look: the copy is a regular shape that takes the size, font, bullets, indents, autofit and box its layout and master gave it, instead of 18 pt unbulleted text | | 2026-11-01 | Clipboard: Ctrl+C, Ctrl+X and Ctrl+V use the system clipboard again, so text and pictures paste from other apps and in-app copies paste back. Since the egui 0.37 migration (#1350) the desktop build had a clipboard that only worked inside the app. On native Wayland, text goes through egui's Wayland clipboard; HTML stays on X11, macOS and Windows | | 2026-10-31 | No Fill shape interiors allow selection and editing of underlying objects, even when a quick style remains; hit-testing uses the renderer’s fill resolution. Outlines, rotation, text targets and actual fills keep their hit behaviour (#1621) | | 2026-10-30 | Print-preview tests use the URL emitted by egui and its exact file path; previews are explicitly removed before the macOS process exits | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9674bb8ad..9ff5cbb71 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -107,7 +107,7 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> { s.clipboard = crate::Clipboard { text: Some(TextBody::from_text(&plain)), plain: plain.clone(), ..Default::default() }; return Ok(plain); } - let shapes: Vec<Shape> = st + let mut shapes: Vec<Shape> = st .selection .shapes .iter() @@ -120,21 +120,28 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> { }) }) .collect(); - // A placeholder pastes on a slide as a regular shape; it keeps the look it inherited here. - let mut shapes = shapes; - if st.selection.target == crate::Target::Slides - && let Some(ctx) = st.current_slide().and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(&st.doc, sl)) - { - shapes.iter_mut().for_each(|sh| deckcraft_model::resolve::detach_placeholder(&ctx, sh)); - } + // Copying is the last chance to read what a placeholder inherits: a cut removes it, and the + // paste can be in another deck. Slide Master view pastes the originals instead. + let placeholders: Vec<Shape> = shapes.iter().filter(|x| x.ph.is_some()).cloned().collect(); + detach_on_slide(&st.doc, &st.selection, &mut shapes); let mids = crate::media_refs::shapes_media(&shapes); let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect(); let plain = shapes.iter().filter_map(|x| x.text.as_ref().map(|t| t.text())).collect::<Vec<_>>().join("\n"); let source_theme = st.current_slide().and_then(|sl| st.doc.master_for(sl)).map(|(m, _)| (m.scheme(), m.theme.fonts.clone())); - s.clipboard = crate::Clipboard { shapes, media, plain: plain.clone(), source_theme, ..Default::default() }; + s.clipboard = crate::Clipboard { shapes, placeholders, media, plain: plain.clone(), source_theme, ..Default::default() }; Ok(plain) } +/// On a slide, a copy of a placeholder is a regular shape: give `shapes` the look they inherit +/// there. In Slide Master view a copy stays a placeholder, so this changes nothing. +pub(crate) fn detach_on_slide(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shapes: &mut [Shape]) { + if sel.target == crate::Target::Slides + && let Some(ctx) = super::text::ctx_for(doc, sel) + { + shapes.iter_mut().for_each(|sh| deckcraft_model::resolve::detach_placeholder(&ctx, sh)); + } +} + fn copying_caret(s: &Session) -> bool { s.active().is_some_and(|d| d.selection.text.as_ref().is_some_and(|t| !t.is_range())) } @@ -326,6 +333,13 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> { return s.edit(|doc, sel| { let media = bring_media("edit.paste", doc, &clip.media)?; let mut shapes = clip.shapes.clone(); + if sel.target != crate::Target::Slides { + for sh in &mut shapes { + if let Some(original) = clip.placeholders.iter().find(|p| p.id == sh.id) { + sh.clone_from(original); + } + } + } reid("edit.paste", doc, &mut shapes)?; crate::media_refs::visit_mut::shapes(&mut shapes, &mut remap_media(&media)); let (mut taken, mut count) = super::current_names(doc, sel); @@ -347,7 +361,8 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> { x.x += off; x.y += off; } - // A pasted placeholder becomes a regular shape; copying gave it its look. + // A placeholder pasted on a slide becomes a regular shape. One copied from a slide + // already has its look; see `copy_inner`. if sh.ph.is_some() && sel.target == crate::Target::Slides { sh.ph = None; } @@ -413,6 +428,7 @@ fn paste_special(s: &mut Session, p: &Value) -> Result<Value> { let saved = s.clipboard.clone(); if let Some((scheme, fonts)) = &saved.source_theme { bake_theme(&mut s.clipboard.shapes, scheme, fonts); + bake_theme(&mut s.clipboard.placeholders, scheme, fonts); } let r = paste(s, &json!({})); let pastes = s.clipboard.pastes; @@ -540,12 +556,7 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> { let mut copies: Vec<Shape> = list.iter().filter(|x| ids.contains(&x.id)).cloned().collect(); let sources: Vec<ShapeId> = copies.iter().map(|c| c.id).collect(); let boxes: Vec<_> = copies.iter().map(|c| xfrm_of(doc, sel, c)).collect(); - // A duplicated placeholder becomes a regular shape that keeps the look it inherited. - if sel.target == crate::Target::Slides - && let Some(ctx) = doc.slides.get(sel.slide).and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(doc, sl)) - { - copies.iter_mut().for_each(|c| deckcraft_model::resolve::detach_placeholder(&ctx, c)); - } + detach_on_slide(doc, sel, &mut copies); // Duplicating the copies of the last Duplicate again repeats how far they were moved // since (#966); anything else gets the usual offset. let (dx, dy) = last diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c6d9f4503..dbd2b68b6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -457,6 +457,9 @@ pub struct MediaStatus { #[derive(Clone, Debug, Default)] pub struct Clipboard { pub shapes: Vec<Shape>, + /// The copied placeholders as they were, by id. `shapes` holds a slide's placeholders as + /// regular shapes; a paste in Slide Master view takes these, which stay placeholders. + pub placeholders: Vec<Shape>, pub slides: Vec<Slide>, /// Media the copied shapes/slides reference. pub media: Vec<deckcraft_model::MediaItem>, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fb7f2b039..05baa3ca3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -267,6 +267,63 @@ fn a_pasted_or_duplicated_placeholder_keeps_its_inherited_look() { assert!(s.doc().unwrap().doc.validate().is_empty()); } +/// Dragging a copy of a placeholder off it keeps the look too: the title's size and font, the +/// body's bullets. `edit.duplicate` is not the only way to duplicate. +#[test] +fn a_placeholder_duplicated_by_dragging_keeps_its_look() { + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let phs: Vec<ShapeId> = s.doc().unwrap().current_slide().unwrap().shapes.iter().filter(|x| x.ph.is_some()).map(|x| x.id).collect(); + assert!(phs.len() >= 2, "a title and a body placeholder"); + for id in phs { + s.execute("text.set", &json!({"id": id.0, "text": "First\nSecond"})).unwrap(); + let want = resolved_look(&s, id); + s.execute("selection.select", &json!({"id": id.0})).unwrap(); + let st = s.doc().unwrap(); + let x = crate::cmd::xfrm_of(&st.doc, &st.selection, st.shape(id).unwrap()); + let (cx, cy) = (x.x + x.w / 2.0, x.y + x.h / 2.0); + let alt = |kind, x, y| PointerEvent { mods: Mods { alt: true, ..Default::default() }, ..tev(kind, x, y) }; + s.pointer(alt(PointerKind::Down, cx, cy)).unwrap(); + s.pointer(alt(PointerKind::Drag, cx + 30.0, cy + 30.0)).unwrap(); + s.pointer(alt(PointerKind::Up, cx + 30.0, cy + 30.0)).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_ne!(copy, id, "the drag made a copy"); + assert!(s.doc().unwrap().shape(id).unwrap().ph.is_some(), "the original stays a placeholder"); + assert!(s.doc().unwrap().shape(copy).unwrap().ph.is_none(), "the copy is a regular shape"); + assert_eq!(resolved_look(&s, copy), want, "placeholder {}", id.0); + } +} + +/// A slide's placeholder pasted in Slide Master view stays a placeholder that inherits from where +/// it lands; only a paste on a slide turns it into a regular shape with the look it had. +#[test] +fn a_slide_placeholder_pasted_in_slide_master_view_stays_a_placeholder() { + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let title = s.doc().unwrap().current_slide().unwrap().shapes.iter().find(|x| x.ph.is_some()).unwrap().id; + s.execute("text.set", &json!({"id": title.0, "text": "Title"})).unwrap(); + let want = resolved_look(&s, title); + let source = s.doc().unwrap().shape(title).unwrap().clone(); + s.execute("selection.select", &json!({"id": title.0})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + + s.execute("view.slideMaster", &json!({})).unwrap(); + for paste in ["edit.paste", "edit.pasteSpecial"] { + s.execute(paste, &json!({"as": "keepSource"})).unwrap(); + let st = s.doc().unwrap(); + let copy = st.shape(st.selection.shapes[0]).unwrap(); + assert_eq!(copy.ph.as_ref().map(|p| p.kind), source.ph.as_ref().map(|p| p.kind), "{paste} keeps the placeholder"); + let list = copy.text.as_ref().map(|t| t.list_style.clone()); + assert_eq!(list, source.text.as_ref().map(|t| t.list_style.clone()), "{paste} adds no baked styles"); + } + s.execute("view.closeMaster", &json!({})).unwrap(); + + s.execute("edit.paste", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert!(s.doc().unwrap().shape(copy).unwrap().ph.is_none(), "on a slide the copy is a regular shape"); + assert_eq!(resolved_look(&s, copy), want); +} + /// The resolved fill, line and effects of shape `id` on the current slide, with their style colours. fn resolved_box(s: &Session, id: ShapeId) -> String { use deckcraft_model::resolve; diff --git a/crates/engine/src/tools/geometry.rs b/crates/engine/src/tools/geometry.rs index cbbd01275..0da6aa60c 100644 --- a/crates/engine/src/tools/geometry.rs +++ b/crates/engine/src/tools/geometry.rs @@ -101,6 +101,7 @@ impl Session { let list = cmd::current_shapes(doc, sel).cloned().unwrap_or_default(); let mut copies: Vec<Shape> = list.iter().filter(|x| ids.contains(&x.id)).cloned().collect(); let boxes: Vec<Xfrm> = copies.iter().map(|c| xfrm_of(doc, sel, c)).collect(); + cmd::edit::detach_on_slide(doc, sel, &mut copies); cmd::edit::reid("edit.duplicate", doc, &mut copies)?; for (c, b) in copies.iter_mut().zip(boxes) { c.xfrm = Some(b); From 65ddd8ad517e15032195059c73f54c690e5d2dbf Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:55:43 +0000 Subject: [PATCH 40/94] Apply review fixes - crates/render/src/placed.rs --- crates/render/src/placed.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/render/src/placed.rs b/crates/render/src/placed.rs index bde0fa157..483db41bc 100644 --- a/crates/render/src/placed.rs +++ b/crates/render/src/placed.rs @@ -160,16 +160,6 @@ fn place(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, s: &Shape, parent: fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId, s: &Shape, body: &TextBody, tr: Rect, m: Affine) { let layout = deckcraft_text::layout(rctx, s, body, &Opts { rect: tr, fields, prompt_color: None, no_shrink: false }); let m = crate::text_transform(m, tr, layout.rotation); - // Text hyperlinks: one box per line segment of a linked run. - for run in layout.runs.iter().filter(|r| r.link && !r.glyphs.is_empty()) { - let Some(link) = run_link(body, run.para, run.chars.0) else { continue }; - let Some(line) = layout.lines.iter().find(|l| l.para == run.para && l.start <= run.chars.0 && run.chars.0 <= l.end) else { continue }; - // The run's visual extent (right-to-left runs run from right to left). - let first = run.glyphs.first().map(|g| g.1).unwrap_or(0.0); - let (x0, x1) = line.span(run.chars.0, run.chars.1).unwrap_or((first, first)); - let r = Rect::new(x0, line.top, x1, line.bottom); - out.links.push(PlacedLink { rect: m.transform_rect_bbox(r), link, shape: owner, text: true }); - } // Field runs carry their saved text (`‹#›`); the layout drew their values, so the body that // goes with it (character offsets, text layer) must hold the same values. let mut placed = body.clone(); @@ -185,6 +175,16 @@ fn place_text(out: &mut Placed, rctx: &Ctx, fields: &SlideFields, owner: ShapeId } } } + // Text hyperlinks: one box per line segment of a linked run. + for run in layout.runs.iter().filter(|r| r.link && !r.glyphs.is_empty()) { + let Some(link) = run_link(&placed, run.para, run.chars.0) else { continue }; + let Some(line) = layout.lines.iter().find(|l| l.para == run.para && l.start <= run.chars.0 && run.chars.0 <= l.end) else { continue }; + // The run's visual extent (right-to-left runs run from right to left). + let first = run.glyphs.first().map(|g| g.1).unwrap_or(0.0); + let (x0, x1) = line.span(run.chars.0, run.chars.1).unwrap_or((first, first)); + let r = Rect::new(x0, line.top, x1, line.bottom); + out.links.push(PlacedLink { rect: m.transform_rect_bbox(r), link, shape: owner, text: true }); + } out.texts.push(PlacedText { layout, transform: m, body: placed }); } From 30ccc38e9032fd240ac56f604693ba9c11df67b6 Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo <s.schott-verdugo@fz-juelich.de> Date: Wed, 4 Nov 2026 22:02:22 +0100 Subject: [PATCH 41/94] Keep Source Formatting uses the slide's colour map Review follow-up on #1658 (CodeRabbit): `source_theme` stored the master's scheme, so a slide or layout that overrides the colour map had its colours fixed through the wrong map. Detaching made this reach a placeholder's inherited colours: a title drawn white under an override pasted black. Store the scheme the slide draws with. Paste as Picture reads the same value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/edit.rs | 6 ++++- crates/engine/src/tests.rs | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ff5cbb71..20874d5dc 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -127,7 +127,11 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> { let mids = crate::media_refs::shapes_media(&shapes); let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect(); let plain = shapes.iter().filter_map(|x| x.text.as_ref().map(|t| t.text())).collect::<Vec<_>>().join("\n"); - let source_theme = st.current_slide().and_then(|sl| st.doc.master_for(sl)).map(|(m, _)| (m.scheme(), m.theme.fonts.clone())); + // The scheme the slide draws with: its or its layout's colour map, else the master's. + let source_theme = st + .current_slide() + .and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(&st.doc, sl)) + .map(|ctx| (ctx.scheme.clone(), ctx.master.theme.fonts.clone())); s.clipboard = crate::Clipboard { shapes, placeholders, media, plain: plain.clone(), source_theme, ..Default::default() }; Ok(plain) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 05baa3ca3..2c3ecedee 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -294,6 +294,48 @@ fn a_placeholder_duplicated_by_dragging_keeps_its_look() { } } +/// Keep Source Formatting fixes a copy's theme colours as the source drew them: through the colour +/// map of its slide or layout, not the master's. A title's inherited `tx1` stays the light colour +/// an override gave it. +#[test] +fn keep_source_formatting_uses_the_slides_colour_map() { + use deckcraft_model::resolve; + let first_run_colour = |s: &Session, id: ShapeId| { + let st = s.doc().unwrap(); + let ctx = resolve::Ctx::for_slide(&st.doc, st.current_slide().unwrap()).unwrap(); + let sh = st.shape(id).unwrap(); + let p = &sh.text.as_ref().unwrap().paragraphs[0]; + resolve::text_color(&ctx, &resolve::run(&ctx, sh, p, &p.runs[0].props)) + }; + let swapped = || Some([("bg1", "dk1"), ("tx1", "lt1"), ("bg2", "dk2"), ("tx2", "lt2")].map(|(a, b)| (a.to_string(), b.to_string())).to_vec()); + for on_layout in [false, true] { + let mut s = session(); + s.execute("slide.new", &json!({})).unwrap(); + let title = s.doc().unwrap().current_slide().unwrap().shapes.iter().find(|x| x.ph.is_some()).unwrap().id; + s.execute("text.set", &json!({"id": title.0, "text": "Title"})).unwrap(); + let plain = first_run_colour(&s, title); + let st = s.doc_mut().unwrap(); + let at = st.selection.slide; + let doc = std::sync::Arc::make_mut(&mut st.doc); + if on_layout { + let layout = doc.slides[at].layout; + let m = std::sync::Arc::make_mut(&mut doc.masters[0]); + m.layouts.iter_mut().find(|l| l.id == layout).unwrap().color_map = swapped(); + } else { + std::sync::Arc::make_mut(&mut doc.slides[at]).color_map = swapped(); + } + let want = first_run_colour(&s, title); + assert_ne!(want, plain, "the override changes how the title draws"); + + s.execute("selection.select", &json!({"id": title.0})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.pasteSpecial", &json!({"as": "keepSource"})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_ne!(copy, title); + assert_eq!(first_run_colour(&s, copy), want, "override on the layout: {on_layout}"); + } +} + /// A slide's placeholder pasted in Slide Master view stays a placeholder that inherits from where /// it lands; only a paste on a slide turns it into a regular shape with the look it had. #[test] From 070f12cc9c8d38dd1f8934a29a5ec2a67882fe0b Mon Sep 17 00:00:00 2001 From: Stephan Schott-Verdugo <s.schott-verdugo@fz-juelich.de> Date: Wed, 4 Nov 2026 22:23:35 +0100 Subject: [PATCH 42/94] Keep Source Formatting resolves colours as the renderer does Review follow-up on #1658 (CodeRabbit), both from storing the slide's mapped scheme in 30ccc38e: - Copying in Slide Master view used the current slide's colour map. Use `ctx_for`, so the theme is that of what is being edited. - `ColorScheme` shares an entry between `dk1` and `tx1`, so a mapped scheme changed direct `dk1` colours too: a dark fill pasted white. `SourceTheme` keeps the theme's colours and the map apart, and `bake_theme` maps only `tx1`, `bg1`, `tx2` and `bg2`, as `Ctx::color` does. The browser image test now checks that non-picture pastes keep their text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/edit.rs | 37 +++++++-------- crates/engine/src/lib.rs | 16 +++++-- crates/engine/src/tests.rs | 84 +++++++++++++++++++++++++++++++++-- crates/ui-egui/src/tests.rs | 4 ++ 4 files changed, 117 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 20874d5dc..743aa8362 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -127,11 +127,12 @@ fn copy_inner(s: &mut Session, p: &Value) -> Result<String> { let mids = crate::media_refs::shapes_media(&shapes); let media = st.doc.media.iter().filter(|m| mids.contains(&m.id)).cloned().collect(); let plain = shapes.iter().filter_map(|x| x.text.as_ref().map(|t| t.text())).collect::<Vec<_>>().join("\n"); - // The scheme the slide draws with: its or its layout's colour map, else the master's. - let source_theme = st - .current_slide() - .and_then(|sl| deckcraft_model::resolve::Ctx::for_slide(&st.doc, sl)) - .map(|ctx| (ctx.scheme.clone(), ctx.master.theme.fonts.clone())); + // The theme of what is being edited: a slide's or layout's colour map, else the master's. + let source_theme = super::text::ctx_for(&st.doc, &st.selection).map(|ctx| crate::SourceTheme { + colors: ctx.master.theme.colors.clone(), + color_map: ctx.color_map.clone(), + fonts: ctx.master.theme.fonts.clone(), + }); s.clipboard = crate::Clipboard { shapes, placeholders, media, plain: plain.clone(), source_theme, ..Default::default() }; Ok(plain) } @@ -430,9 +431,9 @@ fn paste_special(s: &mut Session, p: &Value) -> Result<Value> { "text" | "keepTextOnly" => paste_text(s, &json!({})), "keepSource" | "keepSourceFormatting" => { let saved = s.clipboard.clone(); - if let Some((scheme, fonts)) = &saved.source_theme { - bake_theme(&mut s.clipboard.shapes, scheme, fonts); - bake_theme(&mut s.clipboard.placeholders, scheme, fonts); + if let Some(theme) = &saved.source_theme { + bake_theme(&mut s.clipboard.shapes, theme); + bake_theme(&mut s.clipboard.placeholders, theme); } let r = paste(s, &json!({})); let pastes = s.clipboard.pastes; @@ -447,8 +448,8 @@ fn paste_special(s: &mut Session, p: &Value) -> Result<Value> { /// Replace theme colours and theme fonts with the values they have in `scheme` / `fonts`, so the /// shapes keep their look under another theme. -pub(crate) fn bake_theme(shapes: &mut [Shape], scheme: &deckcraft_color::ColorScheme, fonts: &deckcraft_model::theme::FontScheme) { - fn rec(v: &mut Value, scheme: &deckcraft_color::ColorScheme, fonts: &deckcraft_model::theme::FontScheme, depth: usize) { +pub(crate) fn bake_theme(shapes: &mut [Shape], theme: &crate::SourceTheme) { + fn rec(v: &mut Value, theme: &crate::SourceTheme, depth: usize) { if depth > 256 { return; } @@ -457,7 +458,7 @@ pub(crate) fn bake_theme(shapes: &mut [Shape], scheme: &deckcraft_color::ColorSc if o.get("kind").and_then(Value::as_str) == Some("scheme") && let Some(slot) = o.get("slot").and_then(|x| serde_json::from_value::<deckcraft_color::SchemeSlot>(x.clone()).ok()) && slot != deckcraft_color::SchemeSlot::PhClr - && let Ok(rgb) = serde_json::to_value(scheme.get(slot)) + && let Ok(rgb) = serde_json::to_value(theme.colors.get(deckcraft_model::map_slot(&theme.color_map, slot))) { o.clear(); o.insert("kind".into(), json!("rgb")); @@ -465,14 +466,14 @@ pub(crate) fn bake_theme(shapes: &mut [Shape], scheme: &deckcraft_color::ColorSc return; } for x in o.values_mut() { - rec(x, scheme, fonts, depth + 1); + rec(x, theme, depth + 1); } } - Value::Array(a) => a.iter_mut().for_each(|x| rec(x, scheme, fonts, depth + 1)), + Value::Array(a) => a.iter_mut().for_each(|x| rec(x, theme, depth + 1)), Value::String(t) if t.starts_with('+') => { let set = match t.get(1..3) { - Some("mj") => &fonts.major, - Some("mn") => &fonts.minor, + Some("mj") => &theme.fonts.major, + Some("mn") => &theme.fonts.minor, _ => return, }; let face = match t.get(3..) { @@ -490,7 +491,7 @@ pub(crate) fn bake_theme(shapes: &mut [Shape], scheme: &deckcraft_color::ColorSc } for sh in shapes.iter_mut() { let Ok(mut v) = serde_json::to_value(&*sh) else { continue }; - rec(&mut v, scheme, fonts, 0); + rec(&mut v, theme, 0); if let Ok(baked) = serde_json::from_value::<Shape>(v) { *sh = baked; } @@ -503,8 +504,8 @@ fn paste_picture(s: &mut Session) -> Result<Value> { if clip.shapes.is_empty() { return Err(bad("edit.pasteSpecial", "copy shapes first to paste them as a picture")); } - if let Some((scheme, fonts)) = &clip.source_theme { - bake_theme(&mut clip.shapes, scheme, fonts); + if let Some(theme) = &clip.source_theme { + bake_theme(&mut clip.shapes, theme); } let st = s.doc()?; let mut doc = (*st.doc).clone(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dbd2b68b6..d8ebb5a23 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -454,6 +454,17 @@ pub struct MediaStatus { } /// Clipboard contents copied within the app. +/// The theme a copy drew with. The colours and the map stay apart, as in +/// `deckcraft_model::resolve::Ctx::color`: the map renames only `tx1`, `bg1`, `tx2` and `bg2`, and +/// a direct `dk1` keeps the theme's colour. +#[derive(Clone, Debug)] +pub struct SourceTheme { + /// The theme's own colours, no colour map applied. + pub colors: deckcraft_color::ColorScheme, + pub color_map: Vec<(String, String)>, + pub fonts: deckcraft_model::theme::FontScheme, +} + #[derive(Clone, Debug, Default)] pub struct Clipboard { pub shapes: Vec<Shape>, @@ -465,9 +476,8 @@ pub struct Clipboard { pub media: Vec<deckcraft_model::MediaItem>, pub text: Option<deckcraft_model::TextBody>, pub plain: String, - /// The copied shapes' theme colours (colour map applied) and fonts, for Paste Special › - /// Keep Source Formatting. - pub source_theme: Option<(deckcraft_color::ColorScheme, deckcraft_model::theme::FontScheme)>, + /// The theme the shapes were copied under, for Paste Special › Keep Source Formatting. + pub source_theme: Option<SourceTheme>, /// How many times the shapes were pasted (each paste offsets further). pub pastes: u32, } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2c3ecedee..5f3eb5c0b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -307,7 +307,6 @@ fn keep_source_formatting_uses_the_slides_colour_map() { let p = &sh.text.as_ref().unwrap().paragraphs[0]; resolve::text_color(&ctx, &resolve::run(&ctx, sh, p, &p.runs[0].props)) }; - let swapped = || Some([("bg1", "dk1"), ("tx1", "lt1"), ("bg2", "dk2"), ("tx2", "lt2")].map(|(a, b)| (a.to_string(), b.to_string())).to_vec()); for on_layout in [false, true] { let mut s = session(); s.execute("slide.new", &json!({})).unwrap(); @@ -320,9 +319,9 @@ fn keep_source_formatting_uses_the_slides_colour_map() { if on_layout { let layout = doc.slides[at].layout; let m = std::sync::Arc::make_mut(&mut doc.masters[0]); - m.layouts.iter_mut().find(|l| l.id == layout).unwrap().color_map = swapped(); + m.layouts.iter_mut().find(|l| l.id == layout).unwrap().color_map = swapped_colour_map(); } else { - std::sync::Arc::make_mut(&mut doc.slides[at]).color_map = swapped(); + std::sync::Arc::make_mut(&mut doc.slides[at]).color_map = swapped_colour_map(); } let want = first_run_colour(&s, title); assert_ne!(want, plain, "the override changes how the title draws"); @@ -336,6 +335,85 @@ fn keep_source_formatting_uses_the_slides_colour_map() { } } +/// A colour map that swaps text and background, as a dark slide or layout has. +fn swapped_colour_map() -> Option<Vec<(String, String)>> { + Some([("bg1", "dk1"), ("tx1", "lt1"), ("bg2", "dk2"), ("tx2", "lt2")].map(|(a, b)| (a.to_string(), b.to_string())).to_vec()) +} + +/// A new rectangle in the edited tree, filled with theme colour `slot`. +fn rect_filled_with(s: &mut Session, slot: deckcraft_color::SchemeSlot) -> ShapeId { + use deckcraft_model::{ColorRef, Fill}; + let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let id = ShapeId(u32::try_from(id).unwrap()); + s.edit(|doc, sel| { + let list = crate::shapes_mut(doc, sel).unwrap(); + list.iter_mut().find(|x| x.id == id).unwrap().fill = Some(Fill::solid(ColorRef::scheme(slot))); + Ok(()) + }) + .unwrap(); + id +} + +/// How shape `id`'s fill draws in the edited tree. +fn drawn_fill(s: &Session, id: ShapeId) -> deckcraft_color::Rgba { + use deckcraft_model::{Fill, resolve}; + let st = s.doc().unwrap(); + let ctx = crate::cmd::text::ctx_for(&st.doc, &st.selection).unwrap(); + match resolve::fill(&ctx, st.shape(id).unwrap()).0 { + Some(Fill::Solid { color }) => ctx.color(&color, None), + other => panic!("not a solid fill: {other:?}"), + } +} + +/// Copy the selected shape and paste it with Keep Source Formatting; the copy's id. +fn keep_source_copy(s: &mut Session, id: ShapeId) -> ShapeId { + s.execute("selection.select", &json!({"id": id.0})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.pasteSpecial", &json!({"as": "keepSource"})).unwrap(); + let copy = s.doc().unwrap().selection.shapes[0]; + assert_ne!(copy, id); + copy +} + +/// A colour map renames only `tx1`, `bg1`, `tx2` and `bg2`. Keep Source Formatting fixes every slot +/// as it draws: `tx1` follows the map, while a direct `dk1` stays the theme's dark colour. +#[test] +fn keep_source_formatting_maps_only_the_alias_colours() { + use deckcraft_color::SchemeSlot::{self, *}; + let mut s = session(); + let st = s.doc_mut().unwrap(); + let at = st.selection.slide; + std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut st.doc).slides[at]).color_map = swapped_colour_map(); + let slots: [SchemeSlot; 9] = [Dk1, Lt1, Dk2, Lt2, Tx1, Bg1, Tx2, Bg2, Accent1]; + let mut drawn = vec![]; + for slot in slots { + let id = rect_filled_with(&mut s, slot); + let want = drawn_fill(&s, id); + let copy = keep_source_copy(&mut s, id); + assert_eq!(drawn_fill(&s, copy), want, "{slot:?}"); + drawn.push(want); + } + assert_ne!(drawn[0], drawn[4], "the map sets `tx1` apart from `dk1`"); +} + +/// In Slide Master view a copy draws through the edited master's map, not an override on the slide +/// that happens to be current. +#[test] +fn keep_source_formatting_in_slide_master_view_ignores_the_slides_colour_map() { + use deckcraft_color::SchemeSlot::Tx1; + for master in [false, true] { + let mut s = session(); + let st = s.doc_mut().unwrap(); + let at = st.selection.slide; + std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut st.doc).slides[at]).color_map = swapped_colour_map(); + s.execute("view.slideMaster", &if master { json!({"master": 0}) } else { json!({}) }).unwrap(); + let id = rect_filled_with(&mut s, Tx1); + let want = drawn_fill(&s, id); + let copy = keep_source_copy(&mut s, id); + assert_eq!(drawn_fill(&s, copy), want, "editing the master: {master}"); + } +} + /// A slide's placeholder pasted in Slide Master view stays a placeholder that inherits from where /// it lands; only a paste on a slide turns it into a regular shape with the look it had. #[test] diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 2eca813cf..f8fe10aab 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -419,6 +419,10 @@ fn ctrl_v_pastes_the_picture_a_browser_copied_not_its_link() { let pictures = shapes.iter().filter(|s| matches!(s.kind, deckcraft_model::ShapeKind::Picture { .. })).count(); assert_eq!(pictures, pictures_after, "{text:?}"); assert_eq!(shapes.len(), shapes_before + 1, "one shape, picture or text, for {text:?}"); + if pictures_after == 0 { + let pasted = shapes.last().and_then(|s| s.text.as_ref()).map(deckcraft_model::TextBody::text); + assert_eq!(pasted.as_deref(), Some(text.as_str()), "the text survives"); + } } } From 31abd2d819094b7e3b4a70746e7f804f4695ab0d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 4 Nov 2026 17:45:40 -0500 Subject: [PATCH 43/94] Pass the Linux signing key to the release workflow (#1868) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 09b477f38..b156fa50d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,3 +45,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} From fc18a78e65bc7ef125ee65c0a3279bc0793b7eb5 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:09:50 -0600 Subject: [PATCH 44/94] comment: reject malformed navigation indices (#1547) --- crates/engine/src/cmd/review.rs | 36 ++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/review.rs b/crates/engine/src/cmd/review.rs index 47cf1ff24..351ca29dc 100644 --- a/crates/engine/src/cmd/review.rs +++ b/crates/engine/src/cmd/review.rs @@ -219,7 +219,7 @@ fn neighbour(s: &mut Session, p: &Value, forward: bool) -> Result<Value> { let cmd = if forward { "comment.next" } else { "comment.prev" }; let (threads, slide, index) = { let st = s.doc()?; - (comment_threads(&st.doc), usize_param(p, "slide").unwrap_or(st.selection.slide), usize_param(p, "index")) + (comment_threads(&st.doc), usize_param(p, "slide").unwrap_or(st.selection.slide), super::opt_usize_param(p, "index", cmd)?) }; if threads.is_empty() { return Err(bad(cmd, "no comments")); @@ -862,6 +862,40 @@ mod tests { assert_eq!(here["text"], "on first"); } + #[test] + fn malformed_comment_navigation_index_does_not_change_selection() { + let mut s = Session::with_new(); + s.execute("comment.add", &json!({"text": "first"})).unwrap(); + s.execute("shape.insert", &json!({"preset": "rect", "rect": [10.0, 10.0, 40.0, 40.0]})).unwrap(); + s.execute("slide.new", &json!({})).unwrap(); + s.execute("comment.add", &json!({"text": "second"})).unwrap(); + s.execute("slide.go", &json!({"index": 0})).unwrap(); + let shape = s.doc().unwrap().doc.slides.first().and_then(|slide| slide.shapes.first()).map(|shape| shape.id).unwrap(); + s.doc_mut().unwrap().selection.shapes = vec![shape]; + + for (command, value) in [ + ("comment.next", json!(-1)), + ("comment.next", json!(1.5)), + ("comment.next", json!("bad")), + ("comment.prev", json!(-1)), + ("comment.prev", json!(1.5)), + ("comment.prev", json!("bad")), + ] { + let before = s.doc().unwrap().selection.clone(); + let error = s.execute(command, &json!({"index": value})).unwrap_err(); + assert!(error.to_string().contains("valid index"), "{command} {value}: {error}"); + assert_eq!(s.doc().unwrap().selection, before, "{command} {value}"); + } + + let zero = s.execute("comment.next", &json!({"slide": 0, "index": 0})).unwrap(); + assert_eq!(zero["slide"], 1); + assert_eq!(zero["index"], 0); + s.execute("slide.go", &json!({"index": 0})).unwrap(); + let omitted = s.execute("comment.next", &json!({})).unwrap(); + assert_eq!(omitted["slide"], 0); + assert_eq!(omitted["index"], 0); + } + #[test] fn timestamps_are_iso_utc() { assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z"); From 85de6ca5d76356ebaf3367ad319bd2fdbb0c0155 Mon Sep 17 00:00:00 2001 From: ".CooCoo" <RobertLeeLW@gmail.com> Date: Wed, 4 Nov 2026 15:11:29 -0800 Subject: [PATCH 45/94] Shape Fill: the gradient help says which kinds rotateWithShape keeps upright (#1843) With rotateWithShape false, the renderer lays linear and radial gradients out upright on the slide, while rectangular and path gradients still turn with the shape. The shape.fill params doc now says so. --- crates/engine/src/cmd/shape.rs | 2 +- crates/engine/src/cmd/shape/appearance.rs | 3 ++- crates/engine/src/tests.rs | 3 +++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/shape.rs b/crates/engine/src/cmd/shape.rs index 08ed9be64..a447a20b9 100644 --- a/crates/engine/src/cmd/shape.rs +++ b/crates/engine/src/cmd/shape.rs @@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> { "Shape Fill", ["Shape Format", "Shape Styles"], None, - "{color? | none?: true | background?: true (the slide background shows through; shapes and text boxes only) | gradient?: {stops: [[pos 0..1, color]], kind?: linear|radial|rectangular|path, angle?: deg (linear), focus?: [l, t, r, b] fractions (radial, rectangular and path: where the first stop sits), rotateWithShape?: bool} | picture?: base64 | pattern?: {preset, fg, bg} | transparency?: 0..1 | reset?: true, ids?}; pictureProps?: {tile?: bool, offsetX?, offsetY?: pt, scaleX?, scaleY?: 0..10, align?: tl|t|tr|l|ctr|r|bl|b|br, mirror?: none|x|y|xy, stretch?: [l, t, r, b] fractions, rotateWithShape?: bool} adjusts a picture fill; a group also formats its members", + "{color? | none?: true | background?: true (the slide background shows through; shapes and text boxes only) | gradient?: {stops: [[pos 0..1, color]], kind?: linear|radial|rectangular|path, angle?: deg (linear), focus?: [l, t, r, b] fractions (radial, rectangular and path: where the first stop sits), rotateWithShape?: bool (false keeps linear and radial gradients upright on the slide; rectangular and path gradients turn with the shape when drawn)} | picture?: base64 | pattern?: {preset, fg, bg} | transparency?: 0..1 | reset?: true, ids?}; pictureProps?: {tile?: bool, offsetX?, offsetY?: pt, scaleX?, scaleY?: 0..10, align?: tl|t|tr|l|ctr|r|bl|b|br, mirror?: none|x|y|xy, stretch?: [l, t, r, b] fractions, rotateWithShape?: bool} adjusts a picture fill; a group also formats its members", has_selection, fill ), diff --git a/crates/engine/src/cmd/shape/appearance.rs b/crates/engine/src/cmd/shape/appearance.rs index 4189deaa1..c515d2b2c 100644 --- a/crates/engine/src/cmd/shape/appearance.rs +++ b/crates/engine/src/cmd/shape/appearance.rs @@ -74,7 +74,8 @@ pub(super) fn change(s: &mut Session, p: &Value) -> Result<Value> { /// `{stops: [[pos 0–1, color], …], kind?: linear|radial|rectangular|path, angle?: deg (linear), /// focus?: [l, t, r, b] fractions (radial/rectangular/path: where the first stop sits), -/// rotateWithShape?}`. +/// rotateWithShape?}`. The renderer keeps only linear and radial gradients upright when +/// `rotateWithShape` is false; rectangular and path gradients turn with the shape. pub(crate) fn gradient_param(v: &Value) -> Option<Gradient> { let stops: Vec<GradientStop> = v .get("stops")? diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e37f9d135..12fac5efc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4321,6 +4321,9 @@ fn shape_fill_documents_each_gradient_key_and_kind() { let params = cmd::parse_params(find_command("shape.fill").unwrap().params).unwrap(); let about = params.iter().find(|p| p.name == "gradient").unwrap().about; assert_eq!(cmd::param_keys(about).unwrap(), ["stops", "kind", "angle", "focus", "rotateWithShape"]); + // The renderer keeps only linear and radial gradients upright (`paint::fill_path`). + let rotate = cmd::parse_params(about).unwrap().into_iter().find(|p| p.name == "rotateWithShape").unwrap().about; + assert!(rotate.contains("rectangular and path gradients turn with the shape"), "{rotate}"); for kind in ["linear", "radial", "rectangular", "path"] { assert!(about.contains(kind), "{kind}: {about}"); let g = cmd::shape::gradient_param(&json!({ From f321416b34ded8c85b9d8e6a6fec822af212aa48 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:52:05 +0100 Subject: [PATCH 46/94] Make Previous/Next work in the web presenter popup Fixes #1864 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/ui-egui/src/show/tests.rs | 6 ++++++ crates/ui-egui/src/show/ui.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/show/tests.rs b/crates/ui-egui/src/show/tests.rs index 1dd6b09ef..b948efde2 100644 --- a/crates/ui-egui/src/show/tests.rs +++ b/crates/ui-egui/src/show/tests.rs @@ -1173,6 +1173,12 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { h.run_steps(2); assert_eq!(h.state().show.as_ref().unwrap().state.slide, slide); } + // #1864: the web popup's Previous/Next buttons send the DOM key names. + for (name, slide) in [("ArrowRight", 1), ("ArrowLeft", 0)] { + bridge.borrow_mut().commands.push(Command::Key { name: name.into(), command: false, shift: false, alt: false, ctrl: false }); + h.run_steps(2); + assert_eq!(h.state().show.as_ref().unwrap().state.slide, slide, "{name}"); + } bridge.borrow_mut().commands.push(Command::End); h.run_steps(2); assert!(h.state().show.is_none()); diff --git a/crates/ui-egui/src/show/ui.rs b/crates/ui-egui/src/show/ui.rs index 072714a31..226459755 100644 --- a/crates/ui-egui/src/show/ui.rs +++ b/crates/ui-egui/src/show/ui.rs @@ -94,7 +94,7 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { show.zoom_arm = false; } crate::presenter::Command::Key { name, command, shift, alt, ctrl } => { - if let Some(key) = egui::Key::ALL.iter().copied().find(|key| key.name() == name) { + if let Some(key) = egui::Key::from_name(&name) { let modifiers = egui::Modifiers { command, shift, alt, ctrl, mac_cmd: command && !ctrl }; out.keep &= handle_keys(&mut show, &doc, now, vec![(key, modifiers)], false).0; } From f49ff09b8ac7282598f4c0cfe8b75329b59304ce Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:25:54 +0100 Subject: [PATCH 47/94] Show: All slides opens in the web Presenter View, as on desktop (#1866) --- apps/deckcraft-web/src/presenter.rs | 3 + crates/ui-egui/src/presenter.rs | 100 ++++++++++++++++++++++++++-- crates/ui-egui/src/show.rs | 3 + crates/ui-egui/src/show/tests.rs | 22 +++++- crates/ui-egui/src/show/ui.rs | 29 +++++++- 5 files changed, 149 insertions(+), 8 deletions(-) diff --git a/apps/deckcraft-web/src/presenter.rs b/apps/deckcraft-web/src/presenter.rs index 1ec9a298c..40cafe849 100644 --- a/apps/deckcraft-web/src/presenter.rs +++ b/apps/deckcraft-web/src/presenter.rs @@ -251,6 +251,9 @@ impl Popup { if value.get("nextChanged").and_then(|v| v.as_bool()) == Some(false) { data.next = previous.next.clone(); } + if data.slides.is_none() { + data.slides = previous.slides.clone(); + } } *target.borrow_mut() = Some(data); *received.borrow_mut() = js_sys::Date::now(); diff --git a/crates/ui-egui/src/presenter.rs b/crates/ui-egui/src/presenter.rs index 95569778d..0ad7929bc 100644 --- a/crates/ui-egui/src/presenter.rs +++ b/crates/ui-egui/src/presenter.rs @@ -49,10 +49,15 @@ pub struct Snapshot { pub paused: bool, pub notes_px: f32, pub blank: Option<String>, + /// All slides is open in the presenter window (#1866); the audience keeps the current slide. pub grid: bool, pub zoom_armed: bool, pub current: Option<Preview>, pub next: Option<Preview>, + /// The All slides thumbnails, in slide order, while `grid` is on. `None` in a sent delta + /// means "unchanged since the last snapshot the window received". + #[serde(default)] + pub slides: Option<Vec<Preview>>, } /// Images acknowledged by a successful transport send, never merely attempted images. @@ -60,6 +65,7 @@ pub struct Snapshot { pub struct DeltaCache { current: Option<Preview>, next: Option<Preview>, + slides: Option<Vec<Preview>>, token: String, } impl DeltaCache { @@ -75,6 +81,12 @@ impl DeltaCache { let next_changed = fresh || self.next != snapshot.next; let current = snapshot.current.clone(); let next = snapshot.next.clone(); + let slides = snapshot.slides.clone(); + if !fresh && self.slides == slides { + snapshot.slides = None; + } else if snapshot.slides.is_none() { + snapshot.slides = Some(Vec::new()); + } if !current_changed { snapshot.current = None; } @@ -84,14 +96,28 @@ impl DeltaCache { send(snapshot, current_changed, next_changed)?; self.current = current; self.next = next; + self.slides = slides; self.token = token.to_owned(); Ok(()) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Command { - Key { name: String, command: bool, shift: bool, alt: bool, ctrl: bool }, - Zoom { x: f32, y: f32 }, + Key { + name: String, + command: bool, + shift: bool, + alt: bool, + ctrl: bool, + }, + Zoom { + x: f32, + y: f32, + }, + /// A slide chosen in the presenter window's All slides grid (#1866). + Goto { + slide: usize, + }, End, } /// Implemented by the browser host. Native hosts retain the existing egui viewport. @@ -112,6 +138,8 @@ pub struct View { next: Option<egui::TextureHandle>, previous_current: Option<Preview>, previous_next: Option<Preview>, + grid_source: Option<Vec<Preview>>, + grid: Vec<Option<egui::TextureHandle>>, } impl View { /// Install the same interface and dynamic fallback fonts as SlideApp before layout. @@ -200,6 +228,11 @@ impl View { } }); ui.separator(); + if snapshot.grid && !snapshot.ended { + // All slides opens here, as in the desktop Presenter View; the audience keeps the current slide. + self.grid_ui(ui, snapshot, &mut commands); + return commands; + } ui.columns(2, |columns| { let left = &mut columns[0]; if snapshot.ended { @@ -227,9 +260,6 @@ impl View { if snapshot.zoom_armed { left.label("Click the preview to zoom."); } - if snapshot.grid { - left.label("Choose a slide in the audience window, or press G to return."); - } let right = &mut columns[1]; right.label("Next"); if let Some(texture) = &self.next { @@ -260,6 +290,43 @@ impl View { commands } } +impl View { + fn grid_ui(&mut self, ui: &mut egui::Ui, snapshot: &Snapshot, commands: &mut Vec<Command>) { + let slides = snapshot.slides.as_deref().unwrap_or_default(); + if self.grid_source.as_deref() != Some(slides) { + self.grid_source = Some(slides.to_vec()); + self.grid = slides + .iter() + .enumerate() + .map(|(i, p)| p.image().map(|image| ui.ctx().load_texture(format!("remote-grid-{i}"), image, egui::TextureOptions::LINEAR))) + .collect(); + } + ui.heading("All slides"); + ui.label("Choose a slide to show it, or press G to return."); + if snapshot.total > slides.len() && !slides.is_empty() { + ui.label(format!("First {} slides", slides.len())); + } + egui::ScrollArea::vertical().show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + for (i, texture) in self.grid.iter().enumerate() { + let size = egui::vec2(160.0, 90.0); + let label = format!("{}", i + 1); + let label = if i == snapshot.slide { egui::RichText::new(label).strong() } else { egui::RichText::new(label) }; + let response = match texture { + Some(t) => ui.add(egui::Button::image_and_text( + egui::Image::new(t).fit_to_exact_size(fit_preview(t.size_vec2(), size.x, size.y)), + label, + )), + None => ui.add_sized(size, egui::Button::new(label)), + }; + if response.clicked() { + commands.push(Command::Goto { slide: i }); + } + } + }); + }); + } +} fn fit_preview(size: egui::Vec2, width: f32, height: f32) -> egui::Vec2 { size * (width.max(1.0) / size.x.max(1.0)).min(height.max(1.0) / size.y.max(1.0)) } @@ -282,6 +349,7 @@ mod tests { zoom_armed: false, current: Some(Preview { width: 1, height: 1, rgba: vec![255; 4] }), next: Some(Preview { width: 1, height: 1, rgba: vec![0; 4] }), + slides: None, } } @@ -418,6 +486,7 @@ mod tests { zoom_armed: false, current: None, next: None, + slides: None, }; let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( |ui, (view, snapshot, sent): &mut (View, Snapshot, Vec<Command>)| { @@ -437,6 +506,27 @@ mod tests { assert!(matches!(h.state().2.last(), Some(Command::Key { name, .. }) if name == egui::Key::Space.name())); } + #[test] + fn all_slides_opens_in_the_popup_and_picks_a_slide() { + use egui_kittest::kittest::Queryable; + let thumb = Preview { width: 16, height: 9, rgba: vec![200; 16 * 9 * 4] }; + let mut snapshot = snapshot(); + snapshot.total = 3; + snapshot.grid = true; + snapshot.slides = Some(vec![thumb.clone(), thumb.clone(), thumb]); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( + |ui, (view, snapshot, sent): &mut (View, Snapshot, Vec<Command>)| { + sent.extend(view.ui(ui, snapshot)); + }, + (View::default(), snapshot, Vec::new()), + ); + h.run_steps(2); + assert!(h.query_by_label("Notes").is_none(), "the grid replaces the presenter panes, as on desktop (#1866)"); + h.get_by_label("3").click(); + h.run_steps(2); + assert_eq!(h.state().2, vec![Command::Goto { slide: 2 }]); + } + #[test] fn previews_are_bounded_and_bad_dimensions_are_rejected() { let image = egui::ColorImage::filled([1280, 720], egui::Color32::RED); diff --git a/crates/ui-egui/src/show.rs b/crates/ui-egui/src/show.rs index 0cb2b458b..c1e3f4ab2 100644 --- a/crates/ui-egui/src/show.rs +++ b/crates/ui-egui/src/show.rs @@ -65,6 +65,8 @@ pub struct Show { preview_spawns: usize, remote_preview: Option<crate::presenter::Preview>, remote_next: Option<(usize, crate::presenter::Preview)>, + /// All slides thumbnails sent to the web presenter window while its grid is open (#1866). + remote_grid: Vec<crate::presenter::Preview>, remote_sent: f64, remote_opened: bool, /// The next slide's first frame, rendered in the background while this one is shown so @@ -237,6 +239,7 @@ impl Show { preview_spawns: 0, remote_preview: None, remote_next: None, + remote_grid: vec![], remote_sent: f64::NEG_INFINITY, remote_opened: false, prefetch: None, diff --git a/crates/ui-egui/src/show/tests.rs b/crates/ui-egui/src/show/tests.rs index b948efde2..01b30ff01 100644 --- a/crates/ui-egui/src/show/tests.rs +++ b/crates/ui-egui/src/show/tests.rs @@ -1132,6 +1132,7 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { opens: usize, closes: usize, commands: Vec<Command>, + last: Option<Snapshot>, } struct Mock(Rc<RefCell<Bridge>>); impl Host for Mock { @@ -1145,7 +1146,9 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { fn commands(&mut self) -> Vec<Command> { std::mem::take(&mut self.0.borrow_mut().commands) } - fn update(&mut self, _: Snapshot) {} + fn update(&mut self, snapshot: Snapshot) { + self.0.borrow_mut().last = Some(snapshot); + } fn close(&mut self) { self.0.borrow_mut().closes += 1; } @@ -1179,6 +1182,23 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { h.run_steps(2); assert_eq!(h.state().show.as_ref().unwrap().state.slide, slide, "{name}"); } + // #1866: All slides opens in the web Presenter View, as on desktop; the audience keeps its slide. + bridge.borrow_mut().commands.push(Command::Key { name: "G".into(), command: false, shift: false, alt: false, ctrl: false }); + h.run_steps(2); + let show = h.state().show.as_ref().unwrap(); + assert!(show.presenter_grid && !show.grid, "G from the popup opens its own grid, not the audience's"); + for _ in 0..20 { + h.step(); + std::thread::sleep(std::time::Duration::from_millis(15)); + } + let last = bridge.borrow().last.clone().unwrap(); + assert!(last.grid); + assert_eq!(last.slides.as_ref().map(Vec::len), Some(3), "the popup gets a thumbnail per slide"); + bridge.borrow_mut().commands.push(Command::Goto { slide: 2 }); + h.run_steps(2); + let show = h.state().show.as_ref().unwrap(); + assert!(!show.presenter_grid && !show.grid); + assert_eq!(show.state.slide, 2); bridge.borrow_mut().commands.push(Command::End); h.run_steps(2); assert!(h.state().show.is_none()); diff --git a/crates/ui-egui/src/show/ui.rs b/crates/ui-egui/src/show/ui.rs index 226459755..688d2bb6e 100644 --- a/crates/ui-egui/src/show/ui.rs +++ b/crates/ui-egui/src/show/ui.rs @@ -96,9 +96,18 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { crate::presenter::Command::Key { name, command, shift, alt, ctrl } => { if let Some(key) = egui::Key::from_name(&name) { let modifiers = egui::Modifiers { command, shift, alt, ctrl, mac_cmd: command && !ctrl }; - out.keep &= handle_keys(&mut show, &doc, now, vec![(key, modifiers)], false).0; + // The popup is the Presenter View: G opens All slides there, not on the audience screen (#1866). + out.keep &= handle_keys(&mut show, &doc, now, vec![(key, modifiers)], true).0; } } + crate::presenter::Command::Goto { slide } if show.presenter_grid && slide < doc.slides.len() => { + show.presenter_grid = false; + show.blank = None; + show.zoom = None; + show.zoom_arm = false; + let action = show.state.goto(&doc, slide); + out.keep &= show.apply(action, &doc, now); + } _ => {} } } @@ -143,6 +152,21 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { ); show.remote_next = crate::presenter::Preview::from_image(&crate::textures::to_color_image(&image, false)).map(|image| (n, image)); } + if !show.presenter_grid { + show.remote_grid.clear(); + } else if show.remote_grid.len() < grid_indices(doc.slides.len()).len() { + // A few thumbnails per update keep the audience window responsive on the web. + for i in grid_indices(doc.slides.len()).into_iter().skip(show.remote_grid.len()).take(4) { + let size = (160, (160.0 * doc.slide_size.height / doc.slide_size.width.max(1.0)).clamp(1.0, 640.0) as u32); + let image = deckcraft_render::render_slide( + &doc, + i, + &RenderOpts { scale: size.0 as f64 / doc.slide_size.width.max(1.0), size: Some(size), ..Default::default() }, + ); + let preview = crate::presenter::Preview::from_image(&crate::textures::to_color_image(&image, false)); + show.remote_grid.push(preview.unwrap_or(crate::presenter::Preview { width: 1, height: 1, rgba: vec![0; 4] })); + } + } host.update(crate::presenter::Snapshot { slide: show.state.slide, total: doc.slides.len(), @@ -152,10 +176,11 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { paused: show.timer.paused(), notes_px: show.notes_px, blank: show.blank_name().map(str::to_owned), - grid: show.grid, + grid: show.presenter_grid, zoom_armed: show.zoom_arm, current: show.remote_preview.clone(), next: show.remote_next.as_ref().filter(|(n, _)| Some(*n) == next).map(|(_, image)| image.clone()), + slides: show.presenter_grid.then(|| show.remote_grid.clone()), }); show.remote_sent = now; } From 884e3d3353649870127280eb8bf0bd9c40c5cf48 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:37:37 +0100 Subject: [PATCH 48/94] Show: keep web All slides messages small, clear the grid when the popup closes, show it on the end screen (#1866) --- crates/ui-egui/src/presenter.rs | 6 +++--- crates/ui-egui/src/show.rs | 1 + crates/ui-egui/src/show/tests.rs | 13 ++++++++++++- crates/ui-egui/src/show/ui.rs | 23 +++++++++++++++-------- crates/ui-egui/src/show/zoom.rs | 2 +- 5 files changed, 32 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/presenter.rs b/crates/ui-egui/src/presenter.rs index 0ad7929bc..5d99e63c8 100644 --- a/crates/ui-egui/src/presenter.rs +++ b/crates/ui-egui/src/presenter.rs @@ -228,7 +228,7 @@ impl View { } }); ui.separator(); - if snapshot.grid && !snapshot.ended { + if snapshot.grid { // All slides opens here, as in the desktop Presenter View; the audience keeps the current slide. self.grid_ui(ui, snapshot, &mut commands); return commands; @@ -303,8 +303,8 @@ impl View { } ui.heading("All slides"); ui.label("Choose a slide to show it, or press G to return."); - if snapshot.total > slides.len() && !slides.is_empty() { - ui.label(format!("First {} slides", slides.len())); + if snapshot.total > crate::show::GRID_CAP { + ui.label(format!("First {} slides", crate::show::GRID_CAP)); } egui::ScrollArea::vertical().show(ui, |ui| { ui.horizontal_wrapped(|ui| { diff --git a/crates/ui-egui/src/show.rs b/crates/ui-egui/src/show.rs index c1e3f4ab2..db7983c2b 100644 --- a/crates/ui-egui/src/show.rs +++ b/crates/ui-egui/src/show.rs @@ -18,6 +18,7 @@ mod presenter; mod render; mod ui; mod zoom; +pub(crate) use zoom::GRID_CAP; #[cfg(test)] use media::{on_screen, pointer_on_media_bar, shown_slide_rect, slide_media_bars}; diff --git a/crates/ui-egui/src/show/tests.rs b/crates/ui-egui/src/show/tests.rs index 01b30ff01..a01989ac0 100644 --- a/crates/ui-egui/src/show/tests.rs +++ b/crates/ui-egui/src/show/tests.rs @@ -1133,6 +1133,7 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { closes: usize, commands: Vec<Command>, last: Option<Snapshot>, + gone: bool, } struct Mock(Rc<RefCell<Bridge>>); impl Host for Mock { @@ -1141,7 +1142,7 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { Ok(()) } fn is_open(&self) -> bool { - true + !self.0.borrow().gone } fn commands(&mut self) -> Vec<Command> { std::mem::take(&mut self.0.borrow_mut().commands) @@ -1194,11 +1195,21 @@ fn remote_presenter_uses_the_audience_state_and_closes_with_the_show() { let last = bridge.borrow().last.clone().unwrap(); assert!(last.grid); assert_eq!(last.slides.as_ref().map(Vec::len), Some(3), "the popup gets a thumbnail per slide"); + assert!(last.slides.iter().flatten().all(|p| p.width.max(p.height) <= 96), "thumbnails stay small enough for one message"); + assert!(last.current.is_none() && last.next.is_none(), "the grid replaces both previews"); bridge.borrow_mut().commands.push(Command::Goto { slide: 2 }); h.run_steps(2); let show = h.state().show.as_ref().unwrap(); assert!(!show.presenter_grid && !show.grid); assert_eq!(show.state.slide, 2); + // Closing the popup with its grid open must not hold auto-advance for the rest of the show. + bridge.borrow_mut().commands.push(Command::Key { name: "G".into(), command: false, shift: false, alt: false, ctrl: false }); + h.run_steps(2); + assert!(h.state().show.as_ref().unwrap().presenter_grid); + bridge.borrow_mut().gone = true; + h.run_steps(2); + assert!(!h.state().show.as_ref().unwrap().presenter_grid); + bridge.borrow_mut().gone = false; bridge.borrow_mut().commands.push(Command::End); h.run_steps(2); assert!(h.state().show.is_none()); diff --git a/crates/ui-egui/src/show/ui.rs b/crates/ui-egui/src/show/ui.rs index 688d2bb6e..d048fb93c 100644 --- a/crates/ui-egui/src/show/ui.rs +++ b/crates/ui-egui/src/show/ui.rs @@ -80,6 +80,10 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { && !show.reading && let Some(host) = app.services.presenter.as_mut() { + if show.remote_opened && show.presenter_grid && !host.is_open() { + // A grid left open in the closed popup would hold auto-advance for the rest of the show. + show.presenter_grid = false; + } if !show.remote_opened { show.remote_opened = true; if let Err(message) = host.open() { @@ -157,12 +161,11 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { } else if show.remote_grid.len() < grid_indices(doc.slides.len()).len() { // A few thumbnails per update keep the audience window responsive on the web. for i in grid_indices(doc.slides.len()).into_iter().skip(show.remote_grid.len()).take(4) { - let size = (160, (160.0 * doc.slide_size.height / doc.slide_size.width.max(1.0)).clamp(1.0, 640.0) as u32); - let image = deckcraft_render::render_slide( - &doc, - i, - &RenderOpts { scale: size.0 as f64 / doc.slide_size.width.max(1.0), size: Some(size), ..Default::default() }, - ); + // At most 96 px on the long side: 48 thumbnails stay well under the popup's message limit. + let (w, h) = (doc.slide_size.width.max(1.0), doc.slide_size.height.max(1.0)); + let scale = REMOTE_THUMB / w.max(h); + let size = (((w * scale).round() as u32).max(1), ((h * scale).round() as u32).max(1)); + let image = deckcraft_render::render_slide(&doc, i, &RenderOpts { scale, size: Some(size), ..Default::default() }); let preview = crate::presenter::Preview::from_image(&crate::textures::to_color_image(&image, false)); show.remote_grid.push(preview.unwrap_or(crate::presenter::Preview { width: 1, height: 1, rgba: vec![0; 4] })); } @@ -178,8 +181,9 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { blank: show.blank_name().map(str::to_owned), grid: show.presenter_grid, zoom_armed: show.zoom_arm, - current: show.remote_preview.clone(), - next: show.remote_next.as_ref().filter(|(n, _)| Some(*n) == next).map(|(_, image)| image.clone()), + // The grid replaces both previews in the popup; leaving them out keeps one message small. + current: show.remote_preview.clone().filter(|_| !show.presenter_grid), + next: show.remote_next.as_ref().filter(|(n, _)| Some(*n) == next && !show.presenter_grid).map(|(_, image)| image.clone()), slides: show.presenter_grid.then(|| show.remote_grid.clone()), }); show.remote_sent = now; @@ -189,6 +193,9 @@ pub fn ui(app: &mut SlideApp, ui: &mut Ui) { finish(app, show, &f, out.keep); } +/// Longest side of an All slides thumbnail sent to the web presenter window (#1866). +const REMOTE_THUMB: f64 = 96.0; + fn paint_hidden(ui: &Ui, doc: &Presentation, show: &Show) { if show.started { let full = ui.max_rect(); diff --git a/crates/ui-egui/src/show/zoom.rs b/crates/ui-egui/src/show/zoom.rs index 9c45fd4a2..da6104905 100644 --- a/crates/ui-egui/src/show/zoom.rs +++ b/crates/ui-egui/src/show/zoom.rs @@ -182,7 +182,7 @@ const WHEEL_NOTCHES_PER_DOUBLING: f32 = 4.0; /// PowerPoint's slide show magnifier goes up to 400%. const WHEEL_ZOOM_MAX: f32 = 4.0; -pub(super) const GRID_CAP: usize = 48; +pub(crate) const GRID_CAP: usize = 48; const TOOL_BAR_W: f32 = 520.0; From 7c47d0a9ac98b5cab02e7d4eaca7d52c709e1e55 Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:40:18 -0600 Subject: [PATCH 49/94] Table cell commands refuse a malformed `cells` list instead of dropping entries `cells` must be a list of exact [row, col] pairs inside the table; an entry that is not one, a cell past the table, or more than 100000 entries is refused and names the command, instead of being dropped or read as absent (which acted on the selection or the whole table). Borders use checked arithmetic for the neighbour cell. Split out of the 0-based index PR at review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/table.rs | 64 +++++++++++++++++++++++----------- crates/engine/src/tests.rs | 37 ++++++++++++++++++++ 2 files changed, 80 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 91ac7ac70..86d753a2c 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -253,9 +253,10 @@ fn cell_param(p: &Value, key: &str, cmd: &str) -> Result<Option<(usize, usize)>> None | Some(Value::Null) => return Ok(None), Some(v) => v, }; - let idx = |i: usize| v.as_array().and_then(|a| a.get(i)).and_then(Value::as_u64).and_then(|x| usize::try_from(x).ok()); - match (idx(0), idx(1)) { - (Some(r), Some(c)) => Ok(Some((r, c))), + // Exactly [row, col]: an entry with more is as malformed as one with less. + let idx = |x: &Value| x.as_u64().and_then(|x| usize::try_from(x).ok()); + match v.as_array().map(Vec::as_slice) { + Some([r, c]) if let (Some(r), Some(c)) = (idx(r), idx(c)) => Ok(Some((r, c))), _ => Err(bad(cmd, format!("`{key}` is not a valid cell: {v}"))), } } @@ -389,33 +390,54 @@ fn options(s: &mut Session, p: &Value) -> Result<Value> { }) } +/// At most this many `cells` in one table cell command. +const MAX_CELLS: usize = 100_000; + /// The cells a command acts on: `cells`, else the selected cell range, else the cell holding the /// caret, else every cell. -fn target_cells(s: &Session, p: &Value) -> Result<impl Fn(&Table) -> Vec<(usize, usize)> + use<>> { - let cells: Option<Vec<(usize, usize)>> = p - .get("cells") - .and_then(Value::as_array) - .map(|a| a.iter().take(100_000).filter_map(|c| Some((c.get(0)?.as_u64()? as usize, c.get(1)?.as_u64()? as usize))).collect()); +fn target_cells(s: &Session, p: &Value, cmd: &str) -> Result<impl Fn(&Table) -> Result<Vec<(usize, usize)>> + use<>> { + // `cells` is a list of [row, col]: anything else, or an entry that is not one, is refused, never + // dropped or read as absent (which would act on the selection or the whole table). + let cells: Option<Vec<(usize, usize)>> = match p.get("cells") { + None | Some(Value::Null) => None, + Some(Value::Array(a)) if a.len() > MAX_CELLS => { + return Err(bad(cmd, format!("`cells` lists {} cells; at most {MAX_CELLS}", a.len()))); + } + Some(Value::Array(a)) => Some( + a.iter() + .map(|c| { + cell_param(&json!({ "cell": c }), "cell", cmd)?.ok_or_else(|| bad(cmd, format!("`cells` entry {c} is not a [row, col] cell"))) + }) + .collect::<Result<_>>()?, + ), + Some(v) => return Err(bad(cmd, format!("`cells` is a list of [row, col] cells, not {v}"))), + }; let st = s.doc()?; // A selected range grows over the merged cells it touches; with only a caret, the caret's cell is used. let sel = st.selection.cells.map(|(_, a, b)| (a, b, true)).or_else(|| st.selection.text.as_ref().and_then(|t| t.cell).map(|c| (c, c, false))); + let cmd = cmd.to_string(); Ok(move |t: &Table| match (&cells, sel) { - (Some(c), _) => c.clone(), + // Each listed cell must be in the table, so a command never reports success for a cell + // it could not edit. + (Some(c), _) => match c.iter().find(|(r, c)| *r >= t.n_rows() || *c >= t.n_cols()) { + Some((r, c)) => Err(bad(&cmd, format!("no cell [{r}, {c}]: the table has {} rows and {} columns", t.n_rows(), t.n_cols()))), + None => Ok(c.clone()), + }, (None, Some((a, b, range))) => { let (a, b) = if range { cell_block(t, a, b) } else { (a, b) }; // The selection can name cells outside the table; only walk the ones that exist. let (r1, c1) = (a.0.max(b.0).min(t.n_rows().saturating_sub(1)), a.1.max(b.1).min(t.n_cols().saturating_sub(1))); - (a.0.min(b.0)..=r1).flat_map(|r| (a.1.min(b.1)..=c1).map(move |c| (r, c))).collect() + Ok((a.0.min(b.0)..=r1).flat_map(|r| (a.1.min(b.1)..=c1).map(move |c| (r, c))).collect()) } - _ => (0..t.n_rows()).flat_map(|r| (0..t.n_cols()).map(move |c| (r, c))).collect(), + _ => Ok((0..t.n_rows()).flat_map(|r| (0..t.n_cols()).map(move |c| (r, c))).collect()), }) } fn cell_fill(s: &mut Session, p: &Value) -> Result<Value> { let fill = if bool_or(p, "none", false) { Some(deckcraft_model::Fill::None) } else { color_param(p, "color").map(deckcraft_model::Fill::solid) }; - let targets = target_cells(s, p)?; + let targets = target_cells(s, p, "table.cellFill")?; with_table(s, p, "table.cellFill", move |t| { - for (r, c) in targets(t) { + for (r, c) in targets(t)? { if let Some(cell) = t.cell_mut(r, c) { cell.fill.clone_from(&fill); } @@ -447,9 +469,9 @@ fn borders(s: &mut Session, p: &Value) -> Result<Value> { } // "none" clears to no line, so the table style's own lines don't show through either. let line = if which == "none" { Line::none() } else { line }; - let targets = target_cells(s, p)?; + let targets = target_cells(s, p, "table.borders")?; with_table(s, p, "table.borders", move |t| { - let list = targets(t); + let list = targets(t)?; let (Some(r0), Some(r1), Some(c0), Some(c1)) = (list.iter().map(|x| x.0).min(), list.iter().map(|x| x.0).max(), list.iter().map(|x| x.1).min(), list.iter().map(|x| x.1).max()) else { @@ -463,9 +485,9 @@ fn borders(s: &mut Session, p: &Value) -> Result<Value> { } let n = match side { LEFT => c.checked_sub(1).map(|c| (r, c, RIGHT)), - RIGHT => (c + 1 < cols).then_some((r, c + 1, LEFT)), + RIGHT => c.checked_add(1).filter(|c| *c < cols).map(|c| (r, c, LEFT)), TOP => r.checked_sub(1).map(|r| (r, c, BOTTOM)), - _ => (r + 1 < rows).then_some((r + 1, c, TOP)), + _ => r.checked_add(1).filter(|r| *r < rows).map(|r| (r, c, TOP)), }; if let Some((r, c, side)) = n && let Some(cell) = t.cell_mut(r, c) @@ -523,9 +545,9 @@ fn cell_margins(s: &mut Session, p: &Value) -> Result<Value> { }; let side = |k: &str, i: usize| f64_param(p, k).filter(|v| v.is_finite()).map_or(base[i], |v| v.clamp(0.0, 400.0)); let m = [side("left", 0), side("right", 1), side("top", 2), side("bottom", 3)]; - let targets = target_cells(s, p)?; + let targets = target_cells(s, p, "table.cellMargins")?; with_table(s, p, "table.cellMargins", move |t| { - for (r, c) in targets(t) { + for (r, c) in targets(t)? { if let Some(cell) = t.cell_mut(r, c) { cell.margins = Some(m); } @@ -560,9 +582,9 @@ fn cell_align(s: &mut Session, p: &Value) -> Result<Value> { o => return Err(bad("table.cellAlign", format!("unknown anchor {o:?}; one of top, middle, bottom"))), }), }; - let targets = target_cells(s, p)?; + let targets = target_cells(s, p, "table.cellAlign")?; with_table(s, p, "table.cellAlign", move |t| { - for (r, c) in targets(t) { + for (r, c) in targets(t)? { if let Some(cell) = t.cell_mut(r, c) { if anchor.is_some() { cell.anchor = anchor; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 12fac5efc..e27c1e08b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6509,3 +6509,40 @@ fn save_to_image_path_is_an_error_not_zip_bytes() { } let _ = std::fs::remove_dir_all(&dir); } + +/// Table cell commands refuse a `cells` that is not a list of [row, col] cells in the table, +/// instead of dropping the entry or reading the list as absent (which acts on the selection). +#[test] +fn table_cell_commands_refuse_a_malformed_cells_list() { + let mut s = session(); + let t = table_at(&mut s, &[100.0, 100.0], json!([["a", "b"], ["c", "d"]])); + let rev = s.doc().unwrap().revision; + for cells in [ + json!([[-1, 0]]), + json!([[0]]), + json!([[0, 0], "x"]), + json!([[0, 0, "x"]]), + json!([[0, 2]]), + json!([[0, u64::MAX]]), + json!("0,0"), + json!({"0": 0}), + ] { + for (cmd, extra) in [ + ("table.cellFill", json!({"color": "#FF0000"})), + ("table.cellMargins", json!({"left": 4})), + ("table.cellAlign", json!({"align": "center"})), + ("table.borders", json!({"which": "right"})), + ] { + let mut p = extra.clone(); + p["id"] = json!(t); + p["cells"] = cells.clone(); + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(cmd) && e.contains("cell"), "{cmd} {cells}: {e}"); + } + } + assert_eq!(s.doc().unwrap().revision, rev, "nothing changed"); + let many = json!(vec![[0, 0]; 100_001]); + assert!(s.execute("table.cellFill", &json!({"id": t, "color": "#FF0000", "cells": many})).unwrap_err().to_string().contains("at most")); + s.execute("table.cellFill", &json!({"id": t, "color": "#FF0000", "cells": [[1, 1]]})).unwrap(); + assert!(table_of(&s, t).cell(1, 1).unwrap().fill.is_some() && table_of(&s, t).cell(0, 0).unwrap().fill.is_none()); +} From efd26de81d0b27d091293d5ad89b2a0f175ac5a4 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 02:48:01 +0100 Subject: [PATCH 50/94] Show: clear the web presenter grid in hidden logic, let Enter and Space pick a focused thumbnail (#1866) --- crates/ui-egui/src/app/playback.rs | 4 ++++ crates/ui-egui/src/presenter.rs | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/crates/ui-egui/src/app/playback.rs b/crates/ui-egui/src/app/playback.rs index 73e765ff7..c959829cd 100644 --- a/crates/ui-egui/src/app/playback.rs +++ b/crates/ui-egui/src/app/playback.rs @@ -144,6 +144,10 @@ impl SlideApp { let visible = show::viewport_visible(ctx); let Some(doc) = self.session.active().map(|d| d.doc.clone()) else { return }; let Some(show) = self.show.as_mut() else { return }; + if show.presenter_grid && self.services.presenter.as_ref().is_some_and(|host| !host.is_open()) { + // A web popup closed with its grid open must not hold auto-advance while this tab is hidden (#1866). + show.presenter_grid = false; + } if visible { // A visible logic-only pass (`run_logic`) carries the last full frame's input time. // Anchoring that stale time to `now` would move the hidden clock backwards if the diff --git a/crates/ui-egui/src/presenter.rs b/crates/ui-egui/src/presenter.rs index 5d99e63c8..a58878830 100644 --- a/crates/ui-egui/src/presenter.rs +++ b/crates/ui-egui/src/presenter.rs @@ -175,6 +175,10 @@ impl View { .collect::<Vec<_>>() }); for (key, modifiers) in keys { + if snapshot.grid && matches!(key, egui::Key::Space | egui::Key::Enter) { + // A focused thumbnail takes these to choose its slide; the show ignores them while the grid is open. + continue; + } // Consume once before widgets see Space/Enter, avoiding a second button activation. ui.input_mut(|i| i.consume_key(modifiers, key)); commands.push(Command::Key { @@ -525,6 +529,9 @@ mod tests { h.get_by_label("3").click(); h.run_steps(2); assert_eq!(h.state().2, vec![Command::Goto { slide: 2 }]); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(!h.state().2.iter().any(|c| matches!(c, Command::Key { .. })), "Enter is left to the focused thumbnail"); } #[test] From af9f522c6a9d6be58017a55136422d0ee3512b93 Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:48:16 -0600 Subject: [PATCH 51/94] shape.connect glues to a shape inside a group, and the connector follows the group An agent run found that connecting to a grouped shape answered ok but left the connector's end unset: the sites of a group member were computed in the group's child space, and rerouting only looked at the slide's top-level shapes, so the glue was dropped at once. Both now locate the shape anywhere in the tree with the affine onto the slide, as PowerPoint glues to grouped shapes. shape.sites answers in the same slide space. A line inside a group is refused as `id`: its ends would land in the group's space, and rerouting does not follow grouped connectors. Split out of the connector default sites PR at review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/shape/freeform.rs | 19 ++++++-- crates/engine/src/connect.rs | 49 ++++++++++++++++++-- crates/engine/src/tests.rs | 61 +++++++++++++++++++++++++ 3 files changed, 120 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/shape/freeform.rs b/crates/engine/src/cmd/shape/freeform.rs index f3be4f4bb..c0430c85f 100644 --- a/crates/engine/src/cmd/shape/freeform.rs +++ b/crates/engine/src/cmd/shape/freeform.rs @@ -3,8 +3,9 @@ use super::{ColorRef, Fill, Geom, Line, NO_ID_SPACE, Result, Session, Value, bad pub(super) fn sites(s: &mut Session, p: &Value) -> Result<Value> { let id = id_param(p, "id", "shape.sites")?.ok_or_else(|| bad("shape.sites", "missing `id`"))?; let st = s.doc()?; - let sh = st.shape(id).ok_or_else(|| bad("shape.sites", "no such shape"))?; - Ok(json!(crate::connect::sites(&st.doc, &st.selection, sh).iter().map(|q| [q.x, q.y]).collect::<Vec<_>>())) + // In slide space, as shape.connect uses them, for a shape inside a group too. + let v = crate::connect::sites_of(&st.doc, &st.selection, st.shapes(), id).ok_or_else(|| bad("shape.sites", "no such shape"))?; + Ok(json!(v.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>())) } pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> { @@ -12,8 +13,13 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad("shape.connect", "missing `from` / `to`")); }; let st = s.doc()?; - let site_list = |id| st.shape(id).map(|sh| crate::connect::sites(&st.doc, &st.selection, sh)).unwrap_or_default(); - let (a, b) = (site_list(from), site_list(to)); + // Anywhere in the slide's tree: a shape inside a group takes a connector too (PowerPoint + // glues to grouped shapes), its sites where the group draws them. + let site_list = |id| { + crate::connect::sites_of(&st.doc, &st.selection, st.shapes(), id) + .ok_or_else(|| bad("shape.connect", format!("no shape {} on the current slide", id.0))) + }; + let (a, b) = (site_list(from)?, site_list(to)?); if a.is_empty() || b.is_empty() { return Err(bad("shape.connect", "both shapes need connection sites (lines and groups have none)")); } @@ -35,6 +41,11 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> { }; let (p0, p1) = (a[ia], b[ib]); let id = match id_param(p, "id", "shape.connect")? { + // The ends are in slide space and rerouting follows the slide's own connectors, so a line + // inside a group would be drawn in the group's space and never follow its shapes. + Some(id) if !st.shapes().iter().any(|sh| sh.id == id) && st.shape(id).is_some() => { + return Err(bad("shape.connect", "`id` names a line inside a group; ungroup it first, or leave `id` out for a new connector")); + } Some(id) => id, None => { let preset = str_param(p, "preset").unwrap_or("straightConnector1"); diff --git a/crates/engine/src/connect.rs b/crates/engine/src/connect.rs index 8cdbecda8..5991ba619 100644 --- a/crates/engine/src/connect.rs +++ b/crates/engine/src/connect.rs @@ -1,14 +1,21 @@ //! Connectors glued to shapes: connection sites, snapping line ends to them, and rerouting attached //! connectors whenever the shapes they connect move, resize or rotate. -use deckcraft_geom::{Point, Xfrm}; +use deckcraft_geom::{Affine, Point, Rect, Xfrm}; use deckcraft_model::{Presentation, Shape, ShapeId, ShapeKind}; use crate::Selection; use crate::cmd::xfrm_of; -/// Connection sites of `s` in slide coordinates (index = site index stored on connectors). +/// Connection sites of a top-level shape `s` in slide coordinates (index = site index stored on +/// connectors). For a shape inside a group use [`sites_of`] or [`sites_in`]. pub fn sites(doc: &Presentation, sel: &Selection, s: &Shape) -> Vec<Point> { + sites_in(doc, sel, s, Affine::IDENTITY) +} + +/// Connection sites of `s` in slide coordinates, `to_abs` mapping the space its box lives in (the +/// slide, or the child space of the groups around it) onto the slide. +pub fn sites_in(doc: &Presentation, sel: &Selection, s: &Shape, to_abs: Affine) -> Vec<Point> { if s.is_line() || matches!(s.kind, ShapeKind::Group { .. } | ShapeKind::Ink { .. }) { return vec![]; } @@ -17,10 +24,42 @@ pub fn sites(doc: &Presentation, sel: &Selection, s: &Shape) -> Vec<Point> { if local.is_empty() { local = vec![Point::new(x.w / 2.0, 0.0), Point::new(0.0, x.h / 2.0), Point::new(x.w / 2.0, x.h), Point::new(x.w, x.h / 2.0)]; } - let a = x.affine(); + let a = to_abs * x.affine(); local.into_iter().map(|p| a * p).collect() } +/// The shape `id` anywhere in `shapes` (a group's member included) with the affine that maps the +/// space its box lives in onto the slide: a connector glues to a grouped shape, as in PowerPoint, +/// and its sites are where the group draws them. +pub fn locate<'a>(doc: &Presentation, sel: &Selection, shapes: &'a [Shape], id: ShapeId) -> Option<(&'a Shape, Affine)> { + fn rec<'a>(doc: &Presentation, sel: &Selection, shapes: &'a [Shape], id: ShapeId, to_abs: Affine, depth: usize) -> Option<(&'a Shape, Affine)> { + if depth > 64 { + return None; + } + for s in shapes { + if s.id == id { + return Some((s, to_abs)); + } + if let ShapeKind::Group { children, child } = &s.kind { + let x = xfrm_of(doc, sel, s); + let ch = Rect::new(child.x, child.y, child.x + child.w, child.y + child.h); + let nested = to_abs * deckcraft_geom::group_child_affine(&x, ch); + if let Some(f) = rec(doc, sel, children, id, nested, depth + 1) { + return Some(f); + } + } + } + None + } + rec(doc, sel, shapes, id, Affine::IDENTITY, 0) +} + +/// Connection sites of shape `id` anywhere in `shapes`, in slide coordinates; `None` when there is +/// no such shape. +pub fn sites_of(doc: &Presentation, sel: &Selection, shapes: &[Shape], id: ShapeId) -> Option<Vec<Point>> { + locate(doc, sel, shapes, id).map(|(s, a)| sites_in(doc, sel, s, a)) +} + /// The nearest connection site within `radius` of `p` on any visible shape except `exclude`. pub fn nearest_site( doc: &Presentation, @@ -68,8 +107,8 @@ pub fn reroute(doc: &mut Presentation, sel: &Selection) { let snapshot: Vec<Shape> = list.clone(); let view = doc.clone(); let site = |id: ShapeId, idx: u32| -> Option<Point> { - let s = snapshot.iter().find(|s| s.id == id)?; - let v = sites(&view, sel, s); + // Anywhere in the tree: a connector glued to a shape that is then grouped keeps following it. + let v = sites_of(&view, sel, &snapshot, id)?; v.get(idx as usize).or(v.first()).copied() }; let mut updates: Vec<(usize, Xfrm, bool, bool)> = vec![]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 12fac5efc..63b90abb0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6509,3 +6509,64 @@ fn save_to_image_path_is_an_error_not_zip_bytes() { } let _ = std::fs::remove_dir_all(&dir); } + +/// `shape.connect` glues to a shape inside a group, as PowerPoint does: the connector's +/// end is set to the grouped shape and follows it when the group moves. The glue was dropped at +/// once (the end stayed `None`) because rerouting only looked at the slide's top-level shapes, +/// and the sites of a grouped shape were computed in the group's child space. +#[test] +fn shape_connect_glues_to_a_shape_inside_a_group() { + use deckcraft_model::{ShapeId, ShapeKind}; + let mut s = session(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + let a = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 10, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.insert", &json!({"preset": "rect", "rect": [10, 200, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let g = s.execute("arrange.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap(); + let c = s.execute("shape.insert", &json!({"preset": "rect", "rect": [400, 10, 100, 50]})).unwrap()["id"].as_u64().unwrap(); + let glue = |s: &Session, id: u64| { + let st = s.doc().unwrap(); + match st.shape(ShapeId(id as u32)).unwrap().kind { + ShapeKind::Connector { start, end } => (start.map(|(i, _)| i.0 as u64), end.map(|(i, _)| i.0 as u64)), + _ => (None, None), + } + }; + let near = |p: deckcraft_geom::Point, x: f64, y: f64| (p.x - x).abs() < 1e-6 && (p.y - y).abs() < 1e-6; + // A new connector into the group. + let r = s.execute("shape.connect", &json!({"from": c, "to": a})).unwrap(); + let k = r["id"].as_u64().unwrap(); + assert_eq!(glue(&s, k), (Some(c), Some(a)), "{r}"); + let (p0, p1) = line_ends(&s, k); + assert!(near(p0, 400.0, 35.0), "from C's left site: {p0:?}"); + assert!(near(p1, 110.0, 35.0), "to A's right site in slide space: {p1:?}"); + s.execute("shape.move", &json!({"ids": [g], "dy": 100})).unwrap(); + assert_eq!(glue(&s, k), (Some(c), Some(a)), "the glue survives the move"); + let (_, p1) = line_ends(&s, k); + assert!(near(p1, 110.0, 135.0), "the connector follows the grouped shape: {p1:?}"); + // Re-gluing an existing line with `id`. + let l = s.execute("shape.insert", &json!({"preset": "straightConnector1", "rect": [600, 400, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.connect", &json!({"id": l, "from": c, "to": b})).unwrap(); + assert_eq!(r["id"], l, "{r}"); + assert_eq!(glue(&s, l), (Some(c), Some(b)), "{r}"); + let (_, p1) = line_ends(&s, l); + assert!(near(p1, 110.0, 325.0), "to B's right site (C is mostly to its right) in slide space, B moved with the group: {p1:?}"); + s.execute("shape.move", &json!({"ids": [g], "dx": 50})).unwrap(); + assert_eq!(glue(&s, l), (Some(c), Some(b))); + let (_, p1) = line_ends(&s, l); + assert!(near(p1, 160.0, 325.0), "{p1:?}"); + // shape.sites answers in slide space, as shape.connect uses them: A's right site, A moved + // with the group. + let v = s.execute("shape.sites", &json!({"id": a})).unwrap(); + assert!( + v.as_array().unwrap().iter().any(|q| near(deckcraft_geom::Point::new(q[0].as_f64().unwrap(), q[1].as_f64().unwrap()), 160.0, 135.0)), + "{v}" + ); + // A line inside a group is refused as `id`: its ends would be written in slide space into + // the group's space, and rerouting does not follow grouped connectors. + let m = s.execute("shape.insert", &json!({"preset": "line", "rect": [600, 300, 50, 0]})).unwrap()["id"].as_u64().unwrap(); + let n = s.execute("shape.insert", &json!({"preset": "rect", "rect": [600, 450, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.execute("arrange.group", &json!({"ids": [m, n]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("shape.connect", &json!({"id": m, "from": c, "to": b})).unwrap_err().to_string(); + assert!(e.contains("inside a group"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); +} From ede154d6be565d47b4b9c608103ed88896569ee7 Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Sun, 18 Oct 2026 23:07:03 -0500 Subject: [PATCH 52/94] Outlines leave footer, date and slide-number placeholders out: export, RTF and the outline view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An agent run exporting a deck as an outline got the footer text and the slide-number field (‹#›) as body lines under each title. PowerPoint's outline view shows title and body placeholders only, so the text outline, the RTF outline (Save As ▸ Outline/RTF) and the outline view now skip the footer-row placeholders as they already skipped the title. Split out of the frame export PR at review, which asked for all three together. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/tests.rs | 32 +++++++++++++++++++++++++++ crates/format/src/lib.rs | 4 +++- crates/format/src/rtf.rs | 3 ++- crates/ui-egui/src/sorter.rs | 5 +++-- crates/ui-egui/src/sorter/ui_tests.rs | 21 ++++++++++++++++++ 5 files changed, 61 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 12fac5efc..6741f03d5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6509,3 +6509,35 @@ fn save_to_image_path_is_an_error_not_zip_bytes() { } let _ = std::fs::remove_dir_all(&dir); } + +/// The outline exports (PowerPoint's outline view) holds titles and body text only: footer, +/// date and slide-number placeholders are not body lines. +#[test] +fn outline_export_skips_footer_date_and_slide_number() { + let mut s = session(); + s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "Agenda", "body": "First point\nSecond point"})).unwrap(); + s.execute( + "design.headerFooter", + &json!({"footer": true, "footerText": "Company Confidential", "slideNumber": true, "date": true, "dateText": "1 May 2026"}), + ) + .unwrap(); + let dir = std::env::temp_dir().join(format!("deckcraft-outline-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("deck.md"); + s.execute("file.export", &json!({"path": path.to_string_lossy(), "format": "outline"})).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!(text.contains("Agenda") && text.contains("First point") && text.contains("Second point"), "{text:?}"); + assert!(!text.contains("Company Confidential"), "footer text is not a body line: {text:?}"); + assert!(!text.contains("‹#›"), "the slide-number field is not a body line: {text:?}"); + assert!(!text.contains("1 May 2026"), "the date is not a body line: {text:?}"); + // The RTF outline (Save As ▸ Outline/RTF) too. + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("deck.rtf"); + s.execute("file.export", &json!({"path": path.to_string_lossy(), "format": "rtf"})).unwrap(); + let rtf = std::fs::read_to_string(&path).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!(rtf.contains("Agenda") && rtf.contains("First point"), "{rtf:?}"); + assert!(!rtf.contains("Company Confidential") && !rtf.contains("1 May 2026"), "{rtf:?}"); +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 97caafdb3..4125c2905 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -694,7 +694,9 @@ pub fn slides_to_outline(p: &Presentation) -> String { out.push_str(&s.title().replace('\n', " ")); out.push('\n'); for sh in &s.shapes { - if sh.ph_type().is_some_and(|k| k.is_title()) { + // The title is the slide's line; footer, date and slide-number placeholders are not + // body text (PowerPoint's outline view shows title and body placeholders only). + if sh.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind()) { continue; } if let Some(t) = &sh.text { diff --git a/crates/format/src/rtf.rs b/crates/format/src/rtf.rs index b546a832f..4e7e29583 100644 --- a/crates/format/src/rtf.rs +++ b/crates/format/src/rtf.rs @@ -71,7 +71,8 @@ pub fn slides_to_rtf(p: &Presentation) -> String { } out.push_str("\\b0\\par\n"); for sh in &s.shapes { - if sh.ph_type().is_some_and(|k| k.is_title()) { + // As in the text outline: footer, date and slide-number placeholders are not body text. + if sh.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind()) { continue; } let Some(t) = &sh.text else { continue }; diff --git a/crates/ui-egui/src/sorter.rs b/crates/ui-egui/src/sorter.rs index 6c9626380..5205a835d 100644 --- a/crates/ui-egui/src/sorter.rs +++ b/crates/ui-egui/src/sorter.rs @@ -476,7 +476,7 @@ fn outline_estimate(s: &deckcraft_model::Slide) -> f32 { let lines: usize = s .shapes .iter() - .filter(|x| !x.ph_type().is_some_and(|k| k.is_title())) + .filter(|x| !x.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind())) .filter_map(|x| x.text.as_ref()) .filter(|tb| !tb.is_empty()) .map(|tb| tb.paragraphs.len().max(1)) @@ -512,7 +512,8 @@ fn outline_slide(app: &mut SlideApp, ui: &mut Ui, t: &Tokens, i: usize, s: &deck ui.data_mut(|d| d.insert_temp(id, v)); } }); - for sh in s.shapes.iter().filter(|x| !x.ph_type().is_some_and(|k| k.is_title())) { + // Footer, date and slide-number placeholders are not outline text, as in PowerPoint. + for sh in s.shapes.iter().filter(|x| !x.ph_type().is_some_and(|k| k.is_title() || k.is_footer_kind())) { let Some(tb) = &sh.text else { continue }; if tb.is_empty() { continue; diff --git a/crates/ui-egui/src/sorter/ui_tests.rs b/crates/ui-egui/src/sorter/ui_tests.rs index 966974616..07b42d02f 100644 --- a/crates/ui-egui/src/sorter/ui_tests.rs +++ b/crates/ui-egui/src/sorter/ui_tests.rs @@ -259,3 +259,24 @@ fn shift_and_ctrl_shift_clicks_select_ranges() { click(&mut h, 4, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(selected(&h), vec![0, 2, 3]); } + +/// The outline view lists a slide's title and body text, not its footer, date and slide-number +/// placeholders, as PowerPoint's does: turning them on leaves the slide's outline block as it was. +#[test] +fn the_outline_view_leaves_footer_date_and_slide_number_out() { + let mut s = Session::with_new(); + s.execute("slide.new", &json!({"layout": "titleAndContent", "title": "Agenda", "body": "First point\nSecond point"})).unwrap(); + let slide = |s: &Session| { + let st = s.doc().unwrap(); + st.doc.slides[st.selection.slide].clone() + }; + let plain = super::outline_estimate(&slide(&s)); + s.execute( + "design.headerFooter", + &json!({"footer": true, "footerText": "Company Confidential", "slideNumber": true, "date": true, "dateText": "1 May 2026"}), + ) + .unwrap(); + let with_footer = slide(&s); + assert!(with_footer.shapes.iter().any(|x| x.ph_type().is_some_and(|k| k.is_footer_kind())), "the footers are on the slide"); + assert_eq!(super::outline_estimate(&with_footer), plain); +} From fe35df948cdc354cfe8defeb5cf9ae79c60acbfd Mon Sep 17 00:00:00 2001 From: Zach Berry <1112351+zberry@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:09:40 -0600 Subject: [PATCH 53/94] Flip is refused on a SmartArt graphic instead of turning it into a plain group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PowerPoint greys Flip out for a SmartArt graphic (SmartArt Design ▸ Right to Left is the way to mirror it), also inside a group, as ungrouping would hand the flip to the graphic. Before, a flip turned it into a plain group that the smartArt.* commands then refused. arrange.flipHorizontal and flipVertical reach the check through shape.flip. Split out of the SmartArt PR at review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/shape/size.rs | 10 ++++++++++ crates/engine/src/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/engine/src/cmd/shape/size.rs b/crates/engine/src/cmd/shape/size.rs index af235e403..5a573c625 100644 --- a/crates/engine/src/cmd/shape/size.rs +++ b/crates/engine/src/cmd/shape/size.rs @@ -191,6 +191,16 @@ pub(super) fn rotate(s: &mut Session, p: &Value) -> Result<Value> { pub(super) fn flip(s: &mut Session, p: &Value) -> Result<Value> { let v = str_param(p, "axis").unwrap_or("horizontal").starts_with('v'); edit_geometry(s, p, "shape.flip", |sh| { + // PowerPoint greys Flip out for a SmartArt graphic (SmartArt Design > Right to Left mirrors it), + // also inside a group: ungrouping would hand the flip to the graphic. + let mut graphic = false; + deckcraft_model::walk(std::slice::from_ref(&*sh), &mut |x, _| graphic |= x.diagram.is_some()); + if graphic { + return Err(bad( + "shape.flip", + "Flip is not available for a SmartArt graphic (it would turn it into a plain group); use `smartArt.layout` to change how it is laid out", + )); + } if let Some(x) = sh.xfrm.as_mut() { if v { x.flip_v = !x.flip_v; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 12fac5efc..2410a38bc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6509,3 +6509,27 @@ fn save_to_image_path_is_an_error_not_zip_bytes() { } let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn flip_is_refused_on_a_smartart_graphic_and_leaves_it_a_graphic() { + let mut s = session(); + s.execute("slide.new", &json!({"layout": "blank"})).unwrap(); + s.execute("insert.textBox", &json!({"text": "Goals\nRevenue"})).unwrap(); + let gid = s.execute("smartArt.fromText", &json!({"kind": "blockList"})).unwrap()["id"].as_u64().unwrap(); + for cmd in ["arrange.flipHorizontal", "arrange.flipVertical", "shape.flip"] { + let e = s.execute(cmd, &json!({"ids": [gid]})).unwrap_err().to_string(); + assert!(e.contains("SmartArt") && e.contains("smartArt.layout"), "{cmd}: {e}"); + } + // Grouped with another shape it cannot be flipped either: ungrouping would hand it the flip. + let other = s.execute("insert.textBox", &json!({"text": "x"})).unwrap()["id"].as_u64().unwrap(); + let group = s.execute("arrange.group", &json!({"ids": [gid, other]})).unwrap()["id"].as_u64().unwrap(); + let e = s.execute("shape.flip", &json!({"ids": [group]})).unwrap_err().to_string(); + assert!(e.contains("SmartArt"), "{e}"); + s.execute("arrange.ungroup", &json!({"ids": [group]})).unwrap(); + // Still a SmartArt graphic: smartArt commands keep working. + s.execute("smartArt.layout", &json!({"id": gid, "kind": "cycle"})).unwrap(); + // Ordinary shapes still flip. + let b = s.execute("insert.textBox", &json!({"text": "x"})).unwrap(); + let id = b["id"].as_u64().unwrap(); + assert_eq!(s.execute("arrange.flipHorizontal", &json!({"ids": [id]})).unwrap(), json!(1)); +} From a2d9e71b5e71bfbe2e96499b6dce304118153fe2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:33:51 +0100 Subject: [PATCH 54/94] About: credits tables fit without side-scrolling and their columns resize (#1806) * About: credits tables fit without side-scrolling and their columns resize The Contributors table and the Models table were egui Grids inside a two-way scroll area: they opened wider than the dialog, so they scrolled sideways, and Company and Model sat almost touching. Both are now egui_extras tables. Each column opens at the width of its header and widest cell, the spare width goes to the text columns (Name; Company and Model), and every column edge can be dragged. Widening a column grows the table like a spreadsheet, and only then does it scroll sideways; the header stays put while the rows scroll. Counts and dates are right-aligned and every cell is vertically centred. The sorted column stays highlighted and its direction shows on the toolbar's sort-order button, so headers no longer reserve room for an arrow. The opening widths come from fit_widths, a pure function with unit tests that a fitted table fills its room exactly and that only the text columns give way when room is short. The About dialog opens 820 points wide, so every column fits at its natural width. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Let every credits column be dragged, and refit changed tables The last column was egui's remainder column, which has no drag handle, so it could only be resized from the edge before it. It is now an ordinary column with its own handle. A table keeps its column widths, so switching to a longer name left the Name column at its old width and clipped the text. The table now goes back to the opening fit whenever that fit changes: a longer widest cell or a resized window. Dragged widths are dropped at that point. fit_widths could overflow the room when one column hit the minimum, because the other columns did not take up its share. Columns now give way in proportion to their width above the minimum. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Refit credits tables on what they measure, not the fitted widths Comparing the fitted widths missed the case it was meant for. Name is the only growing column, so a longer name takes its extra width from the spare room and the fit comes out the same: a dragged Name width stayed, clipping the longer name. It could also drop dragged widths by accident. The fit comes from the available width inside the scroll area, which scrolling can nudge, so scrolling a widened table could reset it. The table now compares the natural widths and the clip rect's width, which scrolling does not move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- Cargo.lock | 41 ++- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/dialogs/about.rs | 2 +- crates/ui-egui/src/dialogs/credits.rs | 371 ++++++++++++++++++++++---- 4 files changed, 357 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c86df3540..417823304 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1275,6 +1275,7 @@ dependencies = [ "deckcraft-render", "deckcraft-text", "egui", + "egui_extras", "egui_kittest", "log", "serde", @@ -1520,6 +1521,19 @@ dependencies = [ "winit", ] +[[package]] +name = "egui_extras" +version = "0.37.0" +source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "profiling", +] + [[package]] name = "egui_glow" version = "0.37.0" @@ -1587,6 +1601,26 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum-map" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -3487,7 +3521,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.45.0", + "windows-sys 0.61.2", ] [[package]] @@ -6511,11 +6545,6 @@ name = "egui_demo_lib" version = "0.37.0" source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" -[[patch.unused]] -name = "egui_extras" -version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a" - [[patch.unused]] name = "egui_inspection" version = "0.37.0" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 88b9f770b..166eba220 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -19,6 +19,7 @@ deckcraft-anim = { workspace = true } deckcraft-engine = { workspace = true } deckcraft-media = { workspace = true } egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } +egui_extras = { workspace = true } craft-ui = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/src/dialogs/about.rs b/crates/ui-egui/src/dialogs/about.rs index 03c6629b2..059543b61 100644 --- a/crates/ui-egui/src/dialogs/about.rs +++ b/crates/ui-egui/src/dialogs/about.rs @@ -1,7 +1,7 @@ use super::{Color32, CornerRadius, Rect, Sense, SlideApp, Stroke, Tokens, Ui, pos2, theme, vec2}; /// Room the About credits need for their table; the About tab keeps its compact size. -pub(super) const CREDITS_SIZE: egui::Vec2 = vec2(640.0, 380.0); +pub(super) const CREDITS_SIZE: egui::Vec2 = vec2(820.0, 380.0); /// The Contributors / Models body in a block of its own fixed size, below the tab row. Sizing the /// dialog's `ui` instead (`set_min_size` / `set_max_height`) squeezed the tab row and the first diff --git a/crates/ui-egui/src/dialogs/credits.rs b/crates/ui-egui/src/dialogs/credits.rs index d1bf5b30e..b9b32e56e 100644 --- a/crates/ui-egui/src/dialogs/credits.rs +++ b/crates/ui-egui/src/dialogs/credits.rs @@ -246,12 +246,14 @@ pub fn contributors_ui(ui: &mut egui::Ui) { let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending); ui.label(RichText::new(format!("{} contributors · {} commits", list.len(), group(TOTAL_COMMITS))).small().weak()); ui.separator(); - egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { - if list.is_empty() { - ui.label("No contributor data was built into this copy."); - } else if v.table { - table(ui, &list, &mut v); - } else { + if list.is_empty() { + ui.label("No contributor data was built into this copy."); + } else if v.table { + // The table scrolls vertically itself, under a fixed header; it only scrolls sideways + // once its columns are dragged wider than the dialog. + egui::ScrollArea::horizontal().auto_shrink([false, false]).show(ui, |ui| table(ui, &list, &mut v)); + } else { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.horizontal_wrapped(|ui| { for (i, c) in list.iter().enumerate() { if i > 0 { @@ -260,39 +262,153 @@ pub fn contributors_ui(ui: &mut egui::Ui) { ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); } }); - } - }); + }); + } ui.data_mut(|d| d.insert_temp(id, v)); } -fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { - egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| { - for k in SortKey::ALL { - let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" }; - if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() { - if v.key == k { - v.ascending = !v.ascending; - } else { - v.key = k; - v.ascending = k.default_ascending(); - } +/// How the contributor table's spare width is shared out: all of it to Name. +const CONTRIBUTOR_GROW: [f32; 10] = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]; + +/// How the model table's spare width is shared out: to Company and Model, the text columns. +const MODEL_GROW: [f32; 6] = [1.0, 2.0, 0.0, 0.0, 0.0, 0.0]; + +/// The narrowest a column can be dragged. +const MIN_COLUMN: f32 = 28.0; + +/// The width a column needs for its header and its widest cell. +fn natural(ui: &egui::Ui, header: RichText, cells: impl Iterator<Item = String>) -> f32 { + let measure = |text: egui::WidgetText| text.into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x; + let widest = cells.map(|c| measure(c.into())).fold(measure(header.into()), f32::max); + widest + 2.0 * ui.spacing().button_padding.x +} + +/// Opening column widths: each column's natural width, with the spare room shared out by `grow`, +/// so the columns fill `room` exactly. When there is too little room, only the growing columns +/// give way, each in proportion to its width above [`MIN_COLUMN`], and none goes below that. +fn fit_widths(natural: &[f32], grow: &[f32], room: f32) -> Vec<f32> { + let spare = room - natural.iter().sum::<f32>(); + let weight = grow.iter().sum::<f32>(); + let slack = |w: f32| (w - MIN_COLUMN).max(0.0); + let flexible: f32 = natural.iter().zip(grow).filter(|(_, g)| **g > 0.0).map(|(w, _)| slack(*w)).sum(); + natural + .iter() + .zip(grow) + .map(|(w, g)| { + if *g > 0.0 && spare >= 0.0 { + w + spare * g / weight + } else if *g > 0.0 && flexible > 0.0 { + w - (-spare).min(flexible) * slack(*w) / flexible + } else { + *w } - } - ui.end_row(); - for c in list { - ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary()); - ui.label(group(c.prs)); - ui.label(group(c.commits)); - ui.label(group(c.lines_added)); - ui.label(group(c.lines_deleted)); - ui.label(signed(c.lines_delta())); - ui.label(group(c.binary_added)); - ui.label(group(c.binary_deleted)); - ui.label(day(c.first_commit)); - ui.label(day(c.last_commit)); - ui.end_row(); - } - }); + }) + .collect() +} + +/// A striped table whose columns open at [`fit_widths`], so it fills the width and nothing scrolls +/// sideways. Every column, the last included, can be dragged wider or narrower at its right edge: +/// only a table dragged wider than the window scrolls sideways. Text too long for its column is +/// clipped. When a column's natural width or the window changes, the columns go back to a new fit, +/// dropping any dragged widths. +fn fitted_table<'a>(ui: &'a mut egui::Ui, id: &str, natural: &[f32], grow: &[f32]) -> egui_extras::TableBuilder<'a> { + // Every cell is followed by the item gap, and the vertical scrollbar keeps its margins. + let s = ui.spacing(); + let gaps = s.item_spacing.x * natural.len() as f32; + let bar = s.scroll.bar_width + s.scroll.bar_inner_margin + s.scroll.bar_outer_margin; + let widths = fit_widths(natural, grow, (ui.available_width() - gaps - bar).max(0.0)); + // The table keeps its own column widths, so a change in what they were fitted to has to clear + // them. A longer name can leave the fit itself unchanged, and scrolling can nudge the available + // width, so this compares the natural widths and the clip rect, which scrolling never moves. + let fit = egui::Id::unique(("credits_fit", id)); + let measured = (natural.to_vec(), ui.clip_rect().width()); + let refit = ui.data_mut(|d| d.get_temp::<(Vec<f32>, f32)>(fit)).as_ref() != Some(&measured); + ui.data_mut(|d| d.insert_temp(fit, measured)); + let mut t = + egui_extras::TableBuilder::new(ui).id_salt(id).striped(true).resizable(true).auto_shrink([false, false]).max_scroll_height(f32::INFINITY); + if refit { + t.reset(); + } + for w in widths { + t = t.column(egui_extras::Column::initial(w).at_least(MIN_COLUMN).clip(true)); + } + t +} + +/// Add a cell's widget right-aligned (counts, dates) or left-aligned (names), vertically centred. +fn aligned<R>(ui: &mut egui::Ui, right: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let layout = if right { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; + ui.with_layout(layout, add).inner +} + +fn row_height(ui: &egui::Ui) -> f32 { + ui.text_style_height(&egui::TextStyle::Body) + 6.0 +} + +/// One contributor's table cells after the name, in `SortKey::ALL` order. +fn cells(c: &Contributor) -> [String; 9] { + [ + group(c.prs), + group(c.commits), + group(c.lines_added), + group(c.lines_deleted), + signed(c.lines_delta()), + group(c.binary_added), + group(c.binary_deleted), + day(c.first_commit).to_string(), + day(c.last_commit).to_string(), + ] +} + +/// A contributor-table header. The sorted column is highlighted; its direction shows on the +/// toolbar's sort-order button, so no arrow widens the column. +fn header_text(k: SortKey) -> RichText { + RichText::new(k.label().1).strong() +} + +fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) { + let h = row_height(ui); + let rows: Vec<[String; 9]> = list.iter().map(|c| cells(c)).collect(); + let widths: Vec<f32> = SortKey::ALL + .iter() + .enumerate() + .map(|(i, &k)| match i.checked_sub(1) { + None => natural(ui, header_text(k), list.iter().map(|c| c.name(v.names))), + Some(col) => natural(ui, header_text(k), rows.iter().filter_map(|r| r.get(col).cloned())), + }) + .collect(); + fitted_table(ui, "credits_table", &widths, &CONTRIBUTOR_GROW) + .header(h + 4.0, |mut header| { + for k in SortKey::ALL { + header.col(|ui| { + let r = aligned(ui, k != SortKey::Name, |ui| ui.selectable_label(v.key == k, header_text(k))).on_hover_text(k.label().0); + + if r.clicked() { + if v.key == k { + v.ascending = !v.ascending; + } else { + v.key = k; + v.ascending = k.default_ascending(); + } + } + }); + } + }) + .body(|mut body| { + for (c, cells) in list.iter().zip(rows) { + body.row(h, |mut row| { + row.col(|ui| { + aligned(ui, false, |ui| ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login))) + .on_hover_text(c.summary()); + }); + for text in cells { + row.col(|ui| { + aligned(ui, true, |ui| ui.label(text)); + }); + } + }); + } + }); } /// About ▸ Models: AI models credited in Co-Authored-By trailers. @@ -302,22 +418,48 @@ pub fn models_ui(ui: &mut egui::Ui) { return; } let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1); - egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { - egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| { - for h in ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"] { - ui.label(RichText::new(h).strong()); - } - ui.end_row(); - for m in MODELS { - ui.label(m.company); - ui.label(m.model); - ui.label(m.version); - ui.label(group(m.commits)); - ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64)); - ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted))); - ui.end_row(); - } - }); + let h = row_height(ui); + let titles = ["Company", "Model", "Version", "Commits", "% of all commits", "Lines +/−"]; + // Company, Model and Version read as text; the counts line up on the right. + let right = [false, false, false, true, true, true]; + let rows: Vec<[String; 6]> = MODELS + .iter() + .map(|m| { + [ + m.company.to_string(), + m.model.to_string(), + m.version.to_string(), + group(m.commits), + format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64), + format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)), + ] + }) + .collect(); + let widths: Vec<f32> = titles + .iter() + .enumerate() + .map(|(i, title)| natural(ui, RichText::new(*title).strong(), rows.iter().filter_map(|r| r.get(i).cloned()))) + .collect(); + egui::ScrollArea::horizontal().id_salt("credits_models").auto_shrink([false, false]).show(ui, |ui| { + fitted_table(ui, "credits_models", &widths, &MODEL_GROW) + .header(h + 4.0, |mut header| { + for (title, r) in titles.into_iter().zip(right) { + header.col(|ui| { + aligned(ui, r, |ui| ui.label(RichText::new(title).strong())); + }); + } + }) + .body(|mut body| { + for cells in rows { + body.row(h, |mut row| { + for (text, r) in cells.into_iter().zip(right) { + row.col(|ui| { + aligned(ui, r, |ui| ui.label(text)); + }); + } + }); + } + }); }); } @@ -397,4 +539,131 @@ mod tests { assert_eq!(day("2026-10-07T18:45:23Z"), "2026-10-07"); assert_eq!(day(""), "—"); } + + #[test] + fn columns_fill_the_room_and_spare_width_goes_to_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 300.0), [200.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 2.0, 0.0], 230.0), [110.0, 60.0, 60.0]); + let w = fit_widths(&[123.0, 45.5, 67.25], &[1.0, 0.0, 2.0], 512.0); + assert!((w.iter().sum::<f32>() - 512.0).abs() < 0.01, "a fitted table neither scrolls nor leaves a gap: {w:?}"); + } + + #[test] + fn too_little_room_shrinks_only_growing_columns() { + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 150.0), [50.0, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0, 60.0], &[1.0, 0.0, 0.0], 0.0), [MIN_COLUMN, 40.0, 60.0]); + assert_eq!(fit_widths(&[100.0, 40.0], &[0.0, 0.0], 50.0), [100.0, 40.0]); + } + + #[test] + fn a_column_at_the_minimum_leaves_the_shortfall_to_the_others() { + let w = fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 140.0); + assert!((w.iter().sum::<f32>() - 140.0).abs() < 0.01, "the columns still fit the room: {w:?}"); + assert!(w.iter().all(|c| *c >= MIN_COLUMN), "no column goes below the minimum: {w:?}"); + assert_eq!(fit_widths(&[100.0, 300.0, 50.0], &[1.0, 1.0, 0.0], 0.0), [MIN_COLUMN, MIN_COLUMN, 50.0]); + } + + const WINDOW: f32 = 640.5; + const NATURAL: [f32; 3] = [120.0, 80.0, 80.0]; + const GROW: [f32; 3] = [1.0, 0.0, 0.0]; + + /// One frame of a table long enough to scroll; the rects of its header cells. + fn table_frame(ctx: &egui::Context, width: f32, natural: &[f32], events: Vec<egui::Event>) -> Vec<egui::Rect> { + scrolled_frame(ctx, width, natural, 0.0, events) + } + + /// [`table_frame`], scrolled `offset` points sideways. + fn scrolled_frame(ctx: &egui::Context, width: f32, natural: &[f32], offset: f32, events: Vec<egui::Event>) -> Vec<egui::Rect> { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0))); + let raw = egui::RawInput { screen_rect, events, ..Default::default() }; + let mut cells = Vec::new(); + let out = ctx.run_ui(raw, |ui| { + cells.clear(); + egui::ScrollArea::horizontal().auto_shrink([false, false]).horizontal_scroll_offset(offset).show(ui, |ui| { + fitted_table(ui, "test", natural, &GROW) + .header(20.0, |mut header| { + for _ in natural { + header.col(|ui| cells.push(ui.max_rect())); + } + }) + .body(|mut body| { + for _ in 0..40 { + body.row(20.0, |mut row| { + for _ in natural { + row.col(|ui| { + ui.label("x"); + }); + } + }); + } + }); + }); + }); + out.drop_without_applying_deltas(); + cells + } + + /// A new context with the table open and settled, and the rects of its header cells. + fn opened_table() -> (egui::Context, Vec<egui::Rect>) { + let ctx = egui::Context::default(); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let cells = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + (ctx, cells) + } + + /// Drags a column's right edge, which runs midway through the gap after `cell`, then lets go. + fn drag_edge(ctx: &egui::Context, cell: egui::Rect, by: f32) { + use egui::{Event, Modifiers, PointerButton}; + let start = egui::pos2(cell.right() + 4.0, cell.center().y); + let halfway = start + egui::vec2(by / 2.0, 0.0); + let end = start + egui::vec2(by, 0.0); + let moved = Event::PointerMoved; + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + for event in [moved(start), button(start, true), moved(halfway), moved(end), button(end, false)] { + table_frame(ctx, WINDOW, &NATURAL, vec![event]); + } + } + + #[test] + fn every_column_can_be_dragged_at_its_right_edge_and_stays_there() { + let (_, opened) = opened_table(); + for (dragged, cell) in opened.iter().enumerate() { + let (ctx, _) = opened_table(); + drag_edge(&ctx, *cell, -30.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let after = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + for (column, (was, now)) in opened.iter().zip(&after).enumerate() { + let want = if column == dragged { was.width() - 30.0 } else { was.width() }; + assert!((now.width() - want).abs() < 1.0, "dragging column {dragged}: column {column} is {now:?}, was {was:?}"); + } + } + } + + #[test] + fn a_changed_fit_replaces_the_column_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], -30.0); + let longer_name = table_frame(&ctx, WINDOW, &[200.0, 80.0, 80.0], Vec::new()); + assert!((longer_name[0].width() - opened[0].width()).abs() < 1.0, "a longer name drops a dragged width: {longer_name:?}"); + let wider = table_frame(&ctx, WINDOW, &[120.0, 200.0, 80.0], Vec::new()); + let widths: Vec<f32> = wider.iter().map(|c| c.width().round()).collect(); + assert!(widths.ends_with(&[200.0, 80.0]), "a longer cell widens its column: {widths:?}"); + assert!(wider[2].right() < WINDOW, "the table still fits the window: {wider:?}"); + let narrower = table_frame(&ctx, 400.0, &NATURAL, Vec::new()); + assert!(narrower[2].right() < 400.0, "a narrower window refits the table: {narrower:?}"); + } + + #[test] + fn scrolling_sideways_keeps_dragged_widths() { + let (ctx, opened) = opened_table(); + drag_edge(&ctx, opened[0], 100.0); + table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + let dragged = table_frame(&ctx, WINDOW, &NATURAL, Vec::new()); + assert!((dragged[0].width() - opened[0].width() - 100.0).abs() < 1.0, "the drag took: {dragged:?}"); + for offset in [13.3, 27.77, 41.1, 0.6] { + scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + let scrolled = scrolled_frame(&ctx, WINDOW, &NATURAL, offset, Vec::new()); + assert!((scrolled[0].width() - dragged[0].width()).abs() < 1.0, "scrolled {offset}: {scrolled:?}"); + } + } } From b06d60b8ed9985610e033df98610561f9b41d170 Mon Sep 17 00:00:00 2001 From: sbjwin <sbjwin4271@gmail.com> Date: Thu, 5 Nov 2026 12:35:59 +0900 Subject: [PATCH 55/94] UI: follow Grayscale view mode in slide thumbnails In PowerPoint, turning on Grayscale view mode turns both the active slide canvas and the slide thumbnail pane to grayscale, while Print retains the original full color for output. Previously, DeckCraft only passed `app.ui.grayscale` to the main canvas texture renderer (`Textures::slide`), while thumbnail rendering (`Textures::thumb`) hardcoded `false` and lacked `grayscale` in its cache key. As a result, when Grayscale mode was enabled, the canvas rendered in grayscale but the thumbnail pane remained in full color. - Update `Textures::thumb` to accept `grayscale: bool` and include it in the cache key (`extra: grayscale as u64`). - Pass `app.ui.grayscale` to `Textures::thumb` in the thumbnail pane (`panels/thumbs.rs`), Slide Sorter & Notes Page (`sorter.rs`), and Notes Master view (`canvas.rs`). - Keep Print preview (`backstage/print.rs`) in full color (`false`) to match the actual exported PDF print output. - Add regression test `to_color_image_turns_colors_to_grayscale_when_flag_is_set`. --- crates/ui-egui/src/backstage/print.rs | 3 ++- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/panels/thumbs.rs | 2 +- crates/ui-egui/src/sorter.rs | 5 +++-- crates/ui-egui/src/textures.rs | 29 ++++++++++++++++++++++++--- 5 files changed, 33 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/backstage/print.rs b/crates/ui-egui/src/backstage/print.rs index 612ecaf75..db5d6b972 100644 --- a/crates/ui-egui/src/backstage/print.rs +++ b/crates/ui-egui/src/backstage/print.rs @@ -207,7 +207,8 @@ fn preview(app: &mut SlideApp, ui: &mut Ui, bs: &mut Backstage, doc: &deckcraft_ let mut budget = 4u32; let mut draw_slide = |ui: &mut Ui, i: usize, r: Rect| { let px = (r.width() * ui.ctx().pixels_per_point()).round().clamp(16.0, 1600.0) as u32; - match app.textures.thumb(ui.ctx(), doc, i, px, &mut budget) { + // Print preview matches the actual exported PDF output (always full color). + match app.textures.thumb(ui.ctx(), doc, i, px, false, &mut budget) { Some(tex) => { ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 922435ca5..ca1029cbc 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -299,7 +299,7 @@ pub fn show(app: &mut SlideApp, ui: &mut Ui) { vec2(w as f32 * scale, h as f32 * scale), ); let mut budget = 2; - if let Some(tex) = app.textures.thumb(ui.ctx(), &doc, idx, (r.width() * ppp).round().max(1.0) as u32, &mut budget) { + if let Some(tex) = app.textures.thumb(ui.ctx(), &doc, idx, (r.width() * ppp).round().max(1.0) as u32, app.ui.grayscale, &mut budget) { painter.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } } diff --git a/crates/ui-egui/src/panels/thumbs.rs b/crates/ui-egui/src/panels/thumbs.rs index 946391c35..4956f2b0b 100644 --- a/crates/ui-egui/src/panels/thumbs.rs +++ b/crates/ui-egui/src/panels/thumbs.rs @@ -219,7 +219,7 @@ fn list(app: &mut SlideApp, ui: &mut Ui) { // Only rows in view (plus a little margin) ask for a thumbnail: with every row asking, a // deck bigger than the thumbnail cache evicts its own thumbnails and never settles (#969). let near = ui.clip_rect().expand2(vec2(0.0, 2.0 * row.height())).intersects(row); - let tex = if near { app.textures.thumb(ui.ctx(), &doc, i, wpx, &mut budget) } else { None }; + let tex = if near { app.textures.thumb(ui.ctx(), &doc, i, wpx, app.ui.grayscale, &mut budget) } else { None }; match tex { Some(tex) => { p.image( diff --git a/crates/ui-egui/src/sorter.rs b/crates/ui-egui/src/sorter.rs index 6c9626380..755f1f4a1 100644 --- a/crates/ui-egui/src/sorter.rs +++ b/crates/ui-egui/src/sorter.rs @@ -209,7 +209,8 @@ fn place_slides(app: &mut SlideApp, ui: &mut Ui, g: &Grid<'_>, budget: &mut u32, // Only cells in view (plus a little margin) ask for a thumbnail, so a deck bigger // than the thumbnail cache does not evict its own thumbnails forever (#969). let near = ui.clip_rect().expand2(vec2(0.0, 2.0 * cell.height())).intersects(cell); - let tex = if near { app.textures.thumb(ui.ctx(), g.doc, i, (img.width() * ppp).round() as u32, budget) } else { None }; + let tex = + if near { app.textures.thumb(ui.ctx(), g.doc, i, (img.width() * ppp).round() as u32, app.ui.grayscale, budget) } else { None }; match tex { Some(tex) => { p.image(tex.id(), img, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); @@ -391,7 +392,7 @@ pub fn notes_page(app: &mut SlideApp, ui: &mut Ui) { } let ppp = ui.ctx().pixels_per_point(); let mut budget = 2; - if let Some(tex) = app.textures.thumb(ui.ctx(), &doc, idx, (srect.width() * ppp).round() as u32, &mut budget) { + if let Some(tex) = app.textures.thumb(ui.ctx(), &doc, idx, (srect.width() * ppp).round() as u32, app.ui.grayscale, &mut budget) { ui.painter().image(tex.id(), srect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } ui.painter().rect_stroke(srect, CornerRadius::ZERO, Stroke::new(1.0, Color32::GRAY), egui::StrokeKind::Outside); diff --git a/crates/ui-egui/src/textures.rs b/crates/ui-egui/src/textures.rs index 19a4b4f68..f7accb8b3 100644 --- a/crates/ui-egui/src/textures.rs +++ b/crates/ui-egui/src/textures.rs @@ -363,7 +363,16 @@ impl Textures { /// A thumbnail texture; renders at most `budget` new thumbnails per frame (returns None when /// it is over budget, so the caller draws a placeholder and asks for another frame). - pub fn thumb(&mut self, ctx: &egui::Context, p: &Presentation, index: usize, width_px: u32, budget: &mut u32) -> Option<TextureHandle> { + /// When `grayscale` is true, the thumbnail renders in black-and-white (matching Grayscale view). + pub fn thumb( + &mut self, + ctx: &egui::Context, + p: &Presentation, + index: usize, + width_px: u32, + grayscale: bool, + budget: &mut u32, + ) -> Option<TextureHandle> { let slide = p.slides.get(index)?.clone(); let master = master_of(p, &slide); let h = (width_px as f64 * p.slide_size.height / p.slide_size.width.max(1.0)).round().max(1.0) as u32; @@ -372,7 +381,7 @@ impl Textures { master: master.as_ref().map(|m| Arc::as_ptr(m) as usize).unwrap_or(0), size: (width_px, h), edit: false, - extra: 0, + extra: grayscale as u64, want: Region::slide(width_px, h), editing_text: None, }; @@ -393,7 +402,7 @@ impl Textures { let scale = tw as f64 / p.slide_size.width.max(1.0); let img = deckcraft_render::render_slide(p, index, &RenderOpts { scale, size: Some((tw, th)), threads: 0, ..Default::default() }); self.thumb_renders += 1; - let tex = upload_editor(ctx, format!("thumb-{index}"), to_color_image(&img, false)); + let tex = upload_editor(ctx, format!("thumb-{index}"), to_color_image(&img, grayscale)); // Drop the old entry for this slide address; entries for slides that no longer exist age out. let region = key.want; self.thumbs.insert(key.slide, Entry { key, tex: tex.clone(), region, _slide: slide, _master: master, stamp: clock }); @@ -433,6 +442,20 @@ mod tests { assert_eq!(device_pixel_rect(aligned, ppp), aligned); } + #[test] + fn to_color_image_turns_colors_to_grayscale_when_flag_is_set() { + let img = deckcraft_render::Image { width: 2, height: 1, pixels: vec![0, 0, 255, 255, 255, 0, 0, 255] }; + let color = super::to_color_image(&img, false); + assert_eq!(color.pixels[0], egui::Color32::from_rgba_premultiplied(0, 0, 255, 255)); + assert_eq!(color.pixels[1], egui::Color32::from_rgba_premultiplied(255, 0, 0, 255)); + + let gray = super::to_color_image(&img, true); + assert_eq!(gray.pixels[0].r(), gray.pixels[0].g()); + assert_eq!(gray.pixels[0].g(), gray.pixels[0].b()); + assert_eq!(gray.pixels[1].r(), gray.pixels[1].g()); + assert_eq!(gray.pixels[1].g(), gray.pixels[1].b()); + } + #[test] fn a_bad_scale_does_not_move_the_rect() { let r = Rect::from_min_size(pos2(3.0, 4.0), vec2(10.0, 12.0)); From ebd306acc12e75a5666d3b7a8010daabdeefb26b Mon Sep 17 00:00:00 2001 From: sbjwin <sbjwin4271@gmail.com> Date: Thu, 5 Nov 2026 12:51:29 +0900 Subject: [PATCH 56/94] UI: request repaint on stale thumbnail return to finish grayscale refresh --- crates/ui-egui/src/textures.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/textures.rs b/crates/ui-egui/src/textures.rs index f7accb8b3..d0f764066 100644 --- a/crates/ui-egui/src/textures.rs +++ b/crates/ui-egui/src/textures.rs @@ -394,7 +394,8 @@ impl Textures { return Some(e.tex.clone()); } if *budget == 0 { - // Keep showing the stale thumbnail while the new one waits. + // Keep showing the stale thumbnail while the new one waits; request a repaint to finish rendering. + ctx.request_repaint(); return self.thumbs.get(&key.slide).map(|e| e.tex.clone()); } *budget -= 1; From 75744dd67d2dbd4963ddf1b2b0d69d03e2b54ca3 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:02:42 +0000 Subject: [PATCH 57/94] Apply review fixes - crates/engine/src/tools/drag.rs --- crates/engine/src/tools/drag.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tools/drag.rs b/crates/engine/src/tools/drag.rs index dcee9cf7d..a1abcb93c 100644 --- a/crates/engine/src/tools/drag.rs +++ b/crates/engine/src/tools/drag.rs @@ -236,7 +236,12 @@ impl Session { } } // A connector dragged away from shapes that stay put comes unglued at those ends. - let moved: Vec<ShapeId> = origs2.iter().map(|o| o.0).collect(); + let mut moved: Vec<ShapeId> = vec![]; + for (id, _) in &origs2 { + if let Some(sh) = deckcraft_model::find_shape(list, *id) { + deckcraft_model::walk(std::slice::from_ref(sh), &mut |s, _| moved.push(s.id)); + } + } for sh in list.iter_mut().filter(|s| moved.contains(&s.id)) { if let ShapeKind::Connector { start, end } = &mut sh.kind { for c in [start, end] { From d9186c7ce125924db4c7487842a9559d916e1ef2 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 04:04:02 +0000 Subject: [PATCH 58/94] Apply review fixes - crates/engine/src/cmd/shape/size.rs --- crates/engine/src/cmd/shape/size.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/shape/size.rs b/crates/engine/src/cmd/shape/size.rs index 5a573c625..7568a0632 100644 --- a/crates/engine/src/cmd/shape/size.rs +++ b/crates/engine/src/cmd/shape/size.rs @@ -196,10 +196,7 @@ pub(super) fn flip(s: &mut Session, p: &Value) -> Result<Value> { let mut graphic = false; deckcraft_model::walk(std::slice::from_ref(&*sh), &mut |x, _| graphic |= x.diagram.is_some()); if graphic { - return Err(bad( - "shape.flip", - "Flip is not available for a SmartArt graphic (it would turn it into a plain group); use `smartArt.layout` to change how it is laid out", - )); + return Err(bad("shape.flip", "Flip is not available for a SmartArt graphic; use `smartArt.layout` to change how it is laid out")); } if let Some(x) = sh.xfrm.as_mut() { if v { From afc7f765c94c49eecd742647f33e4b2376f85e4b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:18:29 +0100 Subject: [PATCH 59/94] shape.connect: refuse a grouped non-line id as not a line --- crates/engine/src/cmd/shape/freeform.rs | 2 +- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/shape/freeform.rs b/crates/engine/src/cmd/shape/freeform.rs index c0430c85f..5fd299c9e 100644 --- a/crates/engine/src/cmd/shape/freeform.rs +++ b/crates/engine/src/cmd/shape/freeform.rs @@ -43,7 +43,7 @@ pub(super) fn connect(s: &mut Session, p: &Value) -> Result<Value> { let id = match id_param(p, "id", "shape.connect")? { // The ends are in slide space and rerouting follows the slide's own connectors, so a line // inside a group would be drawn in the group's space and never follow its shapes. - Some(id) if !st.shapes().iter().any(|sh| sh.id == id) && st.shape(id).is_some() => { + Some(id) if !st.shapes().iter().any(|sh| sh.id == id) && st.shape(id).is_some_and(|sh| sh.is_line()) => { return Err(bad("shape.connect", "`id` names a line inside a group; ungroup it first, or leave `id` out for a new connector")); } Some(id) => id, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index db23c803a..7f59ced53 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6569,6 +6569,10 @@ fn shape_connect_glues_to_a_shape_inside_a_group() { let e = s.execute("shape.connect", &json!({"id": m, "from": c, "to": b})).unwrap_err().to_string(); assert!(e.contains("inside a group"), "{e}"); assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); + // A grouped shape that is not a line is refused as not a line, not as a grouped line. + let e = s.execute("shape.connect", &json!({"id": n, "from": c, "to": b})).unwrap_err().to_string(); + assert!(e.contains("not a line"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); } /// The outline exports (PowerPoint's outline view) holds titles and body text only: footer, From 480cbfd4effc3a2e45c20cd74dffa814ec9805c5 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:18:38 +0100 Subject: [PATCH 60/94] Textures::thumb: document the stale thumbnail returned over budget --- crates/ui-egui/src/textures.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/textures.rs b/crates/ui-egui/src/textures.rs index d0f764066..e6e051457 100644 --- a/crates/ui-egui/src/textures.rs +++ b/crates/ui-egui/src/textures.rs @@ -361,8 +361,9 @@ impl Textures { self.thumbs.clear(); } - /// A thumbnail texture; renders at most `budget` new thumbnails per frame (returns None when - /// it is over budget, so the caller draws a placeholder and asks for another frame). + /// A thumbnail texture; renders at most `budget` new thumbnails per frame. Over budget it + /// returns the slide's previous thumbnail if there is one (and asks for another frame), else + /// None, so the caller draws a placeholder. /// When `grayscale` is true, the thumbnail renders in black-and-white (matching Grayscale view). pub fn thumb( &mut self, From 929911326873116404a2d85e00d5fa0ac5326989 Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:34:20 +0800 Subject: [PATCH 61/94] deckcraft-web: speak the host messages through craft-web-host, and add page host mode The transports, the message types and the origin checks come from the shared crate (storytold/craft-libs#420). `data-host="page"` on the canvas now hosts DeckCraft in a page's own document, as in the other apps; the parent bridge keeps its behaviour. --- Cargo.lock | 10 ++ apps/deckcraft-web/Cargo.toml | 2 + apps/deckcraft-web/src/host.rs | 163 +++++++++++---------------------- apps/deckcraft-web/src/web.rs | 12 ++- packaging/web/README.md | 4 +- 5 files changed, 74 insertions(+), 117 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 89aaa91aa..b4059e689 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -935,6 +935,15 @@ dependencies = [ "zip 9.1.0", ] +[[package]] +name = "craft-web-host" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6" +dependencies = [ + "wasm-bindgen", + "web-sys", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1322,6 +1331,7 @@ dependencies = [ name = "deckcraft-web" version = "0.15.0" dependencies = [ + "craft-web-host", "deckcraft-engine", "deckcraft-ui-egui", "eframe", diff --git a/apps/deckcraft-web/Cargo.toml b/apps/deckcraft-web/Cargo.toml index ca04d5be9..58e8657a4 100644 --- a/apps/deckcraft-web/Cargo.toml +++ b/apps/deckcraft-web/Cargo.toml @@ -16,6 +16,8 @@ path = "src/main.rs" [dependencies] deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } +# The host messages (storytold/craft-libs): one contract and one bridge for the web builds. +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs index 85c357a12..5cf4b0399 100644 --- a/apps/deckcraft-web/src/host.rs +++ b/apps/deckcraft-web/src/host.rs @@ -1,17 +1,21 @@ -//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed -//! DeckCraft in an `<iframe>` and keep its files (a Nextcloud app, a personal file server). The -//! same messages as GridCraft's, WordCraft's and PdfCraft's bridges; each is a plain object with a -//! `type`: +//! The host bridge, for pages that embed DeckCraft and keep its files (a Nextcloud app, a personal +//! file server). The messages and the two transports are `craft-web-host`'s +//! (storytold/craft-libs), the same contract as the other Craft apps' bridges, with the +//! `deckcraft:` prefix. This module is DeckCraft's part of it. //! -//! - `deckcraft:ready` (to the parent): `{ version }`, sent once the app is running and -//! listening; send a file now. -//! - `deckcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or +//! - `?host=parent` (an `<iframe>`) talks to the same-origin parent over `postMessage`; +//! `data-host="page"` on the canvas (the page's own document, no iframe) uses DOM +//! `CustomEvent`s on the canvas instead. `?host=parent` wins when both are present. With no +//! parent, or a parent on another origin, there is no bridge: the normal app with downloads. +//! - `deckcraft:ready` (to the host): sent once the app is running and listening; send a file now. DeckCraft +//! reads bytes, so it says `file: false` and a host sends `bytes`. +//! - `deckcraft:open` (from the host): `{ name, bytes }`, bytes an `ArrayBuffer` or //! `Uint8Array`, name a bare file name. It opens like a file picked with File › Open on the //! desktop: a presentation sent with its name (.pptx, .potx, .ppsx, .deckcraft) has that name //! as its file, so Save goes back to it; an outline (.txt, .md, .rtf), a file without a name and //! a damaged file open untitled. -//! - `deckcraft:save` (to the parent): `{ name, saveAs, bytes }` (a transferred `ArrayBuffer`) for -//! every file DeckCraft would otherwise download. The parent stores it and reports failures +//! - `deckcraft:save` (to the host): `{ name, saveAs, bytes }` (with the bytes as a transferred `ArrayBuffer` over `postMessage`) for +//! every file DeckCraft would otherwise download. The host stores it and reports failures //! itself. `saveAs` says whether the file becomes the presentation's file: //! - Save: `false`. It writes the opened file under its own name and format (a .pptx stays a //! .pptx), as the desktop app does. A name the parent never sent (an untitled presentation, an @@ -22,59 +26,46 @@ //! now that file; the next Save sends its name with `false`. //! - Export (PDF, pictures, outline, GIF, handouts, a Save As type that isn't a presentation) //! and Print: `false`. They are copies; the presentation's file stays the same. -//! - `deckcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away. -//! - `deckcraft:failed` (to the parent): `{ error }` when the app couldn't start. +//! - `deckcraft:dirty` whenever unsaved changes appear or go away, `deckcraft:failed` when the +//! app couldn't start. //! -//! Only the parent window on the page's own origin is heard or answered. In host mode the app -//! starts with an empty presentation instead of the sample, which gives way to the first file the -//! parent sends; the parent guards leaving the page, and `?author=` names the user for comments. +//! In host mode the app starts with an empty presentation instead of the sample, which gives way to +//! the first file the host sends; the host guards leaving the page, and `?author=` names the user +//! for comments. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::rc::Rc; +use craft_web_host::web::{FileData, Host, Message}; use deckcraft_ui_egui::{Services, SlideApp}; -use wasm_bindgen::JsCast as _; -use wasm_bindgen::JsValue; -use wasm_bindgen::closure::Closure; + +/// The app id in the host messages (`deckcraft:ready`). +const APP: &str = "deckcraft"; + +/// The name `craft-web-host` gives an open request that carries none (it cleans a host's name and +/// falls back to this): no name is no file, so the presentation opens untitled. +const NAMELESS: &str = "document"; /// The longest user name taken from `?author=` (the preferences' own limit). const MAX_AUTHOR_CHARS: usize = 256; #[derive(Clone)] pub struct Bridge { - window: web_sys::Window, - parent: web_sys::Window, - origin: String, - /// Files the parent sent (the name, if it sent one), waiting for the next frame. + host: Rc<Host>, + /// Files the host sent (the name, if it sent one), waiting for the next frame. opened: Rc<RefCell<Vec<(Option<String>, Vec<u8>)>>>, - /// The unsaved-changes state last reported to the parent. - reported: Rc<Cell<Option<bool>>>, } impl Bridge { - /// `None` when the page isn't framed (there is no parent to talk to), or when the parent is - /// on another origin: messages only go to this origin, so the browser would drop every save - /// without an error while the presentation showed as saved. - pub fn new() -> Option<Self> { - let window = web_sys::window()?; - let parent = window.parent().ok().flatten()?; - if js_sys::Object::is(&parent, &window) { - return None; - } - let origin = window.location().origin().ok()?; - // An opaque origin (a `file://` page in some browsers) can't be a `postMessage` target. - if origin == "null" { - return None; - } - // Reading another origin's location throws, which is `None` too. - if parent.location().origin().ok()? != origin { - return None; - } - Some(Self { window, parent, origin, opened: Rc::default(), reported: Rc::default() }) + /// The bridge for this page, or `None` when DeckCraft isn't hosted: no `?host=parent` and no + /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app + /// with downloads), or a parent on another origin. + pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> { + Some(Self { host: Rc::new(Host::connect(APP, canvas)?), opened: Rc::default() }) } - /// Hand saved and exported files to the parent instead of downloading them, and hear the - /// files it sends. + /// Hand saved and exported files to the host instead of downloading them, and hear the files + /// it sends. pub fn connect(&self, services: &mut Services, ctx: egui::Context) { self.listen(ctx); let bridge = self.clone(); @@ -97,15 +88,15 @@ impl Bridge { } pub fn post_ready(&self) { - self.send(&[("type", "deckcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]); + let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false); } - /// The app couldn't start (no WebGPU or WebGL2, for example): let the parent say so. + /// The app couldn't start (no WebGPU or WebGL2, for example): let the host say so. pub fn post_failed(&self, error: &str) { - self.send(&[("type", "deckcraft:failed".into()), ("error", error.into())]); + let _ = self.host.post_failed(error, None); } - /// Before each frame: open the files the parent sent. + /// Before each frame: open the files the host sent. pub fn open_files(&self, app: &mut SlideApp) { let opened = std::mem::take(&mut *self.opened.borrow_mut()); for (name, bytes) in opened { @@ -113,80 +104,30 @@ impl Bridge { } } - /// After each frame: tell the parent when unsaved changes appear or go away. + /// After each frame: tell the host when unsaved changes appear or go away (the crate does not + /// repeat a state it already reported). pub fn report_dirty(&self, app: &SlideApp) { - let dirty = app.session.documents().iter().any(|d| d.is_dirty()); - if self.reported.get() != Some(dirty) && self.send(&[("type", "deckcraft:dirty".into()), ("dirty", dirty.into())]) { - self.reported.set(Some(dirty)); - } + self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty())); } fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> { let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()); - let buffer = js_sys::Uint8Array::from(bytes).buffer(); - let message = message(&[ - ("type", "deckcraft:save".into()), - ("name", name.as_str().into()), - ("saveAs", save_as.into()), - ("bytes", buffer.clone().into()), - ]) - .ok_or_else(|| "couldn't build the message".to_string())?; - self.parent - .post_message_with_transfer(&message, &self.origin, &js_sys::Array::of1(&buffer)) - .map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}"))) + self.host.post_save(&name, bytes, None, save_as) } - /// Hear `deckcraft:open` from the parent and queue the file for the next frame. + /// Hear `deckcraft:open` and queue the file for the next frame. fn listen(&self, ctx: egui::Context) { - let parent = self.parent.clone(); - let origin = self.origin.clone(); let opened = self.opened.clone(); - let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| { - if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) { + self.host.listen(move |message| { + let Message::Open { name, data } = message else { return }; + let FileData::Bytes(array) = data else { + log::warn!("host file {name} came as a File; DeckCraft reads bytes only; not opened"); return; - } - let data = event.data(); - if string(&data, "type").as_deref() != Some("deckcraft:open") { - return; - } + }; // No name is no file: the presentation opens untitled, never under an invented name. - let name = string(&data, "name").filter(|n| !n.trim().is_empty()); - let Some(bytes) = bytes(&data) else { return }; - opened.borrow_mut().push((name, bytes)); + let name = (name != NAMELESS).then_some(name); + opened.borrow_mut().push((name, array.to_vec())); ctx.request_repaint(); }); - if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() { - // The listener lives as long as the page. - on_message.forget(); - } - } - - /// Post a message to the parent; false if it couldn't be sent. - fn send(&self, fields: &[(&str, JsValue)]) -> bool { - message(fields).is_some_and(|m| self.parent.post_message(&m, &self.origin).is_ok()) - } -} - -fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> { - let m = js_sys::Object::new(); - for (key, value) in fields { - js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?; - } - Some(m) -} - -fn string(data: &JsValue, key: &str) -> Option<String> { - js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string() -} - -/// `bytes` as an `ArrayBuffer` or `Uint8Array`. -fn bytes(data: &JsValue) -> Option<Vec<u8>> { - let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?; - if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() { - Some(array.to_vec()) - } else if bytes.is_instance_of::<js_sys::ArrayBuffer>() { - Some(js_sys::Uint8Array::new(&bytes).to_vec()) - } else { - None } } diff --git a/apps/deckcraft-web/src/web.rs b/apps/deckcraft-web/src/web.rs index 7720b605c..8930a66f4 100644 --- a/apps/deckcraft-web/src/web.rs +++ b/apps/deckcraft-web/src/web.rs @@ -24,11 +24,13 @@ pub fn start() { log::error!("missing <canvas id=\"{CANVAS_ID}\">"); return; }; - // `?host=parent`: a same-origin page framing DeckCraft opens presentations in it and - // stores what it saves (`host`). The presenter popup is never the framed page. - let host = query_param("host").as_deref() == Some("parent") && crate::presenter::token().is_none(); - let bridge = if host { crate::host::Bridge::new() } else { None }; - if host && bridge.is_none() { + // Host modes (`craft-web-host`): `?host=parent`, a same-origin page framing DeckCraft, + // opens presentations in it and stores what it saves (`host`); `data-host="page"` on the + // canvas opts a page in that runs DeckCraft in its own document. The presenter popup is + // never the framed page. + let hosted = crate::presenter::token().is_none(); + let bridge = if hosted { crate::host::Bridge::detect(&canvas) } else { None }; + if hosted && bridge.is_none() && query_param("host").as_deref() == Some("parent") { log::warn!("?host=parent needs a framing page on the same origin; saves download instead"); } let app_bridge = bridge.clone(); diff --git a/packaging/web/README.md b/packaging/web/README.md index 1e96279c0..19cdaedfa 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -86,7 +86,7 @@ Messages are plain objects with a `type`: | Message | Direction | Fields | |---|---|---| -| `deckcraft:ready` | to the page | `version`. The app runs and listens: send the file now. | +| `deckcraft:ready` | to the page | `version`, `appVersion`. The app runs and listens: send the file now. | | `deckcraft:open` | from the page | `name` (a bare file name, such as `Talk.pptx`), `bytes` (`ArrayBuffer` or `Uint8Array`). Opens like File › Open: a presentation (.pptx, .potx, .ppsx, .deckcraft) has that name as its file; an outline (.txt, .md, .rtf), a file sent without a name and a damaged file open untitled. | | `deckcraft:save` | to the page | `name`, `saveAs`, `bytes` (a transferred `ArrayBuffer`), for every file DeckCraft would otherwise download. The page stores it. | | `deckcraft:dirty` | to the page | `dirty`, whenever unsaved changes appear or go away. | @@ -134,6 +134,8 @@ beside it. The page guards leaving itself (DeckCraft adds no guard of its own), </script> ``` +The messages and both transports are the shared contract of [`craft-web-host`](https://github.com/storytold/craft-libs/tree/main/crates/web-host) (storytold/craft-libs#420), the same for every Craft app: its README lists every message, including `saved`, with the compatibility notes. In `deckcraft:ready`, `version` is the contract's (`"1"`) and `appVersion` is this app's release. DeckCraft reads bytes, so a host sends `bytes`, not a `File`. + ## Renderer selection and fallback flags DeckCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to From b225bb16a1bf180263218d5555f69e001f61913b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:49:17 +0000 Subject: [PATCH 62/94] Apply review fixes - apps/deckcraft-web/src/host.rs --- apps/deckcraft-web/src/host.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs index 5cf4b0399..b65d46537 100644 --- a/apps/deckcraft-web/src/host.rs +++ b/apps/deckcraft-web/src/host.rs @@ -46,6 +46,9 @@ const APP: &str = "deckcraft"; /// falls back to this): no name is no file, so the presentation opens untitled. const NAMELESS: &str = "document"; +/// The largest file a host may send, the limit File › Open has on the desktop (2 GiB): a bigger one is refused before it is copied. +const MAX_OPEN_BYTES: f64 = 2_147_483_648.0; + /// The longest user name taken from `?author=` (the preferences' own limit). const MAX_AUTHOR_CHARS: usize = 256; @@ -61,7 +64,12 @@ impl Bridge { /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app /// with downloads), or a parent on another origin. pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> { - Some(Self { host: Rc::new(Host::connect(APP, canvas)?), opened: Rc::default() }) + let host = Host::connect(APP, canvas)?; + // An opaque origin (a file:// page in some browsers) can't be a postMessage target. + if host.mode() == craft_web_host::Mode::Parent && web_sys::window()?.location().origin().ok()? == "null" { + return None; + } + Some(Self { host: Rc::new(host), opened: Rc::default() }) } /// Hand saved and exported files to the host instead of downloading them, and hear the files @@ -118,8 +126,14 @@ impl Bridge { /// Hear `deckcraft:open` and queue the file for the next frame. fn listen(&self, ctx: egui::Context) { let opened = self.opened.clone(); + let host = self.host.clone(); self.host.listen(move |message| { let Message::Open { name, data } = message else { return }; + if data.size() > MAX_OPEN_BYTES { + log::warn!("host file {name} is over 2 GiB; not opened"); + let _ = host.post_failed(&format!("{name} is larger than 2 GiB, the largest file DeckCraft opens"), None); + return; + } let FileData::Bytes(array) = data else { log::warn!("host file {name} came as a File; DeckCraft reads bytes only; not opened"); return; From 73de9900a7105340bec8505c14f322a9037990ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20M=C3=BCller?= <39926428+melandur@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:51:16 +0100 Subject: [PATCH 63/94] Show: Presenter View only with a second display (#1156) * Show: Presenter View only with a second display With one display the presenter window opened on the same screen as the show. Under Hyprland's focus-follows-mouse, whichever window the pointer was over took full screen, and the hidden one stalled every frame: the show lagged, dropped key presses or froze. One display now shows only the slides, as in PowerPoint. The host counts displays through winit's monitor list when a show starts; hosts that can't tell keep Presenter View. * Show: count displays by MonitorHandle Wayland lists one output twice under the same wl_output id, so comparing handles counts it once, and two separate displays with the same name and geometry still count as two. * Show: docs for Presenter View with a second display slideshow-parity and hardware-parity note that on Linux one display shows only the slides, with status lines and revision history; ROADMAP progress log. display_count collects into a BTreeSet (MonitorHandle's Ord matches its Eq). * Show: docs state the one-display rule exactly Presenter View stays off when winit lists exactly one display; if it lists none, the setting is kept. The host callback covers Unix other than macOS, so the docs say Linux and the BSDs. * Apply review fixes - docs/slideshow-parity.md --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- ROADMAP.md | 1 + apps/deckcraft/src/main.rs | 13 +++++++++++++ crates/ui-egui/src/app/playback.rs | 11 ++++++++++- crates/ui-egui/src/presenter_tests.rs | 17 +++++++++++++++++ crates/ui-egui/src/services.rs | 2 ++ docs/hardware-parity.md | 5 +++-- docs/slideshow-parity.md | 5 +++-- 7 files changed, 49 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 2227e6602..edd316276 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -156,6 +156,7 @@ app's JSON control channel (`deckcraft --control PORT`). |---|---| | 2026-11-04 | Ogg Opus recovery keeps trailing packets without granules in the total duration, matching their recovered positions; valid end trimming stays covered | | 2026-11-03 | Web: the `?host=parent` bridge (as in GridCraft, WordCraft and PdfCraft) lets a same-origin page that frames DeckCraft send a presentation and store its saves; Save writes an opened .pptx back as .pptx under its own name, as on the desktop | +| 2026-11-02 | Slide show on Linux and the BSDs: Presenter View stays off when winit lists exactly one display, as in PowerPoint; if it lists none, the setting is kept. On one display the presenter window covered the show, and the hidden window stalled every frame: slide changes took up to ~1.7 s under Hyprland (#1156) | | 2026-11-02 | Native and PPTX saves retain optional table right-to-left direction, including explicit false and omission; two-save round-trip tests keep labeled columns in order | | 2026-11-02 | Text runs preserve alternate-language metadata independently from the main language through native and PPTX saves | | 2026-11-02 | Picture compression measures displayed dimensions through nested group transforms; checklist score unchanged | diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index 2798c2d71..3f872c214 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -143,6 +143,14 @@ fn services(native_wayland: bool) -> Services { } } +/// Displays winit lists for `window`, counting an output Wayland lists twice once. `None` when it +/// lists none: Presenter View then stays as it was. +#[cfg(all(unix, not(target_os = "macos")))] +fn display_count(window: &winit::window::Window) -> Option<usize> { + let n = window.available_monitors().collect::<std::collections::BTreeSet<_>>().len(); + (n > 0).then_some(n) +} + const APP_ID: &str = "ai.storyteller.deckcraft"; const USAGE: &str = "\ @@ -280,6 +288,11 @@ fn main() -> eframe::Result { Box::new(move |cc| { deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx); let mut app = SlideApp::new(Session::new(), services(native_wayland)); + // Presenter View asks winit how many displays there are when a show starts. + #[cfg(all(unix, not(target_os = "macos")))] + if let Some(window) = cc.winit_window().cloned() { + app.services.displays = Some(Box::new(move || display_count(&window))); + } load_prefs(&mut app); app.enable_update_checks(); // AutoRecover: reopen what a previous run left unsaved, then keep it current. diff --git a/crates/ui-egui/src/app/playback.rs b/crates/ui-egui/src/app/playback.rs index c959829cd..c46286807 100644 --- a/crates/ui-egui/src/app/playback.rs +++ b/crates/ui-egui/src/app/playback.rs @@ -32,15 +32,24 @@ impl SlideApp { pub fn start_show(&mut self, from: usize, reading: bool) { self.anim_preview = None; self.media.stop_owned(media::Owner::Editor); + let presenter = self.ui.presenter_view && !reading && self.second_display(); if let Some(d) = self.session.active() { self.show_instance = self.show_instance.wrapping_add(1).max(1); - let mut show = show::Show::new(&d.doc, from, reading, self.ui.presenter_view && !reading); + let mut show = show::Show::new(&d.doc, from, reading, presenter); show.instance = self.show_instance; show.keep_cursor = self.ui.show_keep_cursor; self.show = Some(show); } } + /// Whether a second display can take Presenter View. Like PowerPoint, one display shows only + /// the slides: the presenter window would open on the same screen, and whichever of the two + /// windows ends up behind the other stalls the show (the compositor stops pacing a hidden + /// window). Hosts that can't count displays keep Presenter View. + fn second_display(&mut self) -> bool { + self.services.displays.as_mut().and_then(|f| f()).is_none_or(|n| n >= 2) + } + /// Play custom show `name` from its first slide. Set Up Slide Show is left as it was. pub fn start_custom_show(&mut self, name: &str, reading: bool) { let state = self.session.active().and_then(|d| deckcraft_anim::ShowState::play_custom(&d.doc, name)); diff --git a/crates/ui-egui/src/presenter_tests.rs b/crates/ui-egui/src/presenter_tests.rs index c422ad183..6dbc9a9d5 100644 --- a/crates/ui-egui/src/presenter_tests.rs +++ b/crates/ui-egui/src/presenter_tests.rs @@ -16,3 +16,20 @@ fn show_presenter_answers_on_and_window() { let doc = crate::UI_COMMANDS.iter().find(|c| c.0 == "show.presenter").unwrap().3; assert!(doc.contains("separate window"), "{doc}"); } + +#[test] +fn presenter_view_needs_a_second_display() { + // One display: the presenter window covered the show (or the show covered it) and the + // hidden window stalled every frame. + let presenter = |displays: Option<usize>, setting: bool| { + let services = Services { displays: Some(Box::new(move || displays)), ..Default::default() }; + let mut app = SlideApp::new(Session::with_new(), services); + app.ui.presenter_view = setting; + app.start_show(0, false); + app.show.as_ref().map(|s| s.presenter) + }; + assert_eq!(presenter(Some(1), true), Some(false)); + assert_eq!(presenter(Some(2), true), Some(true)); + assert_eq!(presenter(None, true), Some(true), "a host that can't count displays keeps Presenter View"); + assert_eq!(presenter(Some(2), false), Some(false), "the setting still turns it off"); +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index b6f8a0f50..0ca335a84 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -71,4 +71,6 @@ pub struct Services { pub clipboard_set_html: Option<Box<dyn FnMut(&str, &str) -> bool>>, /// Audio output for media playback (cpal on desktop); without one media plays silently. pub audio_out: Option<Box<dyn deckcraft_media::AudioOut>>, + /// How many displays are connected, when the host can tell: Presenter View needs a second. + pub displays: Option<Box<dyn FnMut() -> Option<usize>>>, } diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index a0b94ac0c..485cf0866 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity with PowerPoint -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-10-14 · **Change:** minor (community PR wave 2026-10-14: picture export DPI, Retina pixel grid (#184), twist to rotate, swipe to turn the page, pen pressure; duplicated rows and headers folded; previous: minor, IME input, #101) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365); PowerPoint for Windows where noted +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** minor (Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, community PR wave 2026-10-14: picture export DPI, Retina pixel grid (#184), twist to rotate, swipe to turn the page, pen pressure; duplicated rows and headers folded; previous: minor, IME input, #101) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365); PowerPoint for Windows where noted What hardware PowerPoint uses and what DeckCraft uses, per platform. Dimension score: **~40% ready** (estimated), **25–45 h** to parity. Performance (unmeasured, ~55%) is tracked here too @@ -34,7 +34,7 @@ because it mostly follows from hardware use. | Feature | PowerPoint | DeckCraft | |---|---|---| -| Detect the projector, show on it, presenter view on the laptop | yes | **no**: the show goes full screen on the current display; presenter view opens as a normal window (egui viewport) | +| Detect the projector, show on it, presenter view on the laptop | yes | **no**: the show goes full screen on the current display; presenter view opens as a normal window (egui viewport). On Linux and the BSDs, when winit lists exactly one display, the show opens without Presenter View, as in PowerPoint; if it lists none, the setting is kept (#1156) | | Swap displays, choose the monitor in Set Up Show | yes | no | | Mirroring-aware behaviour | yes | no | @@ -73,6 +73,7 @@ alignment runs once per transition (#67), and the decoders run in software. | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | On Linux and the BSDs, Presenter View stays off when winit lists exactly one display: the presenter window covered the show and stalled it. If winit lists none, the setting is kept (#1156) | | 2026-10-14 | minor | PNG and JPEG slide export record 144 dpi at the default 2 pixels per point, so a Retina picture opens at the slide's size | | 2026-10-13 | trivial | Editor slide rasters sit on the physical pixel grid (#184) | | 2026-10-14 | trivial | Community PR wave folded: one row each for pinch/two-finger gestures and pen pressure | diff --git a/docs/slideshow-parity.md b/docs/slideshow-parity.md index 137960531..08fff1b5f 100644 --- a/docs/slideshow-parity.md +++ b/docs/slideshow-parity.md @@ -1,6 +1,6 @@ # Slide show and presenter view: parity with PowerPoint -> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** minor (deleting slides removes them from custom shows; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) +> **Last reviewed:** 2026-10-14 · **Last updated:** 2026-11-02 · **Change:** minor (deleting slides removes them from custom shows; previous: minor, Presenter View only with a second display on Linux and the BSDs, #1156; previous: minor, Set Up Slide Show ▸ Keep mouse cursor visible, #1445; previous: minor, Ctrl+wheel zooms the show around the pointer, #1286; previous: major, community PR wave 2026-10-14: interactive decks, laser pointer, See All Slides and zoom, go-to-slide number, custom show playback, presenter timer, clock, notes size and keyboard, Show Media Controls, swipe; breadth 68%; duplicated rows and headers folded; previous: major, created) · **Target:** Microsoft PowerPoint for Mac 16.113 (Microsoft 365) Presenting is the job PowerPoint is hired for. This doc covers the show window, presenter view, rehearsal and recording. Transition and animation playback are in @@ -41,7 +41,7 @@ ready** (estimated), **10–16 h** to parity. | Feature | PowerPoint | DeckCraft | Notes | |---|---|---|---| -| Separate presenter window with current slide, next slide, notes | yes | yes (an egui viewport, 1100×700); the notes keep their bullets, numbers, indents and bold/italic, as in the notes pane | | +| Separate presenter window with current slide, next slide, notes | yes | yes (an egui viewport, 1100×700); the notes keep their bullets, numbers, indents and bold/italic, as in the notes pane | On Linux and the BSDs it stays off if winit lists exactly one display as the show starts, as in PowerPoint: on one display it covered the show, and the hidden window stalled every frame (#1156). If winit lists none, the setting is kept. There is not yet a way to switch to Presenter View by hand during a one-display show. macOS, Windows and the browser are unchanged | | Elapsed timer | yes | yes | | | Pause / reset timer, clock | yes | yes: Pause/Resume and Reset in presenter view (T pauses, R resets); the clock is local time, `--:--` where there is no clock | Pausing the timer does not pause the show, animations or rehearsal | | Slide counter, previous/next/end buttons | yes | yes | | @@ -79,6 +79,7 @@ Reading View in a window with navigation: present (checklist row done). | Date | Change | Summary | |---|---|---| +| 2026-11-02 | minor | On Linux and the BSDs, Presenter View stays off when winit lists exactly one display; if it lists none, the setting is kept (#1156) | | 2026-10-27 | minor | Set Up Slide Show ▸ Keep mouse cursor visible: full-screen shows keep a still pointer, so clickable choices stay targetable; Reading View unchanged (#1445) | | 2026-10-22 | minor | See All Slides from presenter view opens in presenter view, not on the audience screen (#1130) | | 2026-10-14 | trivial | Community PR wave folded: one media playback row, the presenter pen/laser row matches the laser that exists, estimates keep only the open work (~9–16 h); checklist breadth 68% | From bfdcc5cdfa927c157f7c06ad688582ddce776f7d Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:55:08 +0000 Subject: [PATCH 64/94] Apply review fixes - packaging/web/README.md - apps/deckcraft-web/src/host.rs --- apps/deckcraft-web/src/host.rs | 2 +- packaging/web/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs index b65d46537..616b66094 100644 --- a/apps/deckcraft-web/src/host.rs +++ b/apps/deckcraft-web/src/host.rs @@ -27,7 +27,7 @@ //! - Export (PDF, pictures, outline, GIF, handouts, a Save As type that isn't a presentation) //! and Print: `false`. They are copies; the presentation's file stays the same. //! - `deckcraft:dirty` whenever unsaved changes appear or go away, `deckcraft:failed` when the -//! app couldn't start. +//! app couldn't start or refused a file over 2 GiB. //! //! In host mode the app starts with an empty presentation instead of the sample, which gives way to //! the first file the host sends; the host guards leaving the page, and `?author=` names the user diff --git a/packaging/web/README.md b/packaging/web/README.md index 19cdaedfa..05b81fb0d 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -90,7 +90,7 @@ Messages are plain objects with a `type`: | `deckcraft:open` | from the page | `name` (a bare file name, such as `Talk.pptx`), `bytes` (`ArrayBuffer` or `Uint8Array`). Opens like File › Open: a presentation (.pptx, .potx, .ppsx, .deckcraft) has that name as its file; an outline (.txt, .md, .rtf), a file sent without a name and a damaged file open untitled. | | `deckcraft:save` | to the page | `name`, `saveAs`, `bytes` (a transferred `ArrayBuffer`), for every file DeckCraft would otherwise download. The page stores it. | | `deckcraft:dirty` | to the page | `dirty`, whenever unsaved changes appear or go away. | -| `deckcraft:failed` | to the page | `error`, when the app couldn't start (no WebGPU or WebGL2). | +| `deckcraft:failed` | to the page | `error`, when the app couldn't start (no WebGPU or WebGL2) or refused a file over 2 GiB. | `saveAs` says whether the file becomes the presentation's file, as on the desktop: From a2c1633fe37da3ee36f223aac36bbb553cb4ba9c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:59:10 +0100 Subject: [PATCH 65/94] fix(web): refuse a host file of exactly 2 GiB wasm32 cannot allocate a Vec of 2 GiB (isize::MAX is one byte less), so the open check that only rejected a larger file trapped on that boundary. Refuse 2 GiB as well, and say so in the failure the host receives. Co-authored-by: Cursor <cursoragent@cursor.com> --- apps/deckcraft-web/src/host.rs | 12 +++++++----- packaging/web/README.md | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/apps/deckcraft-web/src/host.rs b/apps/deckcraft-web/src/host.rs index 616b66094..d264b13c8 100644 --- a/apps/deckcraft-web/src/host.rs +++ b/apps/deckcraft-web/src/host.rs @@ -27,7 +27,7 @@ //! - Export (PDF, pictures, outline, GIF, handouts, a Save As type that isn't a presentation) //! and Print: `false`. They are copies; the presentation's file stays the same. //! - `deckcraft:dirty` whenever unsaved changes appear or go away, `deckcraft:failed` when the -//! app couldn't start or refused a file over 2 GiB. +//! app couldn't start or refused a file of 2 GiB or larger. //! //! In host mode the app starts with an empty presentation instead of the sample, which gives way to //! the first file the host sends; the host guards leaving the page, and `?author=` names the user @@ -46,7 +46,9 @@ const APP: &str = "deckcraft"; /// falls back to this): no name is no file, so the presentation opens untitled. const NAMELESS: &str = "document"; -/// The largest file a host may send, the limit File › Open has on the desktop (2 GiB): a bigger one is refused before it is copied. +/// The largest file a host may send. File › Open on the desktop refuses anything over 2 GiB. +/// On wasm32 a `Vec` cannot hold 2 GiB (`isize::MAX` is one byte less), so a file of exactly +/// 2 GiB is refused too, before its bytes are copied. const MAX_OPEN_BYTES: f64 = 2_147_483_648.0; /// The longest user name taken from `?author=` (the preferences' own limit). @@ -129,9 +131,9 @@ impl Bridge { let host = self.host.clone(); self.host.listen(move |message| { let Message::Open { name, data } = message else { return }; - if data.size() > MAX_OPEN_BYTES { - log::warn!("host file {name} is over 2 GiB; not opened"); - let _ = host.post_failed(&format!("{name} is larger than 2 GiB, the largest file DeckCraft opens"), None); + if data.size() >= MAX_OPEN_BYTES { + log::warn!("host file {name} is 2 GiB or larger; not opened"); + let _ = host.post_failed(&format!("{name} is 2 GiB or larger, which DeckCraft's web build cannot open"), None); return; } let FileData::Bytes(array) = data else { diff --git a/packaging/web/README.md b/packaging/web/README.md index 05b81fb0d..7a726f3a2 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -90,7 +90,7 @@ Messages are plain objects with a `type`: | `deckcraft:open` | from the page | `name` (a bare file name, such as `Talk.pptx`), `bytes` (`ArrayBuffer` or `Uint8Array`). Opens like File › Open: a presentation (.pptx, .potx, .ppsx, .deckcraft) has that name as its file; an outline (.txt, .md, .rtf), a file sent without a name and a damaged file open untitled. | | `deckcraft:save` | to the page | `name`, `saveAs`, `bytes` (a transferred `ArrayBuffer`), for every file DeckCraft would otherwise download. The page stores it. | | `deckcraft:dirty` | to the page | `dirty`, whenever unsaved changes appear or go away. | -| `deckcraft:failed` | to the page | `error`, when the app couldn't start (no WebGPU or WebGL2) or refused a file over 2 GiB. | +| `deckcraft:failed` | to the page | `error`, when the app couldn't start (no WebGPU or WebGL2) or refused a file of 2 GiB or larger. | `saveAs` says whether the file becomes the presentation's file, as on the desktop: From 9a95c3a63942377b1a4c8d79844a94a54ffac370 Mon Sep 17 00:00:00 2001 From: Luis <43929895+Luis-0508@users.noreply.github.com> Date: Thu, 5 Nov 2026 17:23:44 +0100 Subject: [PATCH 66/94] Release: refresh contributor credits for each release (#1889) (#1890) About > Contributors still showed the snapshot taken for v0.4.0, because nothing regenerated contributors/contributors.json before a release. Opt in to the shared refresh from craft-common-actions: a read-only credits job regenerates the snapshot for the release commit, and the shared release workflow installs it before every source build. The snapshot is not committed back. --- .github/workflows/release.yml | 8 ++++++++ docs/contributors.md | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b156fa50d..6ec9077e0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,7 +19,14 @@ concurrency: cancel-in-progress: false jobs: + # Regenerates contributors/contributors.json for the release commit; every build bundles it. + credits: + permissions: + contents: read + pull-requests: read + uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main release: + needs: credits # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: @@ -30,6 +37,7 @@ jobs: # manifest fails the release instead of silently skipping it. craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69 version: ${{ inputs.version }} + contributors-artifact: ${{ needs.credits.outputs.artifact-name }} secrets: APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} diff --git a/docs/contributors.md b/docs/contributors.md index 14efee2b7..4630d2da5 100644 --- a/docs/contributors.md +++ b/docs/contributors.md @@ -8,7 +8,8 @@ the AI models named in `Co-Authored-By` trailers. - Two files, both **compiled into the binary** by the UI crate's `build.rs` (nothing is read from disk or the network at run time; the web build has them too): - [`contributors/contributors.json`](../contributors/contributors.json): commit stats per GitHub - username. Never hand-edit. + username. Never hand-edit. Release builds regenerate it for the release commit + (`.github/workflows/release.yml`, `credits` job); the copy in the repository is not updated. - [`contributors/people.toml`](../contributors/people.toml): the names people chose for themselves. **Each contributor adds only their own entry**, in their own PR. - Each contributor gets one line: GitHub username (always), display name (opt-in, or their synced From d7343553b39e620e68974b80cbb4d8203b4ac281 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:01 +0100 Subject: [PATCH 67/94] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 ++++++++++++++ AGENTS.md | 63 ++++++++++++++++++++++++++++--- CLAUDE.md | 26 +------------ 3 files changed, 86 insertions(+), 31 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 000000000..de64ad3ee --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 1cacd993b..ef30c8bf7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ +<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb --> +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. +<!-- craft-house-rules:end --> +<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 --> +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. +<!-- craft-house-rules:end --> + # AGENTS.md — rules for every agent and contributor DeckCraft is a clean-room, open-source, pure-Rust presentation application targeting Microsoft @@ -125,14 +178,14 @@ People trust DeckCraft with their talks; a crash loses work. **This outranks fea CLI, control channel and MCP do exactly the same thing. - **The UI is thin**: panels read engine state and act through commands. Colours come from theme tokens. **Never use Tauri**; egui only. -- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic). - **Never break wasm** (`cargo xtask wasm`). ## 5. Quality gates (before every commit) `cargo xtask ci` = fmt check, clippy `-D warnings`, tests (nextest when installed) and doctests, layering check, asset check, wasm -check. Commit after each landed arc with a task id in the message (`M1.2: smart guides`) and push -to `main`. +check. Commit after each landed arc with a task id in the message (`M1.2: smart guides`). +New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots +declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. ## 6. Running and looking at the app @@ -147,13 +200,11 @@ to `main`. `deckcraft-cli run --sample --cmd 'slide.new={"title":"Hi"}' --export out.png`. - MCP: `deckcraft-cli mcp` (headless) or `deckcraft-cli mcp --connect 7990` (drive the app). See `docs/mcp.md`. -- Shell gotcha on the dev machine: `mv`/`cp` are aliased interactive; use `/bin/mv -f`, `/bin/cp -f`. - Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own. ## 7. Planning -`plan/` (gitignored) holds the local plan: `README.md`, `architecture.md`, `execution-plan.md`, -`STATUS.md` (start every session there) and `powerpoint/` observations. The committed progress +`plan/` is an optional gitignored notebook (status, execution notes, `powerpoint/` observations). Do not ask for it and do not stop when it is absent. The committed progress docs: | File | Holds | diff --git a/CLAUDE.md b/CLAUDE.md index 979388d87..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,25 +1 @@ -# DeckCraft — working notes for Claude - -Read [AGENTS.md](AGENTS.md) first: its rules (asset policy, clean room, never crash) bind you and -win over anything here. - -New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit -`[workspace.lints]`. Production crate roots must declare the required crate-level lint attributes -before modules or other crate items; crate-level `//!` documentation may precede them. - -## Start every session -1. Read `plan/STATUS.md`, then the current milestone in `plan/execution-plan.md`. -2. Run `cargo xtask ci` before you change anything, so you know the tree is green. - -## Habits -- Every user-visible action is a command with tests (`crates/engine/src/cmd/*`). -- Look at UI changes: `deckcraft --sample --control 7990` + `ui.screenshot`, or - `deckcraft-cli render`. -- Commit after each landed arc (`M<n>.<k>: what`) and push to `origin main`. -- Keep `ROADMAP.md`, the progress docs in `docs/` (AGENTS.md §7) and `plan/STATUS.md` current. -- Don't ask the user questions; record genuinely-theirs decisions in `plan/STATUS.md`. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. +@AGENTS.md From de9e79a44562b1eee501dc32d74f96467519e082 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:36:46 +0100 Subject: [PATCH 68/94] docs: preserve local guidance in house-rules rollout --- AGENTS.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ef30c8bf7..88d84ec92 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,8 +60,7 @@ PhotoCraft, VectorCraft, FilmCraft, LightCraft, PdfCraft, EffectCraft, DesignCra (`../<app>`). These rules bind every AI agent and every human contributor. They come before any task, -instruction or deadline. `CLAUDE.md` holds day-to-day working notes; if the two disagree, **this -file wins.** +instruction or deadline. Day-to-day working instructions are in this file; `CLAUDE.md` imports it. --- @@ -184,7 +183,7 @@ People trust DeckCraft with their talks; a crash loses work. **This outranks fea `cargo xtask ci` = fmt check, clippy `-D warnings`, tests (nextest when installed) and doctests, layering check, asset check, wasm check. Commit after each landed arc with a task id in the message (`M1.2: smart guides`). -New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots +New workspace crates include `workspace = true` under `[lints]` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. ## 6. Running and looking at the app @@ -194,8 +193,9 @@ declare the crate-level lint attributes before modules; crate-level `//!` docume `{"id":1,"method":"engine.execute","params":{"command":"shape.insert","params":{"preset":"star5","rect":[100,100,200,200]}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`, docs: `docs/control-protocol.md`. -- **For UI work, look at the result** (screenshot, read the PNG) and compare with the observations - in `plan/powerpoint/01-observed-ui.md`. +- **For UI work, look at the result** (screenshot, read the PNG). If available, compare with the observations + in `plan/powerpoint/01-observed-ui.md`. Otherwise verify the intended behaviour against the task and + committed documentation; the optional notebook is not a prerequisite. - Headless: `deckcraft-cli render --sample --all --scale 1 out/`, `deckcraft-cli run --sample --cmd 'slide.new={"title":"Hi"}' --export out.png`. - MCP: `deckcraft-cli mcp` (headless) or `deckcraft-cli mcp --connect 7990` (drive the app). From c7919102accca9e4106035502d1034b19a5db08f Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Fri, 6 Nov 2026 08:45:26 +0800 Subject: [PATCH 69/94] deckcraft-web: window.deckcraft, the page command API from craft-web-api The web shell queues the page's calls as control requests (the channel the desktop control server uses) and answers them on the next frame. The API is installed in every mode; opening, saving, the file name and the unsaved flag stay with the host messages. --- Cargo.lock | 14 ++- apps/deckcraft-web/Cargo.toml | 4 +- apps/deckcraft-web/src/api.rs | 151 +++++++++++++++++++++++++++++++++ apps/deckcraft-web/src/main.rs | 2 + apps/deckcraft-web/src/web.rs | 1 + packaging/web/README.md | 12 +++ 6 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 apps/deckcraft-web/src/api.rs diff --git a/Cargo.lock b/Cargo.lock index b4059e689..5ff27fdd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -935,10 +935,21 @@ dependencies = [ "zip 9.1.0", ] +[[package]] +name = "craft-web-api" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" +dependencies = [ + "js-sys", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", +] + [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6" +source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505" dependencies = [ "wasm-bindgen", "web-sys", @@ -1331,6 +1342,7 @@ dependencies = [ name = "deckcraft-web" version = "0.15.0" dependencies = [ + "craft-web-api", "craft-web-host", "deckcraft-engine", "deckcraft-ui-egui", diff --git a/apps/deckcraft-web/Cargo.toml b/apps/deckcraft-web/Cargo.toml index 58e8657a4..fc3c4f2af 100644 --- a/apps/deckcraft-web/Cargo.toml +++ b/apps/deckcraft-web/Cargo.toml @@ -17,7 +17,9 @@ path = "src/main.rs" deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" } +# The page command API (storytold/craft-libs#413): window.deckcraft over the control channel. +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/apps/deckcraft-web/src/api.rs b/apps/deckcraft-web/src/api.rs new file mode 100644 index 000000000..a343636a6 --- /dev/null +++ b/apps/deckcraft-web/src/api.rs @@ -0,0 +1,151 @@ +//! `window.deckcraft`: the page command API (`craft-web-api`, storytold/craft-libs#413) over the +//! app's own control channel, the one the desktop control server drives (`docs/control-protocol.md`). +//! +//! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, +//! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a [`Request`] that +//! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the +//! reply. A call the page gave up on is released ([`Pending`]), so the app drops it unrun instead of +//! applying a command the page was told had failed. + +use std::sync::Arc; +use std::sync::atomic::AtomicU8; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use deckcraft_ui_egui::ControlRequest; +use serde_json::{Value, json}; + +/// How often a waiting call looks for the app's reply, in milliseconds (about a frame). +#[cfg(target_arch = "wasm32")] +const POLL_MS: i32 = 16; + +/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's +/// timeout fired, or the call was abandoned) releases the request: the app skips it unrun. +struct Pending { + reply: Receiver<Value>, + state: Arc<AtomicU8>, + answered: bool, +} + +impl Pending { + /// `Some` once the app has answered or gone away; `None` while the request is still waiting. + fn poll(&mut self) -> Option<Value> { + match self.reply.try_recv() { + Ok(reply) => { + self.answered = true; + Some(reply) + } + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => { + self.answered = true; + Some(json!({"ok": false, "error": "the app dropped the request"})) + } + } + } +} + +impl Drop for Pending { + fn drop(&mut self) { + if !self.answered { + ControlRequest::abandon(&self.state); + } + } +} + +#[cfg(target_arch = "wasm32")] +pub use web::install; + +#[cfg(target_arch = "wasm32")] +mod web { + use std::rc::Rc; + use std::sync::mpsc::channel; + + use craft_web_api::methods::Methods; + use craft_web_api::page::{PageApi, Request}; + use deckcraft_ui_egui::{ControlRequest, SlideApp}; + use serde_json::json; + use wasm_bindgen_futures::JsFuture; + + use super::{POLL_MS, Pending}; + + /// The app id in `window.<app>`. + const APP: &str = "deckcraft"; + + /// Give the app its control queue and put `window.deckcraft` on the page. An existing + /// `window.deckcraft` keeps the functions it already has. + pub fn install(app: &mut SlideApp, ctx: egui::Context) { + let (queue, requests) = channel::<ControlRequest>(); + app.control_rx = Some(requests); + let request: Request = Rc::new(move |method, params| { + let (control, reply) = ControlRequest::new(method, params); + let mut pending = Pending { reply, state: control.state.clone(), answered: false }; + if queue.send(control).is_err() { + pending.answered = true; + return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) }); + } + ctx.request_repaint(); + Box::pin(async move { + loop { + if let Some(reply) = pending.poll() { + return reply; + } + sleep(POLL_MS).await; + } + }) + }); + if let Err(e) = Rc::new(PageApi::new(APP, Methods::default(), request)).install() { + log::warn!("couldn't install window.{APP}: {e:?}"); + } + } + + async fn sleep(ms: i32) { + let promise = js_sys::Promise::new(&mut |resolve, _| { + if let Some(window) = web_sys::window() { + let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); + } + }); + let _ = JsFuture::from(promise).await; + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::Ordering; + + use super::*; + + /// `ControlRequest`'s `state` values (`deckcraft_ui_egui::control`): the app has started it, or its + /// sender gave up. + const TAKEN: u8 = 1; + const ABANDONED: u8 = 2; + + fn pending() -> (Pending, ControlRequest) { + let (control, reply) = ControlRequest::new("document.inspect", json!({})); + (Pending { reply, state: control.state.clone(), answered: false }, control) + } + + #[test] + fn a_call_the_page_gave_up_on_is_released_so_the_app_skips_it() { + let (waiting, control) = pending(); + drop(waiting); + assert_eq!(control.state.load(Ordering::SeqCst), ABANDONED); + assert!(!control.take(), "the app must not run a request the page was told had failed"); + } + + #[test] + fn an_answered_call_is_not_released() { + let (mut waiting, control) = pending(); + assert!(control.take()); + control.reply.send(json!({"ok": true, "result": 1})).unwrap_or_default(); + assert_eq!(waiting.poll(), Some(json!({"ok": true, "result": 1}))); + drop(waiting); + assert_eq!(control.state.load(Ordering::SeqCst), TAKEN); + } + + #[test] + fn a_request_the_app_never_runs_waits_until_it_is_dropped() { + let (mut waiting, control) = pending(); + assert_eq!(waiting.poll(), None); + drop(control); + assert_eq!(waiting.poll().and_then(|r| r["ok"].as_bool()), Some(false), "the app went away"); + } +} diff --git a/apps/deckcraft-web/src/main.rs b/apps/deckcraft-web/src/main.rs index 8fe335eb8..6964162df 100644 --- a/apps/deckcraft-web/src/main.rs +++ b/apps/deckcraft-web/src/main.rs @@ -21,6 +21,8 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +#[cfg(any(target_arch = "wasm32", test))] +mod api; #[cfg(target_arch = "wasm32")] mod host; #[cfg(target_arch = "wasm32")] diff --git a/apps/deckcraft-web/src/web.rs b/apps/deckcraft-web/src/web.rs index 8930a66f4..1a6c45683 100644 --- a/apps/deckcraft-web/src/web.rs +++ b/apps/deckcraft-web/src/web.rs @@ -79,6 +79,7 @@ pub fn start() { { crate::host::Bridge::set_author(&mut app, &author); } + crate::api::install(&mut app, cc.egui_ctx.clone()); Ok(Box::new(WebShell { app, inbox, bridge: app_bridge })) }), ) diff --git a/packaging/web/README.md b/packaging/web/README.md index 7a726f3a2..7d1e6d6a0 100644 --- a/packaging/web/README.md +++ b/packaging/web/README.md @@ -136,6 +136,18 @@ beside it. The page guards leaving itself (DeckCraft adds no guard of its own), The messages and both transports are the shared contract of [`craft-web-host`](https://github.com/storytold/craft-libs/tree/main/crates/web-host) (storytold/craft-libs#420), the same for every Craft app: its README lists every message, including `saved`, with the compatibility notes. In `deckcraft:ready`, `version` is the contract's (`"1"`) and `appVersion` is this app's release. DeckCraft reads bytes, so a host sends `bytes`, not a `File`. +### Driving it from the page (`window.deckcraft`) + +Every DeckCraft web build puts `window.deckcraft` on the page, from [`craft-web-api`](https://github.com/storytold/craft-libs/tree/main/crates/web-api) (storytold/craft-libs#413), the same shape in every Craft app. `deckcraft.request(method, params)` calls any method of the control channel the desktop app serves (`docs/control-protocol.md`), and `execute(command, params)`, `commands()`, `docInspect(params)`, `uiInspect(params)` and `screenshot(params)` are shortcuts for the common ones. Each returns a Promise that resolves with the method's result and rejects with an `Error`; a call the app does not answer within 30 seconds rejects. + +```js +const deck = await deckcraft.docInspect(); // a summary of the open presentation +await deckcraft.execute("shape.insert", { preset: "roundRect", rect: [100, 100, 240, 120], text: "Hello" }); +const { data } = await deckcraft.screenshot(); // the canvas as PNG (base64) +``` + +The API is there in every mode, with or without a host. Opening a file, handing a saved or exported file to the page, the file name and the unsaved flag stay with the host messages above. + ## Renderer selection and fallback flags DeckCraft renders with wgpu. It uses **WebGPU** when the browser has it and falls back to From 4b1e50a6b0faae3962acb483fdb032e546d1f236 Mon Sep 17 00:00:00 2001 From: Helen Kwok <107752876+helenkwok@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:28:04 +0800 Subject: [PATCH 70/94] deckcraft-web: put each Cargo.toml comment above its own dependency, and say a call the app already took still finishes after a timeout --- apps/deckcraft-web/Cargo.toml | 2 +- apps/deckcraft-web/src/api.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/deckcraft-web/Cargo.toml b/apps/deckcraft-web/Cargo.toml index fc3c4f2af..da9dc7d8e 100644 --- a/apps/deckcraft-web/Cargo.toml +++ b/apps/deckcraft-web/Cargo.toml @@ -16,9 +16,9 @@ path = "src/main.rs" [dependencies] deckcraft-engine = { workspace = true } deckcraft-ui-egui = { workspace = true } -# The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.deckcraft over the control channel. craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } +# The host messages (storytold/craft-libs): one contract and one bridge for the web builds. craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } diff --git a/apps/deckcraft-web/src/api.rs b/apps/deckcraft-web/src/api.rs index a343636a6..5a74db92d 100644 --- a/apps/deckcraft-web/src/api.rs +++ b/apps/deckcraft-web/src/api.rs @@ -4,7 +4,7 @@ //! The crate owns the JavaScript side (`request`, `execute`, `commands`, `docInspect`, `uiInspect`, //! `screenshot`, as promises with a timeout). This module is DeckCraft's part: a [`Request`] that //! queues a [`ControlRequest`] for the app, which answers it on its next frame, and waits for the -//! reply. A call the page gave up on is released ([`Pending`]), so the app drops it unrun instead of +//! reply. A call the page gave up on is released ([`Pending`]), so the app skips it if it has not started it, instead of //! applying a command the page was told had failed. use std::sync::Arc; @@ -19,7 +19,7 @@ use serde_json::{Value, json}; const POLL_MS: i32 = 16; /// A queued control request whose reply has not arrived. Dropping it before the reply (the page's -/// timeout fired, or the call was abandoned) releases the request: the app skips it unrun. +/// timeout fired, or the call was abandoned) releases the request: the app skips it if it has not started it (one it has taken still finishes). struct Pending { reply: Receiver<Value>, state: Arc<AtomicU8>, From a883d6b2d95e48731b93aaa9d211f6a875493fc4 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:14:47 +0000 Subject: [PATCH 71/94] Reject invalid index in shape.adjust and shape.quickStyle Found while testing crates/engine/src/cmd/shape/appearance.rs:8 (adjust, index via usize_param); same pattern in quick_style at :559 Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/shape.rs | 2 +- crates/engine/src/cmd/shape/appearance.rs | 6 +++--- crates/engine/src/tests.rs | 15 +++++++++++++++ 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/shape.rs b/crates/engine/src/cmd/shape.rs index a447a20b9..78b6204bb 100644 --- a/crates/engine/src/cmd/shape.rs +++ b/crates/engine/src/cmd/shape.rs @@ -10,7 +10,7 @@ use serde_json::{Value, json}; use super::{ CommandSpec, NO_ID_SPACE, bad, bool_or, bool_param, cmd, color_param, color_value, edit_geometry, edit_shapes, f64_param, has_selection, - has_slide, id_param, ok, str_param, targets, usize_param, with_param, xfrm_of, + has_slide, id_param, ok, opt_usize_param, str_param, targets, usize_param, with_param, xfrm_of, }; use crate::{Result, Session}; diff --git a/crates/engine/src/cmd/shape/appearance.rs b/crates/engine/src/cmd/shape/appearance.rs index c515d2b2c..4dd406ea3 100644 --- a/crates/engine/src/cmd/shape/appearance.rs +++ b/crates/engine/src/cmd/shape/appearance.rs @@ -1,11 +1,11 @@ use super::{ ColorRef, ColorTransform, Dash, Effects, Fill, Geom, Glow, Gradient, GradientShape, GradientStop, Line, LineEnd, PictureFill, PictureMode, Reflection, Result, Rgba, SchemeSlot, Session, Shadow, ShapeStyle, Value, apply_fill, bad, bool_or, color_param, color_value, edit_geometry, - edit_shapes, f64_param, inherited_fills, json, requested_fill, str_param, targets, usize_param, + edit_shapes, f64_param, inherited_fills, json, opt_usize_param, requested_fill, str_param, targets, }; pub(super) fn adjust(s: &mut Session, p: &Value) -> Result<Value> { - let i = usize_param(p, "index").unwrap_or(0).min(16); + let i = opt_usize_param(p, "index", "shape.adjust")?.unwrap_or(0).min(16); let v = f64_param(p, "value").ok_or_else(|| bad("shape.adjust", "missing `value`"))?; edit_geometry(s, p, "shape.adjust", |sh| { if let Geom::Preset { name, adj } = &mut sh.geom { @@ -556,7 +556,7 @@ pub fn quick_style_for(index: usize) -> (ShapeStyle, Option<Fill>, Option<Line>) } pub(super) fn quick_style(s: &mut Session, p: &Value) -> Result<Value> { - let i = usize_param(p, "index").unwrap_or(1).min(41); + let i = opt_usize_param(p, "index", "shape.quickStyle")?.unwrap_or(1).min(41); let (st, f, l) = quick_style_for(i); edit_shapes(s, p, "shape.quickStyle", |sh| { sh.style = Some(st.clone()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ca1f93d26..7d55a9b16 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7029,3 +7029,18 @@ fn outline_export_skips_footer_date_and_slide_number() { assert!(rtf.contains("Agenda") && rtf.contains("First point"), "{rtf:?}"); assert!(!rtf.contains("Company Confidential") && !rtf.contains("1 May 2026"), "{rtf:?}"); } + +#[test] +fn shape_adjust_and_quick_style_reject_invalid_index() { + let mut s = session(); + let r = s.execute("shape.insert", &json!({"preset": "roundRect", "rect": [100, 100, 200, 100]})).unwrap(); + let id = deckcraft_model::ShapeId(r["id"].as_u64().unwrap() as u32); + let before = s.doc().unwrap().shape(id).unwrap().clone(); + for bad in [json!(-1), json!(1.5)] { + assert!(s.execute("shape.adjust", &json!({"index": bad, "value": 0.4})).is_err(), "adjust accepted {bad}"); + assert!(s.execute("shape.quickStyle", &json!({"index": bad})).is_err(), "quickStyle accepted {bad}"); + } + assert_eq!(s.doc().unwrap().shape(id).unwrap().geom, before.geom); + assert_eq!(s.doc().unwrap().shape(id).unwrap().style, before.style); + s.execute("shape.adjust", &json!({"value": 0.4})).unwrap(); +} From 57780f9e617e65b680d23160cfa935c4bdd82749 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:00:33 +0000 Subject: [PATCH 72/94] Fix format.paragraph silently left-aligning known align names Found while testing crates/engine/src/cmd/format/paragraph.rs:123-129 Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/engine/src/cmd/format/paragraph.rs | 12 +++-------- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/format/paragraph.rs b/crates/engine/src/cmd/format/paragraph.rs index e4b02a4b9..64bb16487 100644 --- a/crates/engine/src/cmd/format/paragraph.rs +++ b/crates/engine/src/cmd/format/paragraph.rs @@ -120,13 +120,7 @@ pub(super) fn line_spacing(s: &mut Session, p: &Value) -> Result<Value> { } pub(super) fn paragraph(s: &mut Session, p: &Value) -> Result<Value> { - let a = str_param(p, "align").map(|a| match a { - "center" => Align::Center, - "right" => Align::Right, - "justify" => Align::Justify, - "distributed" => Align::Distributed, - _ => Align::Left, - }); + let a = str_param(p, "align").map(|a| parse_align("format.paragraph", a)).transpose()?; let ml = f64_param(p, "indentLeft"); let ind = f64_param(p, "indentFirst"); let sb = f64_param(p, "spaceBefore"); @@ -182,10 +176,10 @@ pub(super) fn clamp_pt(v: f64) -> f64 { fn parse_align(cmd: &str, s: &str) -> Result<Align> { Ok(match s { "left" | "l" => Align::Left, - "center" | "ctr" => Align::Center, + "center" | "centre" | "ctr" => Align::Center, "right" | "r" => Align::Right, "justify" | "just" => Align::Justify, - "justLow" => Align::JustLow, + "justLow" | "justifyLow" => Align::JustLow, "distributed" | "dist" => Align::Distributed, "thaiDist" => Align::ThaiDistributed, _ => return Err(bad(cmd, "`align` must be left, center, right, justify, justLow, distributed or thaiDist")), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7d55a9b16..5d2310328 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1713,6 +1713,31 @@ fn tab_moves_between_cells_skipping_merged_ones() { assert_eq!((cell(&s), table_of(&s, id).n_rows()), (Some((2, 0)), 3), "Tab in the last cell adds a row"); } +#[test] +fn format_paragraph_align_names_match_format_align() { + use deckcraft_model::text::Align; + let mut s = session(); + let title = s.doc().unwrap().current_slide().unwrap().shapes[0].id.0; + s.execute("text.edit", &json!({"id": title})).unwrap(); + let para = |s: &Session| s.doc().unwrap().current_slide().unwrap().shapes[0].text.as_ref().unwrap().paragraphs[0].props.align; + for (name, want) in [ + ("justLow", Align::JustLow), + ("justifyLow", Align::JustLow), + ("thaiDist", Align::ThaiDistributed), + ("ctr", Align::Center), + ("centre", Align::Center), + ("r", Align::Right), + ("just", Align::Justify), + ("dist", Align::Distributed), + ("distributed", Align::Distributed), + ("left", Align::Left), + ] { + s.execute("format.paragraph", &json!({"align": name})).unwrap(); + assert_eq!(para(&s), Some(want), "{name}"); + } + assert!(s.execute("format.paragraph", &json!({"align": "bogus"})).is_err()); +} + #[test] fn right_to_left_paragraphs() { let mut s = session(); From 25809faf1ad48305e8b3e401043213951847edb6 Mon Sep 17 00:00:00 2001 From: Nasim <40519831+Naseq@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:48:14 +0430 Subject: [PATCH 73/94] Accessibility: name ribbon drop-downs by purpose and expose the shown text as their value (#1956) (#1963) --- crates/ui-egui/src/ribbon/animations.rs | 2 +- crates/ui-egui/src/ribbon/home.rs | 4 ++-- crates/ui-egui/src/tests.rs | 25 +++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 25 ++++++++++++++++++------- 4 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/ribbon/animations.rs b/crates/ui-egui/src/ribbon/animations.rs index d43801603..daa71ea2e 100644 --- a/crates/ui-egui/src/ribbon/animations.rs +++ b/crates/ui-egui/src/ribbon/animations.rs @@ -164,7 +164,7 @@ pub(super) fn animations(app: &mut SlideApp, ui: &mut Ui) { deckcraft_model::AnimStart::WithPrevious => "With Previous", deckcraft_model::AnimStart::AfterPrevious => "After Previous", }); - dropdown(ui, "astart", s.unwrap_or(""), 112.0, cur.is_some(), |ui| { + dropdown(ui, "Start", s.unwrap_or(""), 112.0, cur.is_some(), |ui| { for (l, v) in [("On Click", "onClick"), ("With Previous", "withPrevious"), ("After Previous", "afterPrevious")] { if ui.button(l).clicked() { run(app, "animation.timing", json!({"start": v})); diff --git a/crates/ui-egui/src/ribbon/home.rs b/crates/ui-egui/src/ribbon/home.rs index 1c27dc983..267f161d3 100644 --- a/crates/ui-egui/src/ribbon/home.rs +++ b/crates/ui-egui/src/ribbon/home.rs @@ -171,7 +171,7 @@ fn font_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) { let size = st.get("size").and_then(Value::as_f64); let fams = font_families(app); let theme_fonts: Vec<String> = fams.iter().take(2).cloned().collect(); - dropdown(ui, "font", &font, 150.0, en, |ui| { + dropdown(ui, "Font", &font, 150.0, en, |ui| { for (k, f) in fams.iter().enumerate() { let label = if k == 0 && theme_fonts.len() == 2 { format!("{f} (Headings)") @@ -196,7 +196,7 @@ fn font_group(app: &mut SlideApp, ui: &mut Ui, st: &Value) { } }); let size_text = size.map(|s| widgets::fmt_num(s, "")).unwrap_or_default(); - dropdown(ui, "size", &size_text, 52.0, en, |ui| { + dropdown(ui, "Font size", &size_text, 52.0, en, |ui| { for s in deckcraft_engine::cmd::format::SIZES.iter().chain([72.0, 80.0, 88.0, 96.0].iter()) { if ui.button(widgets::fmt_num(*s, "")).clicked() { run(app, "format.size", json!({"size": s})); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index f8fe10aab..677e971c5 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1223,6 +1223,31 @@ fn step_app(services: Services) -> egui_kittest::Harness<'static, SlideApp> { h } +/// #1956: the ribbon's drop-downs are announced by their purpose, not by their value or an +/// internal key. Animations › Start with a shape that has no animation was "astart"; Home's Font +/// and Font size boxes were "font" and "size" while nothing told them a font or size. +#[test] +fn ribbon_dropdowns_are_named_by_purpose_even_when_empty() { + use egui::accesskit::Role; + let mut h = step_app(Services::default()); + // A fresh shape, selected but not edited and without an animation. + h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [100.0, 100.0, 200.0, 100.0]})).unwrap(); + h.state_mut().run("text.exit", json!({})).unwrap(); + h.state_mut().ui.tab = "Animations".into(); + h.run_steps(2); + let start = h.get_by_role_and_label(Role::ComboBox, "Start"); + assert_eq!(start.value(), None, "no animation, no start value"); + assert!(h.query_by_label("astart").is_none(), "the internal key is not a name"); + + h.state_mut().ui.tab = "Home".into(); + h.state_mut().run("edit.select", json!({"ids": []})).unwrap(); + h.run_steps(2); + for (name, key) in [("Font", "font"), ("Font size", "size")] { + assert!(h.query_by_role_and_label(Role::ComboBox, name).is_some(), "{name} is named while empty"); + assert!(h.query_by_role_and_label(Role::ComboBox, key).is_none(), "{key} is not announced"); + } +} + /// Copy of a bold selection offers HTML; paste of Pages-like HTML keeps the bold. #[test] fn copy_offers_html_and_paste_keeps_bold() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5bfbf041e..238259e5e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -330,7 +330,9 @@ pub fn rows<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { } /// A text dropdown field (font name, size): shows `current`, opens a popup with `add_items`. -pub fn dropdown(ui: &mut Ui, id: &str, current: &str, width: f32, enabled: bool, add_items: impl FnOnce(&mut Ui)) -> Response { +/// `label` is what assistive technology calls it ("Font", "Start"); `current` is exposed as its +/// value, so an empty box is still announced by its purpose and never by an internal key (#1956). +pub fn dropdown(ui: &mut Ui, label: &str, current: &str, width: f32, enabled: bool, add_items: impl FnOnce(&mut Ui)) -> Response { let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(width, 22.0), if enabled { Sense::click() } else { Sense::hover() }); let painter = ui.painter_at(rect); @@ -350,8 +352,10 @@ pub fn dropdown(ui: &mut Ui, id: &str, current: &str, width: f32, enabled: bool, if enabled { t.text } else { t.text_faint }, ); chevron(&painter, pos2(rect.max.x - 9.0, rect.center().y), 3.0, t.text_dim); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, if current.is_empty() { id } else { current })); - let _ = id; + resp.widget_info(|| egui::WidgetInfo { + current_text_value: (!current.is_empty()).then(|| current.to_string()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, label) + }); egui::Popup::menu(&resp).width(width.max(140.0)).show(|ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, add_items); }); @@ -742,19 +746,26 @@ mod tests { } /// The custom ribbon dropdown is a real combo box in the accessibility tree, named by its - /// current value (0.37's strict unnamed-input check would otherwise reject it). + /// purpose with the shown text as its value. An empty one (no selection to read a font or + /// size from) keeps its name rather than falling back to an internal key (#1956). #[test] - fn the_dropdown_has_a_combo_box_role_and_a_name() { + fn the_dropdown_is_named_by_its_purpose_and_carries_its_value() { let mut harness = egui_kittest::Harness::builder().with_size(vec2(400.0, 200.0)).build_ui(|ui| { theme::install_fonts(ui.ctx()); - dropdown(ui, "font-size", "18 pt", 120.0, true, |ui| { + dropdown(ui, "Font size", "18 pt", 120.0, true, |ui| { ui.label("12 pt"); ui.label("18 pt"); }); + dropdown(ui, "Start", "", 112.0, false, |_| {}); }); harness.run(); - let combo = harness.get_by_role_and_label(Role::ComboBox, "18 pt"); + let combo = harness.get_by_role_and_label(Role::ComboBox, "Font size"); + assert_eq!(combo.value().as_deref(), Some("18 pt")); assert!(combo.rect().width() > 100.0); + assert!(harness.query_by_role_and_label(Role::ComboBox, "18 pt").is_none(), "the value is not its name"); + let empty = harness.get_by_role_and_label(Role::ComboBox, "Start"); + assert_eq!(empty.value(), None, "nothing shown, no value"); + assert!(harness.query_by_label("astart").is_none() && harness.query_by_label("start").is_none(), "no internal key is announced"); } /// #32: clicking the "More Colors" hex field closed the colour menu before anything could be From aefd54d28e5b7a7c661e611f87b48379ff70a096 Mon Sep 17 00:00:00 2001 From: Neil Cawse <neilcawse@geotab.com> Date: Sat, 7 Nov 2026 18:14:24 +0000 Subject: [PATCH 74/94] pptx: preserve 3-D scene and extrusion XML on text bodies and groups --- crates/model/src/resolve.rs | 1 + crates/model/src/text.rs | 6 ++++++ crates/pptx/src/read/dml.rs | 8 +++++++- crates/pptx/src/read/shapes.rs | 4 ++++ crates/pptx/src/write/dml.rs | 6 +++++- crates/pptx/src/write/shapes.rs | 13 ++++++++++++- crates/pptx/tests/it/corpus_style.rs | 27 +++++++++++++++++++++++++++ 7 files changed, 62 insertions(+), 3 deletions(-) diff --git a/crates/model/src/resolve.rs b/crates/model/src/resolve.rs index 30a9d738a..cad10dd04 100644 --- a/crates/model/src/resolve.rs +++ b/crates/model/src/resolve.rs @@ -314,6 +314,7 @@ pub fn body(ctx: &Ctx, shape: &Shape) -> BodyProps { compat_ln_spc: None, vert_overflow: None, horz_overflow: None, + raw3d: None, }); b } diff --git a/crates/model/src/text.rs b/crates/model/src/text.rs index f8f1be062..be13cf14b 100644 --- a/crates/model/src/text.rs +++ b/crates/model/src/text.rs @@ -124,6 +124,9 @@ pub struct BodyProps { pub compat_ln_spc: Option<bool>, pub vert_overflow: Option<TextOverflow>, pub horz_overflow: Option<TextOverflow>, + /// Unmodelled 3-D XML on the text body (`a:scene3d`, `a:sp3d`, `a:flatTx`). + #[serde(skip_serializing_if = "Option::is_none")] + pub raw3d: Option<String>, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -187,6 +190,9 @@ impl BodyProps { self.compat_ln_spc = self.compat_ln_spc.or(p.compat_ln_spc); self.vert_overflow = self.vert_overflow.or(p.vert_overflow); self.horz_overflow = self.horz_overflow.or(p.horz_overflow); + if self.raw3d.is_none() { + self.raw3d.clone_from(&p.raw3d); + } } } diff --git a/crates/pptx/src/read/dml.rs b/crates/pptx/src/read/dml.rs index c8902e4c7..c4e8e3b38 100644 --- a/crates/pptx/src/read/dml.rs +++ b/crates/pptx/src/read/dml.rs @@ -629,7 +629,13 @@ pub fn list_style(imp: &mut Imp, part: &Part, ls: &El) -> ListStyle { } pub fn text_body(imp: &mut Imp, part: &Part, tx: &El) -> TextBody { - let body = tx.child("bodyPr").map(body_pr).unwrap_or_default(); + let mut body = tx.child("bodyPr").map(body_pr).unwrap_or_default(); + if let Some(b) = tx.child("bodyPr") { + let raw3d: String = b.elements().filter(|c| matches!(c.local(), "scene3d" | "sp3d" | "flatTx")).map(|c| part.keep_inner(c)).collect(); + if !raw3d.is_empty() { + body.raw3d = Some(raw3d); + } + } let list_style = tx.child("lstStyle").map(|l| list_style(imp, part, l)).unwrap_or_default(); let paragraphs = tx.children_named("p").take(100_000).map(|p| paragraph(imp, part, p)).collect(); TextBody { body, list_style, paragraphs } diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 3230db100..2710706a5 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -395,6 +395,10 @@ fn grp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Sha if let Some(fx) = pr.child("effectLst") { s.effects = Some(dml::effects(fx)); } + let raw: String = pr.elements().filter(|c| c.is("scene3d")).map(|c| part.keep_inner(c)).collect(); + if !raw.is_empty() { + s.effects.get_or_insert_with(Effects::default).raw3d = Some(raw); + } } let children = sp_tree(imp, part, ctx, e, depth + 1); let child = child.or_else(|| s.xfrm.map(|x| Xfrm::new(x.x, x.y, x.w, x.h))).unwrap_or_default(); diff --git a/crates/pptx/src/write/dml.rs b/crates/pptx/src/write/dml.rs index 8acc648d0..d58745ef3 100644 --- a/crates/pptx/src/write/dml.rs +++ b/crates/pptx/src/write/dml.rs @@ -481,7 +481,8 @@ pub fn body_pr(w: &mut W, b: &BodyProps) { .o("vertOverflow", b.vert_overflow.map(|v| v.xml())) .o("horzOverflow", deckcraft_model::text::TextOverflow::horz_xml(b.horz_overflow)); let warp = b.warp.as_deref().filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())); - if warp.is_none() && b.autofit.is_none() { + let raw3d = b.raw3d.as_deref().filter(|s| !s.is_empty()); + if warp.is_none() && b.autofit.is_none() && raw3d.is_none() { w.empty("a:bodyPr", a); return; } @@ -515,6 +516,9 @@ pub fn body_pr(w: &mut W, b: &BodyProps) { } None => {} } + if let Some(raw) = raw3d { + w.raw(raw); + } w.close("a:bodyPr"); } diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index 3a9ba82d3..0d0c4778a 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -334,7 +334,18 @@ pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth dml::fill(w, x, o, f); } if let Some(fx) = &s.effects { - dml::effects(w, fx); + if fx.fill_overlay.is_some() + || fx.glow.is_some() + || fx.inner_shadow.is_some() + || fx.outer_shadow.is_some() + || fx.reflection.is_some() + || fx.soft_edge.is_some() + { + dml::effects(w, fx); + } + if let Some(raw) = &fx.raw3d { + w.raw(raw); + } } w.close("p:grpSpPr"); shapes(w, x, o, cx, children, depth + 1); diff --git a/crates/pptx/tests/it/corpus_style.rs b/crates/pptx/tests/it/corpus_style.rs index 0a8cacb73..8b4126e44 100644 --- a/crates/pptx/tests/it/corpus_style.rs +++ b/crates/pptx/tests/it/corpus_style.rs @@ -239,6 +239,33 @@ fn theme_and_bevel_survive(once: &Presentation, twice: &Presentation) { let raw = bevel.raw3d.as_deref().unwrap_or(""); assert!(raw.contains("bevelT") && raw.contains("angle") && raw.contains("scene3d"), "{raw}"); assert_eq!(by_name(twice, "Bevel").effects.as_ref().and_then(|e| e.raw3d.as_deref()), Some(raw)); + + let text_3d = + "<a:scene3d><a:camera prst=\"orthographicFront\"/><a:lightRig rig=\"threePt\" dir=\"t\"/></a:scene3d><a:sp3d extrusionH=\"12700\"/>"; + let mut p3 = defaults::new_presentation(None); + let mut sh = shape(&mut p3, "Text3D", 10.0, 10.0, 100.0, 40.0); + sh.text = Some(TextBody { + body: BodyProps { raw3d: Some(text_3d.into()), ..Default::default() }, + paragraphs: vec![Paragraph::new("3D Text")], + ..Default::default() + }); + let grp_3d = "<a:scene3d><a:camera prst=\"isometricTopUp\"/><a:lightRig rig=\"threePt\" dir=\"t\"/></a:scene3d>"; + let mut grp = shape(&mut p3, "Group3D", 10.0, 60.0, 100.0, 40.0); + grp.effects = Some(Effects { raw3d: Some(grp_3d.into()), ..Default::default() }); + grp.kind = ShapeKind::Group { children: vec![sh], child: Xfrm::new(10.0, 10.0, 100.0, 40.0) }; + let layout = defaults::layout_of_kind(&p3, deckcraft_model::LayoutType::Blank).unwrap_or_default(); + let mut s3 = defaults::new_slide(&mut p3, layout).expect("slide"); + s3.shapes.push(grp); + p3.slides.push(Arc::new(s3)); + let r3 = round(&p3); + let r3_twice = round(&r3); + let g3 = by_name(&r3, "Group3D"); + let g3_raw = g3.effects.as_ref().and_then(|e| e.raw3d.as_deref()).unwrap_or(""); + let t3_raw = g3.children()[0].text.as_ref().and_then(|t| t.body.raw3d.as_deref()).unwrap_or(""); + assert!(g3_raw.contains("isometricTopUp"), "{g3_raw}"); + assert!(t3_raw.contains("orthographicFront") && t3_raw.contains("extrusionH=\"12700\""), "{t3_raw}"); + assert_eq!(by_name(&r3_twice, "Group3D").effects.as_ref().and_then(|e| e.raw3d.as_deref()), Some(g3_raw)); + assert_eq!(by_name(&r3_twice, "Group3D").children()[0].text.as_ref().and_then(|t| t.body.raw3d.as_deref()), Some(t3_raw)); } fn connector_glue_survives(p: &Presentation, once: &Presentation, twice: &Presentation) { From 424f575ca5529e2b378d07dfdfc3ca28c6135252 Mon Sep 17 00:00:00 2001 From: Neil Cawse <neilcawse@geotab.com> Date: Sun, 8 Nov 2026 05:26:33 +0000 Subject: [PATCH 75/94] fix(pptx): bound and validate body/group raw3d XML on read/write and expand 3-D tests --- crates/pptx/src/read/dml.rs | 10 +++++-- crates/pptx/src/read/shapes.rs | 8 +++--- crates/pptx/src/write/dml.rs | 17 +++++++++++- crates/pptx/src/write/shapes.rs | 2 +- crates/pptx/tests/it/corpus_style.rs | 40 +++++++++++++++++++++++++--- 5 files changed, 67 insertions(+), 10 deletions(-) diff --git a/crates/pptx/src/read/dml.rs b/crates/pptx/src/read/dml.rs index c4e8e3b38..eb05ea4fe 100644 --- a/crates/pptx/src/read/dml.rs +++ b/crates/pptx/src/read/dml.rs @@ -631,8 +631,14 @@ pub fn list_style(imp: &mut Imp, part: &Part, ls: &El) -> ListStyle { pub fn text_body(imp: &mut Imp, part: &Part, tx: &El) -> TextBody { let mut body = tx.child("bodyPr").map(body_pr).unwrap_or_default(); if let Some(b) = tx.child("bodyPr") { - let raw3d: String = b.elements().filter(|c| matches!(c.local(), "scene3d" | "sp3d" | "flatTx")).map(|c| part.keep_inner(c)).collect(); - if !raw3d.is_empty() { + let mut raw3d = String::new(); + if let Some(sc) = b.child("scene3d") { + raw3d.push_str(&part.keep_inner(sc)); + } + if let Some(sp) = b.child("sp3d").or_else(|| b.child("flatTx")) { + raw3d.push_str(&part.keep_inner(sp)); + } + if !raw3d.is_empty() && raw3d.len() <= 64 * 1024 { body.raw3d = Some(raw3d); } } diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 2710706a5..e1368b427 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -395,9 +395,11 @@ fn grp(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> Sha if let Some(fx) = pr.child("effectLst") { s.effects = Some(dml::effects(fx)); } - let raw: String = pr.elements().filter(|c| c.is("scene3d")).map(|c| part.keep_inner(c)).collect(); - if !raw.is_empty() { - s.effects.get_or_insert_with(Effects::default).raw3d = Some(raw); + if let Some(sc) = pr.child("scene3d") { + let raw = part.keep_inner(sc); + if !raw.is_empty() && raw.len() <= 64 * 1024 { + s.effects.get_or_insert_with(Effects::default).raw3d = Some(raw); + } } } let children = sp_tree(imp, part, ctx, e, depth + 1); diff --git a/crates/pptx/src/write/dml.rs b/crates/pptx/src/write/dml.rs index d58745ef3..d818c8e6b 100644 --- a/crates/pptx/src/write/dml.rs +++ b/crates/pptx/src/write/dml.rs @@ -461,6 +461,21 @@ fn sound_label(name: &str) -> String { if label.is_empty() { "sound.wav".into() } else { label } } +/// Validate an unmodelled 3-D fragment (`a:scene3d`, `a:sp3d`, `a:flatTx`) before writing raw XML. +pub fn valid_raw3d<'a>(raw: &'a str, allowed: &[&str]) -> Option<&'a str> { + if raw.is_empty() || raw.len() > 64 * 1024 { + return None; + } + let wrap = format!("<r xmlns:a=\"{}\">{raw}</r>", crate::opc::NS_A); + let doc = crate::xml::parse(wrap.as_bytes()).ok()?; + let els: Vec<_> = doc.root.elements().collect(); + (!els.is_empty() + && els.len() <= allowed.len() + && doc.root.children.len() == els.len() + && els.iter().all(|e| e.prefix() == "a" && allowed.contains(&e.local()) && !crate::read::has_rel_refs(e))) + .then_some(raw) +} + pub fn body_pr(w: &mut W, b: &BodyProps) { let a = A::new() .o("rot", b.rot.map(|r| (r * 60_000.0).round().clamp(-21_600_000.0, 21_600_000.0) as i64)) @@ -481,7 +496,7 @@ pub fn body_pr(w: &mut W, b: &BodyProps) { .o("vertOverflow", b.vert_overflow.map(|v| v.xml())) .o("horzOverflow", deckcraft_model::text::TextOverflow::horz_xml(b.horz_overflow)); let warp = b.warp.as_deref().filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())); - let raw3d = b.raw3d.as_deref().filter(|s| !s.is_empty()); + let raw3d = b.raw3d.as_deref().and_then(|s| valid_raw3d(s, &["scene3d", "sp3d", "flatTx"])); if warp.is_none() && b.autofit.is_none() && raw3d.is_none() { w.empty("a:bodyPr", a); return; diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index 0d0c4778a..2140211c7 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -343,7 +343,7 @@ pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth { dml::effects(w, fx); } - if let Some(raw) = &fx.raw3d { + if let Some(raw) = fx.raw3d.as_deref().and_then(|s| dml::valid_raw3d(s, &["scene3d"])) { w.raw(raw); } } diff --git a/crates/pptx/tests/it/corpus_style.rs b/crates/pptx/tests/it/corpus_style.rs index 8b4126e44..e64e2f5e6 100644 --- a/crates/pptx/tests/it/corpus_style.rs +++ b/crates/pptx/tests/it/corpus_style.rs @@ -239,9 +239,13 @@ fn theme_and_bevel_survive(once: &Presentation, twice: &Presentation) { let raw = bevel.raw3d.as_deref().unwrap_or(""); assert!(raw.contains("bevelT") && raw.contains("angle") && raw.contains("scene3d"), "{raw}"); assert_eq!(by_name(twice, "Bevel").effects.as_ref().and_then(|e| e.raw3d.as_deref()), Some(raw)); +} +#[test] +fn text_and_group_3d_survive() { let text_3d = "<a:scene3d><a:camera prst=\"orthographicFront\"/><a:lightRig rig=\"threePt\" dir=\"t\"/></a:scene3d><a:sp3d extrusionH=\"12700\"/>"; + let flat_tx = "<a:scene3d><a:camera prst=\"orthographicFront\"/><a:lightRig rig=\"threePt\" dir=\"t\"/></a:scene3d><a:flatTx z=\"0\"/>"; let mut p3 = defaults::new_presentation(None); let mut sh = shape(&mut p3, "Text3D", 10.0, 10.0, 100.0, 40.0); sh.text = Some(TextBody { @@ -249,23 +253,53 @@ fn theme_and_bevel_survive(once: &Presentation, twice: &Presentation) { paragraphs: vec![Paragraph::new("3D Text")], ..Default::default() }); + let mut sh_flat = shape(&mut p3, "FlatTx3D", 10.0, 55.0, 100.0, 40.0); + sh_flat.text = Some(TextBody { + body: BodyProps { raw3d: Some(flat_tx.into()), ..Default::default() }, + paragraphs: vec![Paragraph::new("Flat Text")], + ..Default::default() + }); let grp_3d = "<a:scene3d><a:camera prst=\"isometricTopUp\"/><a:lightRig rig=\"threePt\" dir=\"t\"/></a:scene3d>"; - let mut grp = shape(&mut p3, "Group3D", 10.0, 60.0, 100.0, 40.0); + let mut grp = shape(&mut p3, "Group3D", 10.0, 60.0, 100.0, 80.0); grp.effects = Some(Effects { raw3d: Some(grp_3d.into()), ..Default::default() }); - grp.kind = ShapeKind::Group { children: vec![sh], child: Xfrm::new(10.0, 10.0, 100.0, 40.0) }; + grp.kind = ShapeKind::Group { children: vec![sh, sh_flat], child: Xfrm::new(10.0, 10.0, 100.0, 80.0) }; let layout = defaults::layout_of_kind(&p3, deckcraft_model::LayoutType::Blank).unwrap_or_default(); let mut s3 = defaults::new_slide(&mut p3, layout).expect("slide"); s3.shapes.push(grp); p3.slides.push(Arc::new(s3)); - let r3 = round(&p3); + + let bytes = deckcraft_pptx::export(&p3).expect("export"); + let slide_xml = { + use std::io::Read; + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).expect("zip"); + let mut s = String::new(); + z.by_name("ppt/slides/slide2.xml").expect("slide2").read_to_string(&mut s).expect("utf8"); + s + }; + assert!(!slide_xml.contains("<a:effectLst/>"), "Group3D with only raw3d must not emit empty effectLst: {slide_xml}"); + assert!(slide_xml.contains("<a:flatTx z=\"0\"/>"), "{slide_xml}"); + + let r3 = deckcraft_pptx::import(&bytes).expect("import"); let r3_twice = round(&r3); let g3 = by_name(&r3, "Group3D"); let g3_raw = g3.effects.as_ref().and_then(|e| e.raw3d.as_deref()).unwrap_or(""); let t3_raw = g3.children()[0].text.as_ref().and_then(|t| t.body.raw3d.as_deref()).unwrap_or(""); + let flat_raw = g3.children()[1].text.as_ref().and_then(|t| t.body.raw3d.as_deref()).unwrap_or(""); assert!(g3_raw.contains("isometricTopUp"), "{g3_raw}"); assert!(t3_raw.contains("orthographicFront") && t3_raw.contains("extrusionH=\"12700\""), "{t3_raw}"); + assert!(flat_raw.contains("flatTx"), "{flat_raw}"); assert_eq!(by_name(&r3_twice, "Group3D").effects.as_ref().and_then(|e| e.raw3d.as_deref()), Some(g3_raw)); assert_eq!(by_name(&r3_twice, "Group3D").children()[0].text.as_ref().and_then(|t| t.body.raw3d.as_deref()), Some(t3_raw)); + assert_eq!(by_name(&r3_twice, "Group3D").children()[1].text.as_ref().and_then(|t| t.body.raw3d.as_deref()), Some(flat_raw)); + + // BodyProps::inherit propagates parent raw3d only when child raw3d is None. + let parent_body = BodyProps { raw3d: Some(text_3d.into()), ..Default::default() }; + let mut child_body = BodyProps::default(); + child_body.inherit(&parent_body); + assert_eq!(child_body.raw3d.as_deref(), Some(text_3d)); + let mut override_body = BodyProps { raw3d: Some(flat_tx.into()), ..Default::default() }; + override_body.inherit(&parent_body); + assert_eq!(override_body.raw3d.as_deref(), Some(flat_tx)); } fn connector_glue_survives(p: &Presentation, once: &Presentation, twice: &Presentation) { From 220b52dfdb1f7a8b9aa05031a72103fc1c54c7f7 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:43:41 +0000 Subject: [PATCH 76/94] Apply review fixes - docs/file-format-parity.md --- docs/file-format-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 20d4b4d8e..70b74f7e1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -84,7 +84,7 @@ the round trip even though DeckCraft doesn't model it. | Lines: dash, compound, caps, joins, arrowheads | yes | yes | | | Text: runs, paragraphs, bullets, numbering, levels, autofit, columns, vertical, RTL, script fonts, fields, hyperlinks | yes | yes | Run `lang` and `altLang` are independently retained through native and PPTX saves; other round-trip tests cover `justLow`, date fields and paragraph `defRPr` (the defaults a placeholder's runs inherit, including a link). A click or hover action keeps its sound, `endSnd`, and a custom show's "Show and return". Gradient and outline on a run, autofit, columns, vertical and RTL text, tab stops and line spacing round-trip (`corpus_style.rs`) | | Effects: shadow, glow, soft edges, reflection | yes | yes | On a run, inner shadow, reflection and soft edges are kept along with the outer shadow and glow | -| 3-D: `scene3d`, `sp3d` | kept | kept | A bevel preset with no `sp3d` of its own is written back on shapes and theme effect styles. Bevels, cameras, face lighting and extrusion sides draw approximately | +| 3-D: `scene3d`, `sp3d` | kept | kept | A bevel preset with no `sp3d` of its own is written back on shapes and theme effect styles. `scene3d`, `sp3d` and `flatTx` on a text body (`a:bodyPr`) and `scene3d` on a group (`p:grpSpPr`) are kept as raw XML too. Bevels, cameras, face lighting and extrusion sides draw approximately | | Text warp (`prstTxWarp`) | yes | yes | All 40 presets rendered (`crates/geom/src/warp.rs`); adjust values (`avLst`) round-trip | | Pictures with crop, recolour, duotone, alpha, luminance | yes | yes | | | Tables with styles | yes | yes | Merges, both diagonal borders and optional RTL column direction round-trip; Reuse Slides transfers definitions referenced by source tables, including grouped tables, with conflicting ids remapped | From 809c44654de372bf08670aeb7b91c823ac0d8a0f Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:59:15 +0000 Subject: [PATCH 77/94] Apply review fixes - crates/pptx/src/write/shapes.rs --- crates/pptx/src/write/shapes.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/pptx/src/write/shapes.rs b/crates/pptx/src/write/shapes.rs index 2140211c7..80eabbcf2 100644 --- a/crates/pptx/src/write/shapes.rs +++ b/crates/pptx/src/write/shapes.rs @@ -343,7 +343,9 @@ pub fn shape(w: &mut W, x: &mut Exp, o: &mut Out, cx: &mut Ctx, s: &Shape, depth { dml::effects(w, fx); } - if let Some(raw) = fx.raw3d.as_deref().and_then(|s| dml::valid_raw3d(s, &["scene3d"])) { + if let Some(raw) = + fx.raw3d.as_deref().map(|s| s.find("<a:sp3d").map_or(s, |i| &s[..i])).and_then(|s| dml::valid_raw3d(s, &["scene3d"])) + { w.raw(raw); } } From 02fbb6a976e705a4ef937d71c5145b5d12e06d3b Mon Sep 17 00:00:00 2001 From: Nasim <40519831+Naseq@users.noreply.github.com> Date: Sun, 8 Nov 2026 11:29:22 +0430 Subject: [PATCH 78/94] =?UTF-8?q?Notes:=20pin=20that=20Paste=20reaches=20t?= =?UTF-8?q?he=20focused=20speaker-notes=20field,=20bare=20and=20inside=20t?= =?UTF-8?q?he=20=E2=8C=98V=20batch=20(refs=20#1855)=20(#1856)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/tests.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 677e971c5..d84d7d32f 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1223,6 +1223,31 @@ fn step_app(services: Services) -> egui_kittest::Harness<'static, SlideApp> { h } +/// #1855: text pasted into the focused speaker-notes field lands at its caret. While a stock +/// field has the focus, `SlideApp::keyboard` leaves the batch to it and nothing in the app drops +/// `Paste`, whether it arrives alone or inside the ⌘V batch egui-winit sends (V down, Paste, V up). +#[test] +fn paste_reaches_the_focused_notes_field() { + let mut h = step_app(Services::default()); + let id = egui::Id::unique("notes_edit"); + h.ctx.memory_mut(|m| m.request_focus(id)); + h.run_steps(2); + assert!(h.ctx.memory(|m| m.has_focus(id)), "the notes field has the focus"); + h.event(egui::Event::Text("ab".into())); + h.run_steps(2); + h.event(egui::Event::Paste("PASTED".into())); + h.run_steps(2); + assert_eq!(h.state().notes_buf.2.text, "abPASTED", "a bare Paste event"); + let v = |pressed| egui::Event::Key { key: egui::Key::V, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND }; + h.input_mut().events.extend([v(true), egui::Event::Paste("TWO".into()), v(false)]); + h.run_steps(2); + assert_eq!(h.state().notes_buf.2.text, "abPASTEDTWO", "the ⌘V batch"); + // Leaving the field commits the notes to the slide. + h.ctx.memory_mut(|m| m.surrender_focus(id)); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.slides[0].notes_text(), "abPASTEDTWO"); +} + /// #1956: the ribbon's drop-downs are announced by their purpose, not by their value or an /// internal key. Animations › Start with a shape that has no animation was "astart"; Home's Font /// and Font size boxes were "font" and "size" while nothing told them a font or size. From 76bd26cca036f8db811c6e7c102ddf9fce81e398 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 08:26:05 +0000 Subject: [PATCH 79/94] Don't capitalize the word after a decimal point in sentence case Found while testing crates/model/src/edit.rs:~505 (change_case_parts, sentence branch) Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/model/src/edit.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs index 8f79d9c4c..c5a325f5a 100644 --- a/crates/model/src/edit.rs +++ b/crates/model/src/edit.rs @@ -498,6 +498,11 @@ pub fn next_case(s: &str) -> &'static str { } } +/// Whether the `.` at `i` sits between two ASCII digits (a decimal point or version number). +fn is_decimal_point(all: &[char], i: usize) -> bool { + i > 0 && all[i - 1].is_ascii_digit() && all.get(i + 1).is_some_and(|n| n.is_ascii_digit()) +} + /// Change case: `upper`, `lower`, `sentence`, `title`, `toggle`. pub fn change_case(s: &str, mode: &str) -> String { change_case_parts(&[s], mode).concat() @@ -532,7 +537,7 @@ pub fn change_case_parts(parts: &[&str], mode: &str) -> Vec<String> { } else { out.extend(c.to_lowercase()); } - if (title && c.is_whitespace()) || (!title && matches!(c, '.' | '!' | '?')) { + if (title && c.is_whitespace()) || (!title && matches!(c, '.' | '!' | '?') && !(c == '.' && is_decimal_point(&all, i))) { start = true; } } @@ -558,6 +563,13 @@ mod tests { assert_eq!(change_case("ΟΔΟΣ", "lower"), "οδος"); } + #[test] + fn sentence_case_decimal_point_is_not_a_boundary() { + assert_eq!(change_case("I HAVE 3.5 APPLES", "sentence"), "I have 3.5 apples"); + assert_eq!(change_case_parts(&["V 1.", "2 BETA"], "sentence").concat(), "V 1.2 beta"); + assert_eq!(change_case("HELLO. WORLD", "sentence"), "Hello. World"); + } + #[test] fn title_sigma_across_runs_is_not_final() { assert_eq!(change_case_parts(&["ΟΔΟΣ", "ΑΣ"], "title"), ["Οδοσ", "ας"]); From ccab980657b3fd9e960512969751f4067369e7c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 8 Nov 2026 11:30:36 -0800 Subject: [PATCH 80/94] Updates: the updater reports installing, ready, installed and failed, and installs at exit craft-media, craft-pdf, craft-ui, craft-update and krilla move from craft-libs c5a1cbfb to c7c84230, which carries storytold/craft-libs#687 and #696. The check result window now shows whenever the updater's status is not idle: after Help > Check for Updates, and at the first start after an update, to say that it installed or why it failed. Restart to Update in that window asks the app to close once nothing is unsaved. on_exit starts the helper of a ready update, since on macOS it ends the process before the app is dropped. --- Cargo.lock | 15 ++-- Cargo.toml | 10 +-- apps/deckcraft/src/main.rs | 3 + crates/ui-egui/src/app.rs | 8 ++ crates/ui-egui/src/dialogs/updates_ui.rs | 95 +++++++++++++++++++++--- 5 files changed, 106 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ff27fdd2..62d15529a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,12 +847,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "fixed_decimal", "icu_decimal", @@ -875,7 +875,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "thiserror 2.0.21", ] @@ -883,7 +883,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "krilla", "thiserror 2.0.21", @@ -892,7 +892,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -912,7 +912,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "chrono", "dunce", @@ -2791,7 +2791,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" dependencies = [ "base64 0.22.1", "bumpalo", @@ -6571,7 +6571,6 @@ dependencies = [ "nix", "typed-path", "windows-sys 0.61.2", - "zopfli", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ab2b74291..a919e0504 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,11 +59,11 @@ harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } -craft-media = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.1.0", default-features = false } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } +craft-media = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0", default-features = false } +craft-pdf = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.1.0" } +craft-update = { git = "https://github.com/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", features = ["egui"] } +craft-ui = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0" } i_overlay = "9" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } @@ -109,7 +109,7 @@ codegen-units = 16 debug = 0 [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", version = "=0.8.2" } +krilla = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.8.2" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index 3f872c214..d71817ceb 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -51,6 +51,9 @@ impl eframe::App for App { } fn on_exit(&mut self) { save_prefs(&self.0); + // The window is closing for good: a ready update's helper starts now and installs it once + // the process has exited. + self.0.start_pending_update(); // macOS (#279): end the process here, before eframe tears the window down. AccessKit's // macOS adapter subclasses the window's content view and restores its class on teardown; // AppKit's Touch Bar support observes that view (KVO), so in the next display cycle diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 178ab24ba..8cc53258e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -137,6 +137,14 @@ impl SlideApp { updates_ui::enable(self); } + /// Start the helper of an update that is ready, so that it installs once the process has + /// exited. The desktop shell calls it in `on_exit`, which ends the process on macOS before the + /// app is dropped. Later calls do nothing. + #[cfg(not(target_arch = "wasm32"))] + pub fn start_pending_update(&mut self) { + updates_ui::start_pending_update(self); + } + /// A message that must be seen wherever the user is: a toast, which also shows over the start /// screen and the File tab, where there is no status bar. pub fn notify(&mut self, msg: impl Into<String>) { diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index cdf2bf207..3c62a254d 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -13,13 +13,11 @@ pub(crate) struct Runtime { /// The desktop host turns the check at start on; tests and the web build leave it off. enabled: bool, check_requested: bool, - /// A manual check's result dialog is showing (checking, up to date or failed). - result_open: bool, } impl Default for Runtime { fn default() -> Self { - Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false, result_open: false } + Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false } } } @@ -31,10 +29,15 @@ pub(crate) fn enable(app: &mut SlideApp) { pub(crate) fn request_check(app: &mut SlideApp) { if !matches!(app.updates_rt.updater.status(), Status::Checking) { app.updates_rt.check_requested = true; - app.updates_rt.result_open = true; } } +/// Starts the helper of an update that is ready, so that it installs once the process has exited. +/// Later calls do nothing. +pub(crate) fn start_pending_update(app: &mut SlideApp) { + app.updates_rt.updater.start_pending_update(); +} + pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) { let rt = &mut app.updates_rt; if std::mem::take(&mut rt.check_requested) { @@ -46,21 +49,31 @@ pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) { } pub(crate) fn show(app: &mut SlideApp, ctx: &egui::Context) { - // The restart helper is scheduled before the app closes, so no update starts over unsaved work. + // An installation starts, and a ready update asks the app to close, only while nothing is unsaved. let clean = !app.session.documents().iter().any(|d| d.is_dirty()); match app.updates_rt.updater.show_if(ctx, clean) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), - // The app's close path asks about unsaved work; the restart helper relaunches once the process exits. + // The app's close path asks about unsaved work; `on_exit` starts the restart helper. Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Action::None => {} } + // The result window reports a requested check, and at the first start after an update what + // that update came to (installed, or why it failed). let rt = &mut app.updates_rt; - if rt.result_open { - match CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()) { - CheckResultResponse::Close => rt.result_open = false, - CheckResultResponse::CheckAgain => rt.check_requested = true, - CheckResultResponse::None => {} - } + if !matches!(rt.updater.status(), Status::Idle) { + let response = CheckResultDialog::new(&crate::UPDATE_APP, VERSION).show(ctx, rt.updater.status()); + answer(rt, response); + } +} + +/// Acts on the result window's answer. +fn answer(rt: &mut Runtime, response: CheckResultResponse) { + match response { + CheckResultResponse::Close => rt.updater.dismiss_status(), + CheckResultResponse::CheckAgain => rt.check_requested = true, + // The next frame's `show_if` asks the window to close once nothing is unsaved. + CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), + CheckResultResponse::None => {} } } @@ -77,4 +90,62 @@ mod tests { ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui.ctx())).textures_delta.clear(); assert!(app.updates_rt.updater.prompt_open()); } + + /// An app whose updater keeps its outcome records under `root`, reads no launcher choice and + /// asks no server, with the check at start turned on. + fn app_with_records(root: &std::path::Path) -> SlideApp { + let mut app = SlideApp::new(deckcraft_engine::Session::new(), crate::Services::default()); + app.updates_rt.updater = Updater::new(&crate::UPDATE_APP, VERSION) + .with_paths(craft_update::Paths::under(root)) + .with_pins_path(root.join("pins.json")) + .with_source(std::sync::Arc::new(|| Ok(None))); + app.updates_rt.enabled = true; + app + } + + fn records_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("deckcraft-updates-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + /// The first start after an update reports it; OK dismisses the report. + #[test] + fn the_start_after_an_update_reports_it_until_dismissed() { + let root = records_dir("installed"); + std::fs::create_dir_all(root.join("data")).unwrap(); + std::fs::write(root.join("data").join("self-update-done.txt"), VERSION).unwrap(); + let mut app = app_with_records(&root); + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |ui| { + tick(&mut app, ui.ctx()); + show(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(matches!(app.updates_rt.updater.status(), Status::Updated(_)), "{:?}", app.updates_rt.updater.status()); + answer(&mut app.updates_rt, CheckResultResponse::Close); + assert_eq!(app.updates_rt.updater.status(), &Status::Idle); + let _ = std::fs::remove_dir_all(&root); + } + + /// The first start after a failed update says why; Check Again asks for a new check. + #[test] + fn the_start_after_a_failed_update_reports_why_and_offers_a_new_check() { + let root = records_dir("failed"); + std::fs::create_dir_all(root.join("data").join("logs")).unwrap(); + std::fs::write(root.join("data").join("logs").join("self-update-error.txt"), "the disk is full").unwrap(); + let mut app = app_with_records(&root); + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |ui| { + tick(&mut app, ui.ctx()); + show(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert_eq!(app.updates_rt.updater.status(), &Status::InstallFailed("the disk is full".into())); + answer(&mut app.updates_rt, CheckResultResponse::CheckAgain); + assert!(app.updates_rt.check_requested); + let _ = std::fs::remove_dir_all(&root); + } } From 3504a9da42f6455e16caf1c08794dc546871d206 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 8 Nov 2026 12:11:03 -0800 Subject: [PATCH 81/94] xtask: pdf-deps expects craft-pdf and krilla from the moved craft-libs pin The pdf-deps check compared craft-pdf and krilla against storytold/craft-libs at c5a1cbfb, so the gate stopped at that step once the pin moved to dotCooCoo/craft-libs c7c84230. The expected repository and revision now match the pin in Cargo.toml. --- xtask/src/pdf_deps.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index ad8e8725c..65b32ee8d 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -6,7 +6,8 @@ use std::process::Command; use serde_json::Value; -const SHARED_REV: &str = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7"; +const SHARED_REPO: &str = "https://github.com/dotCooCoo/craft-libs"; +const SHARED_REV: &str = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae"; const REGISTRY: &str = "registry+https://github.com/rust-lang/crates.io-index"; pub fn run(root: &Path) -> Result<(), String> { @@ -70,7 +71,7 @@ fn validate(metadata: &Value) -> Result<(), String> { } matches.first().copied().ok_or_else(|| format!("missing {name}")) }; - let source = format!("git+https://github.com/storytold/craft-libs?rev={SHARED_REV}#{SHARED_REV}"); + let source = format!("git+{SHARED_REPO}?rev={SHARED_REV}#{SHARED_REV}"); for (name, version, expected_source, expected_features) in [ ("craft-pdf", "0.1.0", source.as_str(), vec!["write", "write-simple-text"]), ("krilla", "0.8.2", source.as_str(), vec!["raster-images", "rayon", "simple-text"]), @@ -143,7 +144,7 @@ mod tests { use serde_json::json; fn metadata() -> Value { - let source = format!("git+https://github.com/storytold/craft-libs?rev={SHARED_REV}#{SHARED_REV}"); + let source = format!("git+{SHARED_REPO}?rev={SHARED_REV}#{SHARED_REV}"); json!({ "packages": [ {"id":"app", "name":"deckcraft-pdf"}, From 4ba9a1a5d93529bcc9d726d74fede18e7f9f904e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:33:22 +0100 Subject: [PATCH 82/94] Make polynomial trendline fits independent of x scale and offset Found while testing crates/model/src/trendline.rs:~419 (solve, used by polyfit) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> --- crates/model/src/trendline.rs | 77 ++++++++++++++++++++++++++++++++--- 1 file changed, 71 insertions(+), 6 deletions(-) diff --git a/crates/model/src/trendline.rs b/crates/model/src/trendline.rs index 2b9cdf6b1..f6aa4b5c0 100644 --- a/crates/model/src/trendline.rs +++ b/crates/model/src/trendline.rs @@ -337,16 +337,31 @@ fn fit_moving_avg(pairs: &[(f64, f64)], period: usize) -> Option<(Model, Vec<f64 #[allow(clippy::needless_range_loop)] fn polyfit_with_intercept(xs: &[f64], ys: &[f64], order: usize, b0: f64) -> Option<Vec<f64>> { + // Fit `y - b0 = (x / sx) * q(u)` with `u = (x - xm) / su` and `q` of degree `order - 1`. The + // basis `(x / sx) * u^j` spans the same polynomials as `x^(j + 1)`, but keeps the pivots in + // `solve` independent of the units and the offset of x. + let n = xs.len() as f64; + let sx = xs.iter().fold(0.0_f64, |acc, x| acc.max(x.abs())); + if sx <= 0.0 || !sx.is_finite() { + return None; + } + let xm = xs.iter().sum::<f64>() / n; + let su = match xs.iter().fold(0.0_f64, |acc, x| acc.max((x - xm).abs())) { + s if s > 0.0 && s.is_finite() => s, + _ => 1.0, + }; let m = order; let mut ata = vec![vec![0.0; m]; m]; let mut atb = vec![0.0; m]; for (x, y) in xs.iter().zip(ys) { + let v = x / sx; + let u = (x - xm) / su; let dy = y - b0; for i in 0..m { - let xi = x.powi((i + 1) as i32); + let xi = v * u.powi(i as i32); atb[i] += dy * xi; for j in i..m { - ata[i][j] += xi * x.powi((j + 1) as i32); + ata[i][j] += xi * v * u.powi(j as i32); } } } @@ -355,10 +370,11 @@ fn polyfit_with_intercept(xs: &[f64], ys: &[f64], order: usize, b0: f64) -> Opti ata[i][j] = ata[j][i]; } } - let solved = solve(ata, atb)?; + let centred: Vec<f64> = solve(ata, atb)?.iter().enumerate().map(|(k, c)| c / su.powi(k as i32)).collect(); + let q = expand_shift(¢red, xm); let mut coeff = Vec::with_capacity(order + 1); coeff.push(b0); - coeff.extend(solved); + coeff.extend(q.iter().map(|c| c / sx)); coeff.iter().all(|v| v.is_finite()).then_some(coeff) } @@ -374,7 +390,13 @@ fn polyfit(xs: &[f64], ys: &[f64], order: usize, intercept: Option<f64>) -> Opti return polyfit_with_intercept(xs, ys, order, b0); } let xm = xs.iter().sum::<f64>() / n as f64; - let us: Vec<f64> = xs.iter().map(|x| x - xm).collect(); + // Scale the centred x to unit range so the pivot threshold in `solve` does not depend on the + // units of x. + let s = xs.iter().fold(0.0_f64, |acc, x| acc.max((x - xm).abs())); + if s <= 0.0 || !s.is_finite() { + return None; + } + let us: Vec<f64> = xs.iter().map(|x| (x - xm) / s).collect(); let m = order + 1; let mut ata = vec![vec![0.0; m]; m]; let mut atb = vec![0.0; m]; @@ -393,7 +415,7 @@ fn polyfit(xs: &[f64], ys: &[f64], order: usize, intercept: Option<f64>) -> Opti ata[i][j] = ata[j][i]; } } - let centred = solve(ata, atb)?; + let centred: Vec<f64> = solve(ata, atb)?.iter().enumerate().map(|(k, c)| c / s.powi(k as i32)).collect(); let coeff = expand_shift(¢red, xm); coeff.iter().all(|v| v.is_finite()).then_some(coeff) } @@ -571,6 +593,49 @@ mod tests { assert!((fit.y(3e-10).unwrap() - 3.0).abs() < 1e-6); } + #[test] + fn poly_fits_tiny_x_values() { + let xs = [1e-5, 2e-5, 3e-5, 4e-5, 5e-5]; + let f = |x: f64| 1.0 + 2.0 * x + 3.0 * x * x; + let ys: Vec<f64> = xs.iter().map(|x| f(*x)).collect(); + let fit = line(TrendlineType::Poly).fit(&xs, &ys).expect("poly fit of tiny x values"); + assert!((fit.y(3e-5).unwrap() - f(3e-5)).abs() < 1e-9); + let big: Vec<f64> = xs.iter().map(|x| x * 1e5).collect(); + let scaled = line(TrendlineType::Poly).fit(&big, &ys).expect("poly fit of scaled x values"); + for x in xs { + assert!((fit.y(x).unwrap() - scaled.y(x * 1e5).unwrap()).abs() < 1e-9, "{x}"); + } + } + + #[test] + fn poly_with_intercept_fits_tiny_x_values() { + let xs = [1e-5, 2e-5, 3e-5, 4e-5, 5e-5]; + let f = |x: f64| 1.0 + 2.0 * x + 3.0 * x * x; + let ys: Vec<f64> = xs.iter().map(|x| f(*x)).collect(); + let mut poly = line(TrendlineType::Poly); + poly.intercept = Some(1.0); + let fit = poly.fit(&xs, &ys).expect("poly fit with intercept of tiny x values"); + assert!((fit.y(3e-5).unwrap() - f(3e-5)).abs() < 1e-9); + let big: Vec<f64> = xs.iter().map(|x| x * 1e5).collect(); + let scaled = poly.fit(&big, &ys).expect("poly fit with intercept of scaled x values"); + for x in xs { + assert!((fit.y(x).unwrap() - scaled.y(x * 1e5).unwrap()).abs() < 1e-9, "{x}"); + } + } + + #[test] + fn poly_with_intercept_fits_offset_but_narrow_x_range() { + let xs = [45000.00, 45000.01, 45000.02, 45000.03, 45000.04]; + let f = |x: f64| 1.0 + x * (1.0 + 100.0 * (x - 45000.02)); + let ys: Vec<f64> = xs.iter().map(|x| f(*x)).collect(); + let mut poly = line(TrendlineType::Poly); + poly.intercept = Some(1.0); + let fit = poly.fit(&xs, &ys).expect("poly fit with intercept of offset x values"); + for x in xs { + assert!((fit.y(x).unwrap() - f(x)).abs() < 1e-2, "{x}"); + } + } + #[test] fn linear_fits_offset_but_narrow_x_range() { let xs = [45000.00, 45000.01, 45000.02, 45000.03, 45000.04]; From 5ee82b4e453fe8627902ecf32d5e901983bbcddf Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sun, 8 Nov 2026 19:43:26 -0800 Subject: [PATCH 83/94] Updates: take craft-update from craft-libs main at 1b34eba41 --- Cargo.lock | 14 +++++++------- Cargo.toml | 10 +++++----- xtask/src/pdf_deps.rs | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62d15529a..4a32c8257 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,12 +847,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -875,7 +875,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "thiserror 2.0.21", ] @@ -883,7 +883,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "krilla", "thiserror 2.0.21", @@ -892,7 +892,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -912,7 +912,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "chrono", "dunce", @@ -2791,7 +2791,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/dotCooCoo/craft-libs?rev=c7c84230631cbc01ee928f0a0e0d838b1ed612ae#c7c84230631cbc01ee928f0a0e0d838b1ed612ae" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "base64 0.22.1", "bumpalo", diff --git a/Cargo.toml b/Cargo.toml index a919e0504..e11a5bbd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,11 +59,11 @@ harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } -craft-media = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0", default-features = false } -craft-pdf = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } +craft-media = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", version = "=0.1.0", default-features = false } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", version = "=0.1.0", default-features = false, features = ["write", "write-simple-text"] } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/dotCooCoo/craft-libs", version = "=0.1.0", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", features = ["egui"] } -craft-ui = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.1.0" } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", version = "=0.1.0" } i_overlay = "9" quick-xml = "0.41" zip = { version = "3", default-features = false, features = ["deflate"] } @@ -109,7 +109,7 @@ codegen-units = 16 debug = 0 [patch.crates-io] -krilla = { git = "https://github.com/dotCooCoo/craft-libs", rev = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae", version = "=0.8.2" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", version = "=0.8.2" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 65b32ee8d..fb8e79d9a 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -6,8 +6,8 @@ use std::process::Command; use serde_json::Value; -const SHARED_REPO: &str = "https://github.com/dotCooCoo/craft-libs"; -const SHARED_REV: &str = "c7c84230631cbc01ee928f0a0e0d838b1ed612ae"; +const SHARED_REPO: &str = "https://github.com/storytold/craft-libs"; +const SHARED_REV: &str = "1b34eba41e62138fc2438d2734523b302840b45d"; const REGISTRY: &str = "registry+https://github.com/rust-lang/crates.io-index"; pub fn run(root: &Path) -> Result<(), String> { From c3fb184e9d2fb41758c220b50ee8e1b26c7e3b08 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 10 Nov 2026 17:54:22 -0500 Subject: [PATCH 84/94] engine: index font names and embedded faces instead of rescanning (#1749) Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/fonts.rs | 18 +++++++++++------- crates/engine/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/fonts.rs b/crates/engine/src/fonts.rs index e208f72c7..3d99d3f57 100644 --- a/crates/engine/src/fonts.rs +++ b/crates/engine/src/fonts.rs @@ -1,6 +1,8 @@ //! Fonts a presentation uses that this machine doesn't have, so opening it can say so (its text //! draws in a stand-in; see `FontDb::document_face`). +use std::collections::HashSet; + use deckcraft_fonts::FontDb; use deckcraft_model::resolve::{self, Ctx}; use deckcraft_model::text::{Bullet, TextBody}; @@ -12,8 +14,13 @@ use deckcraft_model::{Presentation, Shape, ShapeKind}; /// font to load and are left for the round trip. pub fn install_embedded_fonts(p: &Presentation) { let db = FontDb::global(); + // Faces can name one media item many times; each is copied and enumerated once. + let mut seen = HashSet::new(); for font in &p.embedded_fonts { for id in font.faces().into_iter().flatten() { + if !seen.insert(id) { + continue; + } let Some(item) = p.media(id) else { continue }; let Some(sfnt) = deckcraft_fonts::embedded_sfnt(&item.data) else { continue }; db.add_font(sfnt.to_vec()); @@ -27,12 +34,8 @@ pub fn install_embedded_fonts(p: &Presentation) { /// and can't be installed, so they aren't reported. pub fn missing_fonts(p: &Presentation) -> Vec<String> { let db = FontDb::global(); - let mut out: Vec<String> = Vec::new(); - for family in used_fonts(p) { - if !family.starts_with('.') && !db.has_family(&family) && !out.iter().any(|f| f.eq_ignore_ascii_case(&family)) { - out.push(family); - } - } + // used_fonts is already free of case-insensitive duplicates. + let mut out: Vec<String> = used_fonts(p).into_iter().filter(|f| !f.starts_with('.') && !db.has_family(f)).collect(); out.sort_by_key(|f| f.to_lowercase()); out } @@ -40,9 +43,10 @@ pub fn missing_fonts(p: &Presentation) -> Vec<String> { /// The families the slides' text runs and bullets are drawn in. pub fn used_fonts(p: &Presentation) -> Vec<String> { let mut out: Vec<String> = Vec::new(); + let mut seen: HashSet<String> = HashSet::new(); let mut add = |f: String| { let f = f.trim().to_string(); - if !f.is_empty() && !out.iter().any(|o| o.eq_ignore_ascii_case(&f)) { + if !f.is_empty() && seen.insert(f.to_ascii_lowercase()) { out.push(f); } }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5d2310328..1c9434f0e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6870,6 +6870,27 @@ fn master_body_placeholder_format_keeps_per_level_formatting() { assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]); } +#[test] +fn many_distinct_fonts_are_listed_once_each_without_a_quadratic_scan() { + // 30,000 runs in 15,000 families, each written twice in different case. + let mut p = deckcraft_model::Presentation::default(); + let slide = std::sync::Arc::make_mut(&mut p.slides[0]); + let mut body = deckcraft_model::text::TextBody::from_text("x"); + let run = body.paragraphs[0].runs[0].clone(); + body.paragraphs[0].runs = (0..30_000) + .map(|i| { + let mut r = run.clone(); + let name = format!("Qqq Font {}", i / 2); + r.props.font = Some(if i % 2 == 0 { name } else { name.to_uppercase() }); + r + }) + .collect(); + slide.shapes[0].text = Some(body); + let used = crate::fonts::used_fonts(&p); + assert_eq!(used.iter().filter(|f| f.starts_with("Qqq Font ")).count(), 15_000); + assert_eq!(crate::fonts::missing_fonts(&p).iter().filter(|f| f.to_ascii_lowercase().starts_with("qqq font ")).count(), 15_000); +} + #[test] fn slide_master_view_rejects_invalid_indices() { let mut s = Session::with_new(); From 1e9c392f675eb3fd3feaea6362fa914592c42084 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 10 Nov 2026 17:54:53 -0500 Subject: [PATCH 85/94] Spelling: remember failed compound tails (#1835) * Spelling: remember failed compound tails * Apply review fixes - crates/engine/src/spell.rs * Apply review fixes - crates/engine/src/spell.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/spell.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/spell.rs b/crates/engine/src/spell.rs index 0eeaa6757..ee76ff89c 100644 --- a/crates/engine/src/spell.rs +++ b/crates/engine/src/spell.rs @@ -304,7 +304,12 @@ impl Dictionary { /// `w` made of dictionary parts allowed in compounds (`COMPOUNDFLAG`, or the begin, middle and /// end flags), each at least `COMPOUNDMIN` characters long. - fn compounded(&self, w: &[char], index: usize) -> bool { + fn compounded(&self, w: &[char], index: usize, failed: &mut HashSet<(usize, usize)>) -> bool { + // `w` is always a tail of the checked word, so its length names it: a (tail, part index) + // that failed once fails again however the earlier parts were split. + if failed.contains(&(w.len(), index)) { + return false; + } if self.compound.is_none() && self.compound_end.is_none() { return false; } @@ -322,10 +327,11 @@ impl Dictionary { if [self.compound, self.compound_end].into_iter().flatten().any(|f| self.compound_part(rest, f, true)) { return true; } - if self.compounded(rest, index + 1) { + if self.compounded(rest, index + 1, failed) { return true; } } + failed.insert((w.len(), index)); false } @@ -352,7 +358,7 @@ impl Dictionary { return true; } } - self.compounded(&w, 0) + self.compounded(&w, 0, &mut HashSet::new()) } /// Is `word` spelt correctly? Capitalised and upper-case forms of a lower-case word pass. @@ -931,6 +937,17 @@ SFX D Y 1\nSFX D 0 ed/S .\n"; } } + #[test] + fn overlapping_compound_roots_with_a_failing_ending_stay_cheap() { + // Roots a..aaaaaaaa overlap, so many splits of "aaa…ab" reach the same (tail, part) state; unmemoized that is millions of searches. + let d = Dictionary::parse( + b"COMPOUNDFLAG X\nCOMPOUNDMIN 1\n".as_slice(), + b"8\na/X\naa/X\naaa/X\naaaa/X\naaaaa/X\naaaaaa/X\naaaaaaa/X\naaaaaaaa/X\n".as_slice(), + ); + assert!(!d.check(&format!("{}b", "a".repeat(99)))); + assert!(d.check(&"a".repeat(20))); + } + #[test] fn runs_give_words_their_language() { use deckcraft_model::{Paragraph, Run, RunProps}; From 54846750d495baabc064bd6e1f27779399188ced Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Tue, 10 Nov 2026 18:42:24 -0500 Subject: [PATCH 86/94] Ink: extend a stroke in place and cap a gesture's samples (#1770) * engine: extend an ink stroke in place and cap a gesture's samples * engine: move the ink extension out of drag * address review: close scribbles at the release point; keep vertices when a capped press adds none * Apply review fixes - crates/engine/src/tools/pointer.rs * raise ink gesture cap to 100000 points --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/cmd/shape/freeform.rs | 2 +- crates/engine/src/tests.rs | 32 +++++++++++++++++++++++++ crates/engine/src/tools.rs | 3 +++ crates/engine/src/tools/click.rs | 8 +++++-- crates/engine/src/tools/drag.rs | 28 +++++++++++++++++----- crates/engine/src/tools/pointer.rs | 5 +++- 6 files changed, 68 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/shape/freeform.rs b/crates/engine/src/cmd/shape/freeform.rs index 5fd299c9e..f6886c75f 100644 --- a/crates/engine/src/cmd/shape/freeform.rs +++ b/crates/engine/src/cmd/shape/freeform.rs @@ -104,7 +104,7 @@ pub(super) fn freeform(s: &mut Session, p: &Value) -> Result<Value> { a.iter() .filter_map(|v| Some(deckcraft_geom::Point::new(v.get(0)?.as_f64()?, v.get(1)?.as_f64()?))) .filter(|q| q.x.is_finite() && q.y.is_finite()) - .take(20_000) + .take(crate::tools::MAX_GESTURE_POINTS) .collect() }) .unwrap_or_default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1c9434f0e..8b1841675 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5433,6 +5433,38 @@ fn pen_pressure_is_kept_and_a_mouse_draws_at_full_width() { assert_eq!(got, vec![vec![0.2, 1.0, 0.4], vec![1.0, 1.0]]); } +#[test] +fn a_long_ink_stroke_is_extended_in_place_and_capped() { + let mut s = session(); + s.set_tool(tools::ToolKind::Ink { mode: "pen".into(), color: deckcraft_model::Rgba::rgb(20, 20, 20), width: 4.0 }); + let ev = |kind, x: f64| tools::PointerEvent { kind, x, y: 80.0, mods: Mods::default(), tol: 3.0, pressure: Some(0.5) }; + s.pointer(ev(PointerKind::Down, 0.0)).unwrap(); + let n = tools::MAX_GESTURE_POINTS + 5_000; + for i in 1..n { + s.pointer(ev(PointerKind::Drag, (i % 500) as f64)).unwrap(); + } + assert_eq!(s.tool.ink_preview.len(), tools::MAX_GESTURE_POINTS); + s.pointer(ev(PointerKind::Up, 0.0)).unwrap(); + let kept: usize = ink_pressures(&s).iter().map(Vec::len).sum(); + assert!((2..=tools::MAX_GESTURE_POINTS).contains(&kept), "{kept}"); +} + +#[test] +fn double_clicking_a_capped_freeform_keeps_its_vertices() { + let mut s = session(); + let ev = |kind, x: f64, y: f64| tools::PointerEvent { kind, x, y, mods: Default::default(), tol: 3.0, pressure: None }; + s.set_tool(tools::ToolKind::Shape { preset: "freeform".into() }); + s.pointer(ev(tools::PointerKind::Down, 100.0, 100.0)).unwrap(); + // Densely clicked vertices, each within the double-click tolerance of the last. + for i in 0..tools::MAX_GESTURE_POINTS + 10 { + s.pointer(ev(tools::PointerKind::Down, 300.0 + i as f64 * 0.001, 100.0)).unwrap(); + } + s.pointer(ev(tools::PointerKind::DoubleClick, 300.0, 100.0)).unwrap(); + let st = s.doc().unwrap(); + let deckcraft_model::Geom::Custom { paths } = &st.shapes().last().unwrap().geom else { panic!("no freeform") }; + assert_eq!(paths[0].d.matches(" L ").count(), tools::MAX_GESTURE_POINTS - 1); +} + fn ink_pressures(s: &Session) -> Vec<Vec<f32>> { let st = s.doc().unwrap(); let Some(sh) = st.shapes().iter().rev().find(|sh| matches!(sh.kind, deckcraft_model::ShapeKind::Ink { .. })) else { diff --git a/crates/engine/src/tools.rs b/crates/engine/src/tools.rs index 82f53dfc3..2b7f78da9 100644 --- a/crates/engine/src/tools.rs +++ b/crates/engine/src/tools.rs @@ -17,6 +17,7 @@ mod geometry; mod hit; mod pointer; +pub(crate) use drag::MAX_GESTURE_POINTS; pub use hit::{line_xfrm, resize_box, table_rows, text_pos}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -275,6 +276,8 @@ pub struct ToolState { pub path_preview: Vec<Point>, pub path_smooth: bool, pub path_closing: bool, + /// Whether the last freeform press added a vertex (it adds none at the point cap). + pub press_added_vertex: bool, /// The shape in Edit Points: its vertices are handles instead of the box's. pub edit_points: Option<ShapeId>, /// The vertex (path, index) whose control handles show in Edit Points. diff --git a/crates/engine/src/tools/click.rs b/crates/engine/src/tools/click.rs index 802eb8c5e..10bc03d98 100644 --- a/crates/engine/src/tools/click.rs +++ b/crates/engine/src/tools/click.rs @@ -4,8 +4,12 @@ use super::{Drag, Hit, Point, Result, Session, ShapeId, ShapeKind, TextSel, Tool impl Session { pub(super) fn double_click(&mut self, p: Point, tol: f64) -> Result<Value> { if let Some(Drag::Freeform { mode, mut points, .. }) = self.tool.drag.clone() { - // The double-click's own click added a duplicate vertex. - while points.len() > 2 && points.last().zip(points.get(points.len() - 2)).is_some_and(|(a, b)| (*a - *b).hypot() <= tol) { + // The double-click's own click added a duplicate vertex (none at the point cap, where + // the existing vertices are all kept). + while self.tool.press_added_vertex + && points.len() > 2 + && points.last().zip(points.get(points.len() - 2)).is_some_and(|(a, b)| (*a - *b).hypot() <= tol) + { points.pop(); } self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false }); diff --git a/crates/engine/src/tools/drag.rs b/crates/engine/src/tools/drag.rs index a1abcb93c..41ade3266 100644 --- a/crates/engine/src/tools/drag.rs +++ b/crates/engine/src/tools/drag.rs @@ -12,9 +12,16 @@ struct MoveDrag { enter_text: Option<(ShapeId, Point)>, } +/// Samples one ink or freeform gesture keeps; later pointer moves extend it no further. +pub(crate) const MAX_GESTURE_POINTS: usize = 100_000; + impl Session { /// Update the active drag interaction using the pointer position and modifiers. pub(super) fn drag(&mut self, p: Point, mods: Mods, tol: f64) -> Result<Value> { + if matches!(self.tool.drag, Some(Drag::Ink { .. })) { + self.extend_ink(p); + return Ok(Value::Null); + } let Some(drag) = self.tool.drag.clone() else { return Ok(Value::Null) }; match drag { Drag::Guide { index } => { @@ -181,7 +188,7 @@ impl Session { } Drag::Freeform { mode, mut points, pressed } => { // Dragging scribbles (except for curves, which only take clicked points). - if pressed && mode != "curve" && points.last().is_none_or(|l| (*l - p).hypot() >= 1.5) { + if pressed && mode != "curve" && points.len() < MAX_GESTURE_POINTS && points.last().is_none_or(|l| (*l - p).hypot() >= 1.5) { points.push(p); } let mut v = points.clone(); @@ -191,15 +198,24 @@ impl Session { self.tool.path_preview = v; self.tool.drag = Some(Drag::Freeform { mode, points, pressed }); } - Drag::Ink { mut points } => { - points.push(self.ink_sample(p)); - self.tool.ink_preview = points.clone(); - self.tool.drag = Some(Drag::Ink { points }); - } + // Handled above. + Drag::Ink { .. } => {} } Ok(Value::Null) } + /// Ink grows by one sample per move: extend it (and its preview) in place rather than + /// copying the whole stroke twice per event, up to [`MAX_GESTURE_POINTS`]. + fn extend_ink(&mut self, p: Point) { + let sample = self.ink_sample(p); + if let Some(Drag::Ink { points }) = self.tool.drag.as_mut() + && points.len() < MAX_GESTURE_POINTS + { + points.push(sample); + self.tool.ink_preview.push(sample); + } + } + fn drag_move(&mut self, drag: MoveDrag, p: Point, mods: Mods, tol: f64) -> Result<Value> { let MoveDrag { ids, start, origs, moved, duplicate, enter_text } = drag; let mut d = p - start; diff --git a/crates/engine/src/tools/pointer.rs b/crates/engine/src/tools/pointer.rs index d20ae9315..e289e5c70 100644 --- a/crates/engine/src/tools/pointer.rs +++ b/crates/engine/src/tools/pointer.rs @@ -228,7 +228,10 @@ impl Session { self.tool.drag = Some(Drag::Freeform { mode, points, pressed: false }); return self.finish_freeform(true); } - points.push(p); + self.tool.press_added_vertex = points.len() < super::MAX_GESTURE_POINTS; + if self.tool.press_added_vertex { + points.push(p); + } self.tool.path_preview = points.clone(); self.tool.drag = Some(Drag::Freeform { mode, points, pressed: true }); return Ok(Value::Null); From 4e87f2b850064881f5c868181db95100e4f3997f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 03:17:58 -0500 Subject: [PATCH 87/94] H.264: bound decoder work from overlapping slices, gaps and queued output (#1706) * H.264: bound decoder work from overlapping slices, gaps and queued output - A macroblock that an earlier slice of the same picture already decoded is refused, so overlapping slices cannot redo the picture's reconstruction once per slice. - The memory budget check counts pictures waiting in the output queue that have left the DPB (one decode call may carry many access units) and the DPB's actual size, counting shared buffers once. - frame_num gap concealment advances the POC state across the skipped run in constant time instead of once per missing frame_num. - Storing a reference picture evicts until the DPB is under capacity, rather than evicting one picture and inserting regardless. * address review: charge pictures already held at their own size in the decoder budget * address review: keep the h264 output-queue byte total incrementally --- crates/h264/src/cabac_mb.rs | 2 +- crates/h264/src/decoder.rs | 53 +++++++++++++++++++++------ crates/h264/src/dpb.rs | 63 ++++++++++++++++++++++++++------ crates/h264/src/picture.rs | 8 +++++ crates/h264/src/slicedec.rs | 12 ++++--- crates/h264/src/synth_tests.rs | 65 +++++++++++++++++++++++++++++++++- 6 files changed, 177 insertions(+), 26 deletions(-) diff --git a/crates/h264/src/cabac_mb.rs b/crates/h264/src/cabac_mb.rs index 78c257e9b..368750292 100644 --- a/crates/h264/src/cabac_mb.rs +++ b/crates/h264/src/cabac_mb.rs @@ -48,7 +48,7 @@ impl SliceDecoder<'_> { let intra_slice = self.sh.slice_type.is_intra(); loop { ensure!(addr < total, "macroblock address {addr} out of range"); - self.start_mb(addr); + self.start_mb(addr)?; let skip = !intra_slice && self.decode_skip_flag(&mut c); if skip { self.decode_skip()?; diff --git a/crates/h264/src/decoder.rs b/crates/h264/src/decoder.rs index a3244d473..455701f92 100644 --- a/crates/h264/src/decoder.rs +++ b/crates/h264/src/decoder.rs @@ -15,7 +15,7 @@ use crate::slicedec::{PicState, SliceDecoder}; use crate::transform::LevelScale; use crate::{ColorInfo, Picture}; use deckcraft_bitstream::{BitReader, annexb_nals, length_prefixed_nals, unescape_rbsp}; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; /// One slice of a picture job. @@ -90,6 +90,10 @@ pub struct Decoder { ls_cache: Vec<(Arc<Pps>, Arc<LevelScale>)>, /// Pictures leaving the DPB, converted once their decoding job has finished. out_queue: VecDeque<Output>, + /// Queued entries per frame id and their summed bytes, kept in step with `out_queue` so the + /// budget check does not rescan it. + queued_ids: HashMap<u32, u64>, + queued_bytes: u64, shared: Arc<Shared>, #[cfg(feature = "threads")] pool: Option<rayon::ThreadPool>, @@ -175,6 +179,8 @@ impl Decoder { active_sps: None, ls_cache: Vec::new(), out_queue: VecDeque::new(), + queued_ids: HashMap::new(), + queued_bytes: 0, shared: Arc::new(Shared::default()), #[cfg(feature = "threads")] pool, @@ -283,7 +289,7 @@ impl Decoder { if !o.frame.is_published(o.frame.mb_h() - 1) && self.out_queue.len() <= max_queue { break; } - let Some(o) = self.out_queue.pop_front() else { break }; + let Some(o) = self.pop_out() else { break }; pics.push(make_picture(&o)); } Ok(pics) @@ -295,7 +301,7 @@ impl Decoder { let mut outs = Vec::new(); self.dpb.flush(&mut outs); self.emit(outs); - let pics = self.out_queue.drain(..).map(|o| make_picture(&o)).collect(); + let pics = std::iter::from_fn(|| self.pop_out()).map(|o| make_picture(&o)).collect(); while let Some(f) = self.in_flight.pop_front() { f.wait_complete(); } @@ -451,13 +457,24 @@ impl Decoder { chroma_planes: if chroma == 0 { 0 } else { 2 }, bytes_per_sample: 1, }; - let pictures = (sps.max_dpb_frames() + 1 + self.max_in_flight) as u64; - ensure!( - shape.fits(pictures, self.memory_budget), - "{}x{} pictures with {pictures} in the decoder exceed the memory budget", - sps.width(), - sps.height() - ); + // Pictures already held count at their own size, not the incoming SPS's: after a + // resolution change, larger pictures of the old size can still be in the DPB or waiting + // for output (one decode call may carry many access units). A buffer shared with a DPB + // entry is counted once. + let pic = shape.bytes().unwrap_or(u64::MAX); + let held = |frames: &mut dyn Iterator<Item = &Arc<Frame>>| frames.fold(0u64, |n, f| n.saturating_add(f.bytes())); + // Queued bytes minus the queue entries that share a DPB frame (each distinct DPB frame once). + let mut ids: Vec<(u32, u64)> = self.dpb.entries.iter().map(|e| (e.frame.id, e.frame.bytes())).collect(); + ids.sort_unstable(); + ids.dedup(); + let shared = ids.iter().fold(0u64, |n, (id, b)| n.saturating_add(self.queued_ids.get(id).copied().unwrap_or(0).saturating_mul(*b))); + let queued = self.queued_bytes.saturating_sub(shared); + let in_dpb = held(&mut self.dpb.entries.iter().map(|e| &e.frame)); + let dpb = sps.max_dpb_frames().max(self.dpb.entries.len()) as u64; + // The DPB (the larger of its new slots and what it holds now), the picture being decoded, + // and what is in flight or queued. + let bytes = pic.saturating_mul(dpb).max(in_dpb).saturating_add(pic).saturating_add(pic.saturating_mul(self.max_in_flight as u64).max(queued)); + ensure!(bytes <= self.memory_budget, "{}x{} pictures with {bytes} bytes in the decoder exceed the memory budget", sps.width(), sps.height()); Ok(()) } @@ -562,8 +579,24 @@ impl Decoder { } fn emit(&mut self, outs: Vec<Output>) { + for o in &outs { + *self.queued_ids.entry(o.frame.id).or_insert(0) += 1; + self.queued_bytes = self.queued_bytes.saturating_add(o.frame.bytes()); + } self.out_queue.extend(outs); } + + fn pop_out(&mut self) -> Option<Output> { + let o = self.out_queue.pop_front()?; + if let Some(n) = self.queued_ids.get_mut(&o.frame.id) { + *n -= 1; + if *n == 0 { + self.queued_ids.remove(&o.frame.id); + } + } + self.queued_bytes = self.queued_bytes.saturating_sub(o.frame.bytes()); + Some(o) + } } /// Decode all slices of one picture and publish its rows. diff --git a/crates/h264/src/dpb.rs b/crates/h264/src/dpb.rs index 46e8f060a..940b1a4c5 100644 --- a/crates/h264/src/dpb.rs +++ b/crates/h264/src/dpb.rs @@ -139,8 +139,9 @@ impl Dpb { let mut unused = (prev_ref_frame_num + 1) % max_frame_num; // Only the last `max_num_ref_frames` "non-existing" frames can survive the sliding window, and // inserting more than that evicts every earlier short-term reference. Skip straight to that tail - // (keeping the POC state walk for every missing frame_num) so a hostile gap of up to 65535 - // frames costs at most `max_num_ref_frames` frame allocations instead of one per missing frame. + // (advancing the POC state across the skipped run in constant time) so a hostile gap of up to + // 65535 frames costs at most `max_num_ref_frames` frame allocations and POC updates instead of + // one per missing frame. let gap = frame_num.wrapping_add(max_frame_num).wrapping_sub(unused) % max_frame_num; let keep = u32::try_from(max_num_ref_frames.max(1)).unwrap_or(u32::MAX); let skip = gap.saturating_sub(keep); @@ -149,10 +150,17 @@ impl Dpb { e.mark = RefMark::Unused; } self.prune(); - for _ in 0..skip { - poc_state(unused); - unused = (unused + 1) % max_frame_num; + // The POC state only advances FrameNumOffset where frame_num decreases, so walking the + // skipped run is the same as visiting its first value, the wrap (if the run crosses + // it) and its last value: constant work however long the gap. + let last = (unused + (skip - 1) % max_frame_num) % max_frame_num; + poc_state(unused); + if last < unused { + poc_state(max_frame_num - 1); + poc_state(0); } + poc_state(last); + unused = (last + 1) % max_frame_num; } let mut guard = 0; while unused != frame_num && guard < max_frame_num { @@ -438,14 +446,15 @@ impl Dpb { } } } else { - while self.entries.len() >= self.capacity { + // Evict until there is room (frame_num gap concealment can leave the DPB over-full), so + // the store never holds more pictures than the memory budget was checked for. + while self.entries.len() >= self.capacity.max(1) { if !self.bump(out) { if let Some(pos) = self.entries.iter().position(|e| !e.needed_for_output) { self.entries.remove(pos); } else { self.entries.remove(0); } - break; } } } @@ -546,6 +555,37 @@ mod tests { (made, walk, left) } + /// (FrameNumOffset, prev frame_num) after `walk`, by the rule of `PocState::update_gap_frame`. + fn poc_after(walk: &[u32], prev: u32, max: u32) -> (u64, u32) { + walk.iter().fold((0, prev), |(off, prev), &f| (if prev > f { off + u64::from(max) } else { off }, f)) + } + + #[test] + fn gap_walk_matches_every_frame_num_for_any_skip() { + for (prev, cur) in [(1, 9), (10, 3), (14, 0), (15, 14), (0, 15), (7, 6)] { + for refs in 1..4 { + let mut dpb = Dpb::new(); + let (_, walk, _) = fill(&mut dpb, prev, cur, 16, refs); + let every: Vec<u32> = (1..16).map(|i| (prev + i) % 16).take_while(|&f| f != cur).collect(); + assert_eq!(poc_after(&walk, prev, 16), poc_after(&every, prev, 16), "{prev} -> {cur}, {refs} refs"); + assert_eq!(walk.last(), every.last(), "{prev} -> {cur}, {refs} refs"); + } + } + } + + #[test] + fn reference_store_evicts_down_to_capacity() { + let mut dpb = Dpb::new(); + dpb.capacity = 2; + // Gap concealment can leave more non-output references than the capacity. + for i in 0..5 { + short(&mut dpb, i, i); + } + let mut out = Vec::new(); + assert!(!dpb.bump_for_space(RefMark::Short, 0, &mut out)); + assert!(dpb.entries.len() < 2, "{} pictures left before storing into a 2-picture DPB", dpb.entries.len()); + } + #[test] fn huge_gap_makes_only_the_frames_that_stay_referenced() { let mut dpb = Dpb::new(); @@ -553,8 +593,9 @@ mod tests { short(&mut dpb, 2, 1); let (made, walk, left) = fill(&mut dpb, 1, 65535, 65536, 4); assert_eq!(made, 4); - // The POC state still walks every missing frame_num, in order. - assert_eq!(walk.len(), 65533); + // The POC state ends where walking every missing frame_num would leave it, in a few steps. + assert_eq!(poc_after(&walk, 1, 65536), poc_after(&(2..65535).collect::<Vec<_>>(), 1, 65536)); + assert!(walk.len() <= 8, "{} POC updates", walk.len()); assert_eq!(walk.first(), Some(&2)); assert_eq!(walk.last(), Some(&65534)); assert_eq!(left, vec![(65531, true), (65532, true), (65533, true), (65534, true)]); @@ -566,7 +607,9 @@ mod tests { short(&mut dpb, 1, 65000); let (made, walk, left) = fill(&mut dpb, 65000, 3, 65536, 2); assert_eq!(made, 2); - assert_eq!(walk.len(), 538); + let every: Vec<u32> = (65001..65536).chain(0..3).collect(); + assert_eq!(poc_after(&walk, 65000, 65536), poc_after(&every, 65000, 65536)); + assert!(walk.len() <= 6, "{} POC updates", walk.len()); assert_eq!(walk.first(), Some(&65001)); assert_eq!(walk.last(), Some(&2)); assert_eq!(left, vec![(1, true), (2, true)]); diff --git a/crates/h264/src/picture.rs b/crates/h264/src/picture.rs index 39add6a08..83331cb95 100644 --- a/crates/h264/src/picture.rs +++ b/crates/h264/src/picture.rs @@ -160,6 +160,14 @@ impl Frame { self.rows.len() } + /// Sample bytes this picture holds (luma and both chroma planes), as the decoder's memory + /// budget counts a picture. + pub fn bytes(&self) -> u64 { + (self.width as u64) + .saturating_mul(self.height as u64) + .saturating_add((self.cwidth as u64).saturating_mul(self.cheight as u64).saturating_mul(2)) + } + /// Publish MB row `r` (ignored if already published). pub fn publish(&self, r: usize, row: FrameRow) { let _ = self.rows[r].set(row); diff --git a/crates/h264/src/slicedec.rs b/crates/h264/src/slicedec.rs index 058ccfe16..649739986 100644 --- a/crates/h264/src/slicedec.rs +++ b/crates/h264/src/slicedec.rs @@ -346,8 +346,11 @@ impl<'a> SliceDecoder<'a> { // Neighbour helpers // ------------------------------------------------------------------------------------------ - /// Set up the current macroblock address and neighbour availability. - pub fn start_mb(&mut self, addr: usize) { + /// Set up the current macroblock address and neighbour availability. A macroblock an earlier + /// slice of this picture already decoded is refused: overlapping slices would otherwise redo + /// the picture's reconstruction once per slice. + pub fn start_mb(&mut self, addr: usize) -> Result<()> { + ensure!(self.pic.mbs[addr].slice_num == u32::MAX, "macroblock {addr} overlaps an earlier slice"); self.mb_addr = addr; self.mb_x = addr % self.mb_w; self.mb_y = addr / self.mb_w; @@ -364,6 +367,7 @@ impl<'a> SliceDecoder<'a> { ]; self.mv_done = 0; self.pic.mbs[addr] = MbState { slice_num: sn, ..MbState::default() }; + Ok(()) } #[inline] @@ -1467,7 +1471,7 @@ impl<'a> SliceDecoder<'a> { let run = r.read_ue()? as usize; ensure!(addr + run <= total, "mb_skip_run out of range"); for _ in 0..run { - self.start_mb(addr); + self.start_mb(addr)?; self.decode_skip()?; self.pic.mb_done(addr); addr += 1; @@ -1477,7 +1481,7 @@ impl<'a> SliceDecoder<'a> { } ensure!(addr < total, "macroblock address {addr} out of range"); } - self.start_mb(addr); + self.start_mb(addr)?; self.decode_mb_cavlc(r)?; self.pic.mb_done(addr); addr += 1; diff --git a/crates/h264/src/synth_tests.rs b/crates/h264/src/synth_tests.rs index 76609dbde..199f5e69d 100644 --- a/crates/h264/src/synth_tests.rs +++ b/crates/h264/src/synth_tests.rs @@ -113,6 +113,7 @@ fn avcc_rejects_a_valid_picture_slice_without_starting_a_picture() { poc_lsb: Some(0), poc_delta: None, wt: None, + first_mb: 0, }, false, ); @@ -153,6 +154,8 @@ struct Pic { /// Explicit weights (luma, cb, cr) as (weight, offset) for refIdx 0 of list 0 and list 1; /// log2 denominators are 5 (luma) and 3 (chroma). wt: Option<[[(i32, i32); 3]; 2]>, + /// first_mb_in_slice (`mbs` then lists the slice's macroblocks from there). + first_mb: u32, } impl Pic { @@ -165,7 +168,7 @@ impl Pic { } fn slice_header(w: &mut BitWriter, p: &Pic, cabac: bool) { - w.write_ue(0); // first_mb + w.write_ue(p.first_mb); w.write_ue(if p.b { 6 } else if p.is_p() { @@ -660,3 +663,63 @@ fn frame_num_gap_is_filled_when_the_sps_allows_gaps() { assert_eq!(out.len(), 2); assert_eq!(dec.stats().frame_num_gaps, 1); } + +/// An IDR picture followed by `pictures` reference P pictures of P_Skip macroblocks. +fn skip_stream(pictures: u32) -> (Vec<u8>, Vec<Vec<u8>>) { + let mut seed = 11u32; + let a: Vec<Option<Vec<u8>>> = (0..NMB).map(|_| Some(random_mb(&mut seed))).collect(); + let mut head = sps(66, 2, false, PocType::T2); + head.extend(pps(false, false)); + head.extend(slice_nal(&Pic { idr: true, frame_num: 0, ref_idc: 3, mbs: a, ..Default::default() }, false)); + let ps = (1..=pictures).map(|k| slice_nal(&Pic { frame_num: k % 16, ref_idc: 2, mbs: vec![None; NMB], ..Default::default() }, false)).collect(); + (head, ps) +} + +#[test] +fn overlapping_slices_are_not_reconstructed_twice() { + let (head, ps) = skip_stream(1); + let mut once = Decoder::with_threads(1); + let mut out = once.decode(&[head.clone(), ps[0].clone()].concat(), 0).unwrap(); + out.extend(once.flush()); + assert!(once.take_error().is_none()); + assert_eq!(out.len(), 2); + // A second slice of the same picture starting at macroblock 1 covers those macroblocks again. + let again = slice_nal(&Pic { frame_num: 1, ref_idc: 2, mbs: vec![None; NMB - 1], first_mb: 1, ..Default::default() }, false); + let mut twice = Decoder::with_threads(1); + let result = twice.decode(&[head, ps[0].clone(), again].concat(), 0); + twice.flush(); + let err = result.err().or_else(|| twice.take_error()).expect("overlapping slice refused"); + assert!(err.to_string().contains("overlaps"), "{err}"); +} + +#[test] +fn output_queue_counts_against_the_memory_budget() { + let (head, ps) = skip_stream(40); + let sps_nal = sps(66, 2, false, PocType::T2); + let parsed = crate::params::Sps::parse(&deckcraft_bitstream::unescape_rbsp(&sps_nal[5..])).unwrap(); + let one = (NMB * 256 + 2 * NMB * 64) as u64; + let budget = (parsed.max_dpb_frames() + 1 + 3) as u64 * one; + // One access unit per call: output drains as it goes, and the stream fits. + let mut dec = Decoder::with_threads(1); + dec.set_memory_budget(budget); + let mut out = dec.decode(&head, 0).unwrap(); + for (i, p) in ps.iter().enumerate() { + out.extend(dec.decode(p, i as i64 + 1).unwrap()); + } + out.extend(dec.flush()); + assert!(dec.take_error().is_none()); + assert_eq!(out.len(), 41); + // Every access unit in one call: the pictures held for output stop fitting the budget. + let mut dec = Decoder::with_threads(1); + dec.set_memory_budget(budget); + let err = dec.decode(&[head, ps.concat()].concat(), 0).expect_err("output queue is over budget"); + assert!(err.to_string().contains("memory budget"), "{err}"); +} + +/// A held picture is charged at its own size (luma and both 4:2:0 chroma planes), the same +/// count the budget uses for the incoming SPS's pictures. +#[test] +fn a_held_frame_is_charged_at_its_own_size() { + let f = crate::picture::Frame::new(0, 0, 2, 3); + assert_eq!(f.bytes(), (2 * 3 * 256 + 2 * 2 * 3 * 64) as u64); +} From 92a0437ab6031f7afc0ec356fae91902b267883d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 03:28:15 -0500 Subject: [PATCH 88/94] Media: check an MP4's sample tables where Symphonia will start reading it (#1737) * media: check an MP4 for oversized sample tables where symphonia will start reading it * address review: run MP4 table guard only for MP4 or unknown containers * Apply review fixes - crates/media/src/probe.rs - crates/media/src/mp4guard.rs - crates/media/src/audio.rs --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/media/src/audio.rs | 4 ++- crates/media/src/mp4guard.rs | 49 ++++++++++++++++++++++++++++++++++++ crates/media/src/probe.rs | 3 ++- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/media/src/audio.rs b/crates/media/src/audio.rs index 5f623a3e2..09f9efa37 100644 --- a/crates/media/src/audio.rs +++ b/crates/media/src/audio.rs @@ -81,7 +81,9 @@ pub fn decode(bytes: &Bytes) -> Result<Pcm> { Some(r) => r, None => contained(|| decode_symphonia(bytes, "mkv")), }, - Container::Mp4 if !crate::mp4guard::tables_fit(bytes) => Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into())), + Container::Mp4 | Container::Unknown | Container::Mp3 if !crate::mp4guard::probe_fits(bytes) => { + Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into())) + } c => contained(|| decode_symphonia(bytes, c.name())), } } diff --git a/crates/media/src/mp4guard.rs b/crates/media/src/mp4guard.rs index ff8e86138..56047979f 100644 --- a/crates/media/src/mp4guard.rs +++ b/crates/media/src/mp4guard.rs @@ -12,6 +12,29 @@ pub(crate) fn tables_fit(b: &[u8]) -> bool { boxes_fit(b, b.len() as u64, 0) } +/// Bytes symphonia's probe scans for a format marker before giving up. +const PROBE_SEARCH_LIMIT: usize = 1024 * 1024; + +/// Whether symphonia can be given `b`, whatever the sniffer made of it: its probe takes the first +/// `ftyp` within its search window as the start of an MP4 (the size field 4 bytes before it), so +/// the table check must start where that parser will, not at offset 0. +pub(crate) fn probe_fits(b: &[u8]) -> bool { + if crate::Container::sniff(b) == crate::Container::Mp4 && !tables_fit(b) { + return false; + } + // The probe reads leading ID3v2 tags as metadata and searches again after the last one. + let mut rest = b; + while rest.starts_with(b"ID3") { + let size = rest.get(6..10).map(|s| s.iter().fold(0usize, |a, &x| (a << 7) | (x & 0x7f) as usize)).unwrap_or(0); + rest = rest.get(10 + size..).unwrap_or(&[]); + } + let head = &rest[..rest.len().min(PROBE_SEARCH_LIMIT + 16)]; + match head.windows(4).position(|w| w == b"ftyp") { + Some(p) => tables_fit(&rest[p.saturating_sub(4)..]), + None => true, + } +} + fn be32(b: &[u8], at: usize) -> Option<u64> { b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as u64) } @@ -74,3 +97,29 @@ fn table_fits(kind: &[u8], body: &[u8], file_len: u64) -> bool { }; be32(body, 4).is_some_and(|count| count <= body.len().saturating_sub(8) as u64 / entry) } + +#[cfg(test)] +mod tests { + use super::*; + + /// An MP4 whose `stsc` count asks for far more entries than the file holds. + fn mp4_with_huge_stsc() -> Vec<u8> { + let stsc = [&24u32.to_be_bytes()[..], b"stsc", &[0, 0, 0, 0], &u32::MAX.to_be_bytes(), &[0; 8]].concat(); + let stbl = [&(stsc.len() as u32 + 8).to_be_bytes()[..], b"stbl", &stsc].concat(); + let moov = [&(stbl.len() as u32 + 8).to_be_bytes()[..], b"moov", &stbl].concat(); + [&16u32.to_be_bytes()[..], b"ftyp", b"isom", &[0; 4], &moov].concat() + } + + #[test] + fn a_prefixed_mp4_is_checked_where_symphonia_starts_it() { + let mp4 = mp4_with_huge_stsc(); + assert!(!tables_fit(&mp4)); + assert!(!probe_fits(&mp4)); + let prefixed = [&b"junk before the file "[..], &mp4].concat(); + assert_eq!(crate::Container::sniff(&prefixed), crate::Container::Unknown); + assert!(tables_fit(&prefixed), "offset 0 sees no MP4 boxes"); + assert!(!probe_fits(&prefixed)); + let far = [&vec![0u8; PROBE_SEARCH_LIMIT + 16][..], &mp4].concat(); + assert!(probe_fits(&far), "past the probe window symphonia never reads it as an MP4"); + } +} diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 97d9a751f..4e8e845c5 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -71,7 +71,8 @@ pub fn probe_headers(bytes: &Bytes) -> Result<MediaInfo> { }; if info.audio.is_none() && info.video.is_none() || info.audio.as_ref().is_some_and(|a| a.sample_rate == 0) { // Plain audio files (and anything our demuxers didn't describe): symphonia's probe. - if c == Container::Mp4 && !crate::mp4guard::tables_fit(bytes) { + // Symphonia opens an MP4 wherever its probe finds an `ftyp` (after leading ID3v2 tags too); other known containers (a WAV's audio bytes can spell an `ftyp`) skip the check. + if matches!(c, Container::Mp4 | Container::Unknown | Container::Mp3) && !crate::mp4guard::probe_fits(bytes) { return Err(MediaError::Corrupt("the MP4's sample tables do not fit the file".into())); } let (codec, rate, channels, frames) = std::panic::catch_unwind(|| crate::audio::probe_symphonia(bytes, c.name())) From eb10e2b9b3362f99f982f8ecdafa5c75e8b22ebe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 03:35:40 -0500 Subject: [PATCH 89/94] Metafile: bound clipping work across all subpaths of one item (#1738) * metafile: bound clipping work across all subpaths of one drawn item * address review: charge fill clipping as polygons grow, one budget per item * address review: charge actual clip work instead of projected polygon growth * address review: share one clip-work allowance between fill and stroke * address review: share one clip-work budget across fill and stroke, give region intersection its own budget --- crates/metafile/src/cliprect.rs | 60 +++++++++++++++-------- crates/metafile/src/emfplus.rs | 10 +++- crates/metafile/src/tests.rs | 85 ++++++++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 25 deletions(-) diff --git a/crates/metafile/src/cliprect.rs b/crates/metafile/src/cliprect.rs index fd9dfc14a..ef6bb7c88 100644 --- a/crates/metafile/src/cliprect.rs +++ b/crates/metafile/src/cliprect.rs @@ -11,6 +11,14 @@ use crate::geom::{Op, P}; /// Line segments per Bézier when a crossing shape is flattened. const CURVE_STEPS: usize = 16; +/// Point-against-edge tests one clipped item may cost (all its subpaths together); an item over +/// it is dropped, as a single polygon over it already was. +const MAX_CLIP_WORK: usize = 1_000_000; + +/// The same allowance for intersecting two clip regions, a budget of its own: two convex +/// 1,000-gons cost about 1.5 million tests once the cut polygon has grown. +pub(crate) const MAX_AREA_CLIP_WORK: usize = 4 * MAX_CLIP_WORK; + /// The bounding box `[l, t, r, b]` of the points in `ops` (control points included). pub(crate) fn ops_bbox(ops: &[Op]) -> Option<[f64; 4]> { let mut b: Option<[f64; 4]> = None; @@ -98,16 +106,18 @@ fn is_rect(clip: &[P]) -> bool { pts_bbox(clip).is_some_and(|b| clip.len() == 4 && clip.iter().all(|p| (p.0 == b[0] || p.0 == b[2]) && (p.1 == b[1] || p.1 == b[3]))) } -/// Sutherland–Hodgman: `poly` cut by convex `clip`. -pub(crate) fn clip_polygon(poly: &[P], clip: &[P]) -> Vec<P> { - if poly.len().saturating_mul(clip.len()) > 1_000_000 { - return Vec::new(); - } +/// Sutherland–Hodgman: `poly` cut by convex `clip`, charging each point visited against each clip +/// edge to `budget`: the polygon +/// can gain a vertex at every edge, so its cost isn't known from its input size alone. `None` +/// once the budget is spent. +pub(crate) fn clip_polygon_within(poly: &[P], clip: &[P], budget: &mut usize) -> Option<Vec<P>> { let mut poly = poly.to_vec(); for i in 0..clip.len() { - if poly.len().saturating_mul(clip.len() - i) > 1_000_000 { - return Vec::new(); + // The work actually done: this edge visits the polygon as it now stands. + if poly.len() > *budget { + return None; } + *budget -= poly.len(); let (a, b) = (clip[i], clip[(i + 1) % clip.len()]); let keep = |p: P| cross(a, b, p) >= 0.0; let cut = |p: P, q: P| { @@ -133,7 +143,7 @@ pub(crate) fn clip_polygon(poly: &[P], clip: &[P]) -> Vec<P> { break; } } - poly + Some(poly) } fn disjoint(b: [f64; 4], c: [f64; 4]) -> bool { @@ -158,15 +168,17 @@ pub(crate) fn clip_raw(raw: Raw, clip: &[P]) -> Vec<Raw> { return Vec::new(); } let subs = flatten(&ops); + // One allowance for the fill and the stroke together; the item goes once it is spent. + let mut budget = MAX_CLIP_WORK; let mut out = Vec::new(); if fill.is_some() { - let f = clip_fill(&subs, clip); + let Some(f) = clip_fill(&subs, clip, &mut budget) else { return Vec::new() }; if !f.is_empty() { out.push(Raw::Path { ops: f, fill, stroke: None, even_odd, region: region.clone() }); } } if stroke.is_some() { - let s = clip_stroke(&subs, clip); + let Some(s) = clip_stroke(&subs, clip, &mut budget) else { return Vec::new() }; if !s.is_empty() { out.push(Raw::Path { ops: s, fill: None, stroke, even_odd, region }); } @@ -181,7 +193,8 @@ pub(crate) fn clip_raw(raw: Raw, clip: &[P]) -> Vec<Raw> { if disjoint(b, cb) { return Vec::new(); } - let f = clip_fill(&flatten(&ops), clip); + let subs = flatten(&ops); + let f = clip_fill(&subs, clip, &mut { MAX_CLIP_WORK }).unwrap_or_default(); if f.is_empty() { Vec::new() } else { vec![Raw::Pattern { ops: f, even_odd, tile, region }] } } Raw::Bitmap { rect, img, region } => crop(rect, img, clip).map(|(rect, img)| vec![Raw::Bitmap { rect, img, region }]).unwrap_or_default(), @@ -230,20 +243,23 @@ pub(crate) fn flatten(ops: &[Op]) -> Vec<(Vec<P>, bool)> { subs } -fn clip_fill(subs: &[(Vec<P>, bool)], clip: &[P]) -> Vec<Op> { +/// The clipped fill of every subpath, its clipping work charged to `budget` with that of the +/// stroke: `None` (the whole item goes) once it is spent. +fn clip_fill(subs: &[(Vec<P>, bool)], clip: &[P], budget: &mut usize) -> Option<Vec<Op>> { let mut ops = Vec::new(); for (pts, _) in subs { - let poly = clip_polygon(pts, clip); + let poly = clip_polygon_within(pts, clip, budget)?; if poly.len() >= 3 { ops.push(Op::M(poly[0])); ops.extend(poly[1..].iter().map(|p| Op::L(*p))); ops.push(Op::Z); } } - ops + Some(ops) } -fn clip_stroke(subs: &[(Vec<P>, bool)], clip: &[P]) -> Vec<Op> { +/// The clipped outline of every subpath; `None` once `budget` is spent. +fn clip_stroke(subs: &[(Vec<P>, bool)], clip: &[P], budget: &mut usize) -> Option<Vec<Op>> { let mut ops = Vec::new(); for (pts, closed) in subs { let mut pts = pts.clone(); @@ -252,7 +268,7 @@ fn clip_stroke(subs: &[(Vec<P>, bool)], clip: &[P]) -> Vec<Op> { } let mut last: Option<P> = None; for w in pts.windows(2) { - let Some((a, b)) = segment(w[0], w[1], clip) else { + let Some((a, b)) = segment(w[0], w[1], clip, budget)? else { last = None; continue; }; @@ -263,21 +279,23 @@ fn clip_stroke(subs: &[(Vec<P>, bool)], clip: &[P]) -> Vec<Op> { last = Some(b); } } - ops + Some(ops) } -/// Cyrus–Beck: the part of segment `a`–`b` inside convex `clip`. -fn segment(a: P, b: P, clip: &[P]) -> Option<(P, P)> { +/// Cyrus–Beck: the part of segment `a`–`b` inside convex `clip`, one unit of `budget` per clip edge +/// visited; the outer `None` is a spent budget. +fn segment(a: P, b: P, clip: &[P], budget: &mut usize) -> Option<Option<(P, P)>> { let d = (b.0 - a.0, b.1 - a.1); let (mut t0, mut t1) = (0.0f64, 1.0f64); for i in 0..clip.len() { + *budget = budget.checked_sub(1)?; let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]); // Inside is cross(e0, e1, p) >= 0, linear in t along the segment. let f0 = cross(e0, e1, a); let df = (e1.0 - e0.0) * d.1 - (e1.1 - e0.1) * d.0; if df == 0.0 { if f0 < 0.0 { - return None; + return Some(None); } } else { let t = -f0 / df; @@ -288,7 +306,7 @@ fn segment(a: P, b: P, clip: &[P]) -> Option<(P, P)> { } } } - (t0 <= t1).then_some(((a.0 + d.0 * t0, a.1 + d.1 * t0), (a.0 + d.0 * t1, a.1 + d.1 * t1))) + Some((t0 <= t1).then_some(((a.0 + d.0 * t0, a.1 + d.1 * t0), (a.0 + d.0 * t1, a.1 + d.1 * t1)))) } /// Crops a bitmap drawn into `rect` = `[x, y, w, h]` (device, positive extents) to the clip diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs index cf5fd97e9..d0f56f862 100644 --- a/crates/metafile/src/emfplus.rs +++ b/crates/metafile/src/emfplus.rs @@ -28,7 +28,7 @@ use std::sync::Arc; use crate::bytes::Bytes; use crate::canvas::Raw; use crate::canvas::{BS_NULL, BS_SOLID, Brush, Canvas, LogFont, PS_NULL, Pen, RawTile, Xform, hatch_tile, mul}; -use crate::cliprect::{clip_polygon, convex, flatten, ops_bbox, pts_bbox, rect_poly}; +use crate::cliprect::{MAX_AREA_CLIP_WORK, clip_polygon_within, convex, flatten, ops_bbox, pts_bbox, rect_poly}; use crate::dib::Rgba; use crate::geom::{Op, P}; use crate::text::{ETO_CLIPPED, Font}; @@ -1170,7 +1170,13 @@ fn area_of_ops(ops: &[Op]) -> Vec<P> { fn area_intersect(a: Area, b: Area) -> Area { match (a, b) { (None, x) | (x, None) => x, - (Some(a), Some(b)) if a.len() >= 3 && b.len() >= 3 => Some(convex(&clip_polygon(&a, &b)).unwrap_or_default()), + (Some(a), Some(b)) if a.len() >= 3 && b.len() >= 3 => { + // Out of work: keep the area so far rather than call the region empty. + match clip_polygon_within(&a, &b, &mut { MAX_AREA_CLIP_WORK }) { + Some(p) => Some(convex(&p).unwrap_or_default()), + None => Some(a), + } + } _ => Some(Vec::new()), } } diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 29fab81ec..766beddab 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -2071,6 +2071,87 @@ fn emfplus_wrap_line_linear_performance() { fn clip_polygon_work_bound() { let poly: Vec<(f64, f64)> = (0..2000).map(|i| (i as f64, i as f64)).collect(); let clip: Vec<(f64, f64)> = (0..2000).map(|i| (i as f64, i as f64)).collect(); - let clipped = crate::cliprect::clip_polygon(&poly, &clip); - assert!(clipped.is_empty(), "excessive polygon clip product rejected"); + assert!(crate::cliprect::clip_polygon_within(&poly, &clip, &mut 1_000_000).is_none(), "excessive polygon clip product rejected"); +} + +#[test] +fn clip_polygon_charges_actual_work_not_projected_growth() { + // Two convex 1,000-gons: the product is exactly the budget, and a cut that adds a vertex must + // not make a later step look over budget. + let gon = |cx: f64| -> Vec<(f64, f64)> { + (0..1000).map(|i| (i as f64 / 1000.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (cx + 100.0 * c, 100.0 * s)).collect() + }; + let clipped = crate::cliprect::clip_polygon_within(&gon(0.0), &gon(30.0), &mut 4_000_000).unwrap(); + assert!(clipped.len() > 100, "the intersection is kept: {}", clipped.len()); +} + +#[test] +fn clip_work_is_shared_by_fill_and_stroke() { + use crate::canvas::Raw; + use crate::geom::Op; + // One zigzag subpath crossing a 512-gon's edge: about 510k point-edge tests per pass, so a + // fill alone fits the allowance but a fill plus a stroke would spend it twice. + let clip: Vec<(f64, f64)> = + (0..512).map(|i| (i as f64 / 512.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (100.0 + 100.0 * c, 100.0 + 100.0 * s)).collect(); + let mut ops = vec![Op::M((0.0, 95.0))]; + ops.extend((1..1000).map(|i| Op::L((i as f64 * 0.19, if i % 2 == 0 { 95.0 } else { 300.0 })))); + ops.push(Op::Z); + let raw = |fill, stroke| Raw::Path { ops: ops.clone(), fill, stroke, even_odd: false, region: None }; + let black = [0, 0, 0, 255]; + assert!(!crate::cliprect::clip_raw(raw(Some(black), None), &clip).is_empty(), "a fill alone is within the allowance"); + assert!(crate::cliprect::clip_raw(raw(Some(black), Some((black, 1.0))), &clip).is_empty(), "fill and stroke share one allowance"); +} + +#[test] +fn clip_work_is_bounded_across_subpaths() { + use crate::canvas::Raw; + use crate::geom::Op; + // 512-gon clip; 4,000 small triangles crossing its edge: each under the per-polygon cap, together + // far over it, for both the fill and the stroke. + let clip: Vec<(f64, f64)> = + (0..512).map(|i| (i as f64 / 512.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (100.0 + 100.0 * c, 100.0 + 100.0 * s)).collect(); + let tri = |x: f64| [Op::M((x, 95.0)), Op::L((x + 1.0, 95.0)), Op::L((x, 300.0)), Op::Z]; + let many: Vec<Op> = (0..4000).flat_map(|i| tri(i as f64 % 200.0)).collect(); + let raw = |ops| Raw::Path { ops, fill: Some([0, 0, 0, 255]), stroke: Some(([0, 0, 0, 255], 1.0)), even_odd: false, region: None }; + assert!(crate::cliprect::clip_raw(raw(many), &clip).is_empty(), "the whole item's clipping work is bounded"); + assert_eq!(crate::cliprect::clip_raw(raw(tri(100.0).to_vec()), &clip).len(), 2, "a small crossing shape is still clipped"); +} + +/// Clipping a fill can add a vertex at every clip edge, so a polygon's work isn't its input size: +/// shapes that pass the up-front estimate but grow while clipped are charged as they grow, against +/// one budget for the whole item. +#[test] +fn growing_fill_clips_share_one_budget() { + use crate::canvas::Raw; + use crate::geom::Op; + let clip: Vec<(f64, f64)> = + (0..512).map(|i| (i as f64 / 512.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (100.0 + 100.0 * c, 100.0 + 100.0 * s)).collect(); + // A triangle around the whole circle: clipped, it becomes the 512-gon, about 130,000 steps. + let tri = [Op::M((-1000.0, -1000.0)), Op::L((1000.0, -1000.0)), Op::L((100.0, 1000.0)), Op::Z]; + let raw = |n: usize| Raw::Path { ops: tri.repeat(n), fill: Some([0, 0, 0, 255]), stroke: None, even_odd: false, region: None }; + // 400 of them pass the estimate (400 x 4 x 512 is under a million) but cost about 52 million. + assert!(crate::cliprect::clip_raw(raw(400), &clip).is_empty(), "the growing work is charged"); + assert_eq!(crate::cliprect::clip_raw(raw(2), &clip).len(), 1, "a couple of them are still clipped"); +} + +#[test] +fn stroke_work_is_charged_and_outside_items_are_cheap() { + use crate::canvas::Raw; + use crate::geom::Op; + let clip: Vec<(f64, f64)> = + (0..512).map(|i| (i as f64 / 512.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (100.0 + 100.0 * c, 100.0 + 100.0 * s)).collect(); + // A stroke-only zigzag of 4,000 segments across the edge: 4,000 x 512 tests, over the allowance. + let mut ops = vec![Op::M((0.0, 95.0))]; + ops.extend((1..4000).map(|i| Op::L((i as f64 * 0.05, if i % 2 == 0 { 95.0 } else { 300.0 })))); + let raw = Raw::Path { ops, fill: None, stroke: Some(([0, 0, 0, 255], 1.0)), even_odd: false, region: None }; + assert!(crate::cliprect::clip_raw(raw, &clip).is_empty(), "stroke work is bounded"); +} + +#[test] +fn region_intersection_over_budget_keeps_the_previous_area() { + let gon = |cx: f64| -> Vec<(f64, f64)> { + (0..1000).map(|i| (i as f64 / 1000.0 * std::f64::consts::TAU).sin_cos()).map(|(s, c)| (cx + 100.0 * c, 100.0 * s)).collect() + }; + assert!(crate::cliprect::clip_polygon_within(&gon(0.0), &gon(30.0), &mut 10).is_none()); + assert!(crate::cliprect::clip_polygon_within(&gon(0.0), &gon(30.0), &mut crate::cliprect::MAX_AREA_CLIP_WORK.clone()).is_some()); } From e0f3639e94e82bf41b532ac3a495342ccfc4d95f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 03:44:11 -0500 Subject: [PATCH 90/94] Undo: count a slide's notes, comments and tags in the memory budget (#1768) * engine: count a slide's notes, comments and tags in the undo memory budget * engine: drive the undo-budget test through slide.rename * address review: size text cost by the Paragraph and Run struct sizes --- crates/engine/src/lib.rs | 28 +++++++++++++++++++++++++--- crates/engine/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d8ebb5a23..754a64f1e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -824,10 +824,32 @@ fn clamp_selection(st: &mut DocState) { /// Default for [`History::byte_limit`]. pub const UNDO_BYTE_BUDGET: usize = 256 << 20; +/// A rough size of a text body in memory: its paragraphs and runs, at their inline struct sizes. +fn text_cost(t: &deckcraft_model::text::TextBody) -> usize { + use deckcraft_model::text::{Paragraph, Run}; + let (para, run) = (std::mem::size_of::<Paragraph>(), std::mem::size_of::<Run>()); + t.paragraphs.iter().map(|p| para + p.runs.iter().map(|r| run + r.text.len()).sum::<usize>()).sum() +} + +/// A rough size of comments in memory, replies included. +fn comments_cost(cs: &[deckcraft_model::Comment], depth: usize) -> usize { + let kids = |c: &deckcraft_model::Comment| if depth < 64 { comments_cost(&c.replies, depth + 1) } else { 0 }; + cs.iter().map(|c| 256 + c.author.len() + c.initials.len() + c.text.len() + c.date.len() + kids(c)).sum() +} + +/// A rough size of a slide's own data besides its shapes: notes, comments, tags and kept XML, +/// all copied with the slide when an edit changes it. +fn slide_extra_cost(s: &deckcraft_model::Slide) -> usize { + text_cost(&s.notes) + + comments_cost(&s.comments, 0) + + s.name.len() + + s.tags.iter().map(|(k, v)| 48 + k.len() + v.len()).sum::<usize>() + + s.raw_ext.as_ref().map_or(0, String::len) +} + /// A rough size of a shape in memory: the struct, its text and kept XML, its children. fn shape_cost(sh: &deckcraft_model::Shape, depth: usize) -> usize { - let text: usize = - sh.text.as_ref().map_or(0, |t| t.paragraphs.iter().map(|p| 96 + p.runs.iter().map(|r| 128 + r.text.len()).sum::<usize>()).sum()); + let text: usize = sh.text.as_ref().map_or(0, text_cost); let kids: usize = if depth < 64 { sh.children().iter().map(|c| shape_cost(c, depth + 1)).sum() } else { 0 }; 768 + text + sh.raw_ext.as_ref().map_or(0, String::len) + kids } @@ -845,7 +867,7 @@ pub fn undo_cost(doc: &Presentation, newer: &Presentation) -> usize { let media: HashSet<*const Vec<u8>> = newer.media.iter().map(|m| Arc::as_ptr(&m.data)).collect(); let mut n = 64 * doc.slides.len(); for s in doc.slides.iter().filter(|s| !slides.contains(&Arc::as_ptr(s))) { - n += 512 + shapes_cost(&s.shapes); + n += 512 + shapes_cost(&s.shapes) + slide_extra_cost(s); } for m in doc.masters.iter().filter(|m| !masters.contains(&Arc::as_ptr(m))) { n += 4096 + shapes_cost(&m.shapes) + m.layouts.iter().map(|l| 512 + shapes_cost(&l.shapes)).sum::<usize>(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8b1841675..4cdff41ff 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3745,6 +3745,25 @@ fn undo_history_is_capped_by_memory_as_well_as_steps() { assert_eq!(s.doc().unwrap().history.undo.len(), 120); } +/// A slide's notes count toward the undo budget: small edits to a slide with large notes keep a +/// copy of those notes per step, and must not slip past the budget as if the slide were empty. +#[test] +fn undo_history_counts_slide_notes() { + let mut s = Session::with_new(); + let notes = "n".repeat(1 << 20); + s.edit(|doc, _| { + std::sync::Arc::make_mut(&mut doc.slides[0]).notes = deckcraft_model::text::TextBody::from_text(¬es); + Ok(()) + }) + .unwrap(); + s.doc_mut().unwrap().history = History { limit: 500, byte_limit: 8 << 20, ..Default::default() }; + for i in 0..40 { + s.execute("slide.rename", &json!({"name": format!("v{i}"), "index": 0})).unwrap(); + } + let n = s.doc().unwrap().history.undo.len(); + assert!((1..=8).contains(&n), "{n} steps of 1 MB notes kept under an 8 MB budget"); +} + #[test] fn picture_styles_replace_each_other_in_one_step() { const PNG: &[u8] = &[ From c532ae749b35c29afd059599c4a666155563ffb8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 03:52:36 -0500 Subject: [PATCH 91/94] Logging: escape control characters and mark continuation lines in log records (#1791) --- apps/deckcraft/src/logging.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/apps/deckcraft/src/logging.rs b/apps/deckcraft/src/logging.rs index f2cbae0d2..fed5d503e 100644 --- a/apps/deckcraft/src/logging.rs +++ b/apps/deckcraft/src/logging.rs @@ -148,7 +148,19 @@ pub fn rotate(dir: &Path) -> std::io::Result<(PathBuf, File)> { /// One formatted log line: `<timestamp> <LEVEL> [<thread>] <target>: <message>\n`. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); - format!("{ts} {level:<5} [{thread}] {target}: {message}\n") + // Messages can embed document-controlled text (a part name, a relationship id): control + // characters other than tab are escaped and each continuation line is marked, so such text + // cannot start a line that looks like a record of its own. + let mut text = String::with_capacity(message.len()); + for c in message.chars() { + match c { + '\n' => text.push_str("\n | "), + '\t' => text.push(c), + c if c.is_control() => text.extend(c.escape_default()), + c => text.push(c), + } + } + format!("{ts} {level:<5} [{thread}] {target}: {text}\n") } /// Where formatted lines go besides standard error: kept in memory until a file is attached, @@ -446,8 +458,13 @@ mod tests { ), "2026-10-08T07:59:17.728Z WARN [main] deckcraft_pptx::opc: pptx: skipping oversized part ppt/media/image1.png\n" ); - // A multi-line message keeps its lines; the record still ends in exactly one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + // A multi-line message keeps its lines, each continuation marked; the record still ends in + // exactly one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n | b\n")); + // Injected line breaks and escape sequences cannot forge a record. + let line = format_line("t", log::Level::Warn, "w", "x", "part a\r\n2026 ERROR [m] y: forged\x1b[2J"); + assert_eq!(line.matches('\n').count(), 2); + assert!(!line.contains('\r') && !line.contains('\x1b')); } #[test] From e3e218a8fc9835c2c88c5f9cf48025d64d5caa1d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 04:00:58 -0500 Subject: [PATCH 92/94] Shape edits: edit each target once and read its box without copying it (#1769) * engine: edit each target shape once and read its box without copying it * engine: check the fill colour field in the repeated-ids test * Apply review fixes - crates/engine/src/tests.rs * address review: shape.lock skips targets inside a targeted group * address review: dedupe shape.lock targets before walking groups --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/engine/src/cmd.rs | 18 +++++++++++------- crates/engine/src/cmd/selection_tests.rs | 8 ++++++++ crates/engine/src/cmd/shape.rs | 19 +++++++++++++++++++ crates/engine/src/tests.rs | 12 ++++++++++++ 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 6f20c4143..e3a50f689 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -466,22 +466,26 @@ fn ctx_xfrm(doc: &deckcraft_model::Presentation, sel: &crate::Selection, shape: /// Run `f` on each target shape (copy-on-write), materialising inherited boxes first. pub(crate) fn edit_shapes(s: &mut Session, p: &Value, cmd: &str, f: impl Fn(&mut deckcraft_model::Shape) -> Result<()>) -> Result<Value> { - let ids = targets(s, p)?; + let mut ids = targets(s, p)?; if ids.is_empty() { return Err(bad(cmd, "no shapes selected")); } + // A shape named twice is edited once. + let mut seen = std::collections::HashSet::new(); + ids.retain(|id| seen.insert(*id)); s.edit(|doc, sel| { - let boxes: Vec<(ShapeId, Xfrm)> = { - let st_shapes: Vec<deckcraft_model::Shape> = - ids.iter().filter_map(|id| current_shapes(doc, sel).and_then(|v| deckcraft_model::find_shape(v, *id)).cloned()).collect(); - st_shapes.iter().map(|sh| (sh.id, xfrm_of(doc, sel, sh))).collect() - }; + // The boxes are read from the shapes in place: no copy of a shape (and its text) per id. + let boxes: std::collections::HashMap<ShapeId, Xfrm> = ids + .iter() + .filter_map(|id| current_shapes(doc, sel).and_then(|v| deckcraft_model::find_shape(v, *id))) + .map(|sh| (sh.id, xfrm_of(doc, sel, sh))) + .collect(); let shapes = crate::shapes_mut(doc, sel).ok_or_else(|| bad(cmd, "no slide"))?; let mut n = 0; for id in &ids { if let Some(sh) = deckcraft_model::find_shape_mut(shapes, *id) { if sh.xfrm.is_none() { - sh.xfrm = boxes.iter().find(|(i, _)| i == id).map(|(_, x)| *x); + sh.xfrm = boxes.get(id).copied(); } f(sh)?; n += 1; diff --git a/crates/engine/src/cmd/selection_tests.rs b/crates/engine/src/cmd/selection_tests.rs index e4e2494b4..07bed2d97 100644 --- a/crates/engine/src/cmd/selection_tests.rs +++ b/crates/engine/src/cmd/selection_tests.rs @@ -135,6 +135,14 @@ fn eye_show_all_and_hide_all() { assert!(!flags(&s, a).0 && flags(&s, g).0 && flags(&s, e).0); } +#[test] +fn lock_group_with_its_child_targeted_leaves_child_locked() { + let (mut s, ids) = deck(); + let (d, g) = (ids[3], ids[7]); + s.execute("shape.lock", &json!({"ids": [g, d, d]})).unwrap(); + assert!(flags(&s, g).1 && flags(&s, d).1); +} + #[test] fn lock_cascades_through_groups_and_undoes() { let (mut s, ids) = deck(); diff --git a/crates/engine/src/cmd/shape.rs b/crates/engine/src/cmd/shape.rs index 78b6204bb..b7b3d3f05 100644 --- a/crates/engine/src/cmd/shape.rs +++ b/crates/engine/src/cmd/shape.rs @@ -374,6 +374,25 @@ fn visible(s: &mut Session, p: &Value) -> Result<Value> { /// (a child can still be unlocked on its own afterwards), as PowerPoint does. fn lock(s: &mut Session, p: &Value) -> Result<Value> { let v = bool_param(p, "locked"); + // A targeted shape inside another targeted group is reached through the group: editing it again + // would toggle it back. + let mut ids = super::targets(s, p)?; + if ids.len() > 1 { + let doc = s.doc()?; + // Walk each distinct group once, however often `ids` repeats it. + let mut once = std::collections::HashSet::new(); + ids.retain(|id| once.insert(*id)); + let mut inside = std::collections::HashSet::new(); + for id in &ids { + if let Some(g) = doc.shape(*id) { + deckcraft_model::walk(g.children(), &mut |c, _| { + inside.insert(c.id); + }); + } + } + ids.retain(|id| !inside.contains(id)); + } + let p = &json!({"ids": ids, "locked": p.get("locked")}); edit_shapes(s, p, "shape.lock", |sh| { let to = v.unwrap_or(!sh.locked); set_locked(sh, to, 0); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4cdff41ff..4f40b2dfb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6921,6 +6921,18 @@ fn master_body_placeholder_format_keeps_per_level_formatting() { assert_eq!(shown(&s), vec![Some(28.0), Some(24.0)]); } +/// A shape named many times in one edit is edited once and not copied per mention. +#[test] +fn repeated_target_ids_edit_the_shape_once() { + let mut s = session(); + let r = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 300, 100], "text": "x".repeat(100_000)})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let edited = s.execute("shape.fill", &json!({"ids": vec![id; 50_000], "color": "#ff0000"})).unwrap(); + assert_eq!(edited, json!(1)); + let v = s.execute("shape.inspect", &json!({"id": id})).unwrap(); + assert_eq!(v["shape"]["fill"]["color"]["base"]["rgb"], json!({"a": 255, "b": 0, "g": 0, "r": 255})); +} + #[test] fn many_distinct_fonts_are_listed_once_each_without_a_quadratic_scan() { // 30,000 runs in 15,000 families, each written twice in different case. From 7bd141c1c9a4d770d585358a0dcb4f392fd6e35f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 04:07:19 -0500 Subject: [PATCH 93/94] xtask: match attribution globs with a table, not backtracking (#1797) --- xtask/src/assets.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/xtask/src/assets.rs b/xtask/src/assets.rs index a7169ee66..da7371b8e 100644 --- a/xtask/src/assets.rs +++ b/xtask/src/assets.rs @@ -61,16 +61,23 @@ pub fn missing(files: &[String], assets_md: &str) -> Vec<String> { files.iter().filter(|f| is_asset(f) && !patterns.iter().any(|p| glob(p, f))).cloned().collect() } -/// `*` matches any run of characters except `/`; everything else literally. +/// `*` matches any run of characters except `/`; everything else literally. Matched with a +/// table over the pattern, so a pattern with many `*` costs pattern length times name length +/// rather than exploring every way to split the name. fn glob(pat: &str, s: &str) -> bool { - match pat.split_once('*') { - None => pat == s, - Some((head, tail)) => { - let Some(rest) = s.strip_prefix(head) else { return false }; - let ends = rest.char_indices().map(|(i, _)| i).chain(std::iter::once(rest.len())); - ends.take_while(|&i| !rest[..i].contains('/')).any(|i| glob(tail, &rest[i..])) + let t: Vec<char> = s.chars().collect(); + // `row[k]`: the pattern so far matches the first k characters of the name. + let mut row = vec![false; t.len() + 1]; + row[0] = true; + for pc in pat.chars() { + let mut next = vec![false; t.len() + 1]; + next[0] = pc == '*' && row[0]; + for k in 1..=t.len() { + next[k] = if pc == '*' { row[k] || (next[k - 1] && t[k - 1] != '/') } else { row[k - 1] && t[k - 1] == pc }; } + row = next; } + row[t.len()] } /// Splits `git ls-files -z` output into real file names (no display quoting of Unicode or special characters). @@ -120,6 +127,15 @@ mod tests { assert_eq!(missing(&["assets/é.png".into()], "`assets/*.svg`"), vec!["assets/é.png".to_string()]); } + #[test] + fn many_wildcards_on_a_failing_name_finish_at_once() { + let pat = format!("{}b", "a*".repeat(40)); + assert!(!glob(&pat, &"a".repeat(60))); + assert!(glob(&pat, &format!("{}b", "a".repeat(60)))); + assert!(!glob("a*b", "a/b")); + assert!(glob("a*b", "ab")); + } + #[test] fn ls_files_output_is_nul_separated_and_unquoted() { let names = parse_ls_files("assets/zażółć.png\0docs/images/a b\nc.png\0".as_bytes()); From a55457ee53d23628c3df77095cf19840d634a25e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Wed, 11 Nov 2026 04:16:05 -0500 Subject: [PATCH 94/94] Spelling: stop an affix header's count at the end of the file, share aliased dictionaries (#1794) * Spelling: stop an affix header's count at the end of the file, share aliased dictionaries * address review: share the first inserted dictionary on a concurrent load --- crates/engine/src/spell.rs | 43 +++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/spell.rs b/crates/engine/src/spell.rs index ee76ff89c..3323151cb 100644 --- a/crates/engine/src/spell.rs +++ b/crates/engine/src/spell.rs @@ -171,7 +171,9 @@ impl Dictionary { ["COMPOUNDWORDMAX", n, ..] => d.compound_max = n.parse().unwrap_or(0), ["REP", n] => { for _ in 0..n.parse::<usize>().unwrap_or(0) { - let r: Vec<&str> = lines.next().unwrap_or("").split_whitespace().collect(); + // The count is the file's claim: stop when the records run out. + let Some(line) = lines.next() else { break }; + let r: Vec<&str> = line.split_whitespace().collect(); if let [_, a, b, ..] = r.as_slice() { d.rep.push((a.replace('_', " "), b.replace('_', " "))); } @@ -182,7 +184,8 @@ impl Dictionary { let Some(flag) = one_flag(Some(flag), mode) else { continue }; let cross = cross.eq_ignore_ascii_case("y"); for _ in 0..n.parse::<usize>().unwrap_or(0) { - let r: Vec<&str> = lines.next().unwrap_or("").split_whitespace().collect(); + let Some(line) = lines.next() else { break }; + let r: Vec<&str> = line.split_whitespace().collect(); let [_, _, strip, add, rest @ ..] = r.as_slice() else { continue }; let (add, cont) = match add.split_once('/') { Some((a, c)) => (a, parse_flags(c, mode)), @@ -582,6 +585,15 @@ fn cache() -> &'static Cache { CACHE.get_or_init(Default::default) } +/// Language strings remembered by [`dictionary`]; a string past it is resolved again on each call. +const MAX_CACHED_LANGS: usize = 256; + +/// Parsed dictionaries by their affix file, so aliases of one language share it. +fn by_files() -> &'static Mutex<HashMap<PathBuf, Arc<Dictionary>>> { + static M: OnceLock<Mutex<HashMap<PathBuf, Arc<Dictionary>>>> = OnceLock::new(); + M.get_or_init(Default::default) +} + /// The dictionary for `lang` (a BCP-47 tag such as `en-US`), loaded once per process. pub fn dictionary(lang: &str) -> Option<Arc<Dictionary>> { let cache = cache(); @@ -592,10 +604,23 @@ pub fn dictionary(lang: &str) -> Option<Arc<Dictionary>> { return d.clone(); } let loaded = find_in(&search_dirs(), lang).and_then(|(a, d)| { - let (a, d) = (std::fs::read(a).ok()?, std::fs::read(d).ok()?); - Some(Arc::new(Dictionary::parse(&a, &d))) + // Tags that resolve to the same files share one parsed dictionary. + if let Ok(m) = by_files().lock() + && let Some(dict) = m.get(&a) + { + return Some(dict.clone()); + } + let (bytes_a, bytes_d) = (std::fs::read(&a).ok()?, std::fs::read(d).ok()?); + let dict = Arc::new(Dictionary::parse(&bytes_a, &bytes_d)); + // A concurrent loader of the same files may have inserted first: share its copy. + if let Ok(mut m) = by_files().lock() { + return Some(m.entry(a).or_insert(dict).clone()); + } + Some(dict) }); - if let Ok(mut c) = cache.lock() { + if let Ok(mut c) = cache.lock() + && c.len() < MAX_CACHED_LANGS + { c.insert(key, loaded.clone()); } loaded @@ -903,6 +928,14 @@ SFX D Y 1\nSFX D 0 ed/S .\n"; assert!(d.suggest("workingslides", 5).contains(&"working slides".to_string())); } + /// An affix header can claim billions of records; parsing stops where the file does. + #[test] + fn a_header_count_past_the_records_ends_with_them() { + let aff = b"SFX S Y 4000000000\nSFX S 0 s .\nREP 4000000000\nREP a b\n"; + let d = Dictionary::parse(aff, b"1\ncat/S\n".as_slice()); + assert!(d.check("cats")); + } + /// #1175: compound splitting is quadratic in the word's length, so a word longer than /// `MAX_CHECK_CHARS` is not checked; shorter ones still are. #[test]