From a97bd20a688f12c7107f239608f6d5ef76b7a4c1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:05:01 +0200 Subject: [PATCH 001/328] Cargo.lock: main's, with #500's designcraft-images dependency of idml --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index afd57fddd..90c55cc62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -997,6 +997,7 @@ dependencies = [ "log", "quick-xml", "regex", + "same-file", "serde", "serde_json", "tempfile", From c708b080333751bb5711638caa8f2a319394f81f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:47:56 +0200 Subject: [PATCH 002/328] Compose: a line past the breaker's estimated wrap segments is re-broken for its segment On narrow segments beside an object, the breaker's estimate of the segments ran out; the lines after it were set for the whole column and placed in one segment, running across the object. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/lib.rs | 4 +++- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index afabb6fad..bdec0b163 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1268,7 +1268,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // paragraph from here, starting with this line's segments as they are. A pass // re-breaks at its first line only for a new line, whose segments it carries, so // every re-break makes progress; their number is capped too. - if (k > 0 || !continues) && rebreaks < 256 && slots.get(k).is_some_and(|&(a, b)| ((b - a) - (x1 - x0)).abs() > 0.5) { + // Past the estimated slots the breaker set the line for the whole column. + let (sa, sb) = slots.get(k).copied().unwrap_or((col.x0, col.x1)); + if (k > 0 || !continues) && rebreaks < 256 && ((sb - sa) - (x1 - x0)).abs() > 0.5 { rebreaks += 1; carry.insert(0, (x0, x1)); if !continues { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index dd038caa5..8e1999ddd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1155,3 +1155,28 @@ fn a_line_fits_when_its_baseline_does() { assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame"); assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } + + +/// Beside an object with text on both sides, every line stays within its segment, however many +/// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a +/// line it set for the whole column ran across the object). +#[test] +fn every_line_beside_a_wrap_stays_within_its_segment() { + let mut s = Session::new(); + s.execute("file.new", &json!({"facingPages": false})).unwrap(); + // Placeholder text: paragraphs of a few sentences, some of them starting beside the object. + let t = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "text", "text": ""})).unwrap(); + s.execute("type.fillWithPlaceholder", &json!({})).unwrap(); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + s.execute("frame.create", &json!({"rect": [196, 160, 416, 490]})).unwrap(); + s.execute("object.textWrap", &json!({"mode": "boundingBox", "offset": 6})).unwrap(); + let d = &s.doc().unwrap().doc; + let c = s.cache.get(d, designcraft_doc::StoryId(t["story"].as_u64().unwrap()), None); + let mut beside = 0; + for l in c.frames.iter().flat_map(|f| &f.lines) { + let end = l.glyphs.iter().filter(|g| g.visible).map(|g| g.x + g.adv).fold(l.x0, f64::max); + assert!(end <= l.x1 + 0.5, "line at {} runs to {end}, past its segment {}..{}", l.baseline, l.x0, l.x1); + beside += usize::from(l.x1 < 400.0 || l.x0 > 400.0); + } + assert!(beside > 20, "lines on both sides of the object: {beside}"); +} From afa015f113239a61e83ad09266ca8d2f38051ec2 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 16 Oct 2026 09:53:40 +0200 Subject: [PATCH 003/328] Text wrap: Alpha Channel contour traced from the image, holes with Include Inside Edges, open gaps kept Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 184 ++++++++++++--- crates/compose/src/tests.rs | 27 +++ crates/doc/src/build.rs | 1 + crates/doc/src/item.rs | 26 ++- crates/doc/src/lib.rs | 23 ++ crates/engine/src/cmd/alpha_wrap.rs | 285 ++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/object.rs | 24 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/tests.rs | 1 - crates/idml/src/export.rs | 6 +- crates/idml/src/import.rs | 2 + crates/idml/src/tests.rs | 7 + crates/render/src/blendspace.rs | 3 + crates/ui-egui/src/i18n.rs | 5 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/panels/mod.rs | 3 + crates/ui-egui/src/panels/properties.rs | 19 +- 25 files changed, 584 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/cmd/alpha_wrap.rs diff --git a/ROADMAP.md b/ROADMAP.md index 2aacdaf9b..739e9bb17 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -347,6 +347,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- 2026-10-16: Text Wrap › Contour › Alpha Channel follows a placed image's transparency, as InDesign's: the outline is traced from the image and follows it when it moves or is refitted; text keeps the open gaps between its parts, and enters enclosed holes with Include Inside Edges. - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change. - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change. - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index bdec0b163..eda488d83 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -369,6 +369,96 @@ impl Contour { } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) } + + /// Occupied intervals across the whole line band, preserving gaps between parts of a + /// concave or compound outline. Project boundary edges and the filled middle slice: any + /// area that starts or ends inside the band is bounded by those projected edges. + fn band_spans(&self, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let (low, high) = (y0 - self.offset, y1 + self.offset); + if !low.is_finite() || !high.is_finite() || high < low { + return self.band_extent(y0, y1).into_iter().collect(); + } + let mut spans = rings_band_spans(&self.rings, low, high); + // Extremely fragmented imported paths use the conservative outer extent, bounding the + // work of subtracting intervals from every line. A traced 128-column mask stays below it. + if spans.len() > 128 { + return self.band_extent(y0, y1).into_iter().collect(); + } + if !self.clip.is_empty() { + let clip = rings_band_spans(&self.clip, low, high); + let mut cut = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { + if a.max(c) < b.min(d) { + cut.push((a.max(c), b.min(d))); + } + if b < d { + i += 1; + } else { + j += 1; + } + } + spans = cut; + } + merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) + } +} + +fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9); + spans.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut out: Vec<(f64, f64)> = Vec::new(); + for (a, b) in spans { + if let Some(last) = out.last_mut().filter(|last| a <= last.1 + 1e-9) { + last.1 = last.1.max(b); + } else { + out.push((a, b)); + } + } + out +} + +fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + let middle = y0 * 0.5 + y1 * 0.5; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); + spans.push((x0.min(x1), x0.max(x1))); + } + if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { + let x = a.x + (middle - a.y) / dy * (b.x - a.x); + if x.is_finite() { + crossings.push((x, if dy > 0.0 { 1i32 } else { -1 })); + } + } + a = b; + } + } + crossings.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut winding = 0i32; + let mut previous = None; + for (x, delta) in crossings { + if winding != 0 + && let Some(start) = previous + { + spans.push((start, x)); + } + winding += delta; + previous = Some(x); + } + merge_spans(spans) } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -431,7 +521,13 @@ fn rings_band_extent(rings: &[Vec], y0: f64, y1: f64) -> Option<(f64, f64 /// The wrap exclusion of `other` (an item whose inner space maps to the spread by `xf`) for a /// frame whose inner space is reached from the spread by `inv`. `left_page` places the object on /// a left page (for the spine sides). -pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, inv: designcraft_geom::Affine, left_page: bool) -> Exclusion { +pub fn exclusion( + doc: &Document, + other: &designcraft_doc::Item, + xf: designcraft_geom::Affine, + inv: designcraft_geom::Affine, + left_page: bool, +) -> Exclusion { let o = other.wrap.offsets; let b = if other.shape == designcraft_doc::Shape::Group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) @@ -452,7 +548,7 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in let contour = matches!(other.wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); return Exclusion { rect, mode: other.wrap.mode, side, contour }; } - let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(other)).and_then( + let contour = (other.wrap.mode == WrapMode::Contour && other.shape != designcraft_doc::Shape::Group).then(|| contour_path(doc, other)).and_then( |(path, frame)| { let c = Contour::of(&path, inv * xf, other.wrap.offsets[0])?; Some(match frame { @@ -466,11 +562,26 @@ pub fn exclusion(other: &designcraft_doc::Item, xf: designcraft_geom::Affine, in } /// The outline a contour wrap follows, in the item's inner space, and for an outline taken from -/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type; -/// detected edges, alpha channels and image paths need the image, so they follow the frame's path -/// (as other frames do). -fn contour_path(it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option) { +/// the placed graphic, the frame path that clips it. Graphic frames follow their contour type. An +/// alpha channel follows the image's traced outline, placed where the graphic is now (so it +/// follows the image when it moves or is refitted); its transparent holes count only with Include +/// Inside Edges. Detected edges and image paths, and an alpha channel not traced (yet), follow the +/// frame's path (as other frames do). +fn contour_path(doc: &Document, it: &designcraft_doc::Item) -> (designcraft_geom::BezPath, Option) { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); + if it.wrap.contour == designcraft_doc::ContourType::AlphaChannel + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, it.wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + { + let to_graphic = designcraft_geom::Affine::scale_non_uniform(g.size.0 / f64::from(o.width), g.size.1 / f64::from(o.height)); + let mut path = o.outer.to_bezpath(); + if it.wrap.inside_edges { + path.extend(o.holes.to_bezpath().iter()); + } + return (g.xf * to_graphic * path, Some(frame)); + } if it.wrap.contour == designcraft_doc::ContourType::BoundingBox && let Some(g) = it.graphic() && let Some(fb) = it.path.bounds() @@ -573,7 +684,7 @@ pub fn frame_specs(doc: &Document, sid: StoryId) -> Vec { .page_at_x(other.bounds().center().x) .and_then(|pi| sp.pages.get(pi)) .is_some_and(|p| p.side == designcraft_doc::PageSide::Left); - let ex = exclusion(other, other.xf, inv, left); + let ex = exclusion(doc, other, other.xf, inv, left); let reach = ex.rect.intersect(item.inner_bounds()); if reach.width() > 0.0 && reach.height() > 0.0 { exclusions.push(ex); @@ -2592,39 +2703,40 @@ fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, size: f64, rtl: bool) let blocked = match ex.mode { WrapMode::JumpToNextColumn if y1 > r.y0 && r.x0 < col.x1 && r.x1 > col.x0 => return vec![], WrapMode::BoundingBox | WrapMode::Contour if overlaps_band => match &ex.contour { - Some(c) => c.band_extent(y0, y1), - None => Some((r.x0, r.x1)), + Some(c) => c.band_spans(y0, y1), + None => vec![(r.x0, r.x1)], }, - _ => None, + _ => Vec::new(), }; - let Some((a, b)) = blocked.filter(|&(a, b)| a < col.x1 && b > col.x0) else { continue }; - cut = true; - // One-sided wraps also block the column on the other side of the object. - let text_left = match ex.side { - WrapSide::LeftSide => Some(true), - WrapSide::RightSide => Some(false), - WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), - WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, - }; - let (a, b) = match text_left { - Some(true) => (a, b.max(col.x1)), - Some(false) => (a.min(col.x0), b), - None => (a, b), - }; - let mut next = Vec::with_capacity(free.len() + 1); - for (fa, fb) in free { - if b <= fa || a >= fb { - next.push((fa, fb)); - continue; - } - if a > fa { - next.push((fa, a)); - } - if b < fb { - next.push((b, fb)); + for (a, b) in blocked.into_iter().filter(|&(a, b)| a < col.x1 && b > col.x0) { + cut = true; + // One-sided wraps also block the column on the other side of the object. + let text_left = match ex.side { + WrapSide::LeftSide => Some(true), + WrapSide::RightSide => Some(false), + WrapSide::LargestArea => Some(r.x0 - col.x0 >= col.x1 - r.x1), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => None, + }; + let (a, b) = match text_left { + Some(true) => (a, b.max(col.x1)), + Some(false) => (a.min(col.x0), b), + None => (a, b), + }; + let mut next = Vec::with_capacity(free.len() + 1); + for (fa, fb) in free { + if b <= fa || a >= fb { + next.push((fa, fb)); + continue; + } + if a > fa { + next.push((fa, a)); + } + if b < fb { + next.push((b, fb)); + } } + free = next; } - free = next; } if !cut { return vec![(col.x0, col.x1)]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d08efe034..9491afb67 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4,6 +4,33 @@ use designcraft_geom::Rect; use super::*; +#[test] +fn contour_intervals_preserve_the_gap_between_legs() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (40.0, 100.0), (30.0, 100.0), (30.0, 20.0), (10.0, 20.0), (10.0, 100.0), (0.0, 100.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 43.0)]); + assert_eq!(c.band_spans(5.0, 15.0), vec![(-3.0, 43.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 35.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(50.0, 60.0), vec![(-3.0, 13.0), (27.0, 38.0)]); +} + +#[test] +fn contour_intervals_cover_the_whole_slanted_line_band() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((0.0, 0.0)); + for p in [(2.0, 0.0), (12.0, 10.0), (10.0, 10.0)] { + path.line_to(p); + } + path.close_path(); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); +} + const LOREM: &str = "Typography is the art and technique of arranging type to make written language legible, readable and appealing when displayed. \ The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing, and letter spacing, and adjusting the space between pairs of letters."; diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index 9fb075553..cc37907bd 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -160,6 +160,7 @@ impl Document { modified: 0, next_id: 0, font_scope: 0, + alpha_outlines: Vec::new(), }; let lid = LayerId(d.alloc()); d.layers.push(Layer { diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 2d2cea760..bfaebe2c2 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -501,7 +501,7 @@ pub enum ContourType { } /// Text Wrap panel settings. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct TextWrap { pub mode: WrapMode, @@ -515,6 +515,30 @@ pub struct TextWrap { /// item transforms it with the path; other path edits keep it as it is. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Contour Options › Include Inside Edges: an Alpha Channel contour also lets text into the + /// transparent holes it encloses (off: holes are blocked with the shape around them). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub inside_edges: bool, + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + pub alpha_threshold: u8, +} + +/// InDesign's default alpha threshold for contour wraps. +pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; + +impl Default for TextWrap { + fn default() -> Self { + TextWrap { + mode: WrapMode::default(), + offsets: [0.0; 4], + invert: false, + side: WrapSide::default(), + contour: ContourType::default(), + path: None, + inside_edges: false, + alpha_threshold: DEFAULT_ALPHA_THRESHOLD, + } + } } /// Frame fitting options (Object → Fitting → Frame Fitting Options). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c0fdc8fe2..47f752322 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -448,6 +448,21 @@ pub struct Asset { pub page: u32, } +/// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the +/// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine +/// traces it again when a document opens. +#[derive(Clone, Debug, PartialEq)] +pub struct AlphaOutline { + pub asset: AssetId, + pub threshold: u8, + pub width: u32, + pub height: u32, + /// The outer boundaries of the visible areas. + pub outer: designcraft_geom::PathData, + /// The boundaries of transparent holes those areas enclose (wound the other way). + pub holes: designcraft_geom::PathData, +} + impl Asset { /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG. pub fn is_raster(&self) -> bool { @@ -501,6 +516,9 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved. + #[serde(skip)] + pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hyperlinks: Vec, @@ -695,6 +713,11 @@ impl Document { if sec.include_prefix { format!("{}{}", sec.prefix, num) } else { num } } + /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. + pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { + self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { self.layers.iter().find(|l| l.id == id) } diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs new file mode 100644 index 000000000..5f4abae58 --- /dev/null +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -0,0 +1,285 @@ +//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels. +//! +//! The outline is traced once per image and threshold, in the image's pixel space, and kept on +//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's +//! current transform, so it follows the image when it is moved, scaled or refitted. +use std::sync::Arc; + +use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode}; +use designcraft_geom::{BezPath, PathData, Point}; + +/// Images larger than this many pixels aren't traced (their contour follows the frame). +const MAX_PIXELS: u64 = 40_000_000; +/// The finest grid an outline is traced on; coarser grids when the outline would be too long. +const MAX_GRID: u32 = 256; +/// Boundary edges an outline may have. +const MAX_EDGES: usize = 1 << 16; + +/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when +/// nothing changed: tracing happens only for an image and threshold not seen before. +pub(crate) fn sync(doc: &mut Document) { + let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + for sp in doc.spreads.iter().chain(doc.parents.iter()) { + for it in &sp.items { + if it.wrap.mode == WrapMode::Contour + && it.wrap.contour == ContourType::AlphaChannel + && let Some(g) = it.graphic() + && !wanted.contains(&(g.asset, it.wrap.alpha_threshold)) + { + wanted.push((g.asset, it.wrap.alpha_threshold)); + } + } + } + if wanted.is_empty() && doc.alpha_outlines.is_empty() { + return; + } + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset)); + for (asset, threshold) in wanted { + if doc.alpha_outline(asset, threshold).is_some() { + continue; + } + let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; + if let Some(o) = trace(&a.data, asset, threshold) { + doc.alpha_outlines.push(Arc::new(o)); + } + } +} + +/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that +/// can't be read, is too large, or has no transparency (its contour is its rectangle). +pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option { + let (w, h) = designcraft_images::pixel_size(data)?; + if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { + return None; + } + let img = designcraft_images::decode_rgba(data)?; + if img.width() != w || img.height() != h { + return None; + } + let mut grid = MAX_GRID; + while grid >= 16 { + let (cols, rows) = (w.min(grid), h.min(grid)); + let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); + if !transparent { + return None; + } + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { + let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); + let path = |rings: &[Vec<(i32, i32)>]| { + let mut p = BezPath::new(); + for ring in rings { + let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy)); + let Some(first) = pts.next() else { continue }; + p.move_to(first); + for q in pts { + p.line_to(q); + } + p.close_path(); + } + PathData::from_bezpath(&p) + }; + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes) }); + } + grid /= 2; + } + None +} + +/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more +/// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image +/// has any transparency. +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { + let mut mask = vec![false; (cols as usize) * (rows as usize)]; + let mut transparent = false; + for (i, px) in rgba.chunks_exact(4).enumerate() { + let alpha = px[3]; + transparent |= alpha < 255; + if alpha > threshold { + let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w)); + let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h)); + if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) { + *c = true; + } + } + } + (mask, transparent) +} + +/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of +/// holes (by winding: each boundary keeps the visible cells on the same side). None when the +/// outline would have more than [`MAX_EDGES`] edges. +#[allow(clippy::type_complexity)] +fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec>, Vec>)> { + use std::collections::BTreeMap; + let visible = |x: i32, y: i32| { + x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false) + }; + let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new(); + let mut count = 0usize; + for y in 0..rows as i32 { + for x in 0..cols as i32 { + if !visible(x, y) { + continue; + } + for (open, a, b) in [ + (!visible(x, y - 1), (x, y), (x + 1, y)), + (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)), + (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)), + (!visible(x - 1, y), (x, y + 1), (x, y)), + ] { + if open { + count += 1; + if count > MAX_EDGES { + return None; + } + edges.entry(a).or_default().push(b); + } + } + } + } + let (mut outer, mut holes) = (Vec::new(), Vec::new()); + while let Some((&start, _)) = edges.first_key_value() { + let mut ring = vec![start]; + let mut at = start; + for _ in 0..=MAX_EDGES { + let next = edges.get_mut(&at).and_then(Vec::pop)?; + if edges.get(&at).is_some_and(Vec::is_empty) { + edges.remove(&at); + } + // Drop the middle of straight runs. + if let [.., a, b] = ring[..] + && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0) + { + ring.pop(); + } + if next == start { + break; + } + ring.push(next); + at = next; + } + // Shoelace in y-down space: positive for outer boundaries, negative for holes. + let area: i64 = ring + .iter() + .zip(ring.iter().cycle().skip(1)) + .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)) + .sum(); + if ring.len() >= 3 { + if area > 0 { outer.push(ring) } else { holes.push(ring) } + } + } + Some((outer, holes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + use crate::Session; + + /// A 64 × 64 PNG: visible where `on(x, y)`. + fn png(on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..64 { + let i = (y * 64 + x) * 4; + pixels[i] = 120; + pixels[i + 3] = if on(x, y) { 255 } else { 0 }; + } + } + designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png() + } + + #[test] + fn traces_outer_boundaries_and_holes_apart() { + // A ring: a square with a square hole. + let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let o = trace(&data, AssetId(1), 25).unwrap(); + assert_eq!((o.width, o.height), (64, 64)); + assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1)); + let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); + assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); + // An opaque image has no alpha outline. + assert!(trace(&png(|_, _| true), AssetId(1), 25).is_none()); + } + + #[test] + fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1); + // Saved and opened again: traced again on open. + let bytes = crate::cmd::file::to_bytes(d); + let back = crate::cmd::file::from_bytes(&bytes).unwrap(); + assert!(back.alpha_outlines.is_empty(), "not saved"); + let st = crate::DocState::new(back, None); + assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open"); + // Wrap off: the outline goes. + s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap(); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); + } + + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no + /// offset, and a caption frame at `caption` with 8 pt "Hi". + fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap(); + s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap(); + s.execute("type.char", &json!({"size": 8})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap(); + (s, image, c["story"].as_u64().unwrap()) + } + + fn overset(s: &Session, story: u64) -> bool { + s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset() + } + + use serde_json::Value; + + /// A caption fits between two legs of a cutout, and the contour follows the image when it's + /// moved within its frame (it isn't a boundary stored where it was traced). + #[test] + fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() { + // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page. + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + assert!(overset(&s, story), "the frame's contour covers the gap"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + // The graphic moved 30 pt right within its frame: its left leg now covers the caption. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(overset(&s, story), "the contour moved with the image"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overset(&s, story)); + } + + /// A hole enclosed by the image stays blocked unless Include Inside Edges is on. + #[test] + fn holes_are_blocked_unless_inside_edges_are_included() { + // A ring: outer 116..212, hole 148..180 on the page. + let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y))); + let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the hole is blocked with the ring around it"); + s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap(); + assert!(!overset(&s, story), "Include Inside Edges lets text into the hole"); + for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] { + assert!(s.execute("object.textWrap", &bad).is_err()); + } + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 0bfb9727c..9147eef0d 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -1,5 +1,6 @@ //! The command registry. Ids follow InDesign's menu structure. +pub(crate) mod alpha_wrap; mod anchored; pub mod anchors; mod articles; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 36bd1dac0..997a209ec 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -584,7 +584,7 @@ pub fn specs() -> Vec { "Text Wrap", ["Window"], Some("Cmd+Alt+W"), - "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side or contour is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping, ids?}; offset or contour drops an imported custom wrap boundary", + "{mode?: none|boundingBox|contour|jumpObject|jumpToNextColumn (boundingBox when absent, unless side, contour, insideEdges or threshold is given: then unchanged), offset?: number|[t,l,b,r], invert?: bool, side?: bothSides|leftSide|rightSide|towardsSpine|awayFromSpine|largestArea, contour?: boundingBox|graphicFrame|sameAsClipping|alphaChannel, insideEdges?: bool (alphaChannel: text may enter transparent holes), threshold?: 0..254 (alphaChannel: pixels more opaque count; default 25), ids?}; offset or contour drops an imported custom wrap boundary", has_selection, text_wrap ), @@ -1523,16 +1523,24 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown side"))?), None => None, }; - // Detected edges, alpha channels and image paths need the image's pixels or paths, which - // composition doesn't read; those types aren't offered. + // Detected edges and image paths need the image's own analysis or paths, which aren't read; + // those types aren't offered. An alpha channel is traced from the image's pixels. let contour = match p.get("contour").map(|v| serde_json::from_value::(v.clone())) { - Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping))) => Some(c), + Some(Ok(c @ (ContourType::BoundingBox | ContourType::GraphicFrame | ContourType::SameAsClipping | ContourType::AlphaChannel))) => Some(c), Some(_) => return Err(bad("object.textWrap", "unsupported contour type")), None => None, }; + let inside_edges = match p.get("insideEdges") { + None => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad("object.textWrap", "`insideEdges` is true or false"))?), + }; + let threshold = match p.get("threshold") { + None => None, + Some(v) => Some(v.as_u64().filter(|t| *t <= 254).ok_or_else(|| bad("object.textWrap", "`threshold` is 0..254"))? as u8), + }; let mode: Option = match p.get("mode") { Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad("object.textWrap", "unknown mode"))?), - None if side.is_some() || contour.is_some() => None, + None if side.is_some() || contour.is_some() || inside_edges.is_some() || threshold.is_some() => None, None => Some(WrapMode::BoundingBox), }; let off = match p.get("offset") { @@ -1560,6 +1568,12 @@ fn text_wrap(s: &mut Session, p: &Value) -> Result { if let Some(c) = contour { i.wrap.contour = c; } + if let Some(v) = inside_edges { + i.wrap.inside_edges = v; + } + if let Some(t) = threshold { + i.wrap.alpha_threshold = t; + } // A custom boundary has the offsets built in and replaces the contour, so setting // either one rebuilds the wrap from the frame. if off.is_some() || contour.is_some() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 745e45647..6fa3daa04 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -131,7 +131,9 @@ impl Drop for FontScope { static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); impl DocState { - pub fn new(doc: Document, path: Option) -> Self { + pub fn new(mut doc: Document, path: Option) -> Self { + // Alpha Channel contour outlines aren't saved: trace them for the document as opened. + crate::cmd::alpha_wrap::sync(&mut doc); let active_layer = doc.default_layer(); let doc = Arc::new(doc); DocState { @@ -589,6 +591,7 @@ impl Session { let r = f(&mut doc, &mut sel)?; crate::cmd::sync_placeholders(&mut doc); crate::cmd::flex::sync(&mut doc); + crate::cmd::alpha_wrap::sync(&mut doc); doc.sync_endnote_story(); st.doc = Arc::new(doc); st.selection = sel; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8e1999ddd..7a305c59f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1156,7 +1156,6 @@ fn a_line_fits_when_its_baseline_does() { assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } - /// Beside an object with text on both sides, every line stays within its segment, however many /// lines the paragraph needs (the breaker's segment estimate can run out on narrow segments; a /// line it set for the whole column ran across the object). diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 4e2c1bef1..ac26f5f85 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -1852,7 +1852,11 @@ impl<'a> Ex<'a> { .attr("Right", num(w.offsets[3]))]) .collect(), ) - .child(El::new("ContourOption").attr("ContourType", names::contour_type_out(w.contour)).attr("IncludeInsideEdges", "false")), + .child( + El::new("ContourOption") + .attr("ContourType", names::contour_type_out(w.contour)) + .attr("IncludeInsideEdges", if w.inside_edges { "true" } else { "false" }), + ), ); match &it.content { Content::Group { items } => { diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index ad6b6447b..6fb042e1b 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -2429,6 +2429,7 @@ impl<'r> Importer<'r> { invert: w.get("Inverse") == Some("true"), side: names::wrap_side_in(w.get("TextWrapSide").unwrap_or("BothSides")), contour: names::contour_type_in(w.find("ContourOption").and_then(|c| c.get("ContourType")).unwrap_or("SameAsClipping")), + inside_edges: w.find("ContourOption").and_then(|c| c.get("IncludeInsideEdges")) == Some("true"), ..TextWrap::default() }; if let Some(o) = w.prop_el("TextWrapOffset") { @@ -2739,6 +2740,7 @@ impl<'r> Importer<'r> { modified: 0, next_id: self.next_id, font_scope: 0, + alpha_outlines: Vec::new(), }; Ok(d) } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index cca7803df..355ec3e7d 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2627,6 +2627,13 @@ fn imports_and_round_trips_text_wrap_side_and_contour_type() { let back = import_idml(&export_idml(&d)).unwrap(); let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone(); assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges)); + assert!(!w.inside_edges); + // An Alpha Channel contour with Include Inside Edges. + d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.item_mut(id).unwrap().wrap.inside_edges = true; + let back = import_idml(&export_idml(&d)).unwrap(); + let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone(); + assert_eq!((w.contour, w.inside_edges), (designcraft_doc::ContourType::AlphaChannel, true)); } /// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 4121831f7..cc861cabc 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -113,6 +113,7 @@ fn same_document(old: &Document, new: &Document) -> bool { modified, next_id, font_scope, + alpha_outlines, } = new; let same_spreads = |a: &[std::sync::Arc], b: &[std::sync::Arc]| { a.len() == b.len() && a.iter().zip(b).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) @@ -124,6 +125,8 @@ fn same_document(old: &Document, new: &Document) -> bool { && old.stories.iter().zip(stories).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) && old.assets.len() == assets.len() && old.assets.iter().zip(assets).all(|((a, x), (b, y))| a == b && std::sync::Arc::ptr_eq(x, y)) + && old.alpha_outlines.len() == alpha_outlines.len() + && old.alpha_outlines.iter().zip(alpha_outlines).all(|(a, b)| std::sync::Arc::ptr_eq(a, b)) && old.title == *title && old.settings == *settings && old.layers == *layers diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 245a6e287..f65158e52 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -58,6 +58,11 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]), ("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]), ("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]), + ( + "Include Inside Edges", + ["Innenkanten einschließen", "Inclure les bords intérieurs", "Incluir bordes interiores", "内側エッジを含める", "包含内边缘"], + ), + ("Alpha Channel", ["Alphakanal", "Couche alpha", "Canal alfa", "アルファチャンネル", "Alpha 通道"]), ( "Bulleted & Numbered Lists", [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index d1dcb7acf..984677f9b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("Include Inside Edges", "تضمين الحواف الداخلية"), ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"), ("Current Page Number", "رقم الصفحة الحالية"), ("Apply Color (,)", "تطبيق اللون (,)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 0f55578b5..d4b2719f6 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("Include Inside Edges", "Innenkanten einschließen"), ("Clear", "Löschen"), ("Duplicate", "Duplizieren"), ("Select All", "Alles auswählen"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 00328ac9f..12f573390 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("Include Inside Edges", "Includi bordi interni"), + ("Alpha Channel", "Canale alfa"), ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"), ("Current Page Number", "Numero di pagina corrente"), ("Apply Color (,)", "Applica colore (,)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index fe9e213e7..8f1c5895a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("Include Inside Edges", "内側エッジを含める"), ("Bulleted & Numbered Lists", "箇条書き"), ("Apply Color (,)", "カラーを適用 (,)"), ("Apply Gradient (.)", "グラデーションを適用 (.)"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b3379c6d7..e540ce17a 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("Include Inside Edges", "შიდა კიდეების ჩართვა"), ("Reverse Path", "ტრაექტორიის შებრუნება"), ("Set Anchor", "საყრდენი წერტილის დაყენება"), ("Clear", "გასუფთავება"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0675a2f66..2cde5eca2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("Include Inside Edges", "Incluir bordas internas"), + ("Alpha Channel", "Canal alfa"), ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"), ("Show Hidden Characters", "Mostrar caracteres ocultos"), ("Current Page Number", "Número da página atual"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 8f1d27f84..824086772 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("Include Inside Edges", "Включити внутрішні краї"), + ("Alpha Channel", "Альфа-канал"), ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"), ("Current Page Number", "Номер поточної сторінки"), ("Apply Color (,)", "Застосувати колір (,)"), diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index fa40f5bec..54216f83f 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -51,6 +51,8 @@ pub struct SelInfo { pub wrap_offsets: [f64; 4], pub wrap_side: String, pub wrap_contour: String, + /// Contour Options › Include Inside Edges (an Alpha Channel contour). + pub wrap_inside_edges: bool, pub locked: bool, } @@ -161,6 +163,7 @@ pub fn sel_info(app: &DesignApp) -> Option { wrap_offsets: first.wrap.offsets, wrap_side: serde_json::to_value(first.wrap.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), wrap_contour: serde_json::to_value(first.wrap.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), + wrap_inside_edges: first.wrap.inside_edges, locked: first.locked, }) } diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 8cbaa2ea6..0b5f3fd62 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1903,11 +1903,22 @@ pub fn wrap_panel(app: &mut DesignApp, ui: &mut egui::Ui) { ]; wrap_combo(app, ui, "wrap_side", "Wrap To", &sides, &[], &i.wrap_side, "side"); if i.wrap == "contour" && i.is_graphic { - // Detected edges, alpha channels and image paths aren't offered: composition doesn't read - // the image. An imported one shows by name and wraps around the frame. - let types = [("boundingBox", "Bounding Box"), ("graphicFrame", "Graphic Frame"), ("sameAsClipping", "Same as Clipping")]; - let shown_only = [("detectEdges", "Detect Edges"), ("alphaChannel", "Alpha Channel"), ("photoshopPath", "Photoshop Path")]; + // Detected edges and image paths aren't offered: they need the image's own analysis or + // paths. An imported one shows by name and wraps around the frame. + let types = [ + ("boundingBox", "Bounding Box"), + ("alphaChannel", "Alpha Channel"), + ("graphicFrame", "Graphic Frame"), + ("sameAsClipping", "Same as Clipping"), + ]; + let shown_only = [("detectEdges", "Detect Edges"), ("photoshopPath", "Photoshop Path")]; wrap_combo(app, ui, "wrap_contour", "Contour Type", &types, &shown_only, &i.wrap_contour, "contour"); + if i.wrap_contour == "alphaChannel" { + let mut inside = i.wrap_inside_edges; + if widgets::checkbox(ui, &mut inside, crate::i18n::tr(&app.ui.language, "Include Inside Edges")).changed() { + let _ = app.run("object.textWrap", json!({"insideEdges": inside})); + } + } } } From 10134b6f29c3ca3d0c69d4f25ec02bf9f12f12b1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Tue, 20 Oct 2026 16:49:15 +0200 Subject: [PATCH 004/328] PR-1084: trace outlines for graphic and nested wraps, and again after a relink Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/lib.rs | 22 +++++++- crates/engine/src/cmd/alpha_wrap.rs | 84 ++++++++++++++++++++++++----- 2 files changed, 92 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2c4ecb52c..a5fec91c3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -604,7 +604,7 @@ impl PdfCrop { /// The outline of a raster image's visible pixels (Text Wrap › Contour › Alpha Channel), in the /// image's pixel space (0..width, 0..height). Derived from the image, so not saved: the engine /// traces it again when a document opens. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug)] pub struct AlphaOutline { pub asset: AssetId, pub threshold: u8, @@ -614,6 +614,26 @@ pub struct AlphaOutline { pub outer: designcraft_geom::PathData, /// The boundaries of transparent holes those areas enclose (wound the other way). pub holes: designcraft_geom::PathData, + /// The image data it was traced from: a relink or link update replaces the asset's data + /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image + /// data alive, and its address can't be reused by new data while it's held.) + pub source: std::sync::Weak>, +} + +impl AlphaOutline { + /// Traced from `data`, the asset's current image data. + pub fn traced_from(&self, data: &Arc>) -> bool { + std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) + } +} + +impl PartialEq for AlphaOutline { + fn eq(&self, other: &Self) -> bool { + (self.asset, self.threshold, self.width, self.height) == (other.asset, other.threshold, other.width, other.height) + && self.outer == other.outer + && self.holes == other.holes + && self.source.ptr_eq(&other.source) + } } impl Asset { diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index ea94aaf9f..717ae8ac5 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -20,20 +20,25 @@ const MAX_EDGES: usize = 1 << 16; pub(crate) fn sync(doc: &mut Document) { let mut wanted: Vec<(AssetId, u8)> = Vec::new(); for sp in doc.spreads.iter().chain(doc.parents.iter()) { - for it in &sp.items { - if it.wrap.mode == WrapMode::Contour - && it.wrap.contour == ContourType::AlphaChannel - && let Some(g) = it.graphic() - && !wanted.contains(&(g.asset, it.wrap.alpha_threshold)) - { - wanted.push((g.asset, it.wrap.alpha_threshold)); - } + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or + // on its placed graphic (Direct Selection sets the graphic's). + for top in &sp.items { + top.walk(&mut |it| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { + wanted.push((g.asset, w.alpha_threshold)); + } + } + }); } } if wanted.is_empty() && doc.alpha_outlines.is_empty() { return; } - doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && doc.assets.contains_key(&o.asset)); + // An outline traced from data the asset no longer has (relinked or updated) is traced again. + let assets = &doc.assets; + doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); for (asset, threshold) in wanted { if doc.alpha_outline(asset, threshold).is_some() { continue; @@ -47,7 +52,7 @@ pub(crate) fn sync(doc: &mut Document) { /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that /// can't be read, is too large, or has no transparency (its contour is its rectangle). -pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option { +pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { let (w, h) = designcraft_images::pixel_size(data)?; if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { return None; @@ -78,7 +83,8 @@ pub(crate) fn trace(data: &[u8], asset: AssetId, threshold: u8) -> Option 1, "the frame is nested"); + assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline"); + // A frame placed and grouped before its wrap is set: traced too. + let second = place(&mut s, 400); + let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.group", &json!({"ids": [second, other2]})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2); + // The image data replaced under the same asset, as a relink does: traced again. + let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let narrower = Arc::new(png(|x, _| (24..40).contains(&x))); + s.edit(|d, _| { + let a = d.assets.get(&g.asset).unwrap(); + let mut a = (**a).clone(); + a.data = narrower.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap(); + assert!(o.traced_from(&narrower)); + let b = o.outer.bounds().unwrap(); + assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); + } + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no /// offset, and a caption frame at `caption` with 8 pt "Hi". fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { From 0e57712bba7d405002804049c97980fc37081bf5 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:24:56 +0200 Subject: [PATCH 005/328] Object styles: corner options, and editing a style's fill, stroke and corners MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An object style now carries Corner Options (`corners`, in a rectangle's path order). New styles take them from the selection, applying the style sets them, and IDML reads and writes them as InDesign's Stroke & Corner Options (EnableStrokeAndCornerOptions, TopLeftCornerOption…). style.object.edit changes more than effects: `fill` (a swatch or {swatch, tint}), `stroke` (fields merged over the style's), `corners` ({shape, size} or four corners), null to stop setting one, and `rename` (every use follows; built-in names and names in use are refused). Items using the style follow each changed attribute while they have the style's value; overridden ones keep theirs. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/doc/src/styles.rs | 9 +- crates/engine/src/cmd/style.rs | 182 +++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 49 +++++++++ crates/idml/src/export.rs | 7 ++ crates/idml/src/import.rs | 6 +- crates/idml/src/tests.rs | 5 + 7 files changed, 236 insertions(+), 23 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a7b5105d3..b1199ed8f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-21** · Object styles carry Corner Options (`corners`), taken from the selection by `style.object.create` and written to IDML (`EnableStrokeAndCornerOptions`, `TopLeftCornerOption`…). `style.object.edit` also changes a style's fill, stroke and corners and renames it (`rename`); the items using the style that haven't overridden an attribute follow each change, as in InDesign. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. - **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change. diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 5c747fdbf..380f0fd3a 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -1,5 +1,6 @@ //! Paragraph, character and object styles with based-on inheritance. +use designcraft_geom::corners::CornerOptions; use serde::{Deserialize, Serialize}; use crate::attrs::{CharAttrs, CharProps, ParaAttrs, ParaProps}; @@ -59,11 +60,17 @@ pub struct ObjectStyle { /// effects differ from the style's (a local override). #[serde(skip_serializing_if = "Option::is_none")] pub effects: Option, + /// Corner Options (Stroke & Corner Options): each corner's shape and size, in path order. + #[serde(skip_serializing_if = "Option::is_none")] + pub corners: Option, } impl ObjectStyle { - /// Gives `it` the fill, stroke, effects and text frame options this style sets. + /// Gives `it` the fill, stroke, corners, effects and text frame options this style sets. pub fn apply_to(&self, it: &mut Item) { + if let Some(c) = self.corners { + it.corners = c; + } if let Some(f) = &self.fill { it.fill = f.clone(); } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index d1bd06ad0..e0eee77b9 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -359,7 +359,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, effects and text frame options of the first selected item), fill?, paragraphStyle?, effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?, effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects match the style's (no effects, when the style set none) take the new effects, items with their own effects keep them → {name, updated}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them → {name, updated}", has_doc, edit_object ), @@ -1507,11 +1507,19 @@ fn create_object(s: &mut Session, p: &Value) -> Result { if let Some(it) = &src { os.fill = Some(it.fill.clone()); os.stroke = Some(it.stroke.clone()); + os.corners = Some(it.corners); os.text_frame = it.text_frame().map(|t| t.options.clone()); os.effects = Some(it.effects.clone()); } - if let Some(sw) = str_param(p, "fill") { - os.fill = Some(designcraft_doc::Fill::swatch(sw)); + const CREATE: &str = "style.object.create"; + if let Some(f) = fill_param(CREATE, p, os.fill.as_ref())? { + os.fill = f; + } + if let Some(st) = group_param(CREATE, p, "stroke", os.stroke.as_ref().unwrap_or(&designcraft_doc::Stroke::default()))? { + os.stroke = st; + } + if let Some(c) = corners_param(CREATE, p, os.corners.unwrap_or_default())? { + os.corners = c; } if let Some(ps) = str_param(p, "paragraphStyle") { os.paragraph_style = Some(ps.to_string()); @@ -1527,6 +1535,68 @@ fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// `p[key]`, an attribute group of a style, merged field by field over `base`: `None` when not +/// given, `Some(None)` for null (the style no longer sets it). +fn group_param(cmd: &str, p: &Value, key: &str, base: &T) -> Result>> { + match p.get(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(v @ Value::Object(_)) => { + let mut cur = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; + merge_json(&mut cur, v.clone(), 0); + serde_json::from_value(cur).map(|t| Some(Some(t))).map_err(|e| bad(cmd, format!("{key}: {e}"))) + } + Some(_) => Err(bad(cmd, format!("`{key}` must be an object or null"))), + } +} + +/// `fill`: a swatch name, `{swatch?, tint?}` over `base`, or null. +fn fill_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Fill>) -> Result>> { + if let Some(sw) = p.get("fill").and_then(Value::as_str) { + return Ok(Some(Some(designcraft_doc::Fill::swatch(sw)))); + } + let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()))?; + if let Some(Some(f)) = &fill + && !(f.tint.is_finite() && (0.0..=1.0).contains(&f.tint)) + { + return Err(bad(cmd, "fill tint must be 0–1")); + } + Ok(fill) +} + +/// `corners`: `{shape?, size?}` for all four, `{corners: [{shape, size}] ×4}`, or null. +fn corners_param( + cmd: &str, + p: &Value, + base: designcraft_geom::corners::CornerOptions, +) -> Result>> { + let Some(v) = p.get("corners") else { return Ok(None) }; + if v.is_null() { + return Ok(Some(None)); + } + let o = v.as_object().ok_or_else(|| bad(cmd, "`corners` must be an object or null"))?; + let mut c = if o.contains_key("corners") { + serde_json::from_value::(v.clone()).map_err(|e| bad(cmd, format!("corners: {e}")))? + } else { + base + }; + if let Some(sh) = o.get("shape") { + let shape = serde_json::from_value(sh.clone()).map_err(|e| bad(cmd, format!("corner shape: {e}")))?; + c.corners.iter_mut().for_each(|k| k.shape = shape); + } + if let Some(sz) = o.get("size") { + let size = sz.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, "corner size must be a number"))?; + c.corners.iter_mut().for_each(|k| k.size = size); + } + for k in &mut c.corners { + if !k.size.is_finite() { + return Err(bad(cmd, "corner sizes must be finite")); + } + k.size = k.size.clamp(0.0, 10_000.0); + } + Ok(Some(Some(c))) +} + fn edit_object(s: &mut Session, p: &Value) -> Result { const CMD: &str = "style.object.edit"; let name = str_param(p, "name").ok_or_else(|| bad(CMD, "missing name"))?.to_string(); @@ -1534,34 +1604,104 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("`{name}` can't be edited"))); } let old = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad(CMD, format!("no object style `{name}`")))?; - let effects = if p.get("effects").is_some_and(Value::is_null) { + let mut new = old.clone(); + if p.get("effects").is_some_and(Value::is_null) { if EFFECT_KEYS.iter().any(|k| p.get(k).is_some()) { return Err(bad(CMD, "`effects: null` can't be combined with effect settings")); } - None - } else { - match effects_param(CMD, p, old.effects.as_ref().unwrap_or(&Effects::default()))? { - Some(e) => Some(e), - None => return Ok(json!({"name": name, "updated": 0})), + new.effects = None; + } else if let Some(e) = effects_param(CMD, p, old.effects.as_ref().unwrap_or(&Effects::default()))? { + new.effects = Some(e); + } + if let Some(f) = fill_param(CMD, p, old.fill.as_ref())? { + new.fill = f; + } + if let Some(st) = group_param(CMD, p, "stroke", old.stroke.as_ref().unwrap_or(&designcraft_doc::Stroke::default()))? { + if let Some(st) = &st + && !(st.weight.is_finite() && st.weight >= 0.0 && st.tint.is_finite()) + { + return Err(bad(CMD, "stroke weight must be a number ≥ 0")); } - }; - if effects == old.effects { + new.stroke = st; + } + if let Some(c) = corners_param(CMD, p, old.corners.unwrap_or_default())? { + new.corners = c; + } + let rename = str_param(p, "rename").map(str::trim).filter(|r| *r != name).map(str::to_string); + if let Some(r) = &rename { + let builtin = name.starts_with('[') && name.ends_with(']'); + if builtin || r.is_empty() || (r.starts_with('[') && r.ends_with(']')) { + return Err(bad(CMD, format!("`{name}` can't be renamed to `{r}`"))); + } + if s.doc()?.doc.styles.object_style(r).is_some() { + return Err(bad(CMD, format!("an object style is already named `{r}`"))); + } + new.name = r.clone(); + } + if new == old { return Ok(json!({"name": name, "updated": 0})); } s.edit(|d, _| { let Some(os) = d.styles_mut().object.iter_mut().find(|o| o.name == name) else { return Err(bad(CMD, format!("no object style `{name}`"))); }; - os.effects = effects.clone(); - // An item follows the style while its effects are the style's. When the style didn't set - // effects before, only items without effects of their own follow (the default styles are - // on most frames). - let follows = old.effects.clone().unwrap_or_default(); - let updated = match &effects { - Some(new) => d.update_items(|it| it.object_style == name && it.effects == follows, |it| it.effects = new.clone()), - None => 0, + *os = new.clone(); + if let Some(r) = &rename { + let st = d.styles_mut(); + for o in &mut st.object { + if o.based_on.as_deref() == Some(name.as_str()) { + o.based_on = Some(r.clone()); + } + } + for n in [&mut st.default_text_frame, &mut st.default_graphic_frame] { + if *n == name { + *n = r.clone(); + } + } + d.update_items(|it| it.object_style == name, |it| it.object_style = r.clone()); + } + // An item follows each attribute the style sets while it has the style's value. When the + // style didn't set it before, items with the default follow (the default styles are on + // most frames). An attribute the style no longer sets stays as it is on the items. + let effects = (new.effects != old.effects).then_some(new.effects.clone()).flatten().map(|e| (old.effects.clone().unwrap_or_default(), e)); + let fill = (new.fill != old.fill).then_some(new.fill.clone()).flatten().map(|f| (old.fill.clone().unwrap_or_default(), f)); + let stroke = (new.stroke != old.stroke) + .then_some(new.stroke.clone()) + .flatten() + .map(|f| (old.stroke.clone().unwrap_or_else(designcraft_doc::Stroke::none), f)); + let corners = (new.corners != old.corners).then_some(new.corners).flatten().map(|c| (old.corners.unwrap_or_default(), c)); + let follows = |it: &Item| { + effects.as_ref().is_some_and(|(o, _)| it.effects == *o) + || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) + || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) + || corners.as_ref().is_some_and(|(o, _)| it.corners == *o) }; - Ok(json!({"name": name, "updated": updated})) + let updated = d.update_items( + |it| it.object_style == new.name && follows(it), + |it| { + if let Some((o, n)) = &effects + && it.effects == *o + { + it.effects = n.clone(); + } + if let Some((o, n)) = &fill + && it.fill == *o + { + it.fill = n.clone(); + } + if let Some((o, n)) = &stroke + && it.stroke == *o + { + it.stroke = n.clone(); + } + if let Some((o, n)) = &corners + && it.corners == *o + { + it.corners = *n; + } + }, + ); + Ok(json!({"name": new.name, "updated": updated})) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9aacf469d..47bfcb523 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -685,6 +685,55 @@ fn object_style_effects_follow_the_style_until_overridden() { assert_eq!(s.doc().unwrap().revision, rev); } +/// The course's "Rounded Corner Image, White Stroke" style: made from a frame with rounded corners +/// and a paper stroke, applied to another frame, then edited (a thicker stroke, bigger corners): +/// the frames that follow the style change, one with its own stroke keeps it; a rename follows. +#[test] +fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { + use designcraft_doc::ItemId; + use designcraft_geom::corners::CornerShape; + let mut s = session(); + let frame = |s: &mut Session, x: f64| { + s.execute("frame.create", &json!({"rect": [x, 36, x + 100.0, 136], "content": "graphic"})).unwrap()["id"].as_u64().unwrap() + }; + let item = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().clone(); + let a = frame(&mut s, 36.0); + s.execute("object.cornerOptions", &json!({"shape": "rounded", "size": 18, "ids": [a]})).unwrap(); + s.execute("object.stroke", &json!({"swatch": "[Paper]", "weight": 2.5, "ids": [a]})).unwrap(); + s.execute("selection.set", &json!({"ids": [a]})).unwrap(); + let name = + s.execute("style.object.create", &json!({"name": "Rounded Corner Image, White Stroke"})).unwrap()["name"].as_str().unwrap().to_string(); + let os = s.doc().unwrap().doc.styles.object_style(&name).cloned().unwrap(); + assert_eq!(os.corners.unwrap().corners[0].shape, CornerShape::Rounded); + let (b, c) = (frame(&mut s, 200.0), frame(&mut s, 360.0)); + s.execute("style.object.apply", &json!({"name": name, "ids": [a, b, c]})).unwrap(); + assert_eq!((item(&s, b).corners, item(&s, b).stroke.weight, item(&s, b).stroke.swatch.as_str()), (item(&s, a).corners, 2.5, "[Paper]")); + s.execute("object.stroke", &json!({"weight": 1, "ids": [c]})).unwrap(); + + let r = s.execute("style.object.edit", &json!({"name": name, "stroke": {"weight": 6}, "corners": {"size": 30}})).unwrap(); + assert_eq!(r["updated"], 3); + assert_eq!((item(&s, a).stroke.weight, item(&s, b).stroke.weight, item(&s, c).stroke.weight), (6.0, 6.0, 1.0)); + assert_eq!(item(&s, b).stroke.swatch, "[Paper]"); + assert!(item(&s, c).corners.corners.iter().all(|k| k.shape == CornerShape::Rounded && k.size == 30.0), "corners follow apart from the stroke"); + s.execute("style.object.edit", &json!({"name": name, "fill": "[Black]"})).unwrap(); + assert_eq!(item(&s, b).fill.swatch, "[Black]"); + + // Renamed, the items keep the style; a name in use or a built-in one is refused. + s.execute("style.object.edit", &json!({"name": name, "rename": "Framed"})).unwrap(); + assert_eq!(item(&s, a).object_style, "Framed"); + assert!(s.doc().unwrap().doc.styles.object_style(&name).is_none()); + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); + assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // null: the style stops setting corners, the items keep theirs. + s.execute("style.object.edit", &json!({"name": "Framed", "corners": null})).unwrap(); + assert!(s.doc().unwrap().doc.styles.object_style("Framed").unwrap().corners.is_none()); + assert_eq!(item(&s, a).corners.corners[0].size, 30.0); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(item(&s, a).object_style, name); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 86fef8e46..e29a6838e 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -1058,6 +1058,13 @@ impl<'a> Ex<'a> { el.set("EnableStroke", bool_s(os.stroke.is_some())); el.set("EnableParagraphStyle", bool_s(os.paragraph_style.is_some())); el.set("EnableTextFrameGeneralOptions", bool_s(os.text_frame.is_some())); + if let Some(c) = &os.corners { + el.set("EnableStrokeAndCornerOptions", "true"); + for (n, c) in ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].iter().zip(c.corners) { + el.set(&format!("{n}CornerOption"), names::corner_out(c.shape)); + el.set(&format!("{n}CornerRadius"), num(c.size)); + } + } if let Some(f) = &os.fill { el.set("FillColor", self.sw(&f.swatch)); el.set("FillTint", pct(f.tint as f64)); diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index d770aef79..6160bb599 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -1271,7 +1271,11 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, text_frame, effects }; + // Corner options, when the style sets them (Stroke & Corner Options): the named corners + // in a rectangle's path order. + let corners = + (e.get("EnableStrokeAndCornerOptions") != Some("false")).then(|| corners(e, "")).flatten().map(|c| CornerOptions { corners: c }); + let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { Some(slot) => *slot = s, None => self.styles.object.push(s), diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 035333da4..19232c54c 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -3553,6 +3553,8 @@ fn object_style_effects_round_trip() { }; d.styles_mut().object.push(ObjectStyle { name: "Photo".into(), effects: Some(fx.clone()), ..Default::default() }); d.styles_mut().object.push(ObjectStyle { name: "Plain".into(), fill: Some(Fill::swatch("Black")), ..Default::default() }); + let rounded = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 9.0); + d.styles_mut().object.push(ObjectStyle { name: "Rounded".into(), corners: Some(rounded), ..Default::default() }); let lid = d.default_layer(); let id = designcraft_doc::ItemId(d.alloc()); let mut it = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0))); @@ -3583,6 +3585,9 @@ fn object_style_effects_round_trip() { assert!((ds.distance - 5.0).abs() < 1e-6 && (ds.angle - DropShadow::default().angle).abs() < 1e-6, "{ds:?}"); assert_eq!(got.feather, 3.0); assert!(style("Plain").effects.is_none()); + // Corner options (Stroke & Corner Options). + assert_eq!(style("Rounded").corners, Some(rounded)); + assert_eq!(style("Plain").corners, None); // The frame's effects are the style's, so it follows later edits of the style. let frames: Vec<_> = back.spreads[0].items.iter().filter(|i| i.object_style == "Photo").collect(); assert_eq!(frames[0].effects, got); From 17da588d8468e64000fd7ef50d97ccddee2747e8 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:39:44 +0200 Subject: [PATCH 006/328] Object Styles panel and the New Object Style / Object Style Options dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Window › Styles › Object Styles, as InDesign's: the selected object's style on top (+ when the object differs from it), the document's object styles (click applies, double-click opens the options, the default graphic and text frame styles marked), Clear Overrides and Create New Style (Alt-click: the dialog), and a menu with New Object Style… and Object Style Options…. The dialog: Style Name; Basic Attributes General (Based On and the Style Settings summary), Fill and Stroke (swatch list, tint, weight) and Stroke & Corner Options (corner shape and size), each included in the style by its checkbox; Effects for Object, with each effect's page from the Effects dialog; Apply Style to Selection for a new style. OK runs style.object.create (then style.object.apply) or style.object.edit. UI command objectStyle.dialog {name?}. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dock.rs | 2 + crates/ui-egui/src/effects_dialog.rs | 8 +- crates/ui-egui/src/i18n.rs | 39 ++ crates/ui-egui/src/i18n/ar.rs | 12 + crates/ui-egui/src/i18n/cs.rs | 12 + crates/ui-egui/src/i18n/it.rs | 13 + crates/ui-egui/src/i18n/ka.rs | 12 + crates/ui-egui/src/i18n/pl.rs | 12 + crates/ui-egui/src/i18n/pt_br.rs | 13 + crates/ui-egui/src/i18n/ru.rs | 12 + crates/ui-egui/src/i18n/uk.rs | 13 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 14 + crates/ui-egui/src/object_style_dialog.rs | 467 ++++++++++++++++++++++ crates/ui-egui/src/panels/styles.rs | 143 ++++++- 17 files changed, 773 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/object_style_dialog.rs diff --git a/ROADMAP.md b/ROADMAP.md index b1199ed8f..e4cf4399e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-21** · Window › Styles › Object Styles: InDesign's Object Styles panel (the selected object's style, `+` when overridden; a click applies a style, a double-click opens its options; the default graphic and text frame styles marked; Clear Overrides; Create New Style, ⌥/Alt-click for the dialog) and its New Object Style / Object Style Options dialog (Style Name; Basic Attributes Fill, Stroke, Stroke & Corner Options, each included by its checkbox; Effects for Object with the effects' pages; Style Settings; Apply Style to Selection). UI command `objectStyle.dialog`. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-21** · Object styles carry Corner Options (`corners`), taken from the selection by `style.object.create` and written to IDML (`EnableStrokeAndCornerOptions`, `TopLeftCornerOption`…). `style.object.edit` also changes a style's fill, stroke and corners and renames it (`rename`); the items using the style that haven't overridden an attribute follow each change, as in InDesign. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8b4043787..251ce9005 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2087,6 +2087,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "colorGroupOptions" => crate::i18n::tr(&app.ui.language, "Color Group Options"), "layerSettings" => crate::i18n::tr(&app.ui.language, "Layer Options"), crate::effects_dialog::ID => crate::i18n::tr(&app.ui.language, "Effects"), + crate::object_style_dialog::ID => crate::i18n::tr(&app.ui.language, crate::object_style_dialog::title(&d)), id => match id.strip_prefix("cmd:").and_then(designcraft_engine::find_command) { Some(c) => crate::i18n::tr(&app.ui.language, c.label.trim_end_matches('…')), None => crate::i18n::tr(&app.ui.language, "Dialog"), @@ -2104,6 +2105,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "newDocument" => 960.0, "numberingSection" => 560.0, crate::effects_dialog::ID => 720.0, + crate::object_style_dialog::ID => 760.0, _ => 640.0, }; let width = preferred_width.min(available.x); @@ -2361,6 +2363,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "colorGroupOptions" => options::color_group_options(app, ui, &mut d), "layerSettings" => options::layer_options(app, ui, &mut d), crate::effects_dialog::ID => crate::effects_dialog::show(app, ui, &mut d), + crate::object_style_dialog::ID => crate::object_style_dialog::show(app, ui, &mut d), "preferences" => preferences(app, ui, &mut d, body_height), "print" => print_dialog(app, ui, &mut d), "pdfImport" => { @@ -3573,6 +3576,7 @@ pub fn confirm(app: &mut DesignApp) -> Result { } "alert" => Ok(Value::Null), crate::effects_dialog::ID => crate::effects_dialog::confirm(app, &d), + crate::object_style_dialog::ID => crate::object_style_dialog::confirm(app, &d), "findChange" => { let result = if d.b("objectMode") { Ok(Value::Null) } else { app.run("find.change", find_change_params(&d)) }; // Confirmation consumes retained bounds before closing, even on an error. diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d4551e813..3612e2968 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -19,6 +19,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ ("effects", "Effects", "panel-effects"), ("paragraphStyles", "Paragraph Styles", "panel-pstyles"), ("characterStyles", "Character Styles", "panel-cstyles"), + ("objectStyles", "Object Styles", "frame-dashed"), ("character", "Character", "panel-character"), ("typography", "Typography", "panel-typography"), ("glyphs", "Glyphs", "panel-character"), @@ -280,6 +281,7 @@ pub fn panel_body(app: &mut DesignApp, ui: &mut egui::Ui, id: &str) { "swatches" => panels::swatches::show(app, ui), "paragraphStyles" => panels::styles::paragraph(app, ui), "characterStyles" => panels::styles::character(app, ui), + "objectStyles" => panels::styles::object(app, ui), "stroke" => panels::properties::stroke_panel(app, ui), "character" => panels::properties::character_panel(app, ui), "typography" => panels::typography::show(app, ui), diff --git a/crates/ui-egui/src/effects_dialog.rs b/crates/ui-egui/src/effects_dialog.rs index 456ca4a58..cd54fc225 100644 --- a/crates/ui-egui/src/effects_dialog.rs +++ b/crates/ui-egui/src/effects_dialog.rs @@ -65,7 +65,7 @@ pub fn open(app: &mut DesignApp, page: &str) { } /// Every effect's settings, those still at their defaults included (the document leaves them out). -fn effects_json(e: &designcraft_doc::Effects) -> Value { +pub(crate) fn effects_json(e: &designcraft_doc::Effects) -> Value { use designcraft_doc::{Bevel, DirectionalFeather, DropShadow, FeatherOptions, GradientFeather, InnerGlow, InnerShadow, OuterGlow, Satin}; let mut fx = serde_json::to_value(e).unwrap_or_else(|_| json!({})); let defaults = [ @@ -90,7 +90,7 @@ fn effects_json(e: &designcraft_doc::Effects) -> Value { } /// Turn the effect of `page` on, as choosing it does (Basic Feather: its default width). -fn turn_on(fx: &mut Value, page: &str) { +pub(crate) fn turn_on(fx: &mut Value, page: &str) { match page { "transparency" => {} "feather" => { @@ -106,7 +106,7 @@ fn turn_on(fx: &mut Value, page: &str) { } } -fn is_on(fx: &Value, page: &str) -> bool { +pub(crate) fn is_on(fx: &Value, page: &str) -> bool { match page { "transparency" => true, "feather" => fx["feather"].as_f64().unwrap_or(0.0) > 0.0, @@ -269,7 +269,7 @@ fn offset(ui: &mut egui::Ui, d: &mut Dialog, key: &str, unit: Unit, global: f64, } /// The settings of `page`. -fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { +pub(crate) fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let lang = app.ui.language.clone(); let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); let unit = app.session.active().map_or(Unit::Points, |st| st.doc.settings.horizontal_units); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index efe089ef9..72d756c7b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -36,6 +36,45 @@ pub const LANGUAGES: &[(&str, &str)] = &[ /// English → [German, French, Spanish, Japanese, Simplified Chinese]. const TABLE: &[(&str, [&str; 5])] = &[ + ("New Object Style", ["Neues Objektformat", "Nouveau style d'objet", "Nuevo estilo de objeto", "新規オブジェクトスタイル", "新建对象样式"]), + ( + "Object Style Options", + ["Objektformatoptionen", "Options de style d'objet", "Opciones de estilo de objeto", "オブジェクトスタイルの設定", "对象样式选项"], + ), + ( + "Object Style Options…", + ["Objektformatoptionen…", "Options de style d'objet…", "Opciones de estilo de objeto…", "オブジェクトスタイルの設定…", "对象样式选项…"], + ), + ("Basic Attributes", ["Grundattribute", "Attributs de base", "Atributos básicos", "基本属性", "基本属性"]), + ( + "Stroke & Corner Options", + ["Kontur- und Eckenoptionen", "Options de contour et d'angle", "Opciones de trazo y esquina", "線とコーナーのオプション", "描边和角选项"], + ), + ("Effects for:", ["Effekte für:", "Effets pour :", "Efectos para:", "効果 :", "效果:"]), + ( + "Apply Style to Selection", + [ + "Format auf Auswahl anwenden", + "Appliquer le style à la sélection", + "Aplicar estilo a la selección", + "選択範囲にスタイルを適用", + "将样式应用于选区", + ], + ), + ("Create New Style", ["Neues Format erstellen", "Créer un style", "Crear nuevo estilo", "新規スタイルを作成", "创建新样式"]), + ("Clear Overrides", ["Abweichungen löschen", "Effacer les remplacements", "Borrar modificaciones", "オーバーライドを消去", "清除覆盖"]), + ("Shape:", ["Form:", "Forme :", "Forma:", "形状 :", "形状:"]), + ("(no attributes)", ["(keine Attribute)", "(aucun attribut)", "(sin atributos)", "(属性なし)", "(无属性)"]), + ( + "Enter a style name.", + [ + "Geben Sie einen Formatnamen ein.", + "Saisissez un nom de style.", + "Escriba un nombre de estilo.", + "スタイル名を入力してください。", + "请输入样式名称。", + ], + ), // Menus. ("File", ["Datei", "Fichier", "Archivo", "ファイル", "文件"]), ("Edit", ["Bearbeiten", "Édition", "Edición", "編集", "编辑"]), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index b050de38b..1872dd73c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("New Object Style", "نمط كائن جديد"), + ("Object Style Options", "خيارات نمط الكائن"), + ("Object Style Options…", "خيارات نمط الكائن…"), + ("Basic Attributes", "السمات الأساسية"), + ("Stroke & Corner Options", "خيارات الحد والزوايا"), + ("Effects for:", "التأثيرات لـ:"), + ("Apply Style to Selection", "تطبيق النمط على التحديد"), + ("Create New Style", "إنشاء نمط جديد"), + ("Clear Overrides", "مسح التجاوزات"), + ("Shape:", "الشكل:"), + ("(no attributes)", "(لا سمات)"), + ("Enter a style name.", "أدخل اسم نمط."), ("Paste Vector Art", "لصق رسم متجه"), ("Baseline Options", "خيارات خط الأساس"), ("Fixed Number", "عدد ثابت"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index e77e72a1c..64261a4de 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -31,6 +31,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Vyjmout"), ("Copy", "Kopírovat"), ("Paste", "Vložit"), + ("New Object Style", "Nový styl objektu"), + ("Object Style Options", "Volby stylu objektu"), + ("Object Style Options…", "Volby stylu objektu…"), + ("Basic Attributes", "Základní atributy"), + ("Stroke & Corner Options", "Volby tahu a rohů"), + ("Effects for:", "Efekty pro:"), + ("Apply Style to Selection", "Použít styl na výběr"), + ("Create New Style", "Vytvořit nový styl"), + ("Clear Overrides", "Vymazat změny"), + ("Shape:", "Tvar:"), + ("(no attributes)", "(žádné atributy)"), + ("Enter a style name.", "Zadejte název stylu."), ("Reverse Path", "Obrátit cestu"), ("Set Anchor", "Nastavit kotvu"), ("Clear", "Vymazat"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index a918a9829..ab7a6840f 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,19 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("New Object Style", "Nuovo stile oggetto"), + ("Object Style Options", "Opzioni stile oggetto"), + ("Object Style Options…", "Opzioni stile oggetto…"), + ("Basic Attributes", "Attributi di base"), + ("Stroke & Corner Options", "Opzioni traccia e angoli"), + ("Effects for:", "Effetti per:"), + ("Apply Style to Selection", "Applica stile alla selezione"), + ("Create New Style", "Crea nuovo stile"), + ("Clear Overrides", "Cancella sostituzioni"), + ("Shape:", "Forma:"), + ("(no attributes)", "(nessun attributo)"), + ("Enter a style name.", "Inserisci un nome di stile."), + ("Corner Options", "Opzioni angolo"), ("Paste Vector Art", "Incolla grafica vettoriale"), ("Baseline Options", "Opzioni linea di base"), ("Fixed Number", "Numero fisso"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index d938c2dc7..fe735f4d7 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("New Object Style", "ახალი ობიექტის სტილი"), + ("Object Style Options", "ობიექტის სტილის პარამეტრები"), + ("Object Style Options…", "ობიექტის სტილის პარამეტრები…"), + ("Basic Attributes", "ძირითადი ატრიბუტები"), + ("Stroke & Corner Options", "კონტურისა და კუთხეების პარამეტრები"), + ("Effects for:", "ეფექტები:"), + ("Apply Style to Selection", "სტილის გამოყენება მონიშნულზე"), + ("Create New Style", "ახალი სტილის შექმნა"), + ("Clear Overrides", "გადაფარვების გასუფთავება"), + ("Shape:", "ფორმა:"), + ("(no attributes)", "(ატრიბუტების გარეშე)"), + ("Enter a style name.", "შეიყვანეთ სტილის სახელი."), ("Inches Decimal", "ინჩები (ათობითი)"), ("Back", "უკან"), ("Warning", "გაფრთხილება"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 68d685d99..f0f7f58a1 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -29,6 +29,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Wytnij"), ("Copy", "Kopiuj"), ("Paste", "Wklej"), + ("New Object Style", "Nowy styl obiektu"), + ("Object Style Options", "Opcje stylu obiektu"), + ("Object Style Options…", "Opcje stylu obiektu…"), + ("Basic Attributes", "Atrybuty podstawowe"), + ("Stroke & Corner Options", "Opcje obrysu i narożników"), + ("Effects for:", "Efekty dla:"), + ("Apply Style to Selection", "Zastosuj styl do zaznaczenia"), + ("Create New Style", "Utwórz nowy styl"), + ("Clear Overrides", "Wyczyść zmiany"), + ("Shape:", "Kształt:"), + ("(no attributes)", "(brak atrybutów)"), + ("Enter a style name.", "Wpisz nazwę stylu."), ("Clear", "Wyczyść"), ("Duplicate", "Powiel"), ("Select All", "Zaznacz wszystko"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 8521de594..b922a37c9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,19 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("New Object Style", "Novo estilo de objeto"), + ("Object Style Options", "Opções de estilo de objeto"), + ("Object Style Options…", "Opções de estilo de objeto…"), + ("Basic Attributes", "Atributos básicos"), + ("Stroke & Corner Options", "Opções de traçado e canto"), + ("Effects for:", "Efeitos para:"), + ("Apply Style to Selection", "Aplicar estilo à seleção"), + ("Create New Style", "Criar novo estilo"), + ("Clear Overrides", "Limpar substituições"), + ("Shape:", "Forma:"), + ("(no attributes)", "(sem atributos)"), + ("Enter a style name.", "Digite um nome de estilo."), + ("Corner Options", "Opções de canto"), ("Paste Vector Art", "Colar arte vetorial"), ("Baseline Options", "Opções de linha de base"), ("Fixed Number", "Número fixo"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 251555ca5..d8630b712 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -33,6 +33,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вырезать"), ("Copy", "Копировать"), ("Paste", "Вставить"), + ("New Object Style", "Новый стиль объекта"), + ("Object Style Options", "Параметры стиля объекта"), + ("Object Style Options…", "Параметры стиля объекта…"), + ("Basic Attributes", "Основные атрибуты"), + ("Stroke & Corner Options", "Параметры обводки и углов"), + ("Effects for:", "Эффекты для:"), + ("Apply Style to Selection", "Применить стиль к выделенному"), + ("Create New Style", "Создать новый стиль"), + ("Clear Overrides", "Удалить переопределения"), + ("Shape:", "Форма:"), + ("(no attributes)", "(нет атрибутов)"), + ("Enter a style name.", "Введите имя стиля."), ("Clear", "Очистить"), ("Duplicate", "Дублировать"), ("Select All", "Выделить все"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index dd4a1434d..242cb0d1e 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -29,6 +29,19 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("New Object Style", "Новий стиль об'єкта"), + ("Object Style Options", "Параметри стилю об'єкта"), + ("Object Style Options…", "Параметри стилю об'єкта…"), + ("Basic Attributes", "Основні атрибути"), + ("Stroke & Corner Options", "Параметри обведення й кутів"), + ("Effects for:", "Ефекти для:"), + ("Apply Style to Selection", "Застосувати стиль до виділеного"), + ("Create New Style", "Створити новий стиль"), + ("Clear Overrides", "Очистити перевизначення"), + ("Shape:", "Форма:"), + ("(no attributes)", "(немає атрибутів)"), + ("Enter a style name.", "Введіть назву стилю."), + ("Corner Options", "Параметри кутів"), ("Paste Vector Art", "Вставити векторну графіку"), ("Baseline Options", "Параметри базової лінії"), ("Fixed Number", "Фіксована кількість"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb98cac7f..1842bdb49 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -21,6 +21,7 @@ pub mod menus; mod modal_drag; mod new_document; mod object_control; +pub mod object_style_dialog; mod panel_docking; pub mod panels; mod prefs; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 79b8b2c4e..237e64f55 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -39,6 +39,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ None, "{page?: transparency|dropShadow|innerShadow|outerGlow|innerGlow|bevel|satin|feather|directionalFeather|gradientFeather} — the Effects dialog for the selected objects", ), + ( + "objectStyle.dialog", + "Object Style…", + None, + "{name?: style} — Object Style Options for the style `name`, or (without it) New Object Style from the selected object", + ), ("app.packageDialog", "Package…", Some("Cmd+Alt+Shift+P"), "{} — choose the package folder to create (file.package)"), ("app.saveSwatches", "Save Swatches for Exchange…", None, "{path?} — write the colour swatches as .ase"), ("app.exportPng", "Export Page as PNG…", Some("Cmd+E"), "{}"), @@ -878,6 +884,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ "ui:window.panel|Stroke|{\"panel\": \"stroke\"}", ">Styles", "ui:window.panel|Character Styles|{\"panel\": \"characterStyles\"}", + "ui:window.panel|Object Styles|{\"panel\": \"objectStyles\"}", "ui:window.panel|Paragraph Styles|{\"panel\": \"paragraphStyles\"}", "<", "ui:window.panel|Text Wrap|{\"panel\": \"textWrap\"}", @@ -1188,6 +1195,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { + match p.get("name").and_then(Value::as_str) { + Some(n) => crate::object_style_dialog::open_edit(app, n), + None => crate::object_style_dialog::open_new(app), + } + Ok(Value::Null) + } "app.loadSwatches" => { if let Some(pick) = app.services.pick_open.as_mut() { return Some(match pick("swatches") { diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs new file mode 100644 index 000000000..b9e1b3ce5 --- /dev/null +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -0,0 +1,467 @@ +//! The Object Styles panel's New Object Style and Object Style Options dialog, laid out as +//! InDesign's: the style's name on top; on the left its Basic Attributes (a checkbox includes one +//! in the style, a click shows its settings) and its effects; on the right the settings of the +//! attribute shown (General sums the style up); Apply Style to Selection for a new style. + +use serde_json::{Value, json}; + +use crate::DesignApp; +use crate::dialogs::Dialog; +use crate::theme::semibold; + +/// The dialog's id. +pub const ID: &str = "objectStyle"; + +/// Basic Attributes: (key, label). General isn't an attribute: it sums the style up. +const ATTRIBUTES: [(&str, &str); 4] = [("general", "General"), ("fill", "Fill"), ("stroke", "Stroke"), ("corners", "Stroke & Corner Options")]; + +/// The dialog for a new style from the selected object (its fill, stroke, corners and effects, +/// as InDesign's New Object Style), named "Object Style n". +pub fn open_new(app: &mut DesignApp) { + let Some(st) = app.session.active() else { return }; + let it = st.selection.items.first().and_then(|i| st.doc.item(*i)).cloned(); + let taken = |n: &str| st.doc.styles.object_style(n).is_some(); + let name = (1..).map(|i| format!("Object Style {i}")).find(|n| !taken(n)).unwrap_or_default(); + let from = it.is_some(); + let fields = json!({ + "new": true, + "name": name, + "basedOn": designcraft_doc::NO_OBJECT_STYLE, + "fill": it.as_ref().map(|i| i.fill.clone()).unwrap_or_default(), + "stroke": it.as_ref().map(|i| i.stroke.clone()).unwrap_or_default(), + "corners": it.as_ref().map(|i| i.corners).unwrap_or_default(), + "fx": crate::effects_dialog::effects_json(&it.map(|i| i.effects).unwrap_or_default()), + "hadEffects": from, + "inc": {"fill": from, "stroke": from, "corners": from}, + "page": "general", + "apply": from, + }); + app.ui.dialog = Some(Dialog::new(ID, fields)); +} + +/// Object Style Options for style `name`. +pub fn open_edit(app: &mut DesignApp, name: &str) { + let Some(os) = app.session.active().and_then(|st| st.doc.styles.object_style(name).cloned()) else { return }; + if name == designcraft_doc::NO_OBJECT_STYLE { + return; + } + let fields = json!({ + "new": false, + "orig": name, + "name": name, + "basedOn": os.based_on.as_deref().unwrap_or(designcraft_doc::NO_OBJECT_STYLE), + "fill": os.fill.clone().unwrap_or_default(), + "stroke": os.stroke.clone().unwrap_or_default(), + "corners": os.corners.unwrap_or_default(), + "fx": crate::effects_dialog::effects_json(&os.effects.clone().unwrap_or_default()), + "hadEffects": os.effects.is_some(), + "inc": {"fill": os.fill.is_some(), "stroke": os.stroke.is_some(), "corners": os.corners.is_some()}, + "page": "general", + "apply": false, + }); + app.ui.dialog = Some(Dialog::new(ID, fields)); +} + +/// The dialog's title: New Object Style or Object Style Options. +pub fn title(d: &Dialog) -> &'static str { + if d.b("new") { "New Object Style" } else { "Object Style Options" } +} + +fn included(d: &Dialog, key: &str) -> bool { + d.fields.get("inc").and_then(|i| i[key].as_bool()).unwrap_or(false) +} + +/// Whether the style sets effects: it did, or one is on now. +fn sets_effects(d: &Dialog) -> bool { + let fx = d.fields.get("fx").cloned().unwrap_or(Value::Null); + d.b("hadEffects") || crate::effects_dialog::PAGES.iter().skip(1).any(|(k, _)| crate::effects_dialog::is_on(&fx, k)) +} + +/// The style's attributes as the commands take them (null: not in the style). +fn attrs(d: &Dialog) -> serde_json::Map { + let mut p = serde_json::Map::new(); + for k in ["fill", "stroke", "corners"] { + p.insert(k.into(), if included(d, k) { d.fields.get(k).cloned().unwrap_or(Value::Null) } else { Value::Null }); + } + p.insert("effects".into(), if sets_effects(d) { d.fields.get("fx").cloned().unwrap_or(Value::Null) } else { Value::Null }); + p +} + +/// OK: the new style (applied to the selection when asked), or the edited one. +pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { + let name = d.s("name").trim().to_string(); + if name.is_empty() { + return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); + } + let mut p = attrs(d); + if d.b("new") { + p.insert("name".into(), json!(name)); + p.insert("fromSelection".into(), json!(false)); + let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; + let made = r["name"].as_str().unwrap_or(&name).to_string(); + if d.b("apply") && app.session.active().is_some_and(|st| !st.selection.items.is_empty()) { + app.run("style.object.apply", json!({"name": made})).map_err(|e| e.to_string())?; + } + Ok(r) + } else { + let orig = d.s("orig"); + p.insert("name".into(), json!(orig)); + if name != orig { + p.insert("rename".into(), json!(name)); + } + // A style that didn't set effects and still doesn't: nothing to say about them. + if p.get("effects").is_some_and(Value::is_null) && !d.b("hadEffects") { + p.remove("effects"); + } + app.run("style.object.edit", Value::Object(p)).map_err(|e| e.to_string()) + } +} + +fn set(d: &mut Dialog, path: &[&str], v: Value) { + let Some((first, rest)) = path.split_first() else { return }; + let mut cur = d.fields.entry(first.to_string()).or_insert(Value::Null); + for k in rest { + if !cur.is_object() { + *cur = json!({}); + } + cur = &mut cur[*k]; + } + *cur = v; +} + +fn get<'a>(d: &'a Dialog, path: &[&str]) -> &'a Value { + let Some((first, rest)) = path.split_first() else { return &Value::Null }; + let mut v = d.fields.get(*first).unwrap_or(&Value::Null); + for k in rest { + v = &v[*k]; + } + v +} + +/// A row of the left-hand lists: a checkbox (when `check` is given) and the label, which shows +/// `page`. +fn list_row(ui: &mut egui::Ui, d: &mut Dialog, page: &str, label: &str, check: Option) -> Option { + let mut out = None; + ui.horizontal(|ui| { + match check { + Some(mut on) => { + if ui.checkbox(&mut on, "").changed() { + out = Some(on); + } + } + None => ui.add_space(24.0), + } + let cur = d.fields.get("page").and_then(Value::as_str) == Some(page); + if ui.selectable_label(cur, crate::rtl::widget(ui, label)).clicked() { + d.fields.insert("page".into(), json!(page)); + } + }); + out +} + +/// The document's swatches, as a list to pick from (InDesign's Fill and Stroke pages). +fn swatch_list(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, key: &str) { + let Some(doc) = app.session.active().map(|st| &st.doc) else { return }; + let cur = get(d, &[key, "swatch"]).as_str().unwrap_or("").to_string(); + let t = crate::theme::Tokens::get(ui.ctx()); + egui::Frame::NONE.stroke(egui::Stroke::new(1.0, t.divider)).inner_margin(egui::Margin::same(4)).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt(("os_swatches", key.to_string())).max_height(220.0).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + for w in doc.swatches.iter().filter(|w| !w.hidden || w.name == cur) { + let picked = ui + .horizontal(|ui| { + let (c, g) = crate::widgets::swatch_colors(doc, &w.name, 1.0); + let r = crate::widgets::swatch_chip(ui, 14.0, c, g); + ui.selectable_label(w.name == cur, &w.name).clicked() || r.clicked() + }) + .inner; + if picked { + set(d, &[key, "swatch"], json!(w.name)); + } + } + }); + }); +} + +/// A number field of the dialog at `path` (a percentage of 0–1 with `percent`). +fn number(ui: &mut egui::Ui, d: &mut Dialog, path: &[&str], suffix: &str, range: (f64, f64), percent: bool) { + let v = get(d, path).as_f64().unwrap_or(0.0); + let shown = if percent { (v * 100.0).round() } else { v }; + let id = format!("os_{}", path.join("_")); + let decimals = if percent { 0 } else { 2 }; + if let Some(n) = crate::widgets::NumField::number(&id, Some(shown), suffix, decimals).width(90.0).spinner().range(range.0, range.1).show(ui) { + set(d, path, json!(if percent { n / 100.0 } else { n })); + } +} + +/// One line per attribute the style sets (InDesign's Style Settings). +fn settings(app: &DesignApp, d: &Dialog) -> Vec { + let tr = |s: &str| crate::i18n::tr(&app.ui.language, s).to_string(); + let mut out = Vec::new(); + if included(d, "fill") { + let f = get(d, &["fill"]); + out.push(format!("{}: {} {:.0}%", tr("Fill"), f["swatch"].as_str().unwrap_or(""), f["tint"].as_f64().unwrap_or(1.0) * 100.0)); + } + if included(d, "stroke") { + let s = get(d, &["stroke"]); + out.push(format!("{}: {}, {} pt", tr("Stroke"), s["swatch"].as_str().unwrap_or(""), s["weight"].as_f64().unwrap_or(0.0))); + } + if included(d, "corners") { + let c = &get(d, &["corners"])["corners"][0]; + let shape: designcraft_geom::corners::CornerShape = serde_json::from_value(c["shape"].clone()).unwrap_or_default(); + out.push(format!("{}: {} {} pt", tr("Corner Options"), tr(shape.label()), c["size"].as_f64().unwrap_or(0.0))); + } + if sets_effects(d) { + let fx = d.fields.get("fx").cloned().unwrap_or(Value::Null); + let on: Vec = + crate::effects_dialog::PAGES.iter().skip(1).filter(|(k, _)| crate::effects_dialog::is_on(&fx, k)).map(|(_, l)| tr(l)).collect(); + out.push(format!("{}: {}", tr("Effects"), if on.is_empty() { tr("(no effects)") } else { on.join(", ") })); + } + out +} + +/// The settings of the attribute shown. +fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { + let tr = |s: &str| crate::i18n::tr(&app.ui.language, s).to_string(); + let title = ATTRIBUTES.iter().find(|a| a.0 == page).map(|a| a.1); + if let Some(title) = title { + crate::rtl::label(ui, egui::RichText::new(tr(title)).font(semibold(14.0))); + ui.add_space(6.0); + } + match page { + "general" => { + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Based On:")); + // Based On isn't editable yet: the style's parent, as it is. + ui.add_enabled_ui(false, |ui| { + let based = d.s("basedOn"); + egui::ComboBox::from_id_salt("os_based_on") + .selected_text(crate::i18n::style_name(&app.ui.language, &based)) + .width(220.0) + .show_ui(ui, |_| {}); + }); + }); + ui.add_space(10.0); + crate::rtl::label(ui, egui::RichText::new(tr("Style Settings:")).font(semibold(12.0))); + let t = crate::theme::Tokens::get(ui.ctx()); + egui::Frame::NONE.stroke(egui::Stroke::new(1.0, t.divider)).inner_margin(egui::Margin::same(8)).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.set_min_height(160.0); + let lines = settings(app, d); + if lines.is_empty() { + crate::rtl::label(ui, egui::RichText::new(tr("(no attributes)")).color(t.text_dim)); + } + for l in lines { + crate::rtl::label(ui, l); + } + }); + } + "fill" | "stroke" => { + let key = page; + ui.add_enabled_ui(included(d, key), |ui| { + swatch_list(app, ui, d, key); + ui.add_space(6.0); + ui.horizontal(|ui| { + if key == "stroke" { + crate::rtl::label(ui, tr("Weight:")); + number(ui, d, &["stroke", "weight"], " pt", (0.0, 1000.0), false); + ui.add_space(12.0); + } + crate::rtl::label(ui, tr("Tint:")); + number(ui, d, &[key, "tint"], "%", (0.0, 100.0), true); + }); + }); + } + "corners" => { + ui.add_enabled_ui(included(d, "corners"), |ui| { + crate::rtl::label(ui, egui::RichText::new(tr("Corner Options")).font(semibold(12.0))); + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Size:")); + let size = get(d, &["corners", "corners"])[0]["size"].as_f64().unwrap_or(0.0); + if let Some(v) = + crate::widgets::NumField::number("os_corner_size", Some(size), " pt", 2).width(90.0).spinner().range(0.0, 10_000.0).show(ui) + { + let mut c = get(d, &["corners"]).clone(); + if let Some(cs) = c["corners"].as_array_mut() { + cs.iter_mut().for_each(|k| k["size"] = json!(v)); + } + d.fields.insert("corners".into(), c); + } + ui.add_space(12.0); + crate::rtl::label(ui, tr("Shape:")); + let cur: designcraft_geom::corners::CornerShape = + serde_json::from_value(get(d, &["corners", "corners"])[0]["shape"].clone()).unwrap_or_default(); + let mut picked = None; + egui::ComboBox::from_id_salt("os_corner_shape").selected_text(tr(cur.label())).width(140.0).show_ui(ui, |ui| { + for s in designcraft_geom::corners::CornerShape::ALL { + if ui.selectable_label(s == cur, tr(s.label())).clicked() { + picked = Some(s); + } + } + }); + if let Some(s) = picked { + let mut c = get(d, &["corners"]).clone(); + if let Some(cs) = c["corners"].as_array_mut() { + cs.iter_mut().for_each(|k| k["shape"] = json!(s)); + } + d.fields.insert("corners".into(), c); + } + }); + }); + } + p => crate::effects_dialog::page_ui(app, ui, d, p), + } +} + +/// The dialog's body. +pub fn show(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { + let lang = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Style Name:")); + let mut name = d.s("name"); + if ui.add(egui::TextEdit::singleline(&mut name).desired_width(300.0)).changed() { + d.fields.insert("name".into(), json!(name)); + } + }); + ui.add_space(8.0); + let page = d.fields.get("page").and_then(Value::as_str).unwrap_or("general").to_string(); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(230.0); + crate::rtl::label(ui, egui::RichText::new(tr("Basic Attributes")).font(semibold(12.0))); + for (key, label) in ATTRIBUTES { + let check = (key != "general").then(|| included(d, key)); + if let Some(on) = list_row(ui, d, key, &tr(label), check) { + set(d, &["inc", key], json!(on)); + } + } + ui.add_space(8.0); + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Effects for:")); + // Stroke, Fill and Text levels aren't in the document model yet: the object only. + ui.add_enabled_ui(false, |ui| { + egui::ComboBox::from_id_salt("os_fx_level").selected_text(tr("Object")).width(100.0).show_ui(ui, |_| {}); + }); + }); + for (key, label) in crate::effects_dialog::PAGES.iter().skip(1) { + let fx = d.fields.get("fx").cloned().unwrap_or(Value::Null); + if let Some(on) = list_row(ui, d, key, &tr(label), Some(crate::effects_dialog::is_on(&fx, key))) + && let Some(f) = d.fields.get_mut("fx") + { + if on { + crate::effects_dialog::turn_on(f, key); + } else if *key == "feather" { + f["feather"] = json!(0.0); + } else { + f[*key]["on"] = json!(false); + } + } + } + }); + ui.add_space(16.0); + ui.vertical(|ui| { + ui.set_min_width(440.0); + page_ui(app, ui, d, &page); + }); + }); + ui.add_space(10.0); + if d.b("new") { + let mut apply = d.b("apply"); + if ui.checkbox(&mut apply, crate::rtl::widget(ui, tr("Apply Style to Selection"))).changed() { + d.fields.insert("apply".into(), json!(apply)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app_with_frame() -> (DesignApp, u64) { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 172, 172], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + (app, id) + } + + fn frame(app: &mut DesignApp, ctx: &egui::Context) -> Vec { + let mut texts = Vec::new(); + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: egui::epaint::Shape, texts: &mut Vec) { + match s { + egui::epaint::Shape::Text(t) => texts.push(t.galley.text().to_string()), + egui::epaint::Shape::Vec(v) => v.into_iter().for_each(|s| walk(s, texts)), + _ => {} + } + } + texts.clear(); + for c in out.shapes { + walk(c.shape, &mut texts); + } + } + texts + } + + /// The course's chapter 15: New Object Style from a frame with rounded corners, a paper + /// stroke and a drop shadow, named and applied to the selection; then Object Style Options + /// with a thicker stroke: the frames using the style follow. + #[test] + fn a_new_object_style_from_the_selection_and_its_options() { + let (mut app, a) = app_with_frame(); + app.run("object.cornerOptions", json!({"shape": "rounded", "size": 12, "ids": [a]})).unwrap(); + app.run("object.stroke", json!({"swatch": "[Paper]", "weight": 2.5, "ids": [a]})).unwrap(); + app.run("object.dropShadow", json!({"on": true, "ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + open_new(&mut app); + let texts = frame(&mut app, &ctx); + for t in [ + "New Object Style", + "Style Name:", + "Basic Attributes", + "Fill", + "Stroke & Corner Options", + "Effects for:", + "Drop Shadow", + "Style Settings:", + "Apply Style to Selection", + ] { + assert!(texts.iter().any(|x| x.trim() == t), "{t}: {texts:?}"); + } + assert!(texts.iter().any(|x| x.starts_with("Stroke: [Paper], 2.5 pt")), "{texts:?}"); + assert!(texts.iter().any(|x| x.starts_with("Effects: Drop Shadow")), "{texts:?}"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Rounded Corner Image, White Stroke")); + d.fields.insert("page".into(), json!("corners")); + } + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|x| x.trim() == "Rounded"), "{texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + let name = "Rounded Corner Image, White Stroke"; + let doc = |app: &DesignApp| app.session.active().unwrap().doc.clone(); + let item = |app: &DesignApp, id: u64| doc(app).item(designcraft_doc::ItemId(id)).unwrap().clone(); + assert_eq!(item(&app, a).object_style, name, "applied to the selection"); + let os = doc(&app).styles.object_style(name).cloned().unwrap(); + assert!(os.corners.is_some() && os.effects.as_ref().unwrap().drop_shadow.on && os.stroke.as_ref().unwrap().weight == 2.5); + + let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + app.run("style.object.apply", json!({"name": name, "ids": [b]})).unwrap(); + open_edit(&mut app, name); + if let Some(d) = app.ui.dialog.as_mut() { + assert_eq!(title(d), "Object Style Options"); + set(d, &["stroke", "weight"], json!(5.0)); + set(d, &["inc", "fill"], json!(false)); + } + frame(&mut app, &ctx); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((item(&app, a).stroke.weight, item(&app, b).stroke.weight), (5.0, 5.0)); + assert!(doc(&app).styles.object_style(name).unwrap().fill.is_none(), "Fill unchecked: no longer in the style"); + assert!(doc(&app).styles.object_style(name).unwrap().effects.as_ref().unwrap().drop_shadow.on, "effects kept"); + } +} diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index f7e6fa803..0f2295340 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -1,4 +1,4 @@ -//! Paragraph Styles and Character Styles panels. +//! Paragraph Styles, Character Styles and Object Styles panels. use egui::{Sense, vec2}; use serde_json::json; @@ -105,6 +105,106 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) { list(app, ui, false); } +/// The selected object's style, and whether the object differs from it (an override: `+`). +fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { + let st = app.session.active()?; + let it = st.selection.items.first().and_then(|i| st.doc.item(*i))?; + let mut styled = it.clone(); + if let Some(os) = st.doc.styles.object_style(&it.object_style) { + os.apply_to(&mut styled); + } + Some((it.object_style.clone(), styled != *it)) +} + +/// Window › Styles › Object Styles, as InDesign's: the selected object's style on top (`+` when +/// it is overridden), the document's object styles (a click applies one to the selection, a +/// double-click opens its options; the default graphic and text frame styles are marked), and at +/// the bottom Clear Overrides and Create New Style (⌥/Alt-click: the New Object Style dialog). +pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let lang = app.ui.language.clone(); + let Some(st) = app.session.active() else { return }; + let names: Vec = st.doc.styles.object.iter().map(|s| s.name.clone()).collect(); + let (default_graphic, default_text) = (st.doc.styles.default_graphic_frame.clone(), st.doc.styles.default_text_frame.clone()); + let current = object_style_of_selection(app); + let selected = current.is_some(); + let shown = |n: &str, over: bool| format!("{}{}", crate::i18n::style_name(&lang, n), if over { "+" } else { "" }); + crate::rtl::label(ui, egui::RichText::new(current.as_ref().map_or_else(String::new, |(n, over)| shown(n, *over))).size(11.0).color(t.text_dim)); + for n in &names { + let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let is_current = current.as_ref().is_some_and(|(c, _)| c == n); + if is_current { + ui.painter().rect_filled(row, 0.0, t.row_selected); + } else if resp.hovered() { + ui.painter().rect_filled(row, 0.0, t.hover); + } + let label = shown(n, is_current && current.as_ref().is_some_and(|c| c.1)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, is_current, &label)); + crate::rtl::paint(ui.painter(), row.min + vec2(24.0, 11.0), egui::Align2::LEFT_CENTER, &label, egui::FontId::proportional(12.5), t.text); + // The default styles of new graphic and text frames, as InDesign marks them. + let mark = egui::Rect::from_center_size(egui::pos2(row.max.x - 14.0, row.center().y), vec2(11.0, 11.0)); + if *n == default_graphic { + ui.painter().rect_stroke(mark, 0.0, egui::Stroke::new(1.0, t.icon), egui::StrokeKind::Inside); + } + if *n == default_text { + ui.painter().rect_stroke(mark, 0.0, egui::Stroke::new(1.0, t.icon), egui::StrokeKind::Inside); + ui.painter().text(mark.center(), egui::Align2::CENTER_CENTER, "T", egui::FontId::proportional(8.5), t.icon); + } + let editable = n != designcraft_doc::NO_OBJECT_STYLE; + if resp.double_clicked() && editable { + crate::object_style_dialog::open_edit(app, n); + } else if resp.clicked() && selected { + let _ = app.run("style.object.apply", json!({"name": n})); + } + resp.context_menu(|ui| { + let label = crate::i18n::style_name(&lang, n); + if editable && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Edit \"{name}\"…").replace("{name}", label))).clicked() { + crate::object_style_dialog::open_edit(app, n); + ui.close(); + } + if ui + .add_enabled(selected, egui::Button::new(crate::rtl::widget(ui, format!("{} \"{}\"", crate::i18n::tr(&lang, "Apply"), label)))) + .clicked() + { + let _ = app.run("style.object.apply", json!({"name": n})); + ui.close(); + } + }); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icons::button(ui, "style-new", 20.0, false, crate::i18n::tr(&lang, "Create New Style")).clicked() { + if ui.input(|i| i.modifiers.alt) { + crate::object_style_dialog::open_new(app); + } else if selected { + let _ = app.run("style.object.create", json!({"name": "Object Style 1", "fromSelection": true})); + } else { + crate::object_style_dialog::open_new(app); + } + } + let over = current.as_ref().is_some_and(|c| c.1); + if ui.add_enabled_ui(over, |ui| icons::button(ui, "style-clear", 20.0, false, crate::i18n::tr(&lang, "Clear Overrides"))).inner.clicked() + && over + { + let _ = app.run("style.object.clearOverrides", json!({})); + } + crate::menus::menu_button(ui, "☰", |ui| { + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "New Object Style…"))).clicked() { + crate::object_style_dialog::open_new(app); + ui.close(); + } + if let Some((n, _)) = current.as_ref().filter(|(n, _)| n != designcraft_doc::NO_OBJECT_STYLE) + && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Object Style Options…"))).clicked() + { + crate::object_style_dialog::open_edit(app, n); + ui.close(); + } + }); + }); + }); +} + /// One style in the list: click applies (⌥ clears overrides), double-click edits, /// right-click: edit, apply, break link, move to group. fn style_row(app: &mut DesignApp, ui: &mut egui::Ui, para: bool, n: &str, current: Option<&str>, overridden: bool, groups: &[String], t: &Tokens) { @@ -235,6 +335,47 @@ mod tests { assert_eq!(h.state().session.doc().unwrap().doc.styles.para("Header").unwrap().chars.size, Some(24.0)); } + /// The Object Styles panel: the selected frame's style is marked (`+` once overridden), a + /// click applies a style, the eraser clears the overrides, + makes a style from the selection. + #[test] + fn object_styles_panel_applies_marks_overrides_and_creates() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [36, 36, 136, 136], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + app.run("style.object.create", json!({"name": "Framed", "fromSelection": false, "stroke": {"swatch": "[Paper]", "weight": 3}})).unwrap(); + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::new("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + object(app, ui); + }, + app, + ); + h.run_steps(4); + h.get_by_label("Framed").click(); + h.run_steps(3); + // The style on top and its row. + assert_eq!(h.get_all_by_label("Framed").count(), 2); + let style = |h: &Harness| h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); + assert_eq!((style(&h).object_style.as_str(), style(&h).stroke.weight), ("Framed", 3.0)); + h.state_mut().run("object.stroke", json!({"weight": 1})).unwrap(); + h.run_steps(3); + assert_eq!(h.get_all_by_label("Framed+").count(), 2); + h.get_by_label("Clear Overrides").click(); + h.run_steps(3); + assert_eq!(style(&h).stroke.weight, 3.0); + assert_eq!(h.get_all_by_label("Framed").count(), 2); + h.get_by_label("Create New Style").click(); + h.run_steps(3); + let styles = h.state().session.active().unwrap().doc.styles.object.iter().map(|o| o.name.clone()).collect::>(); + assert!(styles.contains(&"Object Style 1".to_string()), "{styles:?}"); + } + #[test] fn paragraph_color_override_is_marked_and_cleared_from_the_row_menu() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 025db568cdb16f2073a728647c0ebc278d2b4cd5 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:07:03 +0200 Subject: [PATCH 007/328] style.object.create validates the stroke weight as edit does Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style.rs | 21 ++++++++++++++------- crates/engine/src/tests.rs | 7 +++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index e0eee77b9..0ff7c8a4f 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -1515,7 +1515,7 @@ fn create_object(s: &mut Session, p: &Value) -> Result { if let Some(f) = fill_param(CREATE, p, os.fill.as_ref())? { os.fill = f; } - if let Some(st) = group_param(CREATE, p, "stroke", os.stroke.as_ref().unwrap_or(&designcraft_doc::Stroke::default()))? { + if let Some(st) = stroke_param(CREATE, p, os.stroke.as_ref())? { os.stroke = st; } if let Some(c) = corners_param(CREATE, p, os.corners.unwrap_or_default())? { @@ -1535,6 +1535,18 @@ fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 +/// or the tint isn't finite. +fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { + let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()))?; + if let Some(Some(st)) = &st + && !(st.weight.is_finite() && st.weight >= 0.0 && st.tint.is_finite()) + { + return Err(bad(cmd, "stroke weight must be a number ≥ 0")); + } + Ok(st) +} + /// `p[key]`, an attribute group of a style, merged field by field over `base`: `None` when not /// given, `Some(None)` for null (the style no longer sets it). fn group_param(cmd: &str, p: &Value, key: &str, base: &T) -> Result>> { @@ -1616,12 +1628,7 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { if let Some(f) = fill_param(CMD, p, old.fill.as_ref())? { new.fill = f; } - if let Some(st) = group_param(CMD, p, "stroke", old.stroke.as_ref().unwrap_or(&designcraft_doc::Stroke::default()))? { - if let Some(st) = &st - && !(st.weight.is_finite() && st.weight >= 0.0 && st.tint.is_finite()) - { - return Err(bad(CMD, "stroke weight must be a number ≥ 0")); - } + if let Some(st) = stroke_param(CMD, p, old.stroke.as_ref())? { new.stroke = st; } if let Some(c) = corners_param(CMD, p, old.corners.unwrap_or_default())? { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 47bfcb523..0441f9bd9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -725,6 +725,13 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // A negative stroke weight is refused when creating a style as when editing one. + let styles = s.doc().unwrap().doc.styles.object.len(); + for cmd in ["style.object.create", "style.object.edit"] { + let e = s.execute(cmd, &json!({"name": "Framed", "stroke": {"weight": -3}})).unwrap_err(); + assert!(e.to_string().contains("stroke weight"), "{cmd}: {e}"); + } + assert_eq!(s.doc().unwrap().doc.styles.object.len(), styles); // null: the style stops setting corners, the items keep theirs. s.execute("style.object.edit", &json!({"name": "Framed", "corners": null})).unwrap(); assert!(s.doc().unwrap().doc.styles.object_style("Framed").unwrap().corners.is_none()); From b8e229a5cc692a815307609f62188e2c3e2b3e99 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:10:12 +0200 Subject: [PATCH 008/328] Object style dialog: a refused OK keeps it open with the reason; Czech terms as the catalog's Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 11 +++++- crates/ui-egui/src/i18n/cs.rs | 8 ++--- crates/ui-egui/src/object_style_dialog.rs | 42 +++++++++++++++++++++-- 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 251ce9005..8be3aafb5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3576,7 +3576,16 @@ pub fn confirm(app: &mut DesignApp) -> Result { } "alert" => Ok(Value::Null), crate::effects_dialog::ID => crate::effects_dialog::confirm(app, &d), - crate::object_style_dialog::ID => crate::object_style_dialog::confirm(app, &d), + crate::object_style_dialog::ID => { + let r = crate::object_style_dialog::confirm(app, &d); + if let Err(e) = &r { + // Keep the dialog and its edits open with the reason (an empty or taken name). + let mut d = d.clone(); + d.fields.insert("status".into(), json!(e)); + app.ui.dialog = Some(d); + } + r + } "findChange" => { let result = if d.b("objectMode") { Ok(Value::Null) } else { app.run("find.change", find_change_params(&d)) }; // Confirmation consumes retained bounds before closing, even on an error. diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 64261a4de..b46318852 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -32,14 +32,14 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Copy", "Kopírovat"), ("Paste", "Vložit"), ("New Object Style", "Nový styl objektu"), - ("Object Style Options", "Volby stylu objektu"), - ("Object Style Options…", "Volby stylu objektu…"), + ("Object Style Options", "Možnosti stylu objektu"), + ("Object Style Options…", "Možnosti stylu objektu…"), ("Basic Attributes", "Základní atributy"), - ("Stroke & Corner Options", "Volby tahu a rohů"), + ("Stroke & Corner Options", "Možnosti tahu a rohů"), ("Effects for:", "Efekty pro:"), ("Apply Style to Selection", "Použít styl na výběr"), ("Create New Style", "Vytvořit nový styl"), - ("Clear Overrides", "Vymazat změny"), + ("Clear Overrides", "Zrušit přepsání"), ("Shape:", "Tvar:"), ("(no attributes)", "(žádné atributy)"), ("Enter a style name.", "Zadejte název stylu."), diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index b9e1b3ce5..038e9b7b4 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -99,8 +99,13 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { p.insert("fromSelection".into(), json!(false)); let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; let made = r["name"].as_str().unwrap_or(&name).to_string(); - if d.b("apply") && app.session.active().is_some_and(|st| !st.selection.items.is_empty()) { - app.run("style.object.apply", json!({"name": made})).map_err(|e| e.to_string())?; + // The style exists now, so OK again mustn't make a second one: a refused apply (locked + // objects) goes to the status line and the dialog closes. + if d.b("apply") + && app.session.active().is_some_and(|st| !st.selection.items.is_empty()) + && let Err(e) = app.run("style.object.apply", json!({"name": made})) + { + app.status(e.to_string()); } Ok(r) } else { @@ -324,6 +329,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("name".into(), json!(name)); } }); + // Why OK was refused (an empty or taken name), until the next try. + let status = d.s("status"); + if !status.is_empty() { + crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong)); + } ui.add_space(8.0); let page = d.fields.get("page").and_then(Value::as_str).unwrap_or("general").to_string(); ui.horizontal_top(|ui| { @@ -464,4 +474,32 @@ mod tests { assert!(doc(&app).styles.object_style(name).unwrap().fill.is_none(), "Fill unchecked: no longer in the style"); assert!(doc(&app).styles.object_style(name).unwrap().effects.as_ref().unwrap().drop_shadow.on, "effects kept"); } + + /// A refused OK (an empty name, a name another style has) keeps the dialog and its edits, + /// with the reason shown. + #[test] + fn a_refused_ok_keeps_the_dialog_open_with_the_reason() { + let (mut app, _) = app_with_frame(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + app.run("style.object.create", json!({"name": "Taken", "fromSelection": false})).unwrap(); + app.run("style.object.create", json!({"name": "Mine", "fromSelection": false})).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!(" ")); + set(d, &["stroke", "weight"], json!(7.0)); + } + assert!(crate::dialogs::confirm(&mut app).is_err()); + let d = app.ui.dialog.as_ref().expect("still open"); + assert_eq!(d.s("status"), "Enter a style name."); + assert_eq!(get(d, &["stroke", "weight"]), &json!(7.0), "the edits are kept"); + assert!(frame(&mut app, &ctx).iter().any(|t| t.trim() == "Enter a style name.")); + open_edit(&mut app, "Mine"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Taken")); + } + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("already named"), "{e}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); + } } From ef4bbdb7087eb98d7089a94910f89eb537fe0d1d Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 13:36:47 +0200 Subject: [PATCH 009/328] Object styles: a stroke tint outside 0..1 is refused Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style.rs | 13 ++++++++----- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 0ff7c8a4f..76e878277 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -1536,13 +1536,16 @@ fn create_object(s: &mut Session, p: &Value) -> Result { } /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 -/// or the tint isn't finite. +/// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()))?; - if let Some(Some(st)) = &st - && !(st.weight.is_finite() && st.weight >= 0.0 && st.tint.is_finite()) - { - return Err(bad(cmd, "stroke weight must be a number ≥ 0")); + if let Some(Some(st)) = &st { + if !(st.weight.is_finite() && st.weight >= 0.0) { + return Err(bad(cmd, "stroke weight must be a number ≥ 0")); + } + if !(0.0..=1.0).contains(&st.tint) { + return Err(bad(cmd, "stroke tint must be 0..1")); + } } Ok(st) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0441f9bd9..4770fb16a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -730,6 +730,10 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { for cmd in ["style.object.create", "style.object.edit"] { let e = s.execute(cmd, &json!({"name": "Framed", "stroke": {"weight": -3}})).unwrap_err(); assert!(e.to_string().contains("stroke weight"), "{cmd}: {e}"); + for tint in [-1.0, 1.5] { + let e = s.execute(cmd, &json!({"name": "Framed", "stroke": {"tint": tint}})).unwrap_err(); + assert!(e.to_string().contains("stroke tint"), "{cmd}: {e}"); + } } assert_eq!(s.doc().unwrap().doc.styles.object.len(), styles); // null: the style stops setting corners, the items keep theirs. From 88403c5319feca34d19dca6ca99b0d003ea51105 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:47:44 +0200 Subject: [PATCH 010/328] Object styles: Clear Overrides restores the paragraph style; feather choke kept to 0..100 Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 2 ++ crates/engine/src/cmd/style.rs | 47 ++++++++++++++++++++++++---------- crates/engine/src/tests.rs | 29 +++++++++++++++++++++ 3 files changed, 65 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index cfb13dc53..c7fe4eaf9 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -1254,6 +1254,8 @@ impl Effects { ds.size = len("dropShadow.size", ds.size)?; ds.spread = pct("dropShadow.spread", ds.spread)?; self.feather = len("feather", self.feather)?; + // As IDML import reads it, so a round trip keeps it. + self.feather_options.choke = pct("featherOptions.choke", self.feather_options.choke)?; let e = &mut self.inner_shadow; e.opacity = opacity("innerShadow.opacity", e.opacity)?; e.angle = finite("innerShadow.angle", e.angle)?; diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 76e878277..7bcdcbb1d 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -377,7 +377,7 @@ pub fn specs() -> Vec { "Clear Object Style Overrides", [], None, - "{ids?} — each item takes its object style's fill, stroke, effects and text frame options again → {changed}", + "{ids?} — each item takes its object style's fill, stroke, effects and text frame options again, and a text frame's story its paragraph style → {changed}", super::has_selection, clear_object_overrides ), @@ -1430,18 +1430,33 @@ fn apply_object(s: &mut Session, p: &Value) -> Result { fn clear_object_overrides(s: &mut Session, p: &Value) -> Result { let ids = super::targets(s, p)?; - // Each target with its style's attributes applied, kept only where that changes the item. + // Each target with its style's attributes applied, kept only where that changes the item; + // and a text frame's story back in the style's paragraph style, as applying the style does. let d = &s.doc()?.doc; - let changed: Vec = ids - .iter() - .filter_map(|id| { - let it = d.item(*id)?; - let mut next = it.clone(); - d.styles.object_style(&it.object_style)?.apply_to(&mut next); - (next != *it).then_some(next) - }) - .collect(); - if changed.is_empty() { + let mut changed: Vec = Vec::new(); + let mut restyled: Vec<(designcraft_doc::StoryId, String)> = Vec::new(); + let mut n = 0; + for id in &ids { + let Some(it) = d.item(*id) else { continue }; + let Some(os) = d.styles.object_style(&it.object_style) else { continue }; + let mut next = it.clone(); + os.apply_to(&mut next); + let item_changed = next != *it; + if item_changed { + changed.push(next); + } + let mut story_changed = false; + if let (Some(ps), Some(tf)) = (&os.paragraph_style, it.text_frame()) + && d.story(tf.story).is_some_and(|st| st.paras.iter().any(|f| f.style != *ps)) + { + story_changed = true; + if !restyled.iter().any(|(sid, _)| *sid == tf.story) { + restyled.push((tf.story, ps.clone())); + } + } + n += usize::from(item_changed || story_changed); + } + if n == 0 { return Ok(json!({"changed": 0})); } s.edit(|d, _| { @@ -1450,7 +1465,13 @@ fn clear_object_overrides(s: &mut Session, p: &Value) -> Result { *it = next.clone(); } } - Ok(json!({"changed": changed.len()})) + for (sid, ps) in &restyled { + if let Some(st) = d.story_mut(*sid) { + let len = st.len(); + st.format_paras(0..len, |f| f.style = ps.clone()); + } + } + Ok(json!({"changed": n})) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4770fb16a..6471eb131 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1710,3 +1710,32 @@ fn a_line_fits_when_its_baseline_does() { assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame"); assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line"); } + +/// Clear Overrides puts a text frame's story back in its object style's paragraph style, as +/// applying the style does; and a style's feather choke is kept to 0–100 %, as IDML reads it. +#[test] +fn object_style_clear_overrides_restores_the_paragraph_style_and_choke_is_clamped() { + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap(); + s.execute("style.object.create", &json!({"name": "Captioned", "fromSelection": false, "paragraphStyle": "Caption"})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "One\nTwo"})).unwrap(); + let (id, sid) = (f["id"].as_u64().unwrap(), designcraft_doc::StoryId(f["story"].as_u64().unwrap())); + s.execute("style.object.apply", &json!({"name": "Captioned", "ids": [id]})).unwrap(); + let styles = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().paras.iter().map(|p| p.style.clone()).collect::>(); + assert_eq!(styles(&s), ["Caption", "Caption"]); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let st = std::sync::Arc::make_mut(doc.stories.get_mut(&sid).unwrap()); + st.paras[1].style = designcraft_doc::BASIC_PARAGRAPH.into(); + } + let r = s.execute("style.object.clearOverrides", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["changed"], 1); + assert_eq!(styles(&s), ["Caption", "Caption"]); + let r = s.execute("style.object.clearOverrides", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["changed"], 0, "nothing left to clear"); + + s.execute("style.object.create", &json!({"name": "Soft", "fromSelection": false, "effects": {"feather": 4, "featherOptions": {"choke": 150}}})) + .unwrap(); + let fx = s.doc().unwrap().doc.styles.object_style("Soft").unwrap().effects.clone().unwrap(); + assert_eq!(fx.feather_options.choke, 100.0); +} From f45b02fcc42ff9e92d05aa7feea30c50e5b27a5f Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 14:51:14 +0200 Subject: [PATCH 011/328] Object Styles panel: a story's paragraph style counts as an override; a new style with no effect on sets none Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/object_style_dialog.rs | 22 +++++++++++++++-- crates/ui-egui/src/panels/styles.rs | 29 +++++++++++++++++++++-- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 038e9b7b4..2a9a23ad4 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -71,10 +71,11 @@ fn included(d: &Dialog, key: &str) -> bool { d.fields.get("inc").and_then(|i| i[key].as_bool()).unwrap_or(false) } -/// Whether the style sets effects: it did, or one is on now. +/// Whether the style sets effects: one is on now, or (editing) the style set them already. A new +/// style with every effect off sets none, so applying it leaves the objects' own effects. fn sets_effects(d: &Dialog) -> bool { let fx = d.fields.get("fx").cloned().unwrap_or(Value::Null); - d.b("hadEffects") || crate::effects_dialog::PAGES.iter().skip(1).any(|(k, _)| crate::effects_dialog::is_on(&fx, k)) + (!d.b("new") && d.b("hadEffects")) || crate::effects_dialog::PAGES.iter().skip(1).any(|(k, _)| crate::effects_dialog::is_on(&fx, k)) } /// The style's attributes as the commands take them (null: not in the style). @@ -388,6 +389,23 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod tests { use super::*; + /// A new style made from an object with no effect on sets no effects, so applying it keeps + /// other objects' own. + #[test] + fn a_new_style_without_effects_on_sets_none() { + let (mut app, _) = app_with_frame(); + open_new(&mut app); + let d = app.ui.dialog.clone().unwrap(); + assert!(d.b("hadEffects")); + assert_eq!(attrs(&d)["effects"], Value::Null); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Plain")); + d.fields.insert("apply".into(), json!(false)); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.styles.object_style("Plain").unwrap().effects.is_none()); + } + fn app_with_frame() -> (DesignApp, u64) { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index 0f2295340..f1c057c84 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -105,15 +105,20 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) { list(app, ui, false); } -/// The selected object's style, and whether the object differs from it (an override: `+`). +/// The selected object's style, and whether the object differs from it (an override: `+`): its +/// own attributes, or a text frame's paragraphs in another style than the object style's. fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { let st = app.session.active()?; let it = st.selection.items.first().and_then(|i| st.doc.item(*i))?; let mut styled = it.clone(); + let mut over = false; if let Some(os) = st.doc.styles.object_style(&it.object_style) { os.apply_to(&mut styled); + if let (Some(ps), Some(tf)) = (&os.paragraph_style, it.text_frame()) { + over = st.doc.story(tf.story).is_some_and(|s| s.paras.iter().any(|f| f.style != *ps)); + } } - Some((it.object_style.clone(), styled != *it)) + Some((it.object_style.clone(), over || styled != *it)) } /// Window › Styles › Object Styles, as InDesign's: the selected object's style on top (`+` when @@ -307,6 +312,26 @@ mod tests { use super::*; + /// A text frame whose paragraphs left its object style's paragraph style shows the override + /// mark, and Clear Overrides puts them back. + #[test] + fn a_paragraph_style_change_is_an_object_style_override() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + app.run("style.paragraph.create", serde_json::json!({"name": "Caption"})).unwrap(); + app.run("style.object.create", serde_json::json!({"name": "Captioned", "fromSelection": false, "paragraphStyle": "Caption"})).unwrap(); + let f = app.run("frame.create", serde_json::json!({"rect": [36, 36, 300, 200], "content": "text", "text": "One"})).unwrap(); + app.run("style.object.apply", serde_json::json!({"name": "Captioned", "ids": [f["id"]]})).unwrap(); + app.run("selection.set", serde_json::json!({"ids": [f["id"]]})).unwrap(); + assert_eq!(object_style_of_selection(&app), Some(("Captioned".into(), false))); + app.run("text.select", serde_json::json!({"story": f["story"], "anchor": 0, "focus": 3})).unwrap(); + app.run("style.paragraph.apply", serde_json::json!({"name": designcraft_doc::BASIC_PARAGRAPH})).unwrap(); + app.run("selection.set", serde_json::json!({"ids": [f["id"]]})).unwrap(); + assert_eq!(object_style_of_selection(&app), Some(("Captioned".into(), true)), "the + mark"); + app.run("style.object.clearOverrides", serde_json::json!({})).unwrap(); + assert_eq!(object_style_of_selection(&app), Some(("Captioned".into(), false))); + } + #[test] fn selected_style_context_menu_redefines_its_format() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From fd96b3700fd84d3b05608287bb9c8a1937ffe0c7 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:28:36 +0200 Subject: [PATCH 012/328] Object styles: Paragraph Styles (with Apply Next Style) and Text Frame General Options The course's chapter 39 (Nested Object Styles). Object Style Options gets InDesign's Paragraph Styles page: the paragraph style a text frame's text takes when the object style is applied, and Apply Next Style, which gives the first paragraph that style and each paragraph after it the Next Style of the one before. Its Text Frame General Options page is the Text Frame Options dialog's General page: columns, insets, vertical justification and Ignore Text Wrap. `style.object.create` and `style.object.edit` take `paragraphStyle`, `applyNextStyle` and `textFrame`. Editing moves the frames that still follow the style; text in another paragraph style is an override, which the panel marks and Clear Overrides puts back. IDML reads and writes `ApplyNextParagraphStyle`. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/doc/src/styles.rs | 43 ++++- crates/engine/src/cmd/style.rs | 127 ++++++++++++-- crates/engine/src/tests.rs | 70 ++++++++ crates/idml/src/export.rs | 1 + crates/idml/src/import.rs | 3 +- crates/idml/src/tests/object_styles.rs | 28 +++ crates/ui-egui/src/dialogs.rs | 30 ++-- crates/ui-egui/src/i18n.rs | 14 ++ crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/object_style_dialog.rs | 200 +++++++++++++++++++++- crates/ui-egui/src/panels/styles.rs | 6 +- 21 files changed, 501 insertions(+), 42 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index e4cf4399e..90169f585 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-21** · Object styles nest a paragraph style, as InDesign's: Object Style Options › Paragraph Styles chooses the style a text frame's text takes when the object style is applied, and Apply Next Style gives the first paragraph that style and each paragraph after it the Next Style of the one before (`style.object.create` / `edit`: `paragraphStyle`, `applyNextStyle`; IDML `ApplyNextParagraphStyle`). Object Style Options › Text Frame General Options sets columns, insets, vertical justification and Ignore Text Wrap (`textFrame`). Editing either moves the frames that still follow the style; text in another paragraph style is an override that Clear Overrides puts back. Found in the Learn Skills Daily course, chapter 39. No readiness percentage change. - **2026-10-21** · Window › Styles › Object Styles: InDesign's Object Styles panel (the selected object's style, `+` when overridden; a click applies a style, a double-click opens its options; the default graphic and text frame styles marked; Clear Overrides; Create New Style, ⌥/Alt-click for the dialog) and its New Object Style / Object Style Options dialog (Style Name; Basic Attributes Fill, Stroke, Stroke & Corner Options, each included by its checkbox; Effects for Object with the effects' pages; Style Settings; Apply Style to Selection). UI command `objectStyle.dialog`. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-21** · Object styles carry Corner Options (`corners`), taken from the selection by `style.object.create` and written to IDML (`EnableStrokeAndCornerOptions`, `TopLeftCornerOption`…). `style.object.edit` also changes a style's fill, stroke and corners and renames it (`rename`); the items using the style that haven't overridden an attribute follow each change, as in InDesign. Found in the Learn Skills Daily course, chapter 15. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 380f0fd3a..14bec3776 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::attrs::{CharAttrs, CharProps, ParaAttrs, ParaProps}; use crate::item::{Effects, Fill, Item, Stroke, TextFrameOptions}; -use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat}; +use crate::story::{BASIC_PARAGRAPH, CharFormat, NO_CHAR_STYLE, ParaFormat, Story}; pub const NO_PARA_STYLE: &str = "[No Paragraph Style]"; pub const BASIC_GRAPHICS_FRAME: &str = "[Basic Graphics Frame]"; @@ -54,6 +54,10 @@ pub struct ObjectStyle { pub stroke: Option, #[serde(skip_serializing_if = "Option::is_none")] pub paragraph_style: Option, + /// Paragraph Styles › Apply Next Style: the paragraph style goes on a text frame's first + /// paragraph, and each paragraph after it takes the Next Style of the one before. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub apply_next_style: bool, #[serde(skip_serializing_if = "Option::is_none")] pub text_frame: Option, /// Effects (drop shadow, feather, glows…). An item using the style follows them until its own @@ -84,6 +88,43 @@ impl ObjectStyle { tf.options = o.clone(); } } + + /// The paragraph style of each of a text frame's `n` paragraphs under this style: its + /// paragraph style for all of them, or with Apply Next Style that one first and then each + /// one's Next Style. `None` when the style sets no paragraph style. + pub fn paragraph_styles(&self, styles: &Styles, n: usize) -> Option> { + let mut cur = self.paragraph_style.clone()?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + out.push(cur.clone()); + if self.apply_next_style + && let Some(next) = styles.para(&cur).and_then(|s| s.next_style.clone()) + { + cur = next; + } + } + Some(out) + } + + /// Whether a story's paragraphs are in the paragraph styles this style gives them (they + /// always are when it sets none). + pub fn story_follows(&self, styles: &Styles, st: &Story) -> bool { + self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w)) + } + + /// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it + /// sets none or they already are. + pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool { + if self.story_follows(styles, st) { + return false; + } + let Some(want) = self.paragraph_styles(styles, st.paras.len()) else { return false }; + for (f, w) in st.paras.iter_mut().zip(want) { + f.style = w; + } + st.rev = st.rev.wrapping_add(1); + true + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 7bcdcbb1d..412d97a14 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -359,7 +359,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?, effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them → {name, updated}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them → {name, updated}", has_doc, edit_object ), @@ -1416,12 +1416,11 @@ fn apply_object(s: &mut Session, p: &Value) -> Result { stories.push(tf.story); } } - if let Some(ps) = &os.paragraph_style { - for sid in stories { - if let Some(st) = d.story_mut(sid) { - let len = st.len(); - st.format_paras(0..len, |f| f.style = ps.clone()); - } + // The text takes the style's paragraph style (with Apply Next Style, a chain of them). + let styles = d.styles.clone(); + for sid in stories { + if let Some(st) = d.story_mut(sid) { + os.restyle(&styles, st); } } Ok(Value::Null) @@ -1434,7 +1433,7 @@ fn clear_object_overrides(s: &mut Session, p: &Value) -> Result { // and a text frame's story back in the style's paragraph style, as applying the style does. let d = &s.doc()?.doc; let mut changed: Vec = Vec::new(); - let mut restyled: Vec<(designcraft_doc::StoryId, String)> = Vec::new(); + let mut restyled: Vec<(designcraft_doc::StoryId, ObjectStyle)> = Vec::new(); let mut n = 0; for id in &ids { let Some(it) = d.item(*id) else { continue }; @@ -1446,12 +1445,12 @@ fn clear_object_overrides(s: &mut Session, p: &Value) -> Result { changed.push(next); } let mut story_changed = false; - if let (Some(ps), Some(tf)) = (&os.paragraph_style, it.text_frame()) - && d.story(tf.story).is_some_and(|st| st.paras.iter().any(|f| f.style != *ps)) + if let Some(tf) = it.text_frame() + && d.story(tf.story).is_some_and(|st| !os.story_follows(&d.styles, st)) { story_changed = true; if !restyled.iter().any(|(sid, _)| *sid == tf.story) { - restyled.push((tf.story, ps.clone())); + restyled.push((tf.story, os.clone())); } } n += usize::from(item_changed || story_changed); @@ -1465,10 +1464,10 @@ fn clear_object_overrides(s: &mut Session, p: &Value) -> Result { *it = next.clone(); } } - for (sid, ps) in &restyled { + let styles = d.styles.clone(); + for (sid, os) in &restyled { if let Some(st) = d.story_mut(*sid) { - let len = st.len(); - st.format_paras(0..len, |f| f.style = ps.clone()); + os.restyle(&styles, st); } } Ok(json!({"changed": n})) @@ -1542,8 +1541,14 @@ fn create_object(s: &mut Session, p: &Value) -> Result { if let Some(c) = corners_param(CREATE, p, os.corners.unwrap_or_default())? { os.corners = c; } - if let Some(ps) = str_param(p, "paragraphStyle") { - os.paragraph_style = Some(ps.to_string()); + if let Some(ps) = paragraph_style_param(CREATE, s, p)? { + os.paragraph_style = ps; + } + if let Some(next) = bool_param(CREATE, p, "applyNextStyle")? { + os.apply_next_style = next; + } + if let Some(tf) = text_frame_param(CREATE, p, os.text_frame.as_ref())? { + os.text_frame = tf; } if let Some(e) = effects_param("style.object.create", p, os.effects.as_ref().unwrap_or(&Effects::default()))? { os.effects = Some(e); @@ -1556,6 +1561,46 @@ fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// `paragraphStyle`: a paragraph style's name, or null (the object style sets none). +fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result>> { + match p.get("paragraphStyle") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(Value::String(n)) if s.doc()?.doc.styles.para(n).is_some() => Ok(Some(Some(n.clone()))), + Some(Value::String(n)) => Err(bad(cmd, format!("no paragraph style `{n}`"))), + Some(_) => Err(bad(cmd, "`paragraphStyle` must be a paragraph style's name or null")), + } +} + +/// A true/false parameter, when given. +fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + } +} + +/// `textFrame` (a text frame's options, as `document.inspect` shows them) merged over `base`, or +/// null; refused when the columns aren't 1–40 or a gutter, width or inset isn't 0–15552 pt. +fn text_frame_param( + cmd: &str, + p: &Value, + base: Option<&designcraft_doc::TextFrameOptions>, +) -> Result>> { + let tf = group_param(cmd, p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + if let Some(Some(o)) = &tf { + if !(1..=40).contains(&o.columns) { + return Err(bad(cmd, "text frame columns must be 1–40")); + } + let mut lengths = [o.gutter, o.column_width, o.vj_paragraph_spacing_limit, o.first_baseline_min].into_iter().chain(o.inset); + if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) { + return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt")); + } + } + Ok(tf) +} + /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 /// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { @@ -1658,6 +1703,15 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { if let Some(c) = corners_param(CMD, p, old.corners.unwrap_or_default())? { new.corners = c; } + if let Some(ps) = paragraph_style_param(CMD, s, p)? { + new.paragraph_style = ps; + } + if let Some(next) = bool_param(CMD, p, "applyNextStyle")? { + new.apply_next_style = next; + } + if let Some(tf) = text_frame_param(CMD, p, old.text_frame.as_ref())? { + new.text_frame = tf; + } let rename = str_param(p, "rename").map(str::trim).filter(|r| *r != name).map(str::to_string); if let Some(r) = &rename { let builtin = name.starts_with('[') && name.ends_with(']'); @@ -1701,11 +1755,14 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { .flatten() .map(|f| (old.stroke.clone().unwrap_or_else(designcraft_doc::Stroke::none), f)); let corners = (new.corners != old.corners).then_some(new.corners).flatten().map(|c| (old.corners.unwrap_or_default(), c)); + let frame = + (new.text_frame != old.text_frame).then_some(new.text_frame.clone()).flatten().map(|t| (old.text_frame.clone().unwrap_or_default(), t)); let follows = |it: &Item| { effects.as_ref().is_some_and(|(o, _)| it.effects == *o) || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) || corners.as_ref().is_some_and(|(o, _)| it.corners == *o) + || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options == *o)) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -1730,9 +1787,43 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { { it.corners = *n; } + if let Some((o, n)) = &frame + && let Some(tf) = it.text_frame_mut() + && tf.options == *o + { + tf.options = n.clone(); + } }, ); - Ok(json!({"name": new.name, "updated": updated})) + // The text of the frames using the style takes a new paragraph style (or chain) while it + // is in the old one's; when the style set none before, all of it does. + let mut restyled = 0; + if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) { + let mut stories = Vec::new(); + for sp in d.spreads.iter().chain(d.parents.iter()) { + for it in &sp.items { + it.walk(&mut |i| { + if i.object_style == new.name + && let Some(tf) = i.text_frame() + { + stories.push(tf.story); + } + }); + } + } + stories.sort_unstable(); + stories.dedup(); + let styles = d.styles.clone(); + for sid in stories { + if d.story(sid).is_some_and(|st| old.story_follows(&styles, st)) + && let Some(st) = d.story_mut(sid) + && new.restyle(&styles, st) + { + restyled += 1; + } + } + } + Ok(json!({"name": new.name, "updated": updated, "restyled": restyled})) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6471eb131..a2ac00a60 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -745,6 +745,76 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert_eq!(item(&s, a).object_style, name); } +/// The course's chapter 39 (nested object styles): an object style carries a paragraph style, +/// with Apply Next Style a chain of them, and text frame options. Applying it styles the frame's +/// text; editing it moves the frames that still follow it, not one whose text took another style, +/// which Clear Overrides puts back. +#[test] +fn object_styles_carry_a_paragraph_style_and_text_frame_options() { + use designcraft_doc::ItemId; + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Body Text"})).unwrap(); + s.execute( + "style.paragraph.create", + &json!({"name": "Drop Cap First Paragraph", "nextStyle": "Body Text", "para": {"dropCapLines": 3, "dropCapChars": 1}}), + ) + .unwrap(); + let name = "Text Box Drop Cap"; + s.execute( + "style.object.create", + &json!({"name": name, "fromSelection": false, "paragraphStyle": "Drop Cap First Paragraph", "applyNextStyle": true, "textFrame": {"inset": [4, 4, 4, 4]}}), + ) + .unwrap(); + let frame = |s: &mut Session, x: f64, text: &str| { + let r = s.execute("frame.create", &json!({"rect": [x, 36, x + 200.0, 300], "content": "text", "text": text, "caret": false})).unwrap(); + (r["id"].as_u64().unwrap(), r["story"].clone()) + }; + let ((a, _), (b, b_story)) = (frame(&mut s, 36.0, "One\nTwo\nThree"), frame(&mut s, 300.0, "Alone")); + s.execute("style.object.apply", &json!({"name": name, "ids": [a, b]})).unwrap(); + let styles_of = |s: &Session, id: u64| { + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(id)).unwrap().text_frame().unwrap().story; + d.story(sid).unwrap().paras.iter().map(|p| p.style.clone()).collect::>() + }; + let options = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + assert_eq!(styles_of(&s, a), ["Drop Cap First Paragraph", "Body Text", "Body Text"], "Apply Next Style"); + assert_eq!(styles_of(&s, b), ["Drop Cap First Paragraph"]); + assert_eq!(options(&s, a).inset, [4.0; 4]); + + // b's text takes another paragraph style: its own, kept when the object style changes. + s.execute("text.select", &json!({"story": b_story, "anchor": 0, "focus": 5})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Body Text"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Box Body Text"})).unwrap(); + let r = s + .execute("style.object.edit", &json!({"name": name, "paragraphStyle": "Box Body Text", "applyNextStyle": false, "textFrame": {"columns": 2}})) + .unwrap(); + assert_eq!((r["updated"].as_u64(), r["restyled"].as_u64()), (Some(2), Some(1))); + assert_eq!(styles_of(&s, a), ["Box Body Text"; 3]); + assert_eq!(styles_of(&s, b), ["Body Text"], "its own style stays"); + assert_eq!((options(&s, a).columns, options(&s, a).inset, options(&s, b).columns), (2, [4.0; 4], 2)); + s.execute("style.object.clearOverrides", &json!({"ids": [b]})).unwrap(); + assert_eq!(styles_of(&s, b), ["Box Body Text"]); + + // Refused: an unknown paragraph style, no columns, a negative inset, a word for a switch. + for bad in [ + json!({"paragraphStyle": "Nope"}), + json!({"paragraphStyle": 3}), + json!({"textFrame": {"columns": 0}}), + json!({"textFrame": {"inset": [-1, 0, 0, 0]}}), + json!({"applyNextStyle": "yes"}), + ] { + let mut p = bad.clone(); + p["name"] = json!(name); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); + } + // null: the style no longer sets a paragraph style or frame options; the frames keep theirs. + s.execute("style.object.edit", &json!({"name": name, "paragraphStyle": null, "textFrame": null})).unwrap(); + let os = s.doc().unwrap().doc.styles.object_style(name).cloned().unwrap(); + assert!(os.paragraph_style.is_none() && os.text_frame.is_none()); + assert_eq!((styles_of(&s, a), options(&s, a).columns), (vec!["Box Body Text".to_string(); 3], 2)); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index e29a6838e..ef3f0e683 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -1074,6 +1074,7 @@ impl<'a> Ex<'a> { } if let Some(ps) = &os.paragraph_style { el.set("AppliedParagraphStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, ps)); + el.set("ApplyNextParagraphStyle", bool_s(os.apply_next_style)); } let mut el = with_props(el, props); if let Some(e) = &os.effects { diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 6160bb599..bef706ba3 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -1275,7 +1275,8 @@ impl<'r> Importer<'r> { // in a rectangle's path order. let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false")).then(|| corners(e, "")).flatten().map(|c| CornerOptions { corners: c }); - let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, text_frame, effects, corners }; + let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); + let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { Some(slot) => *slot = s, None => self.styles.object.push(s), diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 4e7f5ef5d..f445c7f41 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -149,6 +149,34 @@ fn item_overrides_and_disabled_categories_turn_style_effects_off() { assert!((ds.opacity - 0.75).abs() < 1e-6); } +/// An object style's paragraph style and Apply Next Style (`ApplyNextParagraphStyle`) round-trip. +#[test] +fn object_style_apply_next_style_round_trips() { + let mut d = small_doc(); + let styles = std::sync::Arc::make_mut(&mut d.styles); + styles.paragraph.push(designcraft_doc::ParagraphStyle { + name: "Opener".into(), + based_on: None, + next_style: Some(designcraft_doc::BASIC_PARAGRAPH.into()), + para: Default::default(), + chars: Default::default(), + shortcut: String::new(), + }); + for (name, next) in [("Chained", true), ("Single", false)] { + styles.object.push(designcraft_doc::ObjectStyle { + name: name.into(), + paragraph_style: Some("Opener".into()), + apply_next_style: next, + ..Default::default() + }); + } + let back = import_idml(&export_idml(&d)).unwrap(); + for (name, next) in [("Chained", true), ("Single", false)] { + let os = back.styles.object_style(name).unwrap(); + assert_eq!((os.paragraph_style.as_deref(), os.apply_next_style), (Some("Opener"), next), "{name}"); + } +} + #[test] fn exported_frames_keep_their_own_values_over_their_object_style() { let mut d = small_doc(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 8be3aafb5..762cfcb05 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -103,7 +103,7 @@ impl Dialog { None => String::new(), } } - fn m(&self, k: &str) -> Option { + pub(crate) fn m(&self, k: &str) -> Option { match self.fields.get(k) { Some(Value::Number(n)) => n.as_f64(), Some(Value::String(s)) => parse_measure(s, self.unit).ok(), @@ -511,16 +511,29 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { } let o = selected_frame_options(app).unwrap_or_default(); let units = app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas); + let shown = text_frame_fields(&o, units, selected_frame_width(app)); + if let Value::Object(m) = &shown { + for (k, v) in m { + d.fields.entry(k.clone()).or_insert_with(|| v.clone()); + } + } + d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(o.inset.iter().all(|v| (v - o.inset[0]).abs() < 1e-9))); + d.fields.insert("_shown".into(), shown); +} + +/// Text frame options `o` as the Text Frame Options dialog's fields, measures in `units`; with the +/// frame's width, a Fixed Number column shows the width it gets. +pub(crate) fn text_frame_fields(o: &designcraft_doc::TextFrameOptions, units: Unit, frame_width: Option) -> Value { let fm = |v: f64| json!(format_measure(v, units)); // Fixed Number: the width each column gets in the frame (shown, as in InDesign). - let inner = selected_frame_width(app).map(|w| w - o.inset[1] - o.inset[3]).unwrap_or(0.0); + let inner = frame_width.map(|w| w - o.inset[1] - o.inset[3]).unwrap_or(0.0); let n = o.columns.max(1) as f64; let width = match o.columns_kind { designcraft_doc::ColumnsKind::FixedWidth if o.column_width > 0.0 => o.column_width, _ => ((inner - o.gutter * (n - 1.0)) / n).max(0.0), }; let kind = |v: Value| v.as_str().unwrap_or_default().to_string(); - let shown = json!({ + json!({ "columns": o.columns, "gutter": fm(o.gutter), "columnsKind": kind(serde_json::to_value(o.columns_kind).unwrap_or_default()), "columnWidth": fm(width), "balanceColumns": o.balance_columns, "ignoreWrap": o.ignore_wrap, @@ -535,14 +548,7 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { "useMinimumHeight": o.auto_size_use_min_height, "minimumHeight": fm(o.auto_size_min_height), "useMinimumWidth": o.auto_size_use_min_width, "minimumWidth": fm(o.auto_size_min_width), "noLineBreaks": o.auto_size_no_line_breaks, - }); - if let Value::Object(m) = &shown { - for (k, v) in m { - d.fields.entry(k.clone()).or_insert_with(|| v.clone()); - } - } - d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(o.inset.iter().all(|v| (v - o.inset[0]).abs() < 1e-9))); - d.fields.insert("_shown".into(), shown); + }) } /// A 0..1 tint as a percentage ("40", "12.5"). @@ -595,7 +601,7 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) } /// Text Frame Options › General: columns, inset spacing, vertical justification, text wrap. -fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { +pub(crate) fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { let tr = |s: &'static str| crate::i18n::tr(lang, s); crate::rtl::label(ui, egui::RichText::new(tr("Columns")).font(semibold(12.0))); egui::Grid::new("tfo_cols").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 72d756c7b..7a4683f6f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1034,6 +1034,20 @@ const TABLE: &[(&str, [&str; 5])] = &[ ], ), ("Load Styles", ["Formate laden", "Charger les styles", "Cargar estilos", "スタイルを読み込み", "加载样式"]), + ( + "Apply Next Style", + ["Nächstes Format anwenden", "Appliquer le style suivant", "Aplicar estilo siguiente", "次のスタイルを適用", "应用下一样式"], + ), + ( + "Text Frame General Options", + [ + "Allgemeine Textrahmenoptionen", + "Options générales du bloc de texte", + "Opciones generales de marco de texto", + "テキストフレーム一般オプション", + "文本框架常规选项", + ], + ), ( "Differs from this document", ["Weicht von diesem Dokument ab", "Diffère de ce document", "Difiere de este documento", "このドキュメントと異なります", "与此文档不同"], diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 1872dd73c..0f0764a47 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -30,6 +30,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "قص"), ("Copy", "نسخ"), ("Paste", "لصق"), + ("Apply Next Style", "تطبيق النمط التالي"), + ("Text Frame General Options", "خيارات عامة لإطار النص"), ("New Object Style", "نمط كائن جديد"), ("Object Style Options", "خيارات نمط الكائن"), ("Object Style Options…", "خيارات نمط الكائن…"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b46318852..70530a249 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Vyjmout"), ("Copy", "Kopírovat"), ("Paste", "Vložit"), + ("Apply Next Style", "Použít další styl"), + ("Text Frame General Options", "Obecné volby textového rámečku"), ("New Object Style", "Nový styl objektu"), ("Object Style Options", "Možnosti stylu objektu"), ("Object Style Options…", "Možnosti stylu objektu…"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index efc128858..38c2a409d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Ausschneiden"), ("Copy", "Kopieren"), ("Paste", "Einfügen"), + ("Apply Next Style", "Nächstes Format anwenden"), + ("Text Frame General Options", "Allgemeine Textrahmenoptionen"), ("Inches Decimal", "Zoll dezimal"), ("Back", "Zurück"), ("Warning", "Warnung"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index ab7a6840f..7835da9dc 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -28,6 +28,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Taglia"), ("Copy", "Copia"), ("Paste", "Incolla"), + ("Apply Next Style", "Applica stile successivo"), + ("Text Frame General Options", "Opzioni generali cornice di testo"), ("New Object Style", "Nuovo stile oggetto"), ("Object Style Options", "Opzioni stile oggetto"), ("Object Style Options…", "Opzioni stile oggetto…"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 5647ca940..ece8f73e9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -30,6 +30,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "カット"), ("Copy", "コピー"), ("Paste", "ペースト"), + ("Apply Next Style", "次のスタイルを適用"), + ("Text Frame General Options", "テキストフレーム一般オプション"), ("Paste Vector Art", "ベクトルアートをペースト"), ("Baseline Options", "ベースラインオプション"), ("Column Rules", "段落境界線"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index fe735f4d7..655dd5363 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "ამოჭრა"), ("Copy", "კოპირება"), ("Paste", "ჩასმა"), + ("Apply Next Style", "შემდეგი სტილის გამოყენება"), + ("Text Frame General Options", "ტექსტის ჩარჩოს ზოგადი პარამეტრები"), ("New Object Style", "ახალი ობიექტის სტილი"), ("Object Style Options", "ობიექტის სტილის პარამეტრები"), ("Object Style Options…", "ობიექტის სტილის პარამეტრები…"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index f0f7f58a1..9543ff5a7 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -29,6 +29,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Wytnij"), ("Copy", "Kopiuj"), ("Paste", "Wklej"), + ("Apply Next Style", "Zastosuj następny styl"), + ("Text Frame General Options", "Ogólne opcje ramki tekstowej"), ("New Object Style", "Nowy styl obiektu"), ("Object Style Options", "Opcje stylu obiektu"), ("Object Style Options…", "Opcje stylu obiektu…"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index b922a37c9..721b08f98 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -31,6 +31,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Recortar"), ("Copy", "Copiar"), ("Paste", "Colar"), + ("Apply Next Style", "Aplicar próximo estilo"), + ("Text Frame General Options", "Opções gerais do quadro de texto"), ("New Object Style", "Novo estilo de objeto"), ("Object Style Options", "Opções de estilo de objeto"), ("Object Style Options…", "Opções de estilo de objeto…"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index d8630b712..e8334fd61 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -33,6 +33,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вырезать"), ("Copy", "Копировать"), ("Paste", "Вставить"), + ("Apply Next Style", "Применить следующий стиль"), + ("Text Frame General Options", "Общие параметры текстового фрейма"), ("New Object Style", "Новый стиль объекта"), ("Object Style Options", "Параметры стиля объекта"), ("Object Style Options…", "Параметры стиля объекта…"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 242cb0d1e..cefcad96a 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -29,6 +29,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Cut", "Вирізати"), ("Copy", "Копіювати"), ("Paste", "Вставити"), + ("Apply Next Style", "Застосувати наступний стиль"), + ("Text Frame General Options", "Загальні параметри текстового фрейму"), ("New Object Style", "Новий стиль об'єкта"), ("Object Style Options", "Параметри стилю об'єкта"), ("Object Style Options…", "Параметри стилю об'єкта…"), diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 2a9a23ad4..0b4055f7d 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -2,6 +2,9 @@ //! InDesign's: the style's name on top; on the left its Basic Attributes (a checkbox includes one //! in the style, a click shows its settings) and its effects; on the right the settings of the //! attribute shown (General sums the style up); Apply Style to Selection for a new style. +//! +//! Paragraph Styles nests a paragraph style in the object style (the course's chapter 39), and +//! Text Frame General Options is the Text Frame Options dialog's General page. use serde_json::{Value, json}; @@ -12,8 +15,30 @@ use crate::theme::semibold; /// The dialog's id. pub const ID: &str = "objectStyle"; -/// Basic Attributes: (key, label). General isn't an attribute: it sums the style up. -const ATTRIBUTES: [(&str, &str); 4] = [("general", "General"), ("fill", "Fill"), ("stroke", "Stroke"), ("corners", "Stroke & Corner Options")]; +/// Basic Attributes: (key, label), in InDesign's order. General isn't an attribute: it sums the +/// style up. +const ATTRIBUTES: [(&str, &str); 6] = [ + ("general", "General"), + ("fill", "Fill"), + ("stroke", "Stroke"), + ("corners", "Stroke & Corner Options"), + ("paragraph", "Paragraph Styles"), + ("textFrame", "Text Frame General Options"), +]; + +/// The fields of the Paragraph Styles and Text Frame General Options pages: the style's paragraph +/// style (`""`: none), Apply Next Style, and text frame options `tf` as the Text Frame Options +/// dialog shows them (`tfBase` keeps the options the page doesn't show). +fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, next: bool, tf: &designcraft_doc::TextFrameOptions) { + let units = app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units); + fields["paragraphStyle"] = json!(paragraph.unwrap_or("")); + fields["applyNext"] = json!(next); + fields["tfBase"] = serde_json::to_value(tf).unwrap_or_default(); + fields["insetLinked"] = json!(tf.inset.iter().all(|v| (v - tf.inset[0]).abs() < 1e-9)); + if let (Value::Object(f), Value::Object(shown)) = (fields, crate::dialogs::text_frame_fields(tf, units, None)) { + f.extend(shown); + } +} /// The dialog for a new style from the selected object (its fill, stroke, corners and effects, /// as InDesign's New Object Style), named "Object Style n". @@ -23,7 +48,9 @@ pub fn open_new(app: &mut DesignApp) { let taken = |n: &str| st.doc.styles.object_style(n).is_some(); let name = (1..).map(|i| format!("Object Style {i}")).find(|n| !taken(n)).unwrap_or_default(); let from = it.is_some(); - let fields = json!({ + // A text frame's options come along; its paragraph style is left to choose, as in InDesign. + let frame = it.as_ref().and_then(|i| i.text_frame()).map(|t| t.options.clone()); + let mut fields = json!({ "new": true, "name": name, "basedOn": designcraft_doc::NO_OBJECT_STYLE, @@ -32,10 +59,11 @@ pub fn open_new(app: &mut DesignApp) { "corners": it.as_ref().map(|i| i.corners).unwrap_or_default(), "fx": crate::effects_dialog::effects_json(&it.map(|i| i.effects).unwrap_or_default()), "hadEffects": from, - "inc": {"fill": from, "stroke": from, "corners": from}, + "inc": {"fill": from, "stroke": from, "corners": from, "paragraph": from, "textFrame": frame.is_some()}, "page": "general", "apply": from, }); + text_fields(app, &mut fields, None, false, &frame.unwrap_or_default()); app.ui.dialog = Some(Dialog::new(ID, fields)); } @@ -45,7 +73,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) { if name == designcraft_doc::NO_OBJECT_STYLE { return; } - let fields = json!({ + let mut fields = json!({ "new": false, "orig": name, "name": name, @@ -55,10 +83,14 @@ pub fn open_edit(app: &mut DesignApp, name: &str) { "corners": os.corners.unwrap_or_default(), "fx": crate::effects_dialog::effects_json(&os.effects.clone().unwrap_or_default()), "hadEffects": os.effects.is_some(), - "inc": {"fill": os.fill.is_some(), "stroke": os.stroke.is_some(), "corners": os.corners.is_some()}, + "inc": { + "fill": os.fill.is_some(), "stroke": os.stroke.is_some(), "corners": os.corners.is_some(), + "paragraph": os.paragraph_style.is_some(), "textFrame": os.text_frame.is_some(), + }, "page": "general", "apply": false, }); + text_fields(app, &mut fields, os.paragraph_style.as_deref(), os.apply_next_style, &os.text_frame.clone().unwrap_or_default()); app.ui.dialog = Some(Dialog::new(ID, fields)); } @@ -85,9 +117,36 @@ fn attrs(d: &Dialog) -> serde_json::Map { p.insert(k.into(), if included(d, k) { d.fields.get(k).cloned().unwrap_or(Value::Null) } else { Value::Null }); } p.insert("effects".into(), if sets_effects(d) { d.fields.get("fx").cloned().unwrap_or(Value::Null) } else { Value::Null }); + let paragraph = d.s("paragraphStyle"); + p.insert("paragraphStyle".into(), if included(d, "paragraph") && !paragraph.is_empty() { json!(paragraph) } else { Value::Null }); + p.insert("applyNextStyle".into(), json!(d.b("applyNext"))); p } +/// The Text Frame General Options page as the style's text frame options (the options it doesn't +/// show as they were), or `None` when the style doesn't set them. +fn frame_options(d: &Dialog) -> Result, String> { + if !included(d, "textFrame") { + return Ok(None); + } + let mut o: designcraft_doc::TextFrameOptions = d.fields.get("tfBase").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); + let bad = |what: &str| format!("Text Frame General Options: {what}"); + let measure = |key: &str| d.m(key).filter(|v| v.is_finite() && (0.0..=15552.0).contains(v)); + o.columns = d.n("columns").filter(|n| (1.0..=40.0).contains(n)).ok_or_else(|| bad("the number of columns is 1–40"))? as u32; + o.gutter = measure("gutter").ok_or_else(|| bad("the gutter is not a measure"))?; + o.columns_kind = serde_json::from_value(json!(d.s("columnsKind"))).unwrap_or(o.columns_kind); + if o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth { + o.column_width = measure("columnWidth").ok_or_else(|| bad("the column width is not a measure"))?; + } + o.balance_columns = d.b("balanceColumns"); + for (side, key) in o.inset.iter_mut().zip(["insetTop", "insetLeft", "insetBottom", "insetRight"]) { + *side = measure(key).ok_or_else(|| bad("an inset is not a measure"))?; + } + o.vertical_justification = serde_json::from_value(json!(d.s("verticalJustification"))).unwrap_or(o.vertical_justification); + o.ignore_wrap = d.b("ignoreWrap"); + Ok(Some(o)) +} + /// OK: the new style (applied to the selection when asked), or the edited one. pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let name = d.s("name").trim().to_string(); @@ -95,6 +154,7 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); } let mut p = attrs(d); + p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| serde_json::to_value(o).unwrap_or_default())); if d.b("new") { p.insert("name".into(), json!(name)); p.insert("fromSelection".into(), json!(false)); @@ -119,6 +179,10 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { if p.get("effects").is_some_and(Value::is_null) && !d.b("hadEffects") { p.remove("effects"); } + // Apply Next Style means nothing without a paragraph style. + if p.get("paragraphStyle").is_some_and(Value::is_null) { + p.remove("applyNextStyle"); + } app.run("style.object.edit", Value::Object(p)).map_err(|e| e.to_string()) } } @@ -217,6 +281,24 @@ fn settings(app: &DesignApp, d: &Dialog) -> Vec { let shape: designcraft_geom::corners::CornerShape = serde_json::from_value(c["shape"].clone()).unwrap_or_default(); out.push(format!("{}: {} {} pt", tr("Corner Options"), tr(shape.label()), c["size"].as_f64().unwrap_or(0.0))); } + let paragraph = d.s("paragraphStyle"); + if included(d, "paragraph") && !paragraph.is_empty() { + let next = if d.b("applyNext") { format!(", {}", tr("Apply Next Style")) } else { String::new() }; + out.push(format!("{}: {}{next}", tr("Paragraph Styles"), crate::i18n::style_name(&app.ui.language, ¶graph))); + } + if included(d, "textFrame") { + let insets: Vec = ["insetTop", "insetLeft", "insetBottom", "insetRight"].iter().map(|k| d.s(k)).collect(); + let inset = if insets.iter().all(|i| *i == insets[0]) { insets[0].clone() } else { insets.join(", ") }; + out.push(format!( + "{}: {} {}, {} {}, {}: {inset}", + tr("Text Frame General Options"), + tr("Columns:"), + d.s("columns"), + tr("Gutter:"), + d.s("gutter"), + tr("Inset Spacing") + )); + } if sets_effects(d) { let fx = d.fields.get("fx").cloned().unwrap_or(Value::Null); let on: Vec = @@ -315,6 +397,34 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { }); }); } + "paragraph" => { + let Some(doc) = app.session.active().map(|st| &st.doc) else { return }; + ui.add_enabled_ui(included(d, "paragraph"), |ui| { + ui.horizontal(|ui| { + crate::rtl::label(ui, tr("Paragraph Style:")); + let cur = d.s("paragraphStyle"); + let shown = if cur.is_empty() { String::new() } else { crate::i18n::style_name(&app.ui.language, &cur).to_string() }; + let mut picked = None; + egui::ComboBox::from_id_salt("os_paragraph_style").selected_text(shown).width(240.0).show_ui(ui, |ui| { + for s in &doc.styles.paragraph { + if ui.selectable_label(s.name == cur, crate::i18n::style_name(&app.ui.language, &s.name)).clicked() { + picked = Some(s.name.clone()); + } + } + }); + if let Some(name) = picked { + d.fields.insert("paragraphStyle".into(), json!(name)); + } + }); + let mut next = d.b("applyNext"); + if ui.checkbox(&mut next, crate::rtl::widget(ui, tr("Apply Next Style"))).changed() { + d.fields.insert("applyNext".into(), json!(next)); + } + }); + } + "textFrame" => { + ui.add_enabled_ui(included(d, "textFrame"), |ui| crate::dialogs::general(&app.ui.language, ui, d)); + } p => crate::effects_dialog::page_ui(app, ui, d, p), } } @@ -414,9 +524,10 @@ mod tests { (app, id) } + /// The texts the dialog paints, once its size has settled (it grows over a few frames). fn frame(app: &mut DesignApp, ctx: &egui::Context) -> Vec { let mut texts = Vec::new(); - for _ in 0..3 { + for _ in 0..8 { let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); @@ -493,6 +604,81 @@ mod tests { assert!(doc(&app).styles.object_style(name).unwrap().effects.as_ref().unwrap().drop_shadow.on, "effects kept"); } + /// The course's chapter 39: a new object style from a text frame nests the "Drop Cap First + /// Paragraph" style (Paragraph Styles page), so the frame's text takes it; Object Style + /// Options › Text Frame General Options then gives the style's frames insets and two columns. + #[test] + fn an_object_style_nests_a_paragraph_style_and_sets_text_frame_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Body Text"})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Drop Cap First Paragraph", "nextStyle": "Body Text", "para": {"dropCapLines": 3}})) + .unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 336], "content": "text", "caret": false})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + open_new(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(included(d, "paragraph") && included(d, "textFrame"), "a text frame's categories are in a new style"); + assert_eq!(d.s("paragraphStyle"), "", "the paragraph style is left to choose"); + let texts = frame(&mut app, &ctx); + for t in ["Paragraph Styles", "Text Frame General Options"] { + assert!(texts.iter().any(|x| x.trim() == t), "{t}: {texts:?}"); + } + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Text Box Drop Cap")); + d.fields.insert("page".into(), json!("paragraph")); + d.fields.insert("paragraphStyle".into(), json!("Drop Cap First Paragraph")); + } + let texts = frame(&mut app, &ctx); + for t in ["Paragraph Style:", "Apply Next Style", "Drop Cap First Paragraph"] { + assert!(texts.iter().any(|x| x.trim() == t), "{t}: {texts:?}"); + } + crate::dialogs::confirm(&mut app).unwrap(); + let doc = |app: &DesignApp| app.session.active().unwrap().doc.clone(); + let story = |app: &DesignApp| { + let d = doc(app); + let sid = d.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().story; + d.story(sid).unwrap().clone() + }; + assert_eq!(doc(&app).item(designcraft_doc::ItemId(id)).unwrap().object_style, "Text Box Drop Cap"); + assert_eq!(story(&app).paras[0].style, "Drop Cap First Paragraph", "the frame's text takes the nested style"); + app.run("type.fillWithPlaceholder", json!({"frame": id})).unwrap(); + assert!(story(&app).paras.iter().all(|p| p.style == "Drop Cap First Paragraph")); + + open_edit(&mut app, "Text Box Drop Cap"); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|x| x.starts_with("Paragraph Styles: Drop Cap First Paragraph")), "Style Settings: {texts:?}"); + if let Some(d) = app.ui.dialog.as_mut() { + assert_eq!(d.s("paragraphStyle"), "Drop Cap First Paragraph"); + d.fields.insert("page".into(), json!("textFrame")); + for k in ["insetTop", "insetLeft", "insetBottom", "insetRight"] { + d.fields.insert(k.into(), json!("4 pt")); + } + d.fields.insert("columns".into(), json!("2")); + } + let texts = frame(&mut app, &ctx); + for t in ["Inset Spacing", "Vertical Justification", "Ignore Text Wrap"] { + assert!(texts.iter().any(|x| x.trim() == t), "{t}: {texts:?}"); + } + crate::dialogs::confirm(&mut app).unwrap(); + let o = doc(&app).item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + assert_eq!((o.columns, o.inset), (2, [4.0; 4])); + let os = doc(&app).styles.object_style("Text Box Drop Cap").cloned().unwrap(); + assert_eq!((os.paragraph_style.as_deref(), os.text_frame.map(|t| t.columns)), (Some("Drop Cap First Paragraph"), Some(2))); + + // A word for the gutter keeps the dialog open with the reason. + open_edit(&mut app, "Text Box Drop Cap"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("gutter".into(), json!("wide")); + } + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("gutter"), "{e}"); + assert!(app.ui.dialog.is_some()); + } + /// A refused OK (an empty name, a name another style has) keeps the dialog and its edits, /// with the reason shown. #[test] diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index f1c057c84..500e3308f 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -106,7 +106,7 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) { } /// The selected object's style, and whether the object differs from it (an override: `+`): its -/// own attributes, or a text frame's paragraphs in another style than the object style's. +/// own attributes, or a text frame's paragraphs in other styles than the object style gives them. fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { let st = app.session.active()?; let it = st.selection.items.first().and_then(|i| st.doc.item(*i))?; @@ -114,8 +114,8 @@ fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { let mut over = false; if let Some(os) = st.doc.styles.object_style(&it.object_style) { os.apply_to(&mut styled); - if let (Some(ps), Some(tf)) = (&os.paragraph_style, it.text_frame()) { - over = st.doc.story(tf.story).is_some_and(|s| s.paras.iter().any(|f| f.style != *ps)); + if let Some(tf) = it.text_frame() { + over = st.doc.story(tf.story).is_some_and(|s| !os.story_follows(&st.doc.styles, s)); } } Some((it.object_style.clone(), over || styled != *it)) From a13c6dde6793b58c0da733e0cb9538d5ab6a58c7 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 00:42:28 +0200 Subject: [PATCH 013/328] Object Styles: objectStyle.dialog reports a style with no options; Polish Clear Overrides MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `objectStyle.dialog` with a style the document doesn't have, or with [None], returned success and opened nothing. `open_edit` now refuses them and the command passes the error on. Polish "Clear Overrides" reads "Wyczyść zastąpienia", as the table's other override action. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/pl.rs | 2 +- crates/ui-egui/src/menus.rs | 12 +++++----- crates/ui-egui/src/object_style_dialog.rs | 29 ++++++++++++++++++----- crates/ui-egui/src/panels/styles.rs | 6 ++--- 4 files changed, 33 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index f0f7f58a1..41bfd2fe2 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -37,7 +37,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Effects for:", "Efekty dla:"), ("Apply Style to Selection", "Zastosuj styl do zaznaczenia"), ("Create New Style", "Utwórz nowy styl"), - ("Clear Overrides", "Wyczyść zmiany"), + ("Clear Overrides", "Wyczyść zastąpienia"), ("Shape:", "Kształt:"), ("(no attributes)", "(brak atrybutów)"), ("Enter a style name.", "Wpisz nazwę stylu."), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 237e64f55..67d6708a6 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1195,13 +1195,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option { - match p.get("name").and_then(Value::as_str) { - Some(n) => crate::object_style_dialog::open_edit(app, n), - None => crate::object_style_dialog::open_new(app), + "objectStyle.dialog" => match p.get("name").and_then(Value::as_str) { + Some(n) => crate::object_style_dialog::open_edit(app, n).map(|()| Value::Null), + None => { + crate::object_style_dialog::open_new(app); + Ok(Value::Null) } - Ok(Value::Null) - } + }, "app.loadSwatches" => { if let Some(pick) = app.services.pick_open.as_mut() { return Some(match pick("swatches") { diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 2a9a23ad4..9dc905b3c 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -39,11 +39,14 @@ pub fn open_new(app: &mut DesignApp) { app.ui.dialog = Some(Dialog::new(ID, fields)); } -/// Object Style Options for style `name`. -pub fn open_edit(app: &mut DesignApp, name: &str) { - let Some(os) = app.session.active().and_then(|st| st.doc.styles.object_style(name).cloned()) else { return }; +/// Object Style Options for style `name`; refused for a style the document doesn't have and for +/// `[None]`, which has no options. +pub fn open_edit(app: &mut DesignApp, name: &str) -> Result<(), String> { + let Some(os) = app.session.active().and_then(|st| st.doc.styles.object_style(name).cloned()) else { + return Err(format!("no object style `{name}`")); + }; if name == designcraft_doc::NO_OBJECT_STYLE { - return; + return Err(format!("`{name}` has no options")); } let fields = json!({ "new": false, @@ -60,6 +63,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) { "apply": false, }); app.ui.dialog = Some(Dialog::new(ID, fields)); + Ok(()) } /// The dialog's title: New Object Style or Object Style Options. @@ -480,7 +484,7 @@ mod tests { let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); app.run("style.object.apply", json!({"name": name, "ids": [b]})).unwrap(); - open_edit(&mut app, name); + open_edit(&mut app, name).unwrap(); if let Some(d) = app.ui.dialog.as_mut() { assert_eq!(title(d), "Object Style Options"); set(d, &["stroke", "weight"], json!(5.0)); @@ -493,6 +497,19 @@ mod tests { assert!(doc(&app).styles.object_style(name).unwrap().effects.as_ref().unwrap().drop_shadow.on, "effects kept"); } + /// `objectStyle.dialog` with a style the document lacks, or `[None]`, is an error and opens + /// nothing; without a name it opens New Object Style. + #[test] + fn the_dialog_command_refuses_a_style_with_no_options() { + let (mut app, _) = app_with_frame(); + for name in ["Nope", designcraft_doc::NO_OBJECT_STYLE] { + assert!(app.run("objectStyle.dialog", json!({"name": name})).is_err(), "{name}"); + assert!(app.ui.dialog.is_none(), "{name}"); + } + app.run("objectStyle.dialog", json!({})).unwrap(); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.b("new"))); + } + /// A refused OK (an empty name, a name another style has) keeps the dialog and its edits, /// with the reason shown. #[test] @@ -512,7 +529,7 @@ mod tests { assert_eq!(d.s("status"), "Enter a style name."); assert_eq!(get(d, &["stroke", "weight"]), &json!(7.0), "the edits are kept"); assert!(frame(&mut app, &ctx).iter().any(|t| t.trim() == "Enter a style name.")); - open_edit(&mut app, "Mine"); + open_edit(&mut app, "Mine").unwrap(); if let Some(d) = app.ui.dialog.as_mut() { d.fields.insert("name".into(), json!("Taken")); } diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index f1c057c84..1de6d53f6 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -157,14 +157,14 @@ pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { } let editable = n != designcraft_doc::NO_OBJECT_STYLE; if resp.double_clicked() && editable { - crate::object_style_dialog::open_edit(app, n); + let _ = crate::object_style_dialog::open_edit(app, n); } else if resp.clicked() && selected { let _ = app.run("style.object.apply", json!({"name": n})); } resp.context_menu(|ui| { let label = crate::i18n::style_name(&lang, n); if editable && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Edit \"{name}\"…").replace("{name}", label))).clicked() { - crate::object_style_dialog::open_edit(app, n); + let _ = crate::object_style_dialog::open_edit(app, n); ui.close(); } if ui @@ -202,7 +202,7 @@ pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { if let Some((n, _)) = current.as_ref().filter(|(n, _)| n != designcraft_doc::NO_OBJECT_STYLE) && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&lang, "Object Style Options…"))).clicked() { - crate::object_style_dialog::open_edit(app, n); + let _ = crate::object_style_dialog::open_edit(app, n); ui.close(); } }); From c22c48dc8e2636b2c481299e3cce16bd1932ee94 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 10:24:19 +0200 Subject: [PATCH 014/328] Object styles hold named corners; IDML styles inherit the corners they don't set An object style's corners are top left, top right, bottom right and bottom left, as InDesign's and as IDML import and export already read them. `corners::named_slots` finds which anchor of a path is at which corner, and `CornerOptions::named_to_path` / `path_to_named` convert: applying a style puts each corner on the anchor at that corner, whatever order the path runs in; a style made from a selection, and redefining one, convert the item's corners. IDML export's `corner_names` uses the same mapping. An IDML object style that sets some corners takes the others from its Based On chain, so applying a child that changes one corner keeps the parent's other corners. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/styles.rs | 6 ++- crates/engine/src/cmd/style.rs | 8 +-- crates/geom/src/corners.rs | 67 ++++++++++++++++++++++++++ crates/idml/src/export.rs | 23 +-------- crates/idml/src/import.rs | 37 +++++++++++--- crates/idml/src/tests/object_styles.rs | 21 ++++++++ 6 files changed, 127 insertions(+), 35 deletions(-) diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 380f0fd3a..ca7b13665 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -60,7 +60,9 @@ pub struct ObjectStyle { /// effects differ from the style's (a local override). #[serde(skip_serializing_if = "Option::is_none")] pub effects: Option, - /// Corner Options (Stroke & Corner Options): each corner's shape and size, in path order. + /// Corner Options (Stroke & Corner Options): each corner's shape and size, by name (top left, + /// top right, bottom right, bottom left), as InDesign's; an item takes them at the anchors at + /// those corners ([`CornerOptions::named_to_path`]). #[serde(skip_serializing_if = "Option::is_none")] pub corners: Option, } @@ -69,7 +71,7 @@ impl ObjectStyle { /// Gives `it` the fill, stroke, corners, effects and text frame options this style sets. pub fn apply_to(&self, it: &mut Item) { if let Some(c) = self.corners { - it.corners = c; + it.corners = c.named_to_path(&it.path); } if let Some(f) = &self.fill { it.fill = f.clone(); diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 7bcdcbb1d..86ad2ea87 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -1528,7 +1528,7 @@ fn create_object(s: &mut Session, p: &Value) -> Result { if let Some(it) = &src { os.fill = Some(it.fill.clone()); os.stroke = Some(it.stroke.clone()); - os.corners = Some(it.corners); + os.corners = Some(it.corners.path_to_named(&it.path)); os.text_frame = it.text_frame().map(|t| t.options.clone()); os.effects = Some(it.effects.clone()); } @@ -1705,7 +1705,7 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { effects.as_ref().is_some_and(|(o, _)| it.effects == *o) || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) - || corners.as_ref().is_some_and(|(o, _)| it.corners == *o) + || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -1726,9 +1726,9 @@ fn edit_object(s: &mut Session, p: &Value) -> Result { it.stroke = n.clone(); } if let Some((o, n)) = &corners - && it.corners == *o + && it.corners == o.named_to_path(&it.path) { - it.corners = *n; + it.corners = n.named_to_path(&it.path); } }, ); diff --git a/crates/geom/src/corners.rs b/crates/geom/src/corners.rs index 5f0e2cfda..9c1bfbb00 100644 --- a/crates/geom/src/corners.rs +++ b/crates/geom/src/corners.rs @@ -55,10 +55,53 @@ pub struct CornerOptions { pub corners: [Corner; 4], } +/// The named corner (0 top left, 1 top right, 2 bottom right, 3 bottom left) each of a path's +/// four anchors is, by its place on the path's bounds. A path that isn't one subpath of four +/// anchors at four different corners keeps a rectangle's order. +pub fn named_slots(path: &PathData) -> [usize; 4] { + let rect_order = [0, 1, 2, 3]; + let Some(sp) = path.subpaths.first() else { return rect_order }; + let Some(b) = path.bounds() else { return rect_order }; + if sp.anchors.len() != 4 { + return rect_order; + } + let c = b.center(); + let mut out = rect_order; + let mut seen = [false; 4]; + for (i, a) in sp.anchors.iter().enumerate() { + let k = match (a.p.y < c.y, a.p.x < c.x) { + (true, true) => 0, + (true, false) => 1, + (false, false) => 2, + (false, true) => 3, + }; + if std::mem::replace(&mut seen[k], true) { + return rect_order; + } + out[i] = k; + } + out +} + impl CornerOptions { pub fn uniform(shape: CornerShape, size: f64) -> Self { Self { corners: [Corner { shape, size }; 4] } } + + /// Named corners (top left, top right, bottom right, bottom left), as an object style holds + /// them, in `path`'s order. + pub fn named_to_path(&self, path: &PathData) -> Self { + Self { corners: named_slots(path).map(|k| self.corners[k]) } + } + + /// `path`-order corners as named corners (top left, top right, bottom right, bottom left). + pub fn path_to_named(&self, path: &PathData) -> Self { + let mut corners = self.corners; + for (i, k) in named_slots(path).into_iter().enumerate() { + corners[k] = self.corners[i]; + } + Self { corners } + } pub fn is_none(&self) -> bool { self.corners.iter().all(Corner::is_none) } @@ -252,6 +295,30 @@ mod tests { use crate::shapes::rectangle; use kurbo::{Rect, Shape}; + /// Named corners go to the anchors at those corners, whatever order the path runs in, and + /// come back the same. + #[test] + fn named_corners_map_to_any_path_order() { + use kurbo::Point; + let named = CornerOptions { + corners: [CornerShape::Rounded, CornerShape::Bevel, CornerShape::Inset, CornerShape::Fancy].map(|shape| Corner { shape, size: 6.0 }), + }; + // Top left, bottom left, bottom right, top right (as InDesign writes a rectangle). + let down_first = PathData::single(SubPath::polyline( + &[Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0), Point::new(100.0, 0.0)], + true, + )); + assert_eq!(named_slots(&down_first), [0, 3, 2, 1]); + let on_path = named.named_to_path(&down_first); + let shapes = on_path.corners.map(|c| c.shape); + assert_eq!(shapes, [CornerShape::Rounded, CornerShape::Fancy, CornerShape::Inset, CornerShape::Bevel]); + assert_eq!(on_path.path_to_named(&down_first), named); + // A rectangle in its own order, and a triangle, keep the order. + assert_eq!(named.named_to_path(&rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))), named); + let tri = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(5.0, 9.0)], true)); + assert_eq!(named.named_to_path(&tri), named); + } + #[test] fn none_is_identity() { let r = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)); diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index a4330f4e2..1fb0f202b 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -3020,28 +3020,7 @@ fn path_geometry(path: &PathData) -> El { /// IDML corner names for anchors 0..4 of a path (by position on its bounding box). pub(crate) fn corner_names(path: &PathData) -> [&'static str; 4] { - let default = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; - let Some(sp) = path.subpaths.first() else { return default }; - if sp.anchors.len() != 4 { - return default; - } - let Some(b) = path.bounds() else { return default }; - let c = b.center(); - let mut out = default; - let mut seen = HashSet::new(); - for (i, a) in sp.anchors.iter().enumerate() { - let n = match (a.p.y < c.y, a.p.x < c.x) { - (true, true) => "TopLeft", - (true, false) => "TopRight", - (false, false) => "BottomRight", - (false, true) => "BottomLeft", - }; - if !seen.insert(n) { - return default; - } - out[i] = n; - } - out + designcraft_geom::corners::named_slots(path).map(|k| ["TopLeft", "TopRight", "BottomRight", "BottomLeft"][k]) } fn format_name(mime: &str) -> &'static str { diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index db1439053..46c604e8f 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -471,11 +471,18 @@ fn parse_point(s: Option<&str>) -> Option { const INDESIGN_CORNER_SIZE: f64 = 12.0; /// The four corners of a paragraph border or shading (`prefix` `ParagraphBorder` / -/// `ParagraphShading`): top left, top right, bottom right, bottom left. Unset when none is given. +/// `ParagraphShading`), or an object style (no prefix): top left, top right, bottom right, +/// bottom left. Unset when none is given. fn corners(e: &El, prefix: &str) -> Option<[Corner; 4]> { + corners_in(&[e], prefix) +} + +/// [`corners`] over `levels` (an object style, then the styles it is based on): each corner's +/// shape and size from the first level that gives it. +fn corners_in(levels: &[&El], prefix: &str) -> Option<[Corner; 4]> { let keys = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; - let shapes = keys.map(|n| e.prop(&format!("{prefix}{n}CornerOption"))); - let sizes = keys.map(|n| e.num(&format!("{prefix}{n}CornerRadius"))); + let shapes = keys.map(|n| levels.iter().find_map(|e| e.prop(&format!("{prefix}{n}CornerOption")))); + let sizes = keys.map(|n| levels.iter().find_map(|e| e.num(&format!("{prefix}{n}CornerRadius")))); if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) { return None; } @@ -1247,6 +1254,7 @@ impl<'r> Importer<'r> { None => self.styles.table.push(ts), } } + let objects_by_self: HashMap<&str, &El> = objects.iter().filter_map(|(_, e)| Some((e.get("Self")?, e))).collect(); for (_, e) in &objects { let name = names::style_name_in(OBJECT_BUILTINS, e.get("Name").unwrap_or("")); let based_on = e.prop("BasedOn").map(|b| { @@ -1274,10 +1282,25 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - // Corner options, when the style sets them (Stroke & Corner Options): the named corners - // in a rectangle's path order. - let corners = - (e.get("EnableStrokeAndCornerOptions") != Some("false")).then(|| corners(e, "")).flatten().map(|c| CornerOptions { corners: c }); + // Corner options, when the style sets them (Stroke & Corner Options), by name. A style + // that sets some corners takes the others from the styles it is based on, as the style + // holds all four. + let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false") && corners(e, "").is_some()) + .then(|| { + let mut levels = vec![e]; + let mut next = e.prop("BasedOn"); + while let Some(b) = next.take() + && levels.len() < 16 + && let Some(s) = objects_by_self.get(b.trim()).copied() + && !levels.iter().any(|l| std::ptr::eq(*l, s)) + { + levels.push(s); + next = s.prop("BasedOn"); + } + corners_in(&levels, "") + }) + .flatten() + .map(|c| CornerOptions { corners: c }); let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { Some(slot) => *slot = s, diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 4e7f5ef5d..10b0d940b 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -227,3 +227,24 @@ fn feathers_come_from_the_object_style_unless_its_category_turns_them_off() { assert!(fx[2].gradient_feather.on); assert!(!fx[2].directional_feather.on, "the item's own setting wins"); } + +/// A style that sets one corner takes the others from the style it is based on, so applying it +/// keeps the based-on style's rounded corners; and a style's named corners go to the anchors at +/// those corners of a frame whose path runs top left, bottom left, bottom right, top right. +#[test] +fn a_style_setting_one_corner_inherits_the_others_and_names_them() { + let child = r#" + ObjectStyle/Round + "#; + let d = fixture(&format!("{ROUND}{child}"), &[(r#"AppliedObjectStyle="ObjectStyle/Child""#, "")]); + let style = d.styles.object.iter().find(|s| s.name == "Child").unwrap(); + let c = style.corners.expect("the child sets corners").corners; + assert_eq!(c.map(|c| c.shape), [CornerShape::Rounded, CornerShape::Bevel, CornerShape::Rounded, CornerShape::Rounded], "{c:?}"); + assert_eq!(c.map(|c| c.size), [17.0, 4.0, 17.0, 17.0]); + // Applied to the fixture's frame (anchors top left, bottom left, bottom right, top right): + // the bevel goes to the top right anchor, the last. + let mut it = (*d.spreads[0].items[0]).clone(); + it.corners = Default::default(); + style.apply_to(&mut it); + assert_eq!(it.corners.corners.map(|c| c.shape), [CornerShape::Rounded, CornerShape::Rounded, CornerShape::Rounded, CornerShape::Bevel]); +} From 496b2fe4dc2adf77831533bb3cf5afd0b647d2cb Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 10:28:47 +0200 Subject: [PATCH 015/328] New Object Style: the selected object's corners as named corners With #1455's named style corners merged, the dialog seeds the style's corners from the selected item through `path_to_named`, so a frame whose path runs in another order gives each corner its own options. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/object_style_dialog.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 9dc905b3c..1678a2dee 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -29,7 +29,8 @@ pub fn open_new(app: &mut DesignApp) { "basedOn": designcraft_doc::NO_OBJECT_STYLE, "fill": it.as_ref().map(|i| i.fill.clone()).unwrap_or_default(), "stroke": it.as_ref().map(|i| i.stroke.clone()).unwrap_or_default(), - "corners": it.as_ref().map(|i| i.corners).unwrap_or_default(), + // A style holds named corners (top left, top right, …), the item its path's. + "corners": it.as_ref().map(|i| i.corners.path_to_named(&i.path)).unwrap_or_default(), "fx": crate::effects_dialog::effects_json(&it.map(|i| i.effects).unwrap_or_default()), "hadEffects": from, "inc": {"fill": from, "stroke": from, "corners": from}, From 65d19f87ed4345fe7b70c2dbfbd879335dcabdbf Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 11:06:31 +0200 Subject: [PATCH 016/328] Alpha text wrap: read pixels with as_chunks Clippy 1.99 (CI) prefers `as_chunks::<4>()` to `chunks_exact(4)` for a constant chunk size (`chunks_exact_to_as_chunks`). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/alpha_wrap.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 717ae8ac5..54eefe7b7 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -97,7 +97,7 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { let mut mask = vec![false; (cols as usize) * (rows as usize)]; let mut transparent = false; - for (i, px) in rgba.chunks_exact(4).enumerate() { + for (i, px) in rgba.as_chunks::<4>().0.iter().enumerate() { let alpha = px[3]; transparent |= alpha < 255; if alpha > threshold { From 7cb5ec5829c25c466c245224ef198eba2a8ee437 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 11:58:57 +0200 Subject: [PATCH 017/328] IDML object styles: legacy all-corner attributes; parity notes the Object Style Options dialog An object style that gives its corners only with `CornerOption` and `CornerRadius` keeps them; at each level of the Based On chain a per-corner attribute wins over those, as for page items. The parity assessment no longer says there is no Object Style Options dialog. Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/import.rs | 11 +++++++++-- crates/idml/src/tests/object_styles.rs | 13 +++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index a8630010e..74067df60 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -481,8 +481,15 @@ fn corners(e: &El, prefix: &str) -> Option<[Corner; 4]> { /// shape and size from the first level that gives it. fn corners_in(levels: &[&El], prefix: &str) -> Option<[Corner; 4]> { let keys = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"]; - let shapes = keys.map(|n| levels.iter().find_map(|e| e.prop(&format!("{prefix}{n}CornerOption")))); - let sizes = keys.map(|n| levels.iter().find_map(|e| e.num(&format!("{prefix}{n}CornerRadius")))); + // An object style (no prefix) may give all four with the legacy `CornerOption` / + // `CornerRadius`; at each level a per-corner attribute wins over it, as for page items. + let legacy = |e: &El, what: &str| if prefix.is_empty() { e.prop(&format!("Corner{what}")) } else { None }; + let shapes = keys.map(|n| levels.iter().find_map(|e| e.prop(&format!("{prefix}{n}CornerOption")).or_else(|| legacy(e, "Option")))); + let sizes = keys.map(|n| { + levels + .iter() + .find_map(|e| e.num(&format!("{prefix}{n}CornerRadius")).or_else(|| legacy(e, "Radius").and_then(|v| v.trim().parse::().ok()))) + }); if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) { return None; } diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 41624f855..faaef4f32 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -276,3 +276,16 @@ fn a_style_setting_one_corner_inherits_the_others_and_names_them() { style.apply_to(&mut it); assert_eq!(it.corners.corners.map(|c| c.shape), [CornerShape::Rounded, CornerShape::Rounded, CornerShape::Rounded, CornerShape::Bevel]); } + +/// An object style giving its corners only with the legacy all-corners `CornerOption` and +/// `CornerRadius` keeps them, so applying it to another frame rounds it. +#[test] +fn a_style_with_legacy_all_corner_attributes_keeps_its_corners() { + let legacy = r#" + $ID/[None] + "#; + let d = fixture(legacy, &[]); + let style = d.styles.object.iter().find(|s| s.name == "Legacy").unwrap(); + let c = style.corners.expect("the legacy corners").corners; + assert!(c.iter().all(|c| c.shape == CornerShape::Rounded && c.size == 9.0), "{c:?}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c7e0678d7..8cf0029c5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -412,7 +412,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Nested styles (through/up to N sentences, words, characters, letters, digits, tabs, breaks, spaces or given characters) and GREP styles (regex → character style), edited in Paragraph Style Options and composed under local formatting; `ui.dialog.open` for agents. Nested line styles are still to come; nested and GREP styles round-trip through IDML. - Table and cell styles (round-trip through IDML): cell styles (fill, insets, vertical justification, strokes, paragraph style) and table styles (region cell styles, border, alternating rows, spacing); apply from the Table panel, edits re-apply to every user; `style.cell.*`, `style.table.*`. - Style groups: paragraph and character styles shown in group folders, Move to Group (new, existing, none); `style.group` renames every use (styles, stories, table cells, footnotes, object styles). -- Object styles carry effects: `style.object.create` keeps the selection's effects, `style.object.apply` sets them, and `style.object.edit {name, dropShadow?, feather?, …, effects?: null}` changes them on the style and on every item whose effects still match it (items with their own effects keep them; `style.object.clearOverrides` returns them to the style). New frames take their default style's effects. Effect values that aren't finite numbers are refused and the others clamped, in these commands and in the `object.*` effect commands. IDML carries only the drop shadow and feather, for ObjectStyles (read per effects category flag, settings from the BasedOn chain) as for items; the other effects stay in `.designcraft` files. There is no Object Style Options dialog yet. +- Object styles carry effects: `style.object.create` keeps the selection's effects, `style.object.apply` sets them, and `style.object.edit {name, dropShadow?, feather?, …, effects?: null}` changes them on the style and on every item whose effects still match it (items with their own effects keep them; `style.object.clearOverrides` returns them to the style). New frames take their default style's effects. Effect values that aren't finite numbers are refused and the others clamped, in these commands and in the `object.*` effect commands. IDML carries only the drop shadow and feather, for ObjectStyles (read per effects category flag, settings from the BasedOn chain) as for items; the other effects stay in `.designcraft` files. Object Style Options is a dialog (from the Object Styles panel), with General, Fill, Stroke, Stroke & Corner Options, Paragraph Styles (with Apply Next Style) and Text Frame General Options pages. - Scrubby zoom: drag the Zoom tool left or right to zoom continuously around the press point. - Spring-loaded Zoom: hold Cmd+Space (Ctrl+Space on Windows/Linux) for the Zoom cursor and click/scrubby zoom; Alt-click zooms out. Release returns to the previous tool without changing the document or undo history. Text-frame and text-field typing suppress the shortcut; Space remains Hand. - Guides belong to the active layer: hidden with it (or with its Show Guides off) and locked with it. From 782c38e31a8bdc5e35177318803352d118d64d98 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 12:07:37 +0200 Subject: [PATCH 018/328] Alpha text wrap: an image with no outline is remembered, not traced on every edit `sync` keeps a zero-size outline for an image `trace` finds none in (opaque, unreadable, too large); composition takes it as no outline (the frame), and like a traced one it is dropped when the asset data changes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/alpha_wrap.rs | 33 ++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 54eefe7b7..8a94ae818 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -44,12 +44,19 @@ pub(crate) fn sync(doc: &mut Document) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; - if let Some(o) = trace(&a.data, asset, threshold) { - doc.alpha_outlines.push(Arc::new(o)); - } + // An image with no outline (opaque, unreadable, too large) is remembered as an empty + // one, so later edits don't decode it again; the contour is then the frame's. + let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); + doc.alpha_outlines.push(Arc::new(o)); } } +/// The empty outline standing for an image `trace` found none in: zero-size, which composition +/// takes as no outline, and dropped like a traced one when the asset's data changes. +fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { + AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } +} + /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that /// can't be read, is too large, or has no transparency (its contour is its rectangle). pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { @@ -235,6 +242,26 @@ mod tests { assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); } + /// An image with no outline (here opaque) is remembered as an empty one: later edits don't + /// trace it again, and the contour is the frame's. + #[test] + fn an_image_with_no_outline_is_not_traced_on_every_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|_, _| true); + let id = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .clone(); + s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let first = s.doc().unwrap().doc.alpha_outlines.clone(); + assert_eq!(first.len(), 1, "remembered"); + assert_eq!((first[0].width, first[0].height), (0, 0), "as no outline"); + s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); + let after = &s.doc().unwrap().doc.alpha_outlines; + assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); + } + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and /// traced again when the image's data changes under the same asset (relink, link update). #[test] From 8574b55bce817a3c3735469f35b0c51a5ab0fb4f Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 17:00:43 +0200 Subject: [PATCH 019/328] i18n: Include Inside Edges is an interface string (the catalog check from #1576) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 7d5b13e2a..79fdc3e80 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -4893,6 +4893,7 @@ mod tests { "Equal fixed heights for the selected rows; cell text may become overset.", "Found", "Grab bag", + "Include Inside Edges", "Key Object", "Load Styles", "layer", From 5d8ce25d49ae51ff77602199389a37977095aa96 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Sat, 24 Oct 2026 12:58:00 +0200 Subject: [PATCH 020/328] i18n: keys main added to fr.rs are in the shared table here: keep one The catalogue test refuses a key in both fr.rs and the shared table (CI). The shared row keeps the French; it matches, or takes fr.rs's text. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/fr.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 681230d84..3704bda04 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -233,7 +233,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Numbering & Section Options", "Options de numérotation et de section"), ("OK", "OK"), ("Object Style", "Style d'objet"), - ("Object Style Options…", "Options de style d'objet…"), ("Object Styles", "Styles d'objet"), ("Object/Anchored Object", "Objet/Objet ancré"), ("Object/Arrange", "Objet/Disposition"), From b424ffc02e2811ea29a090b384618b844c6f33bb Mon Sep 17 00:00:00 2001 From: moppeeer Date: Sun, 25 Oct 2026 17:45:48 +0100 Subject: [PATCH 021/328] Text frame fields: the document's baseline grid comes in as a parameter main's custom baseline grid read it from `app` inside text_frame_fields, which this branch made app-free for the Object Style dialog; both callers pass it now. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 14 ++++++++++---- crates/ui-egui/src/object_style_dialog.rs | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c488487e6..57ceed4d2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -576,7 +576,7 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { } let o = selected_frame_options(app).unwrap_or_default(); let units = app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas); - let shown = text_frame_fields(&o, units, selected_frame_width(app)); + let shown = text_frame_fields(&o, units, selected_frame_width(app), &document_grid(app)); if let Value::Object(m) = &shown { for (k, v) in m { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); @@ -586,9 +586,15 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { d.fields.insert("_shown".into(), shown); } +/// The active document's baseline grid (the default one without a document). +pub(crate) fn document_grid(app: &DesignApp) -> designcraft_doc::BaselineGrid { + app.session.active().map(|s| s.doc.settings.baseline_grid.clone()).unwrap_or_default() +} + /// Text frame options `o` as the Text Frame Options dialog's fields, measures in `units`; with the -/// frame's width, a Fixed Number column shows the width it gets. -pub(crate) fn text_frame_fields(o: &designcraft_doc::TextFrameOptions, units: Unit, frame_width: Option) -> Value { +/// frame's width, a Fixed Number column shows the width it gets. Without a custom baseline grid of +/// its own, the frame shows `doc_grid`'s start and increment. +pub(crate) fn text_frame_fields(o: &designcraft_doc::TextFrameOptions, units: Unit, frame_width: Option, doc_grid: &designcraft_doc::BaselineGrid) -> Value { let fm = |v: f64| json!(format_measure(v, units)); // Fixed Number: the width each column gets in the frame (shown, as in InDesign). let inner = frame_width.map(|w| w - o.inset[1] - o.inset[3]).unwrap_or(0.0); @@ -600,7 +606,7 @@ pub(crate) fn text_frame_fields(o: &designcraft_doc::TextFrameOptions, units: Un let kind = |v: Value| v.as_str().unwrap_or_default().to_string(); // A frame without a custom baseline grid shows the document grid's start and increment. let grid = o.baseline_grid.unwrap_or_else(|| { - let g = app.session.active().map(|s| s.doc.settings.baseline_grid.clone()).unwrap_or_default(); + let g = doc_grid; let relative_to = match g.relative_to { designcraft_doc::GridRelative::TopOfPage => designcraft_doc::FrameGridRelative::TopOfPage, designcraft_doc::GridRelative::TopMargin => designcraft_doc::FrameGridRelative::TopMargin, diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index fc1fbbd1a..c6206fe43 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -35,7 +35,7 @@ fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, nex fields["applyNext"] = json!(next); fields["tfBase"] = serde_json::to_value(tf).unwrap_or_default(); fields["insetLinked"] = json!(tf.inset.iter().all(|v| (v - tf.inset[0]).abs() < 1e-9)); - if let (Value::Object(f), Value::Object(shown)) = (fields, crate::dialogs::text_frame_fields(tf, units, None)) { + if let (Value::Object(f), Value::Object(shown)) = (fields, crate::dialogs::text_frame_fields(tf, units, None, &crate::dialogs::document_grid(app))) { f.extend(shown); } } From 443a62aa7cdc73a1f10f62a3d23534c4a31e66f4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Sun, 25 Oct 2026 17:46:01 +0100 Subject: [PATCH 022/328] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 7 ++++++- crates/ui-egui/src/object_style_dialog.rs | 4 +++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 57ceed4d2..f738d26ac 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -594,7 +594,12 @@ pub(crate) fn document_grid(app: &DesignApp) -> designcraft_doc::BaselineGrid { /// Text frame options `o` as the Text Frame Options dialog's fields, measures in `units`; with the /// frame's width, a Fixed Number column shows the width it gets. Without a custom baseline grid of /// its own, the frame shows `doc_grid`'s start and increment. -pub(crate) fn text_frame_fields(o: &designcraft_doc::TextFrameOptions, units: Unit, frame_width: Option, doc_grid: &designcraft_doc::BaselineGrid) -> Value { +pub(crate) fn text_frame_fields( + o: &designcraft_doc::TextFrameOptions, + units: Unit, + frame_width: Option, + doc_grid: &designcraft_doc::BaselineGrid, +) -> Value { let fm = |v: f64| json!(format_measure(v, units)); // Fixed Number: the width each column gets in the frame (shown, as in InDesign). let inner = frame_width.map(|w| w - o.inset[1] - o.inset[3]).unwrap_or(0.0); diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index c6206fe43..61b7cbe7b 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -35,7 +35,9 @@ fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, nex fields["applyNext"] = json!(next); fields["tfBase"] = serde_json::to_value(tf).unwrap_or_default(); fields["insetLinked"] = json!(tf.inset.iter().all(|v| (v - tf.inset[0]).abs() < 1e-9)); - if let (Value::Object(f), Value::Object(shown)) = (fields, crate::dialogs::text_frame_fields(tf, units, None, &crate::dialogs::document_grid(app))) { + if let (Value::Object(f), Value::Object(shown)) = + (fields, crate::dialogs::text_frame_fields(tf, units, None, &crate::dialogs::document_grid(app))) + { f.extend(shown); } } From 20ab8b39e7a0018e3f6cb25f551c300fd2751626 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 08:48:22 -0700 Subject: [PATCH 023/328] Layers: Duplicate Layer copies a layer's settings and objects above it layer.duplicate adds " copy" above a layer, with the layer's settings, a copy of every object on it and copies of its ruler guides, on document and parent pages, in one undo step. Copied text frames stay threaded to the copies of frames on the same layer and are not threaded to frames on other layers. The anchored objects in a copied story get new ids, and so do its tables and its text anchors outside table cells and notes; its cross-references point at the copied anchors. A group goes on the new layer with all its members, and a copied live caption follows the copied object. A copied override of a parent item overrides that item's copy, and is detached when the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. A layer whose objects nest more than 64 levels deep is refused. The Layers panel runs it from a layer's context menu (Duplicate Layer "") and when a layer is dropped on Create New Layer. --- ROADMAP.md | 1 + crates/engine/src/cmd/layout.rs | 626 +++++++++++++++++++++++++++- crates/ui-egui/src/panels/layers.rs | 32 +- docs/target-app-parity.md | 2 +- 4 files changed, 658 insertions(+), 3 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6a3696361..b5e8e41e5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -381,6 +381,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-25** · Duplicate Layer (`layer.duplicate`; the layer's context menu in the Layers panel, or a layer dropped on Create New Layer) adds a copy named after the layer with " copy" added ("Art copy" for Art) above the layer, with its settings, a copy of every object on it and copies of its ruler guides, on document and parent pages, in one undo step. Copied frames stay threaded to the copies of frames on the same layer and are not threaded to frames on other layers. A copied override of a parent item overrides that item's copy, and pages hide the copy where they hide the parent item. No readiness percentage change. - **2026-10-24** · Panels dock through the suite's shared docking (craft-libs), and on desktop a floating panel opens in its own window that can leave the main window: keys pressed there run the main window's shortcuts, clipboard and tool keys, and the canvas paints no tool cursor while another of the app's windows has the pointer. The web build keeps floating panels in the page. No readiness percentage change. - **2026-10-24** · Story Options rejects malformed or nonexistent explicit story/frame IDs without changing the selected story, including an invalid frame alongside a valid story. Null targets remain absent; omitted targets still use the selection. No readiness percentage change. - **2026-10-24** · Text Frame Options explains that a custom baseline-grid increment must be a measure greater than zero when zero, a negative value or a non-measure is entered. Validation is unchanged. No readiness percentage change. diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index d67f469f0..9e6c2d017 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1,6 +1,9 @@ //! Layout menu and Pages/Layers panels: pages, spreads, parents, margins & columns, layers. -use designcraft_doc::{LAYER_COLORS, Layer, LayerId, Margins, SpreadId}; +use std::collections::HashMap; +use std::sync::Arc; + +use designcraft_doc::{Content, Guide, Item, ItemId, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, SpreadRef, Story, StoryId}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, ok, str_param}; @@ -770,6 +773,15 @@ pub fn specs() -> Vec { s.doc_mut()?.active_layer = r; Ok(json!({"id": r.0})) }), + cmd!( + "layer.duplicate", + "Duplicate Layer", + [], + None, + "{id} → {id}. Adds a copy of the layer's settings and objects (document and parent spreads) above it, named \" copy\"", + has_doc, + duplicate_layer + ), cmd!( "layer.set", "Layer Options…", @@ -1359,6 +1371,242 @@ fn set_layer(s: &mut Session, p: &Value) -> Result { }) } +/// Duplicate Layer: a new layer above `id` with its settings and a copy of every object on it, on document and parent +/// spreads, in one undo step. Copied text frames stay threaded to the other copied frames of their story, and each copy +/// of a story holds all of its text. A copied override of a parent item overrides that item's copy, or is detached when +/// the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. +fn duplicate_layer(s: &mut Session, p: &Value) -> Result { + const ID: &str = "layer.duplicate"; + let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); + let r = s.edit(|d, _| { + let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad(ID, "no such layer"))?; + let mut seen = std::collections::HashSet::new(); + if d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter()).any(|it| it.layer == id && too_deep(it, d, &mut seen)) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } + let new_id = LayerId(d.alloc()); + let mut layer = d.layers[i].clone(); + layer.id = new_id; + layer.name = copy_name(&d.layers, &layer.name); + d.layers.insert(i, layer); + let src = d.clone(); + let mut stories = HashMap::new(); + let mut ids = HashMap::new(); + let refs = (0..src.parents.len()).map(SpreadRef::Parent).chain((0..src.spreads.len()).map(SpreadRef::Doc)); + let mut copies = Vec::new(); + for r in refs { + let Some(sp) = src.spread(r) else { continue }; + for it in sp.items.iter().filter(|it| it.layer == id) { + let mut copy = Item::clone(it); + super::object::renumber(d, &src, &mut copy, &mut stories); + map_ids(it, ©, &mut ids); + copies.push((r, copy)); + } + } + // Every copy has its id before overrides are pointed at the copied parent items. + for (r, mut copy) in copies { + move_copy(&mut copy, new_id, &ids); + d.insert_item(r, copy, None)?; + } + // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of + // anchored text frames get copies in turn. + let mut pending: Vec = stories.values().copied().collect(); + while let Some(new) = pending.pop() { + let Some(mut st) = d.story(new).cloned() else { continue }; + renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); + d.stories.insert(new, Arc::new(st)); + } + // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references + // and those of the other copies point at, and tables with ids of their own. + let mut anchors = HashMap::new(); + for (old, new) in &stories { + let Some(mut st) = d.story(*new).cloned() else { continue }; + st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); + for (k, a) in (1..).zip(st.anchors.iter_mut()) { + let id = (new.0 << 24) + k; + anchors.insert(a.id, id); + Arc::make_mut(a).id = id; + } + let mut tables = HashMap::new(); + for (t, mut table) in std::mem::take(&mut st.tables) { + let n = d.alloc(); + Arc::make_mut(&mut table).id = n; + tables.insert(t, n); + st.tables.insert(n, table); + } + for pf in &mut st.paras { + pf.table = pf.table.and_then(|t| tables.get(&t).copied()); + } + d.stories.insert(*new, Arc::new(st)); + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + remap_xrefs(st, &anchors); + } + } + // A page, document or parent, hides a parent item's copy where it hides the parent item, and its ruler guides on + // the layer get copies on the new layer. + let hidden = |pg: &designcraft_doc::Page| -> Vec { pg.overridden.iter().filter_map(|o| ids.get(o).copied()).collect() }; + for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) { + if sp.pages.iter().all(|pg| hidden(pg).is_empty() && pg.guides.iter().all(|g| g.layer != Some(id))) { + continue; + } + for pg in &mut Arc::make_mut(sp).pages { + let copies = hidden(pg); + pg.overridden.extend(copies); + let guides: Vec<_> = pg.guides.iter().filter(|g| g.layer == Some(id)).map(|g| Guide { layer: Some(new_id), ..g.clone() }).collect(); + pg.guides.extend(guides); + } + } + Ok(new_id) + })?; + s.doc_mut()?.active_layer = r; + Ok(json!({"id": r.0})) +} + +/// The name of a copy of layer `name`: " copy", then " copy 2" and up while a layer has the name. +fn copy_name(layers: &[Layer], name: &str) -> String { + let base = format!("{name} copy"); + let taken = |n: &str| layers.iter().any(|l| l.name == n); + if !taken(&base) { + return base; + } + (2..).map(|k| format!("{base} {k}")).find(|n| !taken(n)).unwrap_or(base) +} + +/// Record each id of `orig` and its descendants against the matching id in `copy`. +fn map_ids(orig: &Item, copy: &Item, ids: &mut HashMap) { + ids.insert(orig.id, copy.id); + for (o, c) in orig.children().iter().zip(copy.children()) { + map_ids(o, c, ids); + } +} + +/// A layer whose groups, anchored objects, table cells and notes nest deeper than this within one story or object is +/// not duplicated. +const MAX_COPY_DEPTH: usize = 64; + +/// Whether `it`, or a story its text frames reach directly or through anchored text frames, nests groups, anchored +/// objects, table cells and notes deeper than [`MAX_COPY_DEPTH`]. Stories in `seen` were checked already and are skipped. +fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collections::HashSet) -> bool { + fn item(it: &Item, depth: usize, next: &mut Vec) -> bool { + if let Some(t) = it.text_frame() { + next.push(t.story); + } + depth > MAX_COPY_DEPTH || it.children().iter().any(|c| item(c, depth + 1, next)) + } + fn story(st: &Story, depth: usize, next: &mut Vec) -> bool { + depth > MAX_COPY_DEPTH + || st.objects.iter().any(|o| item(&o.item, depth + 1, next)) + || st.tables.values().flat_map(|t| &t.cells).any(|c| story(&c.text, depth + 1, next)) + || st.notes.iter().chain(&st.endnotes).any(|n| story(&n.text, depth + 1, next)) + } + let mut next = Vec::new(); + if item(it, 0, &mut next) { + return true; + } + while let Some(sid) = next.pop() { + if seen.insert(sid) + && let Some(st) = d.story(sid) + && story(st, 0, &mut next) + { + return true; + } + } + false +} + +/// Give the items anchored in `st`, and in the stories of its table cells and notes, new ids from `d` (recorded in `ids`) +/// and layer `to`. An anchored text frame's story gets one copy, recorded in `stories`, that every copied frame of the +/// story shares; a new copy goes on `pending`, and its frame list is filled in afterwards. [`too_deep`] bounds the nesting. +fn renumber_anchored( + d: &mut designcraft_doc::Document, + st: &mut Story, + to: LayerId, + stories: &mut HashMap, + ids: &mut HashMap, + pending: &mut Vec, +) { + for o in &mut st.objects { + renumber_anchored_item(d, &mut Arc::make_mut(o).item, to, stories, ids, pending); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + renumber_anchored(d, &mut c.text, to, stories, ids, pending); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_anchored(d, &mut Arc::make_mut(n).text, to, stories, ids, pending); + } +} + +/// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for +/// their targets. [`too_deep`] bounds the nesting. +fn remap_xrefs(st: &mut Story, map: &HashMap) { + for x in &mut st.xrefs { + if let Some(n) = map.get(&x.target) { + Arc::make_mut(x).target = *n; + } + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + remap_xrefs(&mut c.text, map); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + remap_xrefs(&mut Arc::make_mut(n).text, map); + } +} + +/// [`renumber_anchored`] for one anchored item and its descendants. +fn renumber_anchored_item( + d: &mut designcraft_doc::Document, + it: &mut Item, + to: LayerId, + stories: &mut HashMap, + ids: &mut HashMap, + pending: &mut Vec, +) { + let id = ItemId(d.alloc()); + ids.insert(it.id, id); + it.id = id; + it.layer = to; + if let Content::Text(tf) = &mut it.content { + tf.story = match stories.get(&tf.story) { + Some(n) => *n, + None => { + let n = StoryId(d.alloc()); + let mut copy = d.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); + copy.id = n; + copy.frames.clear(); + d.stories.insert(n, Arc::new(copy)); + stories.insert(tf.story, n); + pending.push(n); + n + } + }; + } + for c in it.children_mut().into_iter().flatten() { + renumber_anchored_item(d, Arc::make_mut(c), to, stories, ids, pending); + } +} + +/// Put `it` and its descendants on layer `to`, and point overrides at the copied parent items and live captions at the +/// copied objects. A copy whose parent item was not copied is detached from it, so the original override stays the only +/// one of that item. +fn move_copy(it: &mut Item, to: LayerId, ids: &HashMap) { + it.layer = to; + it.overrides = it.overrides.and_then(|o| ids.get(&o).copied()); + if let Some(c) = &mut it.live_caption + && let Some(n) = ids.get(&c.source) + { + c.source = *n; + } + for c in it.children_mut().into_iter().flatten() { + move_copy(Arc::make_mut(c), to, ids); + } +} + #[cfg(test)] mod setup_tests { use serde_json::json; @@ -1570,6 +1818,382 @@ mod layer_tests { assert_eq!(d.layers.len(), 1); assert_eq!(d.item(designcraft_doc::ItemId(f)).unwrap().layer.0, l4); } + + fn on_layer(d: &designcraft_doc::Document, layer: u64) -> Vec> { + d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter().filter(|i| i.layer.0 == layer).cloned()).collect() + } + + #[test] + fn duplicate_layer_copies_settings_and_objects_above_the_original() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.set", &json!({"id": art, "color": "Red", "printable": false, "showGuides": false})).unwrap(); + let rect = s.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.execute("frame.create", &json!({"spread": 1, "rect": [10, 10, 60, 60]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "horizontal", "position": 200, "page": 0, "liquid": true})).unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + s.execute("frame.create", &json!({"rect": [100, 100, 150, 150]})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 300, "page": 0})).unwrap(); + s.execute("layer.set", &json!({"id": art, "locked": true})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": art})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.layers.iter().map(|l| l.id.0).collect::>(), [copy, art, base], "the copy sits right above the original"); + let (l, o) = (d.layer(designcraft_doc::LayerId(copy)).unwrap(), d.layer(designcraft_doc::LayerId(art)).unwrap()); + assert_eq!(l.name, "Art copy"); + assert_eq!((l.color, l.visible, l.locked, l.printable, l.show_guides), (o.color, o.visible, o.locked, o.printable, o.show_guides)); + assert_eq!(s.doc().unwrap().active_layer.0, copy); + let (orig, copies) = (on_layer(&d, art), on_layer(&d, copy)); + assert_eq!(copies.len(), 2, "both spreads' objects"); + for (a, b) in orig.iter().zip(&copies) { + assert_ne!(a.id, b.id); + assert_eq!((a.xf, a.path.clone()), (b.xf, b.path.clone())); + assert_eq!(d.find(a.id).unwrap().spread, d.find(b.id).unwrap().spread); + } + assert_eq!(on_layer(&d, base).len(), 1, "other layers' objects stay as they were"); + let guides = &d.spreads[0].pages[0].guides; + assert_eq!(guides.len(), 3, "Art's guide gets a copy; the base layer's does not"); + let (g, c) = (&guides[0], &guides[2]); + assert_eq!((g.layer, c.layer), (Some(designcraft_doc::LayerId(art)), Some(designcraft_doc::LayerId(copy)))); + assert_eq!((g.orientation, g.position, g.liquid), (c.orientation, c.position, c.liquid)); + assert!(d.item(designcraft_doc::ItemId(rect)).is_some()); + // A second copy gets a name of its own; bad ids change nothing. + s.execute("layer.duplicate", &json!({"id": art})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers[1].name, "Art copy 2"); + s.execute("edit.undo", &json!({})).unwrap(); + for bad in [json!({"id": 999}), json!({})] { + assert!(s.execute("layer.duplicate", &bad).is_err(), "{bad}"); + } + // One undo step. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers, before.layers); + assert_eq!(d.all_items(), before.all_items()); + } + + #[test] + fn duplicate_layer_keeps_threads_on_the_layer_only() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = |s: &mut crate::Session, rect: [f64; 4], t: &str| { + s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": t})).unwrap()["id"].as_u64().unwrap() + }; + // a → b on Base, c on Art at the end of the same thread. + let b = text(&mut s, [10.0, 200.0, 100.0, 240.0], ""); + let a = text(&mut s, [10.0, 10.0, 100.0, 50.0], "One two three four five six seven eight nine ten eleven twelve"); + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + let art = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap(); + let c = text(&mut s, [300.0, 10.0, 400.0, 50.0], ""); + s.execute("text.thread", &json!({"from": b, "to": c})).unwrap(); + let _ = art; + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let story = |id: u64| d.item(designcraft_doc::ItemId(id)).and_then(|i| i.text_frame()).map(|t| t.story).unwrap(); + let orig = d.story(story(a)).unwrap(); + assert_eq!(orig.frames.iter().map(|f| f.0).collect::>(), [a, b, c], "the original thread is unchanged"); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2); + let sid = copies[0].text_frame().unwrap().story; + assert_eq!(copies[1].text_frame().unwrap().story, sid, "the copies share one story"); + let st = d.story(sid).unwrap(); + assert_ne!(sid, orig.id); + assert_eq!(st.text, orig.text, "the copy holds the whole text"); + // Thread order as in the original (a's copy first, though b's copy was made first), without c. + let pos = |id: designcraft_doc::ItemId| d.find(id).map(|l| l.path.clone()); + let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().xf).collect(); + let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().xf).collect(); + assert_eq!(order, want); + assert!(st.frames.iter().all(|f| pos(*f).is_some())); + } + + #[test] + fn duplicate_layer_copies_parent_items_and_their_overrides() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let folio = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 720, 300, 750], "content": "text", "text": "Folio"}); + let parent = s.execute("frame.create", &folio).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + // Page 3's override is deleted, which keeps the parent item hidden there. + let gone = s.execute("layout.overrideParentItems", &json!({"page": 2})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [gone]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + // Parent B, based on A, hides the folio on its page. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + s.edit(|d, _| { + let a = d.parents[0].id; + let bp = std::sync::Arc::make_mut(&mut d.parents[1]); + bp.parent.as_mut().unwrap().based_on = Some(a); + bp.pages[0].parent = Some(a); + bp.pages[0].overridden.push(designcraft_doc::ItemId(parent)); + Ok(()) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + assert_eq!(copies.len(), 2, "the parent item and page 2's override"); + let p2 = copies.iter().find(|i| matches!(d.find(i.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(0))).unwrap(); + let o2 = copies.iter().find(|i| i.overrides.is_some()).unwrap(); + assert_ne!((p2.id.0, o2.id.0), (parent, o)); + assert_eq!(o2.overrides, Some(p2.id), "the override's copy overrides the parent item's copy"); + assert_eq!(d.page_of_item(o2.id), Some(1)); + let overridden = |page: usize| { + let (si, pi) = d.page_loc(page).unwrap(); + d.spreads[si].pages[pi].overridden.clone() + }; + assert_eq!(overridden(1), [designcraft_doc::ItemId(parent), p2.id], "page 2 hides both parent items"); + assert_eq!(overridden(2), [designcraft_doc::ItemId(parent), p2.id], "page 3 too, without an override"); + assert!(overridden(0).is_empty(), "page 1 shows both"); + assert_eq!(d.parents[1].pages[0].overridden, [designcraft_doc::ItemId(parent), p2.id], "parent B hides both"); + } + + #[test] + fn duplicate_layer_moves_whole_groups_and_finds_later_parent_items() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [20, 0, 30, 10]})).unwrap()["id"].as_u64().unwrap(); + // The group takes the base layer from its first member; b stays on Art inside it. + let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": base})).unwrap(); + // Parent A's item overrides one on parent B, which comes after it in the document. + s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap(); + let on_b = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 1}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let on_a = + s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + s.edit(|d, _| { + d.item_mut(designcraft_doc::ItemId(on_a)).unwrap().overrides = Some(designcraft_doc::ItemId(on_b)); + Ok(()) + }) + .unwrap(); + let d = s.doc().unwrap().doc.clone(); + let layer_of = |id: u64| d.item(designcraft_doc::ItemId(id)).unwrap().layer.0; + assert_eq!((layer_of(g), layer_of(b)), (base, d.layers.iter().find(|l| l.name == "Art").unwrap().id.0)); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + let copies = on_layer(&d, copy); + let group = copies.iter().find(|i| !i.children().is_empty()).unwrap(); + assert!(group.children().iter().all(|c| c.layer.0 == copy), "the copied group is on the new layer as a whole"); + let in_parent = + |i: usize| copies.iter().find(|c| matches!(d.find(c.id).unwrap().spread, designcraft_doc::SpreadRef::Parent(p) if p == i)).unwrap(); + assert_eq!(in_parent(0).overrides, Some(in_parent(1).id), "A's copy overrides B's copy"); + } + + #[test] + fn duplicate_layer_gives_anchored_objects_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let b = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 7})).unwrap(); + // Two anchored text frames threaded in one story, as IDML import makes them. + let threaded = s + .edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let (r, r2) = (designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 40.0)); + let (first, story) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Symbol", ParaFormat::default())?; + let (second, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r2, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [first, second] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = story; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(story).ok_or(designcraft_doc::DocError::NoStory(story))?.frames = vec![first, second]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != first && i.id != second); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + Ok(story) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let symbols: Vec<_> = d.anchored_items().into_iter().filter_map(|(_, i)| i.text_frame().map(|t| (i.id, t.story))).collect(); + assert_eq!(symbols.len(), 4); + let copied = symbols.iter().map(|s| s.1).find(|s| *s != threaded).unwrap(); + let st = d.story(copied).unwrap(); + assert_eq!(st.text, "Symbol"); + assert_eq!(st.frames.len(), 2, "the copies share one story"); + let order = |story: &designcraft_doc::Story| story.frames.iter().map(|f| d.anchored_item(*f).unwrap().path.clone()).collect::>(); + assert_eq!(order(st), order(d.story(threaded).unwrap()), "in the original thread order"); + let anchored: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_none()).map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + assert_ne!(anchored[0].0, anchored[1].0, "the copy's anchored object has an id of its own"); + let mut layers: Vec<_> = anchored.iter().map(|a| a.1).collect(); + layers.sort_unstable(); + let mut want = vec![base, copy]; + want.sort_unstable(); + assert_eq!(layers, want, "the copy's anchored object is on the new layer"); + } + + #[test] + fn duplicate_layer_points_copied_live_captions_at_the_copied_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 272, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.altText", &json!({"text": "First", "ids": [a]})).unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "Photo: {altText}", "live": true})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + let frame = copies.iter().find(|i| i.live_caption.is_none()).unwrap(); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, frame.id, "the caption's copy follows the frame's copy"); + assert_ne!(frame.id.0, a); + } + + #[test] + fn duplicate_layer_gives_copied_text_anchors_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Heading\rSee "}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let anchor = s + .edit(|d, _| { + let a = d.paragraph_anchor(sid, 0).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let format = d.xref_formats[0].name.clone(); + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let end = st.len(); + st.insert_xref(end, designcraft_doc::CrossRef { target: a, format }); + Ok(a) + }) + .unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let (orig, st) = (d.story(sid).unwrap(), d.story(copied).unwrap()); + assert_eq!((orig.anchors[0].id, orig.xrefs[0].target), (anchor, anchor), "the original is unchanged"); + assert_ne!(st.anchors[0].id, anchor, "the copy's anchor has an id of its own"); + assert_eq!(st.anchors[0].name, orig.anchors[0].name); + assert_eq!(st.xrefs[0].target, st.anchors[0].id, "the copied cross-reference points at the copied paragraph"); + assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); + } + + #[test] + fn duplicate_layer_gives_copied_tables_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let st = d.story(copied).unwrap(); + let tables: Vec = st.tables.keys().copied().collect(); + assert_eq!(tables.len(), 1); + let new = tables[0]; + assert_ne!(new, table, "the copy's table has an id of its own"); + assert_eq!(st.tables[&new].id, new); + assert_eq!(st.paras.iter().filter_map(|pf| pf.table).collect::>(), [new], "the copied paragraph holds the copied table"); + d.check().unwrap(); + s.execute("table.insertRow", &json!({"table": new})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.story(sid).unwrap().tables[&table].nrows(), 1, "the original table is unchanged"); + assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); + } + + /// 40 stories, each holding two anchored text frames threaded in the next: 2^40 paths, 40 stories. + #[test] + fn duplicate_layer_checks_each_shared_story_once() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let top = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.edit(|d, _| { + use designcraft_doc::{AnchoredObject, ParaFormat}; + let r = designcraft_geom::Rect::new(0.0, 0.0, 60.0, 30.0); + let mut outer = top; + for _ in 0..40 { + let (a, inner) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "Link", ParaFormat::default())?; + let (b, spare) = d.add_text_frame(designcraft_doc::SpreadRef::Doc(0), r, d.default_layer(), "", ParaFormat::default())?; + let mut items = Vec::new(); + for f in [a, b] { + let mut it = d.item(f).cloned().ok_or(designcraft_doc::DocError::NoItem(f))?; + if let designcraft_doc::Content::Text(tf) = &mut it.content { + tf.story = inner; + } + items.push(it); + } + d.stories.remove(&spare); + d.story_mut(inner).ok_or(designcraft_doc::DocError::NoStory(inner))?.frames = vec![a, b]; + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != a && i.id != b); + let st = d.story_mut(outer).ok_or(designcraft_doc::DocError::NoStory(outer))?; + for it in items.into_iter().rev() { + st.insert_object(0, AnchoredObject::new(it, Default::default())); + } + outer = inner; + } + Ok(()) + }) + .unwrap(); + s.doc().unwrap().doc.check().unwrap(); + let before = s.doc().unwrap().doc.stories.len(); + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + assert_eq!(d.stories.len(), 2 * before, "one copy of each story"); + } + + #[test] + fn duplicate_layer_refuses_objects_nested_too_deeply() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let mut g = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + for _ in 0..super::MAX_COPY_DEPTH + 1 { + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + g = s.execute("object.group", &json!({"ids": [g, f]})).unwrap()["id"].as_u64().unwrap(); + } + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + + #[test] + fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let logo = json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 72, 144, 144]}); + let parent = s.execute("frame.create", &logo).unwrap()["id"].as_u64().unwrap(); + let o = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [o]})).unwrap(); + s.execute("object.setLayer", &json!({"layer": base})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copies = on_layer(d, copy); + assert_eq!(copies.len(), 1, "the override only: the parent item is on Art"); + assert_eq!(copies[0].overrides, None, "a plain object, so the original override stays the only one"); + assert_eq!(d.item(designcraft_doc::ItemId(o)).unwrap().overrides, Some(designcraft_doc::ItemId(parent))); + let (si, pi) = d.page_loc(1).unwrap(); + assert_eq!(d.spreads[si].pages[pi].overridden, [designcraft_doc::ItemId(parent)]); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 1f5382ac2..34a503158 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -453,6 +453,11 @@ pub fn show(app: &mut DesignApp, ui: &mut Ui) { ui.close(); } ui.separator(); + let duplicate = crate::i18n::tr(&language, "Duplicate Layer \"{name}\"").replace("{name}", &l.name); + if ui.button(crate::rtl::widget(ui, duplicate)).clicked() { + cmds.push(("layer.duplicate", json!({"id": l.id.0}))); + ui.close(); + } if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&language, "Delete Layer"))).clicked() { cmds.push(("layer.delete", json!({"id": l.id.0}))); ui.close(); @@ -550,7 +555,14 @@ pub fn show(app: &mut DesignApp, ui: &mut Ui) { if icons::button(ui, "trash", 20.0, false, crate::i18n::tr(&app.ui.language, "Delete Layer")).clicked() { let _ = app.run("layer.delete", json!({"id": active.0})); } - if icons::button(ui, "plus", 20.0, false, crate::i18n::tr(&app.ui.language, "Create New Layer")).clicked() { + // Create New Layer; a layer dropped on it is duplicated. + let dragging = matches!(egui::DragAndDrop::payload::(ui.ctx()).as_deref(), Some(LayersDrag::Layer(_))); + let plus = icons::button(ui, "plus", 20.0, dragging, crate::i18n::tr(&app.ui.language, "Create New Layer")); + if let Some(payload) = plus.dnd_release_payload::() { + if let LayersDrag::Layer(id) = *payload { + let _ = app.run("layer.duplicate", json!({"id": id.0})); + } + } else if plus.clicked() { let _ = app.run("layer.new", json!({})); } }); @@ -670,6 +682,24 @@ mod tests { assert_eq!(layers(h.state()), ["Art", "Layer 1"], "one undo step"); } + #[test] + fn a_layer_dropped_on_create_new_layer_is_duplicated() { + use egui_kittest::kittest::Queryable; + let mut app = app(); + app.run("layer.new", json!({"name": "Art"})).unwrap(); + app.run("frame.create", json!({"rect": [0, 0, 10, 10]})).unwrap(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let mut h = panel(app); + let plus = h.get_by_label("Create New Layer").rect().center(); + // Rows: Art, its rectangle, Layer 1. Drop Layer 1 on the button. + drag(&mut h, row(2, 0.5, false), plus); + assert_eq!(layers(h.state()), ["Art", "Layer 1 copy", "Layer 1"]); + drag(&mut h, row(0, 0.5, false), plus); + assert_eq!(layers(h.state()), ["Art copy", "Art", "Layer 1 copy", "Layer 1"]); + let d = &h.state().session.active().unwrap().doc; + assert_eq!(d.spreads[0].items.iter().filter(|i| i.layer == d.layers[0].id).count(), 1, "the copy holds the rectangle"); + } + #[test] fn dragging_objects_and_the_selection_square_moves_them_between_layers() { let mut app = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 428ed9bf7..51073d762 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -441,7 +441,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); the result keeps the frontmost object's look and content, so a photo intersected with shapes behind it shows through them (Subtract keeps the backmost); `object.pathfinder`. - Pathfinder panel as InDesign's: Paths (Join Path `path.join`, Open/Close Path, Reverse Path), Pathfinder, Convert Shape, Convert Point (`path.convertPoints`: plain, corner, smooth, symmetrical). - Make / Release Compound Path (⌘8; nested paths become holes), Create Outlines (⇧⌘O; one path per text colour), Scissors tool (C) with `path.split`. -- Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character). +- Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Duplicate, Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character). - Floating panels: drag a panel's tab, or a group by its drag bar, off the dock (or choose Float Panel) into a movable floating window that resizes from every edge; Dock Panel (in its tab menu and ≡ menu) puts it back where it was; positions persist; `window.panel.float` / `window.panel.dock` (aliases `window.floatPanel` / `window.dockPanel`). - Place SVG (vector in PDF export via krilla-svg, resvg on screen, text in the bundled fonts), Photoshop (.psd/.psb composite in its colour mode — Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK, Lab, 8/16-bit — with merged transparency; extra alpha and spot channels don't change the image), BMP, and Illustrator files saved with PDF compatibility (.ai). A swatch on a placed greyscale or bitmap image (IDML ``) colours it on screen and in PDF. New `designcraft-images` crate (L2) for sniffing, sizes and decoding. EPS is still missing. - View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough). From d11a050a67166e738c1c48856f3d12cc1fccb0d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 15:26:23 -0700 Subject: [PATCH 024/328] Layers: Duplicate Layer numbers copies in story order and is translated Duplicate Layer gave the copied stories' tables and anchored objects their new ids in hash-map order, so the ids differed from run to run. It now takes the stories in order. The Layers panel's "Duplicate Layer" menu item has a row in every interface language. --- crates/engine/src/cmd/layout.rs | 37 +++++++++++++++++++++++++++++--- crates/ui-egui/src/i18n.rs | 18 ++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + 12 files changed, 62 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 9e6c2d017..361e2f40b 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1409,17 +1409,21 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { d.insert_item(r, copy, None)?; } // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of - // anchored text frames get copies in turn. + // anchored text frames get copies in turn. The story copies are taken in story order. let mut pending: Vec = stories.values().copied().collect(); + pending.sort_unstable(); + pending.reverse(); while let Some(new) = pending.pop() { let Some(mut st) = d.story(new).cloned() else { continue }; renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); d.stories.insert(new, Arc::new(st)); } // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references - // and those of the other copies point at, and tables with ids of their own. + // and those of the other copies point at, and tables with ids of their own, allocated in story order. let mut anchors = HashMap::new(); - for (old, new) in &stories { + let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); + order.sort_unstable_by_key(|(_, new)| *new); + for (old, new) in &order { let Some(mut st) = d.story(*new).cloned() else { continue }; st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { @@ -2116,6 +2120,33 @@ mod layer_tests { assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); } + #[test] + fn duplicate_layer_numbers_copied_tables_and_anchored_objects_in_story_order() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + for k in 0..8 { + let y = 72 + 80 * k; + let text = json!({"rect": [72, y, 400, y + 60], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [450, y, 474, y + 40]})).unwrap()["id"].as_u64().unwrap(); + s.execute("anchored.insert", &json!({"ids": [b], "story": sid.0, "pos": 0})).unwrap(); + } + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let mut stories: Vec<_> = on_layer(d, copy).iter().filter_map(|i| i.text_frame().map(|t| t.story)).collect(); + stories.sort_unstable(); + assert_eq!(stories.len(), 8); + let tables: Vec = stories.iter().map(|sid| *d.story(*sid).unwrap().tables.keys().next().unwrap()).collect(); + let objects: Vec = stories.iter().map(|sid| d.story(*sid).unwrap().objects[0].item.id.0).collect(); + assert!(tables.is_sorted(), "the copied tables take ids in story order: {tables:?}"); + assert!(objects.is_sorted(), "the copied anchored objects take ids in story order: {objects:?}"); + } + /// 40 stories, each holding two anchored text frames threaded in the next: 2^40 paths, 40 stories. #[test] fn duplicate_layer_checks_each_shared_story_once() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d1b462ab5..27f4df308 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -4562,6 +4562,10 @@ const TABLE: &[(&str, [&str; 5])] = &[ "“{name}”的图层选项…", ], ), + ( + "Duplicate Layer \"{name}\"", + ["Ebene „{name}“ duplizieren", "Dupliquer le calque « {name} »", "Duplicar capa «{name}»", "レイヤー「{name}」を複製", "复制图层“{name}”"], + ), ("Swatch Name:", ["Farbfeldname:", "Nom de la nuance :", "Nombre de muestra:", "スウォッチ名:", "色板名称:"]), ( "Name with Color Value", @@ -4968,6 +4972,20 @@ mod tests { } } + #[test] + fn duplicate_layer_menu_item_is_localized_in_every_interface_language() { + let key = "Duplicate Layer \"{name}\""; + for (code, name) in LANGUAGES { + let label = tr(code, key); + if code.is_empty() { + assert_eq!(label, key, "{name}"); + } else { + assert_ne!(label, key, "{name} shows the Layers panel's Duplicate Layer item in English"); + assert!(label.contains("{name}"), "{name}"); + } + } + } + #[test] fn context_captions_come_from_their_context_or_the_plain_translation() { for (lang, table) in CONTEXT_TABLES { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index f1dbe0acd..6aecde83c 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1813,6 +1813,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "خيارات مجموعة الألوان…"), ("Layer Options", "خيارات الطبقة"), ("Layer Options for \"{name}\"…", "خيارات الطبقة \"{name}\"…"), + ("Duplicate Layer \"{name}\"", "تكرار الطبقة \"{name}\""), ("Swatch Name:", "اسم حامل اللون:"), ("Name with Color Value", "التسمية بقيمة اللون"), ("Color Type:", "نوع اللون:"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 2969d4cff..49b9ae716 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -210,6 +210,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Delete Column", "Odstranit sloupec"), ("Delete Condition", "Odstranit podmínku"), ("Delete Layer", "Odstranit vrstvu"), + ("Duplicate Layer \"{name}\"", "Duplikovat vrstvu „{name}“"), ("Delete Page", "Odstranit stránku"), ("Delete Row", "Odstranit řádek"), ("Delete Swatch", "Odstranit vzorek"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index aaf49bdb3..3ab1df80b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -2040,6 +2040,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Farbgruppenoptionen …"), ("Layer Options", "Ebenenoptionen"), ("Layer Options for \"{name}\"…", "Ebenenoptionen für „{name}“ …"), + ("Duplicate Layer \"{name}\"", "Ebene „{name}“ duplizieren"), ("Swatch Name:", "Farbfeldname:"), ("Name with Color Value", "Name mit Farbwert"), ("Color Type:", "Farbtyp:"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index db671bc83..cd68c8a53 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1865,6 +1865,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Opzioni gruppo colori…"), ("Layer Options", "Opzioni livello"), ("Layer Options for \"{name}\"…", "Opzioni livello \"{name}\"…"), + ("Duplicate Layer \"{name}\"", "Duplica livello \"{name}\""), ("Swatch Name:", "Nome campione:"), ("Name with Color Value", "Nome con valore colore"), ("Color Type:", "Tipo colore:"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 01814f271..abeca545d 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -2123,6 +2123,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "カラーグループオプション…"), ("Layer Options", "レイヤーオプション"), ("Layer Options for \"{name}\"…", "「{name}」のレイヤーオプション…"), + ("Duplicate Layer \"{name}\"", "レイヤー「{name}」を複製"), ("Swatch Name:", "スウォッチ名:"), ("Name with Color Value", "カラー値を名前にする"), ("Color Type:", "カラータイプ:"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index e4136880b..ebd613805 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -2155,6 +2155,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Last commit", "ბოლო კომიტი"), ("Layer Options", "შრის პარამეტრები"), ("Layer Options for \"{name}\"…", "შრის პარამეტრები: „{name}“…"), + ("Duplicate Layer \"{name}\"", "შრის დუბლირება: „{name}“"), ("Leader:", "მიმთითებელი:"), ("Leading Model:", "სტრიქონთაშორისი ინტერვალის მოდელი:"), ("Left-aligned tab", "მარცხნივ სწორებული ტაბულაცია"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index bd3d96b9a..dfae05867 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -211,6 +211,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Delete Column", "Usuń kolumnę"), ("Delete Condition", "Usuń warunek"), ("Delete Layer", "Usuń warstwę"), + ("Duplicate Layer \"{name}\"", "Powiel warstwę „{name}”"), ("Delete Page", "Usuń stronę"), ("Delete Row", "Usuń wiersz"), ("Delete Swatch", "Usuń próbkę"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index d8125cfe4..84f61b9ea 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1417,6 +1417,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Opções do grupo de cores…"), ("Layer Options", "Opções de camada"), ("Layer Options for \"{name}\"…", "Opções da camada \"{name}\"…"), + ("Duplicate Layer \"{name}\"", "Duplicar camada \"{name}\""), ("Swatch Name:", "Nome da amostra:"), ("Name with Color Value", "Nome com valor da cor"), ("Color Type:", "Tipo de cor:"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 5e8b58806..ffcb2d8c8 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -210,6 +210,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Delete Column", "Удалить столбец"), ("Delete Condition", "Удалить условие"), ("Delete Layer", "Удалить слой"), + ("Duplicate Layer \"{name}\"", "Дублировать слой «{name}»"), ("Delete Page", "Удалить страницу"), ("Delete Row", "Удалить строку"), ("Delete Swatch", "Удалить образец"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index f0cf41017..8725858ba 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1833,6 +1833,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Параметри групи кольорів…"), ("Layer Options", "Параметри шару"), ("Layer Options for \"{name}\"…", "Параметри шару «{name}»…"), + ("Duplicate Layer \"{name}\"", "Дублювати шар «{name}»"), ("Swatch Name:", "Назва зразка:"), ("Name with Color Value", "Назва за значенням кольору"), ("Color Type:", "Тип кольору:"), From 9702c9676a1985cd47df78af194565d16e0aeb55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 16:44:29 -0700 Subject: [PATCH 025/328] Copy: copied text gets text anchors and tables of its own Edit > Duplicate, Paste and Duplicate Spread gave a copied story a new id but kept its text anchor ids and its table ids, so the copy and the original shared them. A cross-reference in the copy resolved to the original's paragraph, and a table command given only a table id could change the original instead of the copy. The copy's text anchors now get ids from its own story id, and its tables get new document ids that its paragraphs follow. A copied cross-reference points at the copy of its destination when the same copy makes both: for Edit > Duplicate, within each selected object; for Paste and Duplicate Spread, across every copied story. Other cross-references keep their destination. Copying groups nested more than 64 levels deep is refused. --- crates/engine/src/cmd/edit.rs | 12 +- crates/engine/src/cmd/object.rs | 271 +++++++++++++++++++++++++++++++- 2 files changed, 273 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index a10e9ae2f..8f6b19dde 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -91,15 +91,17 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< let mut stories = std::collections::HashMap::new(); let fresh: Vec = list .iter() - .map(|i| { - let mut i = i.clone(); - super::object::renumber(d, &items, &mut i, &mut stories); + .map(|orig| { + let mut i = orig.clone(); + if !super::object::renumber(d, &items, &mut i, &mut stories) { + return Err(designcraft_doc::DocError::Invalid(format!("{} nests groups too deeply to copy", orig.id))); + } if d.layer(i.layer).is_none() { i.layer = d.default_layer(); } - i + Ok(i) }) - .collect(); + .collect::>()?; let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 5c0e7e814..c467eb258 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1056,7 +1056,9 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp let Some(it) = src.item(*id) else { continue }; let mut copy = it.clone(); copy.xf = Affine::translate(off) * copy.xf; - renumber(dst, src, &mut copy, &mut story_map); + if !renumber(dst, src, &mut copy, &mut story_map) { + return Err(designcraft_doc::DocError::Invalid(format!("{id} nests groups too deeply to copy")).into()); + } if dst.layer(copy.layer).is_none() { copy.layer = dst.default_layer(); } @@ -1067,6 +1069,9 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp Ok(out) } +/// Groups nesting deeper than this are not copied: [`renumber`] reports them. +const MAX_COPY_DEPTH: usize = 64; + /// The id to reference in `dst` for asset `id` of `src`. When `src` lacks the asset (a missing graphic), the reference /// gets a fresh id from `dst`, so it stays missing: `src`'s id may already name, or later be allocated to, another /// image in `dst`. @@ -1074,8 +1079,15 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { dst.adopt_asset(src, id).unwrap_or_else(|| AssetId(dst.alloc())) } -/// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. -pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) { +/// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. `stories` maps +/// the stories of `src` copied so far to their copies. False when its groups nest deeper than [`MAX_COPY_DEPTH`]: the +/// items below that keep their ids, and the copy must not be used. +pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { + renumber_in(dst, src, it, stories, 0) +} + +/// [`renumber`] for an item `depth` groups deep. +fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap, depth: usize) -> bool { it.id = ItemId(dst.alloc()); let my_id = it.id; if let Some(m) = it.media.as_mut() @@ -1091,6 +1103,7 @@ pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, storie let n = StoryId(dst.alloc()); let mut st = src.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); st.id = n; + renumber_marks(dst, src, stories, &mut st); let mut assets = HashMap::new(); for a in designcraft_doc::story_asset_refs(&st) { let na = adopt_or_dangle(dst, src, a); @@ -1114,12 +1127,99 @@ pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, storie g.asset = adopt_or_dangle(dst, src, g.asset); } Content::Group { items } => { - for c in items.iter_mut() { - renumber(dst, src, Arc::make_mut(c), stories); + if depth >= MAX_COPY_DEPTH { + return false; } + let mut complete = true; + for c in items.iter_mut() { + complete &= renumber_in(dst, src, Arc::make_mut(c), stories, depth + 1); + } + return complete; } Content::Unassigned => {} } + true +} + +/// Give the text anchors and tables of `st`, a new copy of a story of `src`, ids of their own (anchors from the story's +/// id, tables from `dst`). Cross-references in `st` and in the copies `stories` already lists point at the copies of +/// their destinations where those are copied, and the copy's paragraphs follow its tables. +fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) { + let base = st.id.0 << 24; + let mut anchors = HashMap::new(); + for (k, a) in (1..).zip(st.anchors.iter_mut()) { + anchors.insert(a.id, base + k); + Arc::make_mut(a).id = base + k; + } + for (old, new) in stories { + if let (Some(o), Some(n)) = (src.story(*old), dst.story(*new)) { + anchors.extend(o.anchors.iter().zip(&n.anchors).map(|(a, b)| (a.id, b.id))); + } + } + // An earlier copy's targets are found again from its original: a new anchor id can be another original's. + for (old, new) in stories { + if let (Some(o), Some(copy)) = (src.story(*old), dst.story_mut(*new)) { + retarget_xrefs(copy, o, &anchors, 0); + } + } + remap_xrefs(st, &anchors, 0); + let mut tables = HashMap::new(); + for (old, mut table) in std::mem::take(&mut st.tables) { + let id = dst.alloc(); + Arc::make_mut(&mut table).id = id; + tables.insert(old, id); + st.tables.insert(id, table); + } + for pf in &mut st.paras { + pf.table = pf.table.map(|t| tables.get(&t).copied().unwrap_or(t)); + } +} + +/// Point the cross-references in `st`, and in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] +/// levels, at the anchors `map` gives for their targets. +fn remap_xrefs(st: &mut Story, map: &HashMap, depth: usize) { + if map.is_empty() { + return; + } + for x in &mut st.xrefs { + if let Some(n) = map.get(&x.target) { + Arc::make_mut(x).target = *n; + } + } + if depth >= MAX_COPY_DEPTH { + return; + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + remap_xrefs(&mut c.text, map, depth + 1); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + remap_xrefs(&mut Arc::make_mut(n).text, map, depth + 1); + } +} + +/// Point the cross-references in `copy`, a copy of `orig`, and in the stories of its table cells and notes down to +/// [`MAX_COPY_DEPTH`] levels, at the anchors `map` gives for the targets of the matching references in `orig`. +fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth: usize) { + for (x, o) in copy.xrefs.iter_mut().zip(&orig.xrefs) { + let target = map.get(&o.target).copied().unwrap_or(o.target); + if x.target != target { + Arc::make_mut(x).target = target; + } + } + if depth >= MAX_COPY_DEPTH { + return; + } + // Copied tables have new ids, given in the order of the old ones, so the two maps list them in the same order. + for (t, o) in copy.tables.values_mut().zip(orig.tables.values()) { + for (c, oc) in Arc::make_mut(t).cells.iter_mut().zip(&o.cells) { + retarget_xrefs(&mut c.text, &oc.text, map, depth + 1); + } + } + for (n, o) in copy.notes.iter_mut().zip(&orig.notes).chain(copy.endnotes.iter_mut().zip(&orig.endnotes)) { + retarget_xrefs(&mut Arc::make_mut(n).text, &o.text, map, depth + 1); + } } fn transform_move(s: &mut Session, p: &Value) -> Result { @@ -5078,6 +5178,167 @@ mod copy_ids_tests { assert_eq!((r["created"].as_u64(), ids(&r).len()), (Some(3), 3), "{r}"); assert!(ids(&r).iter().all(|i| s.doc().unwrap().doc.item(designcraft_doc::ItemId(*i)).is_some())); } + + /// A selected text frame whose story holds a paragraph anchor, a cross-reference to it and a table. + fn marked_frame(s: &mut crate::Session) -> (u64, designcraft_doc::StoryId) { + s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap(); + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Results\nSee "}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 12, "focus": 12})).unwrap(); + s.execute("xref.insert", &json!({"paragraph": "Results"})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap(); + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + (f, sid) + } + + /// The copy of story `orig` made for item `copy` has a text anchor and a table of its own, and its cross-reference + /// points at its own anchor. A table command naming the copy's table changes the copy alone. + fn assert_own_marks(s: &mut crate::Session, orig: designcraft_doc::StoryId, copy: u64) { + let d = s.doc().unwrap().doc.clone(); + let sid = d.item(designcraft_doc::ItemId(copy)).unwrap().text_frame().unwrap().story; + assert_ne!(sid, orig); + let (o, c) = (d.story(orig).unwrap(), d.story(sid).unwrap()); + let (oa, ca) = (o.anchors[0].id, c.anchors[0].id); + assert_ne!(oa, ca, "the copy's anchor has an id of its own"); + assert_eq!(d.find_anchor(ca).map(|(at, _)| at), Some(sid)); + assert_eq!((o.xrefs[0].target, c.xrefs[0].target), (oa, ca), "each cross-reference points at its own story's anchor"); + let (ot, ct) = (*o.tables.keys().next().unwrap(), *c.tables.keys().next().unwrap()); + assert_ne!(ot, ct, "the copy's table has an id of its own"); + assert_eq!(c.tables[&ct].id, ct); + assert_eq!(c.paras.iter().filter_map(|pf| pf.table).collect::>(), [ct], "the copied paragraph holds the copied table"); + d.check().unwrap(); + // The table commands are enabled with the insertion point in a table: here the original's. + let cell = designcraft_doc::CellAddr { table: ot, row: 0, col: 0 }; + s.edit(|_, sel| { + sel.text = Some(designcraft_doc::TextSel { story: orig, anchor: 0, focus: 0, frame: None, cell: Some(cell) }); + Ok(()) + }) + .unwrap(); + s.execute("table.insertRow", &json!({"table": ct})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.story(orig).unwrap().tables[&ot].nrows(), 1, "the original table is unchanged"); + assert_eq!(d.story(sid).unwrap().tables[&ct].nrows(), 2); + } + + #[test] + fn duplicated_text_gets_anchors_and_tables_of_its_own() { + let mut s = crate::Session::new(); + let (_, sid) = marked_frame(&mut s); + let copy = s.execute("edit.duplicate", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + assert_own_marks(&mut s, sid, copy); + } + + #[test] + fn pasted_text_gets_anchors_and_tables_of_its_own() { + let mut s = crate::Session::new(); + let (_, sid) = marked_frame(&mut s); + s.execute("edit.copy", &json!({})).unwrap(); + let copy = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + assert_own_marks(&mut s, sid, copy); + } + + #[test] + fn duplicated_spreads_get_anchors_and_tables_of_their_own() { + let mut s = crate::Session::new(); + let (f, sid) = marked_frame(&mut s); + s.execute("layout.pages.duplicateSpread", &json!({"spread": 0})).unwrap(); + let d = &s.doc().unwrap().doc; + let copy = d.spreads[1].items.iter().find(|i| i.text_frame().is_some()).unwrap().id.0; + assert_ne!(copy, f); + assert_own_marks(&mut s, sid, copy); + } + + #[test] + fn groups_nested_too_deeply_are_not_copied() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = |s: &mut crate::Session| s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap(); + let mut g = frame(&mut s); + for _ in 0..=super::MAX_COPY_DEPTH { + let other = frame(&mut s); + g = s.execute("object.group", &json!({"ids": [g, other]})).unwrap()["id"].as_u64().unwrap(); + } + let text = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "text", "text": "Host"})).unwrap()["id"].as_u64(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(text.unwrap())).unwrap().text_frame().unwrap().story; + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("transform.move", &json!({"dx": 10, "dy": 0, "copy": true, "ids": [g]})).is_err()); + assert_eq!(s.doc().unwrap().doc, before, "nothing is copied"); + // Nor pasted into text as an anchored object. + s.execute("selection.set", &json!({"ids": [g]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + assert!(s.execute("edit.paste", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().doc, before, "nothing is pasted"); + } + + #[test] + fn pasted_cross_references_follow_the_pasted_anchors_of_other_stories() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let frame = |s: &mut crate::Session, rect: [f64; 4], text: &str| { + let id = s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap(); + (id, s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().story) + }; + // Each story refers to the other, so one of the two is pasted before its destination. + let (a, first) = frame(&mut s, [72.0, 72.0, 300.0, 200.0], "Methods, see "); + let (b, second) = frame(&mut s, [72.0, 300.0, 300.0, 400.0], "Results, see "); + s.execute("text.select", &json!({"story": first.0, "anchor": 13, "focus": 13})).unwrap(); + s.execute("xref.insert", &json!({"paragraph": "Results"})).unwrap(); + s.execute("text.select", &json!({"story": second.0, "anchor": 13, "focus": 13})).unwrap(); + s.execute("xref.insert", &json!({"paragraph": "Methods"})).unwrap(); + s.execute("selection.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // Into another document, which holds no anchor of the original's: its stories get other ids. + s.execute("file.new", &json!({})).unwrap(); + for _ in 0..3 { + frame(&mut s, [0.0, 0.0, 50.0, 50.0], ""); + } + s.execute("selection.set", &json!({"ids": []})).unwrap(); + let ids = s.execute("edit.paste", &json!({})).unwrap()["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect::>(); + let d = &s.doc().unwrap().doc; + let story = |id: u64| d.story(d.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().story).unwrap(); + for (refers, dest) in [(story(ids[0]), story(ids[1])), (story(ids[1]), story(ids[0]))] { + assert_eq!(refers.xrefs[0].target, dest.anchors[0].id, "the cross-reference points at the pasted destination"); + assert_eq!(d.find_anchor(refers.xrefs[0].target).map(|(at, _)| at), Some(dest.id)); + } + } + + /// The first copy's new anchor id is the second original's anchor id, as can happen between two documents. + #[test] + fn copied_cross_references_keep_their_destination_when_new_ids_repeat_old_ones() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.edit(|d, _| { + d.next_id += 1000; + Ok(()) + }) + .unwrap(); + let frame = |s: &mut crate::Session, rect: [f64; 4], text: &str| { + let id = s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap(); + (designcraft_doc::ItemId(id), s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().story) + }; + let (a, first) = frame(&mut s, [72.0, 72.0, 300.0, 200.0], "Methods, see "); + let (b, second) = frame(&mut s, [72.0, 300.0, 300.0, 400.0], "Results"); + s.execute("text.select", &json!({"story": first.0, "anchor": 13, "focus": 13})).unwrap(); + s.execute("xref.insert", &json!({"paragraph": "Methods"})).unwrap(); + s.execute("text.select", &json!({"story": second.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("anchor.create", &json!({"name": "Results"})).unwrap(); + let src = s.doc().unwrap().doc.as_ref().clone(); + assert_eq!(src.story(second).unwrap().anchors[0].id, (second.0 << 24) + 1); + // The copy of `first` gets story id `second`: one id goes to the frame, the next to its story. + let mut t = crate::Session::new(); + t.execute("file.new", &json!({})).unwrap(); + let mut dst = t.doc().unwrap().doc.as_ref().clone(); + assert!(dst.next_id < second.0 - 2); + dst.next_id = second.0 - 2; + let ids = super::duplicate_from(&mut dst, &src, &[a, b], designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap(); + let story = |id: designcraft_doc::ItemId| dst.story(dst.item(id).unwrap().text_frame().unwrap().story).unwrap(); + let (one, two) = (story(ids[0]), story(ids[1])); + assert_eq!(one.id, second); + assert_eq!(one.xrefs[0].target, one.anchors[0].id, "the copy still refers to its own paragraph"); + assert_ne!(two.anchors[0].id, one.anchors[0].id); + } } #[cfg(test)] From 4bc6f8a730f1f12321f5a442b94f30513d7a3f93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 17:37:35 -0700 Subject: [PATCH 026/328] =?UTF-8?q?Tables:=20Table=20=E2=80=BA=20Go=20to?= =?UTF-8?q?=20Row=E2=80=A6=20selects=20a=20row=20by=20its=20number,=20as?= =?UTF-8?q?=20in=20InDesign?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit InDesign's Table menu has Go to Row…, which jumps to a row given its number. When the table has header or footer rows, the user chooses Header or Footer from a menu. DesignCraft had no such command. table.goToRow {row, section?} selects the row, counted from 1 within its section, and reports the page that shows it. Table › Go to Row… opens a dialog on the selected row; OK selects the row typed and moves the view to its page when that page is not the one at the center of the view. A row past the section's last row, or a section the table does not have, is refused and the dialog stays open with the reason. --- ROADMAP.md | 1 + crates/engine/src/cmd/table.rs | 135 +++++++++++++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 104 ++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 2 + crates/ui-egui/src/i18n/uk.rs | 2 + crates/ui-egui/src/menus.rs | 6 ++ docs/gaps.md | 11 +-- 16 files changed, 272 insertions(+), 7 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6a3696361..8f466b9bc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -403,6 +403,7 @@ Newest first. - **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change. - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change. - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change. +- **2026-10-25** · Table › Go to Row… (`table.goToRow {row, section?}`): as in InDesign, a dialog takes a row number and, when the table has header or footer rows, the section is chosen from a menu. The menu lists Body Rows and those of Header Rows and Footer Rows that the table has. DesignCraft counts the row from 1 within its section and selects it, and the view moves to the row's page when that page is not the one at the center of the view. A row number past the section's last row is refused. No readiness percentage change. - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change. - **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change. - **2026-10-24** · Custom-positioned anchored objects honour Relative to Spine (`anchored.options {spineRelative}`, IDML `SpineRelative`): the settings describe a left-hand page and mirror on a right-hand page, so marginal notes stay in the outside margin on both pages of a spread. On right-hand pages they took the left-hand placement and landed in the inside margin, across the spine or over the body text. No readiness percentage change. diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 54d8e5a41..881487629 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -401,6 +401,15 @@ fn table_specs() -> Vec { cmd!(noundo "table.selectColumn", "Select Column", ["Table", "Select"], None, "{story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)}", in_table, |s, p| { select(s, &super::with_param(p, "what", json!("column"))) }), + cmd!( + noundo "table.goToRow", + "Go to Row…", + ["Table"], + None, + "{row: number (from 1, counted within the section), section?: header|body|footer (default: body), story?, table?}: selects the row → {story, table, range, page: the page showing the row (from 1), or null when the row is overset}", + in_table, + go_to_row + ), cmd!(noundo "table.nextCell", "Next Cell", [], None, "{}", in_cell, |s, _| step_cell(s, true)), cmd!(noundo "table.prevCell", "Previous Cell", [], None, "{}", in_cell, |s, _| step_cell(s, false)), cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get), @@ -1531,6 +1540,54 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(json!({"story": g.story.0, "table": g.table, "range": r})) } +/// Table › Go to Row…: select row `row` (from 1) of the header, body or footer rows. +fn go_to_row(s: &mut Session, p: &Value) -> Result { + const ID: &str = "table.goToRow"; + // Only the table comes from `p`: `row` here counts within a section, not from the table's top. + let mut at = serde_json::Map::new(); + for key in ["story", "table"] { + if let Some(v) = p.get(key) { + at.insert(key.into(), v.clone()); + } + } + let g = target(s, &Value::Object(at), ID)?; + let n = p.get("row").and_then(Value::as_u64).filter(|&n| n >= 1).ok_or_else(|| bad(ID, "row must be a whole number from 1"))?; + let (index, owners, nc) = { + let st = s.doc()?; + let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?; + let (h, f, nr) = (t.header_rows(), t.footer_rows(), t.nrows()); + let (section, first, count) = match str_param(p, "section").unwrap_or("body") { + "header" => ("header", 0, h), + "body" => ("body", h, nr.saturating_sub(h + f)), + "footer" => ("footer", nr.saturating_sub(f), f), + other => return Err(bad(ID, format!("unknown section `{other}` (header, body or footer)"))), + }; + if count == 0 { + return Err(bad(ID, format!("the table has no {section} rows"))); + } + let n = usize::try_from(n).unwrap_or(usize::MAX); + if n > count { + return Err(bad(ID, format!("row {n} is past the last of the table's {count} {section} rows"))); + } + (first + n - 1, t.owners(), t.ncols()) + }; + let r = select(s, &json!({"story": g.story.0, "table": g.table, "rows": [index, index], "what": "row"}))?; + // The page of the frame that shows the row: the cells that start in it or reach it from above. + let start = index.saturating_mul(nc); + let cells: Vec<(usize, usize)> = owners.get(start..start.saturating_add(nc)).map(<[_]>::to_vec).unwrap_or_default(); + let st = s.doc()?; + let cs = s.cache.get(&st.doc, g.story, None); + let frame = cs.frames.iter().find_map(|ft| { + ft.tables + .iter() + .filter(|t| t.table == g.table) + .any(|t| t.cells.iter().any(|c| !c.repeated && cells.contains(&(c.row, c.col)))) + .then_some(ft.frame) + }); + let page = frame.and_then(|f| st.doc.page_of_item(f)).map(|p| p + 1); + Ok(json!({"story": r["story"], "table": r["table"], "range": r["range"], "page": page})) +} + /// Move the caret to the next/previous cell (Tab / Shift-Tab), selecting its text. Tab in the last /// cell adds a row. pub(crate) fn step_cell(s: &mut Session, forward: bool) -> Result { @@ -2321,6 +2378,84 @@ mod sort_tests { } } +#[cfg(test)] +mod go_to_row_tests { + use designcraft_doc::CellRange; + use serde_json::json; + + use crate::Session; + + /// A table of 1 header, 3 body and 1 footer rows, 2 columns wide, with the caret in its first cell. + fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 3, "cols": 2, "headerRows": 1, "footerRows": 1})).unwrap(); + s + } + + fn selected(s: &Session) -> CellRange { + s.doc().unwrap().selection.cells.unwrap().range + } + + #[test] + fn go_to_row_selects_a_row_counted_within_its_section() { + let mut s = session(); + let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 }, "the second body row, under the header row"); + assert_eq!(r["page"], 1); + s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 0, c0: 0, r1: 0, c1: 1 }); + s.execute("table.goToRow", &json!({"row": 1, "section": "footer"})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 4, c0: 0, r1: 4, c1: 1 }); + s.execute("table.goToRow", &json!({"row": 3, "section": "body"})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 3, c0: 0, r1: 3, c1: 1 }); + // The caret goes to the row's first cell. + assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.cell).map(|c| (c.row, c.col)), Some((3, 0))); + } + + #[test] + fn go_to_row_refuses_rows_outside_the_section() { + let mut s = session(); + s.execute("table.goToRow", &json!({"row": 1})).unwrap(); + let before = selected(&s); + for p in [ + json!({"row": 4}), + json!({"row": 0}), + json!({"row": -1}), + json!({"row": "2"}), + json!({}), + json!({"row": 2, "section": "footer"}), + json!({"row": 1, "section": "side"}), + ] { + assert!(s.execute("table.goToRow", &p).is_err(), "{p}"); + assert_eq!(selected(&s), before, "{p} leaves the selection"); + } + s.execute("table.options", &json!({"headerRows": 0, "footerRows": 0})).unwrap(); + assert!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).is_err()); + assert!(s.execute("table.goToRow", &json!({"row": 1, "section": "footer"})).is_err()); + } + + #[test] + fn go_to_row_names_the_page_that_shows_the_row() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap(); + let b = s.execute("frame.create", &json!({"spread": 1, "rect": [72, 72, 400, 600], "content": "unassigned"})).unwrap(); + s.execute("text.thread", &json!({"from": a["id"], "to": b["id"]})).unwrap(); + s.execute("text.select", &json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 20, "cols": 2, "headerRows": 1})).unwrap(); + for row in 0..21 { + s.execute("table.setRowHeight", &json!({"row": row, "height": 20, "mode": "exactly"})).unwrap(); + } + assert_eq!(s.execute("table.goToRow", &json!({"row": 1})).unwrap()["page"], 1); + assert_eq!(s.execute("table.goToRow", &json!({"row": 20})).unwrap()["page"], 2); + // The header row repeats on page 2; the row itself is the one on page 1. + assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); + } +} + #[cfg(test)] mod arabic_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e93e64679..cf384faf6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,6 +1005,52 @@ fn doc_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas) } +/// Table › Go to Row…: opens on the target table's first selected row, numbered within its header, +/// body or footer rows. +pub fn open_go_to_row(app: &mut DesignApp) { + let Ok(t) = app.run("table.get", json!({})) else { return }; + let (h, f, r) = (count_at(&t, "headerRows"), count_at(&t, "footerRows"), count_at(&t["range"], "r0")); + let nr = t["rows"].as_array().map_or(0, Vec::len); + let (section, n) = if r < h { + ("header", r + 1) + } else if r >= nr.saturating_sub(f) { + ("footer", r + 1 - nr.saturating_sub(f)) + } else { + ("body", r + 1 - h) + }; + app.ui.dialog = Some(Dialog::new( + "goToRow", + json!({"story": t["story"], "table": t["table"], "section": section, "row": n.to_string(), "hasHeader": h > 0, "hasFooter": f > 0}), + )); +} + +fn count_at(v: &Value, k: &str) -> usize { + v[k].as_u64().and_then(|n| usize::try_from(n).ok()).unwrap_or(0) +} + +/// The Go to Row dialog: the section menu shows when the table has header or footer rows. +fn go_to_row_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { + let tr = |s: &'static str| crate::i18n::tr(&app.ui.language, s); + ui.horizontal(|ui| { + if d.b("hasHeader") || d.b("hasFooter") { + let mut opts = Vec::new(); + if d.b("hasHeader") { + opts.push(("header", tr("Header Rows"))); + } + opts.push(("body", tr("Body Rows"))); + if d.b("hasFooter") { + opts.push(("footer", tr("Footer Rows"))); + } + combo(ui, d, "section", &opts); + } + crate::rtl::label(ui, tr("Row")); + text_field_named(ui, d, "row", 60.0, tr("Row")); + }); + if let Some(st) = d.fields.get("status").and_then(Value::as_str) { + ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim)); + } +} + /// Layout › Create Guides…: guides go on the page in view (or the parent page being edited), not /// on the first page, and the gutters are typed in the document's ruler unit. pub fn open_create_guides(app: &mut DesignApp) { @@ -2266,6 +2312,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "ruby" => crate::i18n::tr(&app.ui.language, "Ruby"), "newDocument" => crate::i18n::tr(&app.ui.language, "New Document"), "frameSize" => crate::i18n::tr(&app.ui.language, "Rectangle"), + "goToRow" => crate::i18n::tr(&app.ui.language, "Go to Row"), "goToPage" => crate::i18n::tr(&app.ui.language, "Go to Page"), "insertTable" => crate::i18n::tr(&app.ui.language, "Create Table"), "cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"), @@ -3027,6 +3074,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { text_field(ui, &mut d, "page", 80.0); }); } + "goToRow" => go_to_row_dialog(app, ui, &mut d), "ruby" => style_cjk::ruby_dialog(app, ui, &mut d), "insertTable" => { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0))); @@ -3342,6 +3390,29 @@ pub fn confirm(app: &mut DesignApp) -> Result { ) } "ruby" => app.run("type.ruby", style_cjk::ruby_params(&d)), + "goToRow" => { + // Anything but a whole number goes as typed, and the command's message names the fault. + let typed = d.s("row").trim().to_string(); + let row = typed.parse::().map_or_else(|_| json!(typed), |n| json!(n)); + let p = json!({"story": d.fields.get("story"), "table": d.fields.get("table"), "section": d.s("section"), "row": row}); + let r = app.run("table.goToRow", p); + match &r { + Ok(v) => { + // The view moves when the row's page is not the page at the center of the view. + if let Some(page) = v["page"].as_u64().and_then(|p| usize::try_from(p).ok()).and_then(|p| p.checked_sub(1)) + && crate::canvas::current_page(app) != Some(page) + { + crate::canvas::go_to_page(app, page); + } + } + Err(e) => { + let mut d = d.clone(); + d.fields.insert("status".into(), json!(e)); + app.ui.dialog = Some(d); + } + } + r + } "goToPage" => { // A page name ("iv", "A-3"), a number, or "+n" for an absolute position. let typed = match d.fields.get("page") { @@ -10930,6 +11001,39 @@ mod tests { assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]); } + #[test] + fn go_to_row_dialog_selects_the_row_and_shows_its_page() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 2, "facingPages": false})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + let a = app.run("frame.create", json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap(); + let b = app.run("frame.create", json!({"spread": 1, "rect": [72, 72, 400, 600], "content": "unassigned"})).unwrap(); + app.run("text.thread", json!({"from": a["id"], "to": b["id"]})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("table.insert", json!({"rows": 20, "cols": 2, "headerRows": 1})).unwrap(); + for row in 0..21 { + app.run("table.setRowHeight", json!({"row": row, "height": 20, "mode": "exactly"})).unwrap(); + } + app.run("table.select", json!({"rows": [2, 2]})).unwrap(); + crate::canvas::go_to_page(&mut app, 0); + crate::menus::activate(&mut app, "table.goToRow", &Value::Null); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!(d.id, "goToRow"); + assert_eq!((d.s("section"), d.s("row")), ("body".to_string(), "2".to_string()), "it opens on the selected row"); + assert!(d.b("hasHeader") && !d.b("hasFooter")); + // A row that is not a whole number keeps the dialog open with the reason, and the view stays. + ctl(&mut app, "ui.dialog.set", json!({"field": "row", "value": "x"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], false); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.id == "goToRow" && d.fields.contains_key("status"))); + assert_eq!(crate::canvas::current_page(&app), Some(0)); + ctl(&mut app, "ui.dialog.set", json!({"field": "row", "value": "20"})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + assert!(app.ui.dialog.is_none()); + let range = app.session.active().unwrap().selection.cells.unwrap().range; + assert_eq!((range.r0, range.r1, range.c0, range.c1), (20, 20, 0, 1)); + assert_eq!(crate::canvas::current_page(&app), Some(1), "the view goes to the page that shows the row"); + } + #[test] fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() { let mut app = facing_app(4); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d1b462ab5..b1c001457 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1104,6 +1104,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Generate QR Code", ["Generate QR Code", "Générer un code QR", "Generate QR Code", "Generate QR Code", "生成二维码"]), ("Go To", ["Go To", "Atteindre", "Go To", "Go To", "转到"]), ("Go to Page", ["Go to Page", "Atteindre la page", "Go to Page", "Go to Page", "转到页面"]), + ("Go to Row", ["Go to Row", "Atteindre la ligne", "Go to Row", "Go to Row", "转到行"]), ("Gutter", ["Gutter", "Gouttière", "Gutter", "Gutter", "栏间距"]), ("Header Rows", ["Header Rows", "Lignes d'en-tête", "Header Rows", "Header Rows", "表头行"]), ("Height", ["Height", "Hauteur", "Height", "Height", "高度"]), @@ -2082,6 +2083,7 @@ const TABLE: &[(&str, [&str; 5])] = &[ ], ), ("Go to Page…", ["Go to Page…", "Atteindre la page…", "Go to Page…", "Go to Page…", "转到页面…"]), + ("Go to Row…", ["Go to Row…", "Atteindre la ligne…", "Go to Row…", "Go to Row…", "转到行…"]), ("Gradient Feather", ["Gradient Feather", "Contour progressif dégradé", "Gradient Feather", "Gradient Feather", "渐变羽化"]), ("Gridify", ["Gridify", "Mettre en grille", "Gridify", "Gridify", "网格化"]), ("Group Transparency", ["Group Transparency", "Transparence du groupe", "Group Transparency", "Group Transparency", "编组透明度"]), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index f1dbe0acd..ec9d19fb2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -203,6 +203,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Numbering & Section Options…", "خيارات الترقيم والأقسام…"), ("Go to Page…", "انتقال إلى صفحة…"), ("Go to Page", "انتقال إلى صفحة"), + ("Go to Row…", "انتقال إلى صف…"), + ("Go to Row", "انتقال إلى صف"), ("Next Page", "الصفحة التالية"), ("Previous Page", "الصفحة السابقة"), ("First Page", "الصفحة الأولى"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 2969d4cff..a33caff35 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -578,6 +578,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Přejít na zdroj"), ("Go to Footnote Reference", "Přejít na odkaz poznámky pod čarou"), ("Go to Page…", "Přejít na stránku…"), + ("Go to Row…", "Přejít na řádek…"), + ("Go to Row", "Přejít na řádek"), ("Gradient Feather", "Přechodové zjemnění okraje"), ("Gridify", "Rozmístit do mřížky"), ("Group Transparency", "Průhlednost skupiny"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index aaf49bdb3..62905e04c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -278,6 +278,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Generate QR Code", "QR-Code erzeugen"), ("Go To", "Gehe zu"), ("Go to Page", "Gehe zu Seite"), + ("Go to Row", "Gehe zu Zeile"), ("Gutter", "Spaltenabstand"), ("Header Rows", "Tabellenkopfzeilen"), ("Height", "Höhe"), @@ -615,6 +616,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Gehe zu Quelle"), ("Go to Footnote Reference", "Gehe zu Fußnotenverweis"), ("Go to Page…", "Gehe zu Seite …"), + ("Go to Row…", "Gehe zu Zeile …"), ("Gradient Feather", "Weiche Verlaufskante"), ("Gridify", "Rastern"), ("Group Transparency", "Gruppentransparenz"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index db671bc83..170cef352 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -706,6 +706,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Vai all'origine"), ("Go to Footnote Reference", "Vai al riferimento della nota a piè di pagina"), ("Go to Page…", "Vai alla pagina…"), + ("Go to Row…", "Vai alla riga…"), + ("Go to Row", "Vai alla riga"), ("Gradient Feather", "Bordi sfocati con sfumatura"), ("Gridify", "Disponi a griglia"), ("Group Transparency", "Trasparenza gruppo"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 01814f271..c5c988f94 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -463,6 +463,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Generate QR Code", "QR コードを生成"), ("Go To", "移動"), ("Go to Page", "ページへ移動"), + ("Go to Row", "行へ移動"), ("Gutter", "段間"), ("Header Rows", "ヘッダー行"), ("Height", "高さ"), @@ -807,6 +808,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "リンク元へ移動"), ("Go to Footnote Reference", "脚注参照番号へ移動"), ("Go to Page…", "ページへ移動…"), + ("Go to Row…", "行へ移動…"), ("Gradient Feather", "グラデーションぼかし"), ("Gridify", "グリッド化"), ("Group Transparency", "グループの透明"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index e4136880b..be140a61a 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -634,6 +634,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "წყაროზე გადასვლა"), ("Go to Footnote Reference", "სქოლიოს მითითებაზე გადასვლა"), ("Go to Page…", "გვერდზე გადასვლა…"), + ("Go to Row…", "სტრიქონზე გადასვლა…"), + ("Go to Row", "სტრიქონზე გადასვლა"), ("Gradient Feather", "კიდეების გრადიენტული შერბილება"), ("Gridify", "ბადედ განლაგება"), ("Group Transparency", "ჯგუფის გამჭვირვალობა"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index bd3d96b9a..36a56e169 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -585,6 +585,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Przejdź do źródła"), ("Go to Footnote Reference", "Przejdź do odwołania przypisu"), ("Go to Page…", "Przejdź do strony…"), + ("Go to Row…", "Przejdź do wiersza…"), + ("Go to Row", "Przejdź do wiersza"), ("Gradient Feather", "Wtapianie gradientowe"), ("Gridify", "Rozmieść w siatce"), ("Group Transparency", "Przezroczystość grupy"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index d8125cfe4..367022022 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -208,6 +208,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Create Guides…", "Criar guias…"), ("Numbering & Section Options…", "Opções de numeração e de seção…"), ("Go to Page…", "Ir para página…"), + ("Go to Row…", "Ir para linha…"), + ("Go to Row", "Ir para linha"), ("Go to Page", "Ir para página"), ("Next Page", "Próxima página"), ("Previous Page", "Página anterior"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 5e8b58806..c13694de9 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -565,6 +565,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Перейти к источнику"), ("Go to Footnote Reference", "Перейти к ссылке на сноску"), ("Go to Page…", "Перейти к странице…"), + ("Go to Row…", "Перейти к строке…"), + ("Go to Row", "Перейти к строке"), ("Gradient Feather", "Градиентная растушевка"), ("Gridify", "Разместить в виде сетки"), ("Group Transparency", "Прозрачность группы"), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index f0cf41017..237067ed3 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -709,6 +709,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Go To Source", "Перейти до джерела"), ("Go to Footnote Reference", "Перейти до посилання на виноску"), ("Go to Page…", "Перейти до сторінки…"), + ("Go to Row…", "Перейти до рядка…"), + ("Go to Row", "Перейти до рядка"), ("Gradient Feather", "Градієнтне розтушовування"), ("Gridify", "Розмістити сіткою"), ("Group Transparency", "Прозорість групи"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index e3226044b..58c9a24a0 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -818,6 +818,8 @@ pub const MENUS: &[(&str, &[&str])] = &[ "cmd:table.distributeColumns", "cmd:table.distributeRows", "-", + "cmd:table.goToRow", + "-", "ui:app.tablePanel", ], ), @@ -2662,6 +2664,10 @@ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) { app.ui.dialog = Some(crate::dialogs::Dialog::new("textFrameOptions", json!({}))); return; } + if params.is_null() && id == "table.goToRow" { + crate::dialogs::open_go_to_row(app); + return; + } // New Paragraph/Character Style…: the style options for the new style. if params.is_null() && matches!(id, "style.paragraph.create" | "style.character.create") { crate::dialogs::open_new_style(app, id == "style.paragraph.create"); diff --git a/docs/gaps.md b/docs/gaps.md index ea5b70840..85274ecd4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -150,8 +150,8 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · ### 12. Tables in depth (F) - **Missing:** anchored objects in cells not drawn (#163); Table ▸ Table Options and Cell Options - submenus as InDesign lays them out, Diagonal Lines, Edit Header/Footer, - Go to Row; general reliability (#20). + submenus as InDesign lays them out, Diagonal Lines, Edit Header/Footer; general reliability + (#20). - **Estimate:** 25–40 h. ### 13. Hyphenation and spelling languages (T, L) @@ -177,13 +177,10 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Estimate:** 30–50 h. ### 16. Menu items still missing (U) -- **Missing:** 149 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes -- **Missing:** 150 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes +- **Missing:** 147 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes and Track Changes submenus (the panels and commands exist), hyperlink and cross-reference - update commands, Convert Bullets/Numbering to Text, Convert Variable to Text, Object ▸ Clear - Effects / Clear All Transparency / Rotate 180° / Reverse Path, update commands, Convert Bullets/Numbering to Text, Object ▸ Clear - Effects / Clear All Transparency / Rotate 180° / Reverse Path, Layout ▸ Go Back/Forward, + Effects / Clear All Transparency / Rotate 180°, Window ▸ Arrange (2-up … 6-up), Trap Presets, Overlays, Edit ▸ Assign Profiles / Convert to Profile / Edit Original, File ▸ Open PDF / Document and Print Presets / User Settings, Type ▸ Size presets, Table ▸ Table Options / Cell Options submenus, Paste Before/After, From 3b2373bf8d8a09c4d210d943d452280ea6f26f88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 25 Oct 2026 21:10:04 -0700 Subject: [PATCH 027/328] Tables: Go to Row runs on a named table and stays with its document table.goToRow given a story and table now selects the row when the selection is outside a table, as table.select does. The Table menu item still needs the selection in a table. The Go to Row dialog keeps the document it was opened for. If another document became active before OK, that document becomes active again and the row is selected there; if it has closed, OK selects nothing. --- crates/engine/src/cmd/table.rs | 13 ++++++++- crates/ui-egui/src/dialogs.rs | 48 +++++++++++++++++++++++++++++++++- crates/ui-egui/src/menus.rs | 15 +++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index 881487629..c84d370c8 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -407,7 +407,7 @@ fn table_specs() -> Vec { ["Table"], None, "{row: number (from 1, counted within the section), section?: header|body|footer (default: body), story?, table?}: selects the row → {story, table, range, page: the page showing the row (from 1), or null when the row is overset}", - in_table, + in_table_or_ids, go_to_row ), cmd!(noundo "table.nextCell", "Next Cell", [], None, "{}", in_cell, |s, _| step_cell(s, true)), @@ -2437,6 +2437,17 @@ mod go_to_row_tests { assert!(s.execute("table.goToRow", &json!({"row": 1, "section": "footer"})).is_err()); } + #[test] + fn go_to_row_selects_a_row_of_a_named_table_outside_the_selection() { + let mut s = session(); + let t = s.execute("table.get", &json!({})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [72, 720, 500, 760], "content": "text", "text": "Notes"})).unwrap(); + s.execute("text.select", &json!({"story": other["story"], "anchor": 0, "focus": 0})).unwrap(); + assert!(s.execute("table.goToRow", &json!({"row": 2})).is_err(), "no table named and none selected"); + s.execute("table.goToRow", &json!({"story": t["story"], "table": t["table"], "row": 2})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 }); + } + #[test] fn go_to_row_names_the_page_that_shows_the_row() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cf384faf6..e62249b26 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1020,7 +1020,15 @@ pub fn open_go_to_row(app: &mut DesignApp) { }; app.ui.dialog = Some(Dialog::new( "goToRow", - json!({"story": t["story"], "table": t["table"], "section": section, "row": n.to_string(), "hasHeader": h > 0, "hasFooter": f > 0}), + json!({ + "uid": app.session.active().map(|doc| doc.uid), + "story": t["story"], + "table": t["table"], + "section": section, + "row": n.to_string(), + "hasHeader": h > 0, + "hasFooter": f > 0 + }), )); } @@ -3391,6 +3399,13 @@ pub fn confirm(app: &mut DesignApp) -> Result { } "ruby" => app.run("type.ruby", style_cjk::ruby_params(&d)), "goToRow" => { + // The story and table belong to the document the dialog was opened for: that document + // becomes active first, and when it has closed, nothing is selected. + let uid = d.fields.get("uid").and_then(Value::as_u64); + if uid.is_some() && uid != app.session.active().map(|doc| doc.uid) { + let Some(i) = app.session.documents().iter().position(|doc| Some(doc.uid) == uid) else { return Ok(Value::Null) }; + app.run("file.activate", json!({"index": i}))?; + } // Anything but a whole number goes as typed, and the command's message names the fault. let typed = d.s("row").trim().to_string(); let row = typed.parse::().map_or_else(|_| json!(typed), |n| json!(n)); @@ -11034,6 +11049,37 @@ mod tests { assert_eq!(crate::canvas::current_page(&app), Some(1), "the view goes to the page that shows the row"); } + /// Go to Row's OK goes to the row of the table in the document the dialog was opened for, even + /// when another document became active meanwhile; when that document has closed, nothing is selected. + #[test] + fn go_to_row_dialog_goes_to_the_document_it_was_opened_for() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let table_doc = |app: &mut DesignApp, title: &str| { + app.run("file.new", json!({"title": title})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 500, 700], "content": "text", "text": ""})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("table.insert", json!({"rows": 3, "cols": 2})).unwrap(); + }; + table_doc(&mut app, "first"); + crate::menus::activate(&mut app, "table.goToRow", &Value::Null); + table_doc(&mut app, "second"); + setup_fields(&mut app, json!({"row": "3"})); + confirm(&mut app).unwrap(); + let active = app.session.active().unwrap(); + assert_eq!(active.doc.title, "first", "the dialog's document becomes active"); + assert_eq!(active.selection.cells.map(|c| (c.range.r0, c.range.r1)), Some((2, 2))); + let second = app.session.documents().iter().find(|d| d.doc.title == "second").unwrap(); + assert!(second.selection.cells.is_none(), "the other document's selection stays"); + + crate::menus::activate(&mut app, "table.goToRow", &Value::Null); + app.run("file.close", json!({})).unwrap(); + let before = app.session.active().unwrap().selection.clone(); + setup_fields(&mut app, json!({"row": "1"})); + assert_eq!(confirm(&mut app), Ok(Value::Null)); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().selection, before, "the dialog's document closed"); + } + #[test] fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() { let mut app = facing_app(4); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 58c9a24a0..7f970b798 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -2576,6 +2576,10 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + // Go to Row runs on a named table from anywhere; the menu item needs the selection in a table. + if id == "table.goToRow" { + return enabled(app, "table.selectColumn"); + } if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { return false; } @@ -3751,6 +3755,17 @@ mod tests { } } + #[test] + fn go_to_row_is_enabled_in_a_table() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [72, 72, 500, 700], "content": "text", "text": "Notes"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + assert!(!menu_enabled(&app, "table.goToRow"), "the insertion point is not in a table"); + app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap(); + assert!(menu_enabled(&app, "table.goToRow")); + } + #[test] fn pdf_export_menu_item_opens_the_dialog_or_exports() { // No params: the menu item opens the options dialog. From 99083a76d42f4690fc418b55d1ec6bbf169e9ceb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 26 Oct 2026 01:18:05 -0700 Subject: [PATCH 028/328] Layers: Duplicate Layer copies hyperlinks on the copied objects and text Duplicate Layer copied a layer's objects and stories but not the hyperlinks on them, so the copies had no links. Each hyperlink whose source is a copied object or a copied story now gets a copy with an id of its own, pointing at the copy and going to the same destination. --- crates/engine/src/cmd/layout.rs | 56 +++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 361e2f40b..3d098a674 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -3,7 +3,9 @@ use std::collections::HashMap; use std::sync::Arc; -use designcraft_doc::{Content, Guide, Item, ItemId, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, SpreadRef, Story, StoryId}; +use designcraft_doc::{ + Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, SpreadRef, Story, StoryId, +}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, ok, str_param}; @@ -1374,7 +1376,8 @@ fn set_layer(s: &mut Session, p: &Value) -> Result { /// Duplicate Layer: a new layer above `id` with its settings and a copy of every object on it, on document and parent /// spreads, in one undo step. Copied text frames stay threaded to the other copied frames of their story, and each copy /// of a story holds all of its text. A copied override of a parent item overrides that item's copy, or is detached when -/// the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. +/// the parent item is on another layer. Pages hide a parent item's copy where they hide the parent item. Hyperlinks on +/// copied objects and text get copies that go to the same destinations. fn duplicate_layer(s: &mut Session, p: &Value) -> Result { const ID: &str = "layer.duplicate"; let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); @@ -1448,6 +1451,22 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { remap_xrefs(st, &anchors); } } + // The hyperlinks of copied objects and copied text get copies with ids of their own and the same destinations. + let links: Vec<_> = src + .hyperlinks + .iter() + .filter_map(|h| { + let source = match &h.source { + HyperlinkSource::Item { id } => HyperlinkSource::Item { id: *ids.get(id)? }, + HyperlinkSource::Text { story, start, end } => HyperlinkSource::Text { story: *stories.get(story)?, start: *start, end: *end }, + }; + Some((h, source)) + }) + .collect(); + for (h, source) in links { + let id = d.alloc(); + d.hyperlinks.push(Hyperlink { id, source, ..h.clone() }); + } // A page, document or parent, hides a parent item's copy where it hides the parent item, and its ruler guides on // the layer get copies on the new layer. let hidden = |pg: &designcraft_doc::Page| -> Vec { pg.overridden.iter().filter_map(|o| ids.get(o).copied()).collect() }; @@ -2064,6 +2083,39 @@ mod layer_tests { assert_ne!(frame.id.0, a); } + #[test] + fn duplicate_layer_copies_the_hyperlinks_of_its_objects_and_text() { + use designcraft_doc::{HyperlinkDest, HyperlinkSource}; + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"pages": 2})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [72, 72, 172, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [a], "url": "https://example.com/a", "name": "Logo"})).unwrap(); + let t = s.execute("frame.create", &json!({"rect": [72, 200, 400, 300], "content": "text", "text": "Read more here"})).unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(t["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 5, "focus": 9})).unwrap(); + s.execute("hyperlink.create", &json!({"page": 2})).unwrap(); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let other = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].as_u64().unwrap(); + s.execute("hyperlink.create", &json!({"ids": [other], "email": "info@example.com"})).unwrap(); + let before = s.doc().unwrap().doc.hyperlinks.clone(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.hyperlinks[..3], before[..], "the original hyperlinks are unchanged"); + let copies = on_layer(&d, copy); + let frame = copies.iter().find(|i| i.text_frame().is_none()).unwrap().id; + let story = copies.iter().find_map(|i| i.text_frame()).unwrap().story; + let added = &d.hyperlinks[3..]; + assert_eq!(added.len(), 2, "the other layer's hyperlink gets no copy"); + assert_eq!((&added[0].name, &added[0].source, &added[0].dest), (&before[0].name, &HyperlinkSource::Item { id: frame }, &before[0].dest)); + assert_eq!(added[1].source, HyperlinkSource::Text { story, start: 5, end: 9 }); + assert_eq!((&added[1].name, &added[1].dest), (&before[1].name, &HyperlinkDest::Page(1))); + let ids: std::collections::HashSet = d.hyperlinks.iter().map(|h| h.id).collect(); + assert_eq!(ids.len(), 5, "each copy has an id of its own"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.hyperlinks, before, "one undo step removes the copies"); + } + #[test] fn duplicate_layer_gives_copied_text_anchors_their_own_ids() { let mut s = crate::Session::new(); From abc794396b8ad8a2842e43e482d6aed355288cbb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 26 Oct 2026 02:15:28 -0700 Subject: [PATCH 029/328] Layers: Duplicate Layer gives tables in copied cells and notes ids of their own Tables inside a copied table cell or note kept the original table's id, so two tables in the document shared one id. Duplicate Layer now renumbers them at every depth, with the paragraphs that hold them. --- crates/engine/src/cmd/layout.rs | 71 ++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 3d098a674..31661848f 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1422,7 +1422,8 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { d.stories.insert(new, Arc::new(st)); } // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references - // and those of the other copies point at, and tables with ids of their own, allocated in story order. + // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes + // included, allocated in story order. let mut anchors = HashMap::new(); let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); order.sort_unstable_by_key(|(_, new)| *new); @@ -1434,16 +1435,7 @@ fn duplicate_layer(s: &mut Session, p: &Value) -> Result { anchors.insert(a.id, id); Arc::make_mut(a).id = id; } - let mut tables = HashMap::new(); - for (t, mut table) in std::mem::take(&mut st.tables) { - let n = d.alloc(); - Arc::make_mut(&mut table).id = n; - tables.insert(t, n); - st.tables.insert(n, table); - } - for pf in &mut st.paras { - pf.table = pf.table.and_then(|t| tables.get(&t).copied()); - } + renumber_tables(d, &mut st); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -1563,6 +1555,28 @@ fn renumber_anchored( } } +/// Give the tables of `st`, and the tables in the stories of its table cells and notes, new ids from `d`, and point the +/// paragraphs that hold them at the new ids. [`too_deep`] bounds the nesting. +fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { + let mut tables = HashMap::new(); + for (t, mut table) in std::mem::take(&mut st.tables) { + let n = d.alloc(); + let table_mut = Arc::make_mut(&mut table); + table_mut.id = n; + for c in &mut table_mut.cells { + renumber_tables(d, &mut c.text); + } + tables.insert(t, n); + st.tables.insert(n, table); + } + for pf in &mut st.paras { + pf.table = pf.table.and_then(|t| tables.get(&t).copied()); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_tables(d, &mut Arc::make_mut(n).text); + } +} + /// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for /// their targets. [`too_deep`] bounds the nesting. fn remap_xrefs(st: &mut Story, map: &HashMap) { @@ -2172,6 +2186,41 @@ mod layer_tests { assert_eq!(d.story(copied).unwrap().tables[&new].nrows(), 2, "a command naming the copy's table changes the copy"); } + #[test] + fn duplicate_layer_gives_tables_in_copied_cells_their_own_ids() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": sid.0, "anchor": 4, "focus": 4})).unwrap(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = d.alloc(); + let deepest = d.alloc(); + let mut nested = designcraft_doc::Table::new(inner, 1, 1, 0, 0, 40.0); + nested.cells[0].text.insert_table(0, designcraft_doc::Table::new(deepest, 1, 1, 0, 0, 20.0)); + d.story_mut(sid).unwrap().table_mut(table).unwrap().cells[0].text.insert_table(0, nested); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let outer = d.story(copied).unwrap().tables.values().next().unwrap(); + let cell = &outer.cells[0].text; + let new_inner = *cell.tables.keys().next().unwrap(); + assert_ne!(new_inner, inner, "a table in a copied cell has an id of its own"); + assert_eq!(cell.tables[&new_inner].id, new_inner); + assert_eq!(cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_inner], "the copied cell holds the copied table"); + let inner_cell = &cell.tables[&new_inner].cells[0].text; + let new_deepest = *inner_cell.tables.keys().next().unwrap(); + assert_ne!(new_deepest, deepest, "a table nested deeper has an id of its own"); + assert_eq!(inner_cell.paras.iter().filter_map(|pf| pf.table).collect::>(), [new_deepest]); + let ids = [outer.id, new_inner, new_deepest, table, inner, deepest]; + assert_eq!(ids.iter().collect::>().len(), ids.len(), "every table id is unique: {ids:?}"); + let orig = d.story(sid).unwrap().tables[&table].cells[0].text.tables.keys().copied().collect::>(); + assert_eq!(orig, [inner], "the original's nested table keeps its id"); + } + #[test] fn duplicate_layer_numbers_copied_tables_and_anchored_objects_in_story_order() { let mut s = crate::Session::new(); From 1c424288a931c0dee22eca5c8505a26ab6ef87b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 08:54:35 -0700 Subject: [PATCH 030/328] Remap text anchors in duplicated cells and notes --- crates/engine/src/cmd/layout/layers.rs | 88 ++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index f9943007a..fc8c7ecf2 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -119,6 +119,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { Arc::make_mut(a).id = id; } renumber_tables(d, &mut st); + renumber_nested_anchors(d, &mut st, &mut anchors); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -260,6 +261,25 @@ fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { } } +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { + for anchor in &mut st.anchors { + let id = d.alloc(); + anchors.insert(anchor.id, id); + Arc::make_mut(anchor).id = id; + } + renumber_nested_anchors(d, st, anchors); + } + for table in st.tables.values_mut() { + for cell in &mut Arc::make_mut(table).cells { + child(d, &mut cell.text, anchors); + } + } + for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + child(d, &mut Arc::make_mut(note).text, anchors); + } +} + /// Point the cross-references in `st`, and in the stories of its table cells and notes, at the anchors `map` gives for /// their targets. [`too_deep`] bounds the nesting. fn remap_xrefs(st: &mut Story, map: &HashMap) { @@ -709,6 +729,74 @@ mod layer_tests { assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); } + #[test] + fn duplicate_layer_remaps_anchors_in_cells_and_notes() { + use designcraft_doc::Story; + use std::sync::Arc; + + fn add_anchor(st: &mut Story, id: u64) { + st.insert_anchor(0, "Nested heading"); + Arc::make_mut(&mut st.anchors[0]).id = id; + st.insert_xref(st.len(), designcraft_doc::CrossRef { target: id, format: String::new() }); + } + fn collect(st: &Story, values: &mut Vec<(u64, u64)>) { + for (a, x) in st.anchors.iter().zip(st.xrefs.iter()) { + values.push((a.id, x.target)); + } + for table in st.tables.values() { + for cell in &table.cells { + collect(&cell.text, values); + } + } + for note in st.notes.iter().chain(st.endnotes.iter()) { + collect(¬e.text, values); + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + let nested_id = d.alloc(); + let anchor_ids = [d.alloc(), d.alloc(), d.alloc(), d.alloc()]; + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + add_anchor(cell, anchor_ids[0]); + let mut nested = designcraft_doc::Table::new(nested_id, 1, 1, 0, 0, 20.0); + add_anchor(&mut nested.cells[0].text, anchor_ids[1]); + cell.insert_table(cell.len(), nested); + cell.insert_note(cell.len(), "Footnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.notes[0]).text, anchor_ids[2]); + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + add_anchor(&mut Arc::make_mut(&mut cell.endnotes[0]).text, anchor_ids[3]); + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + collect(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 4); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + collect(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + let unique: std::collections::HashSet<_> = after.iter().map(|(id, _)| *id).collect(); + assert_eq!(unique.len(), after.len()); + for (id, target) in &after { + assert!(!anchor_ids.contains(id), "copied nested anchor retains original id {id}"); + assert_eq!(id, target, "copied reference points to its copied anchor"); + } + let mut unchanged = Vec::new(); + collect(d.story(sid).unwrap(), &mut unchanged); + assert_eq!(unchanged, original); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let mut redone = Vec::new(); + collect(s.doc().unwrap().doc.story(copied).unwrap(), &mut redone); + assert_eq!(redone, after); + } + #[test] fn duplicate_layer_gives_copied_tables_their_own_ids() { let mut s = crate::Session::new(); From b11913eb9cb21a654c2d0b457152364bfa4d6736 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 28 Oct 2026 14:33:20 -0700 Subject: [PATCH 031/328] Layers: copied anchors in cells and notes get ids no other anchor has Duplicate Layer gave the text anchors in copied table cells and notes the document's next ids, which can equal the ids of anchors that cell and note stories number on their own. Each copy now skips every anchor id already in the document. The layer commands also import what they use since main moved them into their own module. --- crates/engine/src/cmd/layout.rs | 7 +-- crates/engine/src/cmd/layout/layers.rs | 86 +++++++++++++++++++++++--- 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index fbb8b2a52..5ec6abb4d 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -1,11 +1,6 @@ //! Layout menu and Pages/Layers panels: pages, spreads, parents, margins & columns, layers. -use std::collections::HashMap; -use std::sync::Arc; - -use designcraft_doc::{ - Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, LAYER_COLORS, Layer, LayerId, Margins, SpreadId, SpreadRef, Story, StoryId, -}; +use designcraft_doc::{LAYER_COLORS, Layer, LayerId, Margins, SpreadId}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_doc, ok, str_param}; diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 05bfa4c66..a527df660 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,4 +1,9 @@ -use super::{LAYER_COLORS, LayerId, Result, Session, Value, bad, ok}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use designcraft_doc::{Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; + +use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; /// Layer Options: every field in one undo step; a bad name or colour changes nothing. pub(super) fn set_layer(s: &mut Session, p: &Value) -> Result { @@ -105,6 +110,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. let mut anchors = HashMap::new(); + let mut used = HashSet::new(); + for st in d.stories.values() { + anchor_ids(st, &mut used); + } let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); order.sort_unstable_by_key(|(_, new)| *new); for (old, new) in &order { @@ -116,10 +125,11 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { for (k, a) in (1..).zip(st.anchors.iter_mut()) { let id = (new.0 << 24) + k; anchors.insert(a.id, id); + used.insert(id); Arc::make_mut(a).id = id; } renumber_tables(d, &mut st); - renumber_nested_anchors(d, &mut st, &mut anchors); + renumber_nested_anchors(d, &mut st, &mut anchors, &mut used); d.stories.insert(*new, Arc::new(st)); } for new in stories.values() { @@ -261,22 +271,40 @@ fn renumber_tables(d: &mut designcraft_doc::Document, st: &mut Story) { } } -fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { - fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap) { +/// Add the ids of the text anchors in `st`, and in the stories of its table cells and notes at any depth, to `used`. +/// The walk keeps its own stack, so a story on another layer that nests deeper than [`too_deep`] allows is read too. +fn anchor_ids(st: &Story, used: &mut HashSet) { + let mut stack = vec![st]; + while let Some(st) = stack.pop() { + used.extend(st.anchors.iter().map(|a| a.id)); + stack.extend(st.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + stack.extend(st.notes.iter().chain(st.endnotes.iter()).map(|n| &n.text)); + } +} + +/// Give the text anchors in the stories of the table cells and notes of `st` new ids from `d` that are not in `used` +/// (recorded in `anchors` and `used`). [`too_deep`] bounds the nesting. +fn renumber_nested_anchors(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { + fn child(d: &mut designcraft_doc::Document, st: &mut Story, anchors: &mut HashMap, used: &mut HashSet) { for anchor in &mut st.anchors { - let id = d.alloc(); + let id = loop { + let id = d.alloc(); + if used.insert(id) { + break id; + } + }; anchors.insert(anchor.id, id); Arc::make_mut(anchor).id = id; } - renumber_nested_anchors(d, st, anchors); + renumber_nested_anchors(d, st, anchors, used); } for table in st.tables.values_mut() { for cell in &mut Arc::make_mut(table).cells { - child(d, &mut cell.text, anchors); + child(d, &mut cell.text, anchors, used); } } for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - child(d, &mut Arc::make_mut(note).text, anchors); + child(d, &mut Arc::make_mut(note).text, anchors, used); } } @@ -797,6 +825,48 @@ mod layer_tests { assert_eq!(redone, after); } + #[test] + fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + fn ids(st: &designcraft_doc::Story, out: &mut Vec) { + out.extend(st.anchors.iter().map(|a| a.id)); + for table in st.tables.values() { + for cell in &table.cells { + ids(&cell.text, out); + } + } + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let table_id = d.alloc(); + // The cell's anchors take the ids the document hands out next, as anchors made in a cell story can. + let start = d.alloc(); + let mut table = designcraft_doc::Table::new(table_id, 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + for k in 1..=64 { + cell.insert_anchor(0, "Heading"); + Arc::make_mut(&mut cell.anchors[0]).id = start + k; + } + d.story_mut(sid).unwrap().insert_table(0, table); + let mut original = Vec::new(); + ids(d.story(sid).unwrap(), &mut original); + assert_eq!(original.len(), 64); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let copied = on_layer(d, copy)[0].text_frame().unwrap().story; + let mut after = Vec::new(); + ids(d.story(copied).unwrap(), &mut after); + assert_eq!(after.len(), original.len()); + for id in &after { + assert!(!original.contains(id), "copied cell anchor {id} has the id of an original anchor"); + } + } + #[test] fn duplicate_layer_gives_copied_tables_their_own_ids() { let mut s = crate::Session::new(); From 5b51b16b05c2c03b4e6c712279638ca0208322e4 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:10:35 +0100 Subject: [PATCH 032/328] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 68e674b6e..591974004 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -301,7 +301,7 @@ fn interface_strings() -> HashSet<&'static str> { "Equal fixed heights for the selected rows; cell text may become overset.", "Found", "Grab bag", - "Include Inside Edges", + "Include Inside Edges", "Key Object", "Load Styles", "layer", From 9e9efb3ba3b9d047b3782a22282cd807a33c3872 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 21:31:11 +0100 Subject: [PATCH 033/328] Alpha text wrap: the default threshold re-exported from main's split item module Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index 1d2feb6a8..fc997825b 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,7 +29,7 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, + AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; From faee83dad68be3506a62d918df7e42723a880bed Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:24:59 +0100 Subject: [PATCH 034/328] Georgian: main's rows where the branch added the same keys again Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ka.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index cd3a889a8..d0b94f549 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -36,7 +36,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Text Frame General Options", "ტექსტის ჩარჩოს ზოგადი პარამეტრები"), ("New Object Style", "ახალი ობიექტის სტილი"), ("Object Style Options", "ობიექტის სტილის პარამეტრები"), - ("Object Style Options…", "ობიექტის სტილის პარამეტრები…"), ("Basic Attributes", "ძირითადი ატრიბუტები"), ("Stroke & Corner Options", "კონტურისა და კუთხეების პარამეტრები"), ("Effects for:", "ეფექტები:"), From 72c06ea4ac676e4bf0f10fe7061a36b9542025a3 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:33:44 +0100 Subject: [PATCH 035/328] IDML object style import: the HashMap import in main's split styles module Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/import/styles.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 013036d6a..9f5b6f69c 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use designcraft_geom::corners::CornerOptions; use super::object_style::{corners, corners_in}; From 1141f3a22b58d45c56e3cc4a3fe968748a1ecbbd Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 29 Oct 2026 22:40:12 +0100 Subject: [PATCH 036/328] Object styles: the branch's true/false parameter helper, beside the other object style parameters in main's split module Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/object.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 732d9fba6..7fcc3d1f3 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -159,6 +159,15 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// A true/false parameter, when given. +fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + } +} + /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 /// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { From 197f75941e179d5c9009fd52d75f58069c52b00c Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 00:01:01 +0100 Subject: [PATCH 037/328] Dropdowns: craft_ui::ComboBox, as main's clippy configuration asks Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/object_style_dialog.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 61b7cbe7b..5ce0d56a5 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -333,7 +333,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { // Based On isn't editable yet: the style's parent, as it is. ui.add_enabled_ui(false, |ui| { let based = d.s("basedOn"); - egui::ComboBox::from_id_salt("os_based_on") + craft_ui::ComboBox::from_id_salt("os_based_on") .selected_text(crate::i18n::style_name(&app.ui.language, &based)) .width(220.0) .show_ui(ui, |_| {}); @@ -390,7 +390,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let cur: designcraft_geom::corners::CornerShape = serde_json::from_value(get(d, &["corners", "corners"])[0]["shape"].clone()).unwrap_or_default(); let mut picked = None; - egui::ComboBox::from_id_salt("os_corner_shape").selected_text(tr(cur.label())).width(140.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("os_corner_shape").selected_text(tr(cur.label())).width(140.0).show_ui(ui, |ui| { for s in designcraft_geom::corners::CornerShape::ALL { if ui.selectable_label(s == cur, tr(s.label())).clicked() { picked = Some(s); @@ -415,7 +415,7 @@ fn page_ui(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, page: &str) { let cur = d.s("paragraphStyle"); let shown = if cur.is_empty() { String::new() } else { crate::i18n::style_name(&app.ui.language, &cur).to_string() }; let mut picked = None; - egui::ComboBox::from_id_salt("os_paragraph_style").selected_text(shown).width(240.0).show_ui(ui, |ui| { + craft_ui::ComboBox::from_id_salt("os_paragraph_style").selected_text(shown).width(240.0).show_ui(ui, |ui| { for s in &doc.styles.paragraph { if ui.selectable_label(s.name == cur, crate::i18n::style_name(&app.ui.language, &s.name)).clicked() { picked = Some(s.name.clone()); @@ -472,7 +472,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { crate::rtl::label(ui, tr("Effects for:")); // Stroke, Fill and Text levels aren't in the document model yet: the object only. ui.add_enabled_ui(false, |ui| { - egui::ComboBox::from_id_salt("os_fx_level").selected_text(tr("Object")).width(100.0).show_ui(ui, |_| {}); + craft_ui::ComboBox::from_id_salt("os_fx_level").selected_text(tr("Object")).width(100.0).show_ui(ui, |_| {}); }); }); for (key, label) in crate::effects_dialog::PAGES.iter().skip(1) { From c31ad07f38e0403a5a0fc687cbbdf7331aa5353f Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 16 Oct 2026 14:19:00 +0200 Subject: [PATCH 038/328] =?UTF-8?q?InDesign's=20type=20shortcuts:=20Justif?= =?UTF-8?q?y=20All=20Lines=20=E2=87=A7=E2=8C=98F,=20Em=20Space=20=E2=87=A7?= =?UTF-8?q?=E2=8C=98M,=20En=20Space=20=E2=87=A7=E2=8C=98N,=20Paragraph=20R?= =?UTF-8?q?ules=20=E2=8C=A5=E2=8C=98J?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - type.justifyAll ("Justify all lines", ⇧⌘F) next to Justify Left ⇧⌘J. - Insert White Space › Em Space and En Space become app.insertEmSpace / app.insertEnSpace, so the menu (and the Mac menu bar) shows ⇧⌘M / ⇧⌘N; they are enabled at an insertion point only. - Paragraph Rules… gets ⌥⌘J, shown in the Paragraph panel menu. - On the Mac a menu-bar insert (Em/En Space, Current Page Number) does nothing while a text field has focus, instead of typing at the canvas caret behind it. --- ROADMAP.md | 4 +- crates/engine/src/cmd/text.rs | 26 +++++ crates/ui-egui/src/menus/invoke.rs | 8 ++ crates/ui-egui/src/menus/run.rs | 2 + crates/ui-egui/src/menus/state.rs | 3 + crates/ui-egui/src/menus/tables.rs | 4 +- crates/ui-egui/src/menus/tests.rs | 94 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 4 +- .../src/panels/properties/typography.rs | 7 +- docs/target-app-parity.md | 2 +- 10 files changed, 148 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ad3f52a14..004b957c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -63,7 +63,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`). - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. -- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu (⌥⌘J) and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. @@ -756,3 +756,5 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. + +- **2026-10-16** · InDesign's type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus. No readiness percentage change. diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 8e6038741..9109e98fd 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -241,6 +241,10 @@ pub fn specs() -> Vec { s, &json!({"align": "leftJustified"}) )), + cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| format_paras( + s, + &json!({"align": "fullyJustified"}) + )), cmd!( "type.bold", "Bold", @@ -432,3 +436,25 @@ pub fn specs() -> Vec { ), ] } + +#[cfg(test)] +mod alignment_shortcut_tests { + use serde_json::json; + + use crate::Session; + + /// InDesign's Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. + #[test] + fn justify_all_lines_has_indesigns_shortcut_and_justifies_the_last_line_too() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 3, "focus": 3})).unwrap(); + // From Justify Left, so the result is not a default or a neighbouring justification. + s.execute("type.justify", &json!({})).unwrap(); + assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "leftJustified"); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "fullyJustified"); + assert_eq!(crate::find_command("type.justifyAll").and_then(|c| c.shortcut), Some("Cmd+Shift+F")); + } +} diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index d11b8deaa..628dff472 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -141,6 +141,11 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param if params.is_null() && ctx.text_edit_focused() && forward_to_text_edit(app, ctx, id) { return; } + // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change) + // the character would land at the canvas caret, not where the person is typing. + if params.is_null() && ctx.text_edit_focused() && TEXT_INSERTS.contains(&id) { + return; + } // The canvas text editor is not an egui TextEdit, so its clipboard events must pass through // egui for the desktop integration to read/write the macOS clipboard. if params.is_null() && app.session.wants_text() && matches!(id, "edit.copy" | "edit.cut" | "edit.paste") && forward_to_text_edit(app, ctx, id) { @@ -149,6 +154,9 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param activate(app, id, params); } +/// Menu items that type a character at the canvas insertion point. +const TEXT_INSERTS: [&str; 3] = ["app.insertCurrentPageNumber", "app.insertEmSpace", "app.insertEnSpace"]; + /// The editing commands a focused text field takes from the native menu bar. pub(super) const TEXT_FIELD_COMMANDS: [&str; 6] = ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"]; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 6a8d797b5..41188e16e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -778,6 +778,8 @@ fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option app.run("text.insert", json!({"text": "\u{e000}", "raw": true})), + "app.insertEmSpace" => app.run("text.insert", json!({"text": "\u{2003}", "raw": true})), + "app.insertEnSpace" => app.run("text.insert", json!({"text": "\u{2002}", "raw": true})), // `panel_docking::command` takes the dock panels (and the Window › Styles group) first. "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties"); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index f9e78c28f..8c7a84d88 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -172,6 +172,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + if matches!(id, "app.insertEmSpace" | "app.insertEnSpace") { + return enabled(app, "text.insert"); + } if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { return false; } diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index 4d63d485f..f3d02596b 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -244,8 +244,8 @@ pub const MENUS: &[(&str, &[&str])] = &[ "<", "<", ">Insert White Space", - "cmd:text.insert|Em Space|{\"text\": \"\u{2003}\", \"raw\": true}", - "cmd:text.insert|En Space|{\"text\": \"\u{2002}\", \"raw\": true}", + "ui:app.insertEmSpace", + "ui:app.insertEnSpace", "cmd:text.insert|Nonbreaking Space|{\"text\": \"\u{a0}\", \"raw\": true}", "cmd:text.insert|Hair Space|{\"text\": \"\u{200a}\", \"raw\": true}", "cmd:text.insert|Sixth Space|{\"text\": \"\u{2006}\", \"raw\": true}", diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5e82f6d3f..b0f6af869 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2202,6 +2202,100 @@ fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_num assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}"); } +/// A key press with `modifiers` through the window's shortcut dispatch, one frame. +fn press(app: &mut crate::DesignApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + let events = [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec(); + native_frame(app, ctx, events, None); +} + +fn story_text(app: &crate::DesignApp, story: &Value) -> String { + let d = &app.session.doc().unwrap().doc; + d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text.clone() +} + +#[test] +fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { + use egui::{Key, Modifiers}; + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); + let story = frame["story"].clone(); + // A selected frame and no insertion point: the spaces have nowhere to go, as in InDesign. + app.run("selection.set", json!({"ids": [frame["id"]]})).unwrap(); + assert!(app.session.doc().unwrap().selection.text.is_none()); + assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "ab"); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + assert!(menu_enabled(&app, "app.insertEmSpace") && menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "a\u{2003}b", "⇧⌘M types an em space at the caret"); + press(&mut app, &ctx, Key::N, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "a\u{2003}\u{2002}b", "⇧⌘N an en space after it"); + app.run("type.justify", json!({})).unwrap(); + press(&mut app, &ctx, Key::F, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["align"], "fullyJustified", "⇧⌘F justifies all lines"); + // Guard: ⌥⇧⌘J is another chord (InDesign's Justification…); the rules want Shift up. + press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("justification"), "⌥⇧⌘J opens Justification"); + app.ui.dialog = None; + press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("paragraphRules"), "⌥⌘J opens Paragraph Rules"); + // Each chord belongs to one command only, so the editor shows no conflict and nothing else fires. + let all = effective_shortcuts(&app); + for (sc, id) in [ + ("Cmd+Shift+F", "type.justifyAll"), + ("Cmd+Shift+M", "app.insertEmSpace"), + ("Cmd+Shift+N", "app.insertEnSpace"), + ("Cmd+Alt+J", "app.paragraphRulesDialog"), + ] { + let owners: Vec<&str> = all.iter().filter(|(_, s)| s == sc).map(|(i, _)| i.as_str()).collect(); + assert_eq!(owners, [id], "{sc}"); + } +} + +#[test] +fn insert_white_space_shows_the_em_and_en_space_shortcuts() { + let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1; + let white = ty + .iter() + .find_map(|i| match i { + Item::Sub(n, c) if n == "Insert White Space" => Some(c.clone()), + _ => None, + }) + .unwrap(); + // Null params, so the macOS menu bar carries the accelerator too. + for (label, sc) in [("Em Space", "Cmd+Shift+M"), ("En Space", "Cmd+Shift+N")] { + assert!( + white.iter().any(|i| matches!(i, Item::Cmd { label: l, shortcut: Some(s), params, .. } if l == label && *s == sc && params.is_null())), + "{label}" + ); + } +} + +#[test] +fn native_insert_shortcuts_leave_the_document_alone_while_a_field_has_focus() { + // On the Mac the menu bar takes ⇧⌘M before the window: with Quick Apply's field focused it + // must not type into the story behind it. + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let story = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + app.ui.palette = Some("x".into()); + for _ in 0..3 { + native_frame(&mut app, &ctx, vec![], None); + } + assert!(ctx.text_edit_focused()); + for id in ["app.insertEmSpace", "app.insertEnSpace", "app.insertCurrentPageNumber"] { + native_frame(&mut app, &ctx, vec![], Some(id)); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(story_text(&app, &story), "ab", "{id}"); + } + assert_eq!(app.ui.palette.as_deref(), Some("x")); +} + #[test] fn custom_workspaces_save_apply_and_delete() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 649469f30..1defda7f5 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -121,7 +121,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ( "app.paragraphRulesDialog", "Paragraph Rules…", - None, + Some("Cmd+Alt+J"), "{rule?: ruleAbove|ruleBelow} — Rule Above / Rule Below of the selected paragraphs (type.para)", ), ( @@ -165,6 +165,8 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("app.characterStylesPanel", "Character Styles", Some("Cmd+Shift+F11"), "{} — the Character Styles panel"), ("app.paragraphStylesPanel", "Paragraph Styles", Some("Cmd+F11"), "{} — the Paragraph Styles panel"), ("app.insertCurrentPageNumber", "Current Page Number", Some("Cmd+Alt+Shift+N"), "{} — the Current Page Number marker at the insertion point"), + ("app.insertEmSpace", "Em Space", Some("Cmd+Shift+M"), "{} — an em space at the insertion point"), + ("app.insertEnSpace", "En Space", Some("Cmd+Shift+N"), "{} — an en space at the insertion point"), ("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"), ("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"), ("view.zoomOut", "Zoom Out", Some("Cmd+-"), "{}"), diff --git a/crates/ui-egui/src/panels/properties/typography.rs b/crates/ui-egui/src/panels/properties/typography.rs index d4959c406..178dfb529 100644 --- a/crates/ui-egui/src/panels/properties/typography.rs +++ b/crates/ui-egui/src/panels/properties/typography.rs @@ -381,7 +381,12 @@ fn paragraph_panel_menu(app: &mut DesignApp, ui: &mut Ui, p: &Value) { ("Paragraph Rules…", "app.paragraphRulesDialog"), ("Paragraph Borders and Shading…", "app.paragraphBordersDialog"), ] { - if item(ui, label, None, true) { + let mut b = egui::Button::new(crate::rtl::widget(ui, crate::i18n::tr(&lang, label))); + if let Some(sc) = crate::menus::shortcut_of(app, id) { + b = b.shortcut_text(crate::menus::shortcut_text(&sc)); + } + if ui.add(b).clicked() { + ui.close(); command = Some(id); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 239920184..26d13d3de 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,7 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`). - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. -- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu (⌥⌘J) and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From 21267510dc2656959dffdd841ad1408be29df2a5 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 13:57:36 +0100 Subject: [PATCH 039/328] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/item.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rs index fc997825b..30711b5d9 100644 --- a/crates/doc/src/item.rs +++ b/crates/doc/src/item.rs @@ -29,8 +29,8 @@ pub use paint::{ path_length_bound, }; pub use text_frame::{ - AutoSize, ColumnsKind, DEFAULT_ALPHA_THRESHOLD, ContourType, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, TextFrameOptions, - TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, + AutoSize, ColumnsKind, ContourType, DEFAULT_ALPHA_THRESHOLD, FirstBaseline, FrameBaselineGrid, FrameGridRelative, PathAlign, PathType, TextFrame, + TextFrameOptions, TextWrap, VerticalJustification, WrapMode, WrapSide, vertical_text_xf, }; fn is_zero_usize(v: &usize) -> bool { From 4d30380930a6122268bcf73baf05181753fcfa5a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:19:33 +0100 Subject: [PATCH 040/328] IDML export: no unused HashSet import in main's split item module Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/item.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 83d689d47..f53c70465 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -1,6 +1,6 @@ use super::common::{affine_s, bool_s, p, pct, uid, with_props}; use super::{ - Affine, ColumnsKind, Content, El, Ex, HashSet, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, + Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, num, pt, }; From 1fe2e6b7e5f664359f87dcaa998577c946ff34b0 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:26:28 +0100 Subject: [PATCH 041/328] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/idml/src/export/item.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index f53c70465..0f6b73307 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -1,7 +1,6 @@ use super::common::{affine_s, bool_s, p, pct, uid, with_props}; use super::{ - Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, - num, pt, + Affine, ColumnsKind, Content, El, Ex, Item, Node, OBJECT_BUILTINS, PathData, Shape, TextFrameOptions, base64_encode, escape_id, names, num, pt, }; impl<'a> Ex<'a> { From 2ea8aa673930e86a014c2adb3effea291ded0a84 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 15:31:56 +0100 Subject: [PATCH 042/328] Object styles: the paragraph style and text frame parameter helpers in main's split module; Object Styles in the styles icon family Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/style/object.rs | 31 +++++++++++++++++++++++ crates/ui-egui/src/panel_docking.rs | 2 +- crates/ui-egui/src/panel_docking/tests.rs | 2 +- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 7fcc3d1f3..fb2467e5f 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -159,6 +159,37 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// `paragraphStyle`: a paragraph style's name, or null (the object style sets none). +fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result>> { + match p.get("paragraphStyle") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(Value::String(n)) if s.doc()?.doc.styles.para(n).is_some() => Ok(Some(Some(n.clone()))), + Some(Value::String(n)) => Err(bad(cmd, format!("no paragraph style `{n}`"))), + Some(_) => Err(bad(cmd, "`paragraphStyle` must be a paragraph style's name or null")), + } +} + +/// `textFrame` (a text frame's options, as `document.inspect` shows them) merged over `base`, or +/// null; refused when the columns aren't 1–40 or a gutter, width or inset isn't 0–15552 pt. +fn text_frame_param( + cmd: &str, + p: &Value, + base: Option<&designcraft_doc::TextFrameOptions>, +) -> Result>> { + let tf = group_param(cmd, p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + if let Some(Some(o)) = &tf { + if !(1..=40).contains(&o.columns) { + return Err(bad(cmd, "text frame columns must be 1–40")); + } + let mut lengths = [o.gutter, o.column_width, o.vj_paragraph_spacing_limit, o.first_baseline_min].into_iter().chain(o.inset); + if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) { + return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt")); + } + } + Ok(tf) +} + /// A true/false parameter, when given. fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 801a96ae3..709eb0d02 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -114,7 +114,7 @@ impl Placed { const ICON_GROUPS: &[&[&str]] = &[ &["stroke", "color", "swatches", "gradient"], &["effects"], - &["characterStyles", "paragraphStyles"], + &["characterStyles", "paragraphStyles", "objectStyles"], &["character", "paragraph", "typography"], &["glyphs", "story"], &["table"], diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 77b721098..a4e7f97ef 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -881,7 +881,7 @@ fn placed_panels_leave_their_icon_groups() { let column = icon_column(None, &mut placed).unwrap(); let groups: Vec> = column.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect(); assert_eq!(groups.first().unwrap(), &["stroke", "color", "gradient"]); - assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles"]); + assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles", "objectStyles"]); assert_eq!(groups.len(), ICON_GROUPS.len() - 1); } From e0b8e593e3212eb96af3ecf0919184d0372da142 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 18:01:53 +0100 Subject: [PATCH 043/328] egui 0.37: the renamed APIs in this branch's code Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/styles.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index 2b3b159c5..fac694ace 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -144,7 +144,7 @@ pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().rect_filled(row, 0.0, t.hover); } let label = shown(n, is_current && current.as_ref().is_some_and(|c| c.1)); - resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, is_current, &label)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_current, &label)); crate::rtl::paint(ui.painter(), row.min + vec2(24.0, 11.0), egui::Align2::LEFT_CENTER, &label, egui::FontId::proportional(12.5), t.text); // The default styles of new graphic and text frames, as InDesign marks them. let mark = egui::Rect::from_center_size(egui::pos2(row.max.x - 14.0, row.center().y), vec2(11.0, 11.0)); @@ -379,7 +379,7 @@ mod tests { app.run("style.object.create", json!({"name": "Framed", "fromSelection": false, "stroke": {"swatch": "[Paper]", "weight": 3}})).unwrap(); let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state( |ui, app: &mut DesignApp| { - let id = egui::Id::new("test_fonts"); + let id = egui::Id::unique("test_fonts"); if ui.data(|d| d.get_temp::(id)).is_none() { crate::theme::install_fonts(ui.ctx(), ""); ui.data_mut(|d| d.insert_temp(id, true)); From 332dd539b2252b981fb2ec869500a93fb7a99ce1 Mon Sep 17 00:00:00 2001 From: moppeeer Date: Fri, 30 Oct 2026 18:04:24 +0100 Subject: [PATCH 044/328] Object Styles: an icon group of its own after the paragraph and character styles The styles group stays Character and Paragraph Styles, as the floating styles group and its tests expect. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panel_docking.rs | 3 ++- crates/ui-egui/src/panel_docking/tests.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 709eb0d02..31366dfb5 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -114,7 +114,8 @@ impl Placed { const ICON_GROUPS: &[&[&str]] = &[ &["stroke", "color", "swatches", "gradient"], &["effects"], - &["characterStyles", "paragraphStyles", "objectStyles"], + &["characterStyles", "paragraphStyles"], + &["objectStyles"], &["character", "paragraph", "typography"], &["glyphs", "story"], &["table"], diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index a4e7f97ef..77b721098 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -881,7 +881,7 @@ fn placed_panels_leave_their_icon_groups() { let column = icon_column(None, &mut placed).unwrap(); let groups: Vec> = column.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect(); assert_eq!(groups.first().unwrap(), &["stroke", "color", "gradient"]); - assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles", "objectStyles"]); + assert_eq!(groups.get(1).unwrap(), &["characterStyles", "paragraphStyles"]); assert_eq!(groups.len(), ICON_GROUPS.len() - 1); } From c2b4514ee6ed434c822ac81ecc52fa53b154dac7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:25:42 -0700 Subject: [PATCH 045/328] Tables: Go to Row shows the caret in the frame that shows the row table.goToRow and table.select naming a table in another story kept the previous caret's frame, so frame commands that follow acted on the other story's frame. The caret's frame is now kept only within the same story, and Go to Row puts it in the frame that shows the row. The Table menu order test lists Go to Row after Distribute Columns Evenly. --- crates/engine/src/cmd/table/selection.rs | 22 ++++++++++++++++++++-- crates/ui-egui/src/menus/tests.rs | 2 ++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index 833a84e22..f29b3ca58 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -24,7 +24,8 @@ pub(super) fn select(s: &mut Session, p: &Value) -> Result { _ => {} } let st = s.doc_mut()?; - let frame = st.selection.text.and_then(|t| t.frame); + // The caret's frame is kept only within the same story. + let frame = st.selection.text.filter(|t| t.story == g.story).and_then(|t| t.frame); st.selection = Selection { cells: Some(TableSel { story: g.story, table: g.table, range: r }), text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }) }), @@ -79,6 +80,12 @@ pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result { .then_some(ft.frame) }); let page = frame.and_then(|f| st.doc.page_of_item(f)).map(|p| p + 1); + // The caret is shown in the frame that shows the row. + if let Some(f) = frame + && let Some(t) = s.doc_mut()?.selection.text.as_mut() + { + t.frame = Some(f); + } Ok(json!({"story": r["story"], "table": r["table"], "range": r["range"], "page": page})) } @@ -251,10 +258,19 @@ mod go_to_row_tests { let mut s = session(); let t = s.execute("table.get", &json!({})).unwrap(); let other = s.execute("frame.create", &json!({"rect": [72, 720, 500, 760], "content": "text", "text": "Notes"})).unwrap(); - s.execute("text.select", &json!({"story": other["story"], "anchor": 0, "focus": 0})).unwrap(); + // A click in the other frame: the caret is shown in that frame. + s.execute("text.placeCaret", &json!({"frame": other["id"], "point": [80, 730]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0), other["id"].as_u64()); assert!(s.execute("table.goToRow", &json!({"row": 2})).is_err(), "no table named and none selected"); s.execute("table.goToRow", &json!({"story": t["story"], "table": t["table"], "row": 2})).unwrap(); assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 }); + let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0); + assert_ne!(frame, other["id"].as_u64(), "the caret is not left in the other story's frame"); + // table.select naming the table from another story does not keep that story's frame either. + s.execute("text.placeCaret", &json!({"frame": other["id"], "point": [80, 730]})).unwrap(); + s.execute("table.select", &json!({"story": t["story"], "table": t["table"], "what": "table"})).unwrap(); + let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0); + assert_ne!(frame, other["id"].as_u64()); } #[test] @@ -271,6 +287,8 @@ mod go_to_row_tests { } assert_eq!(s.execute("table.goToRow", &json!({"row": 1})).unwrap()["page"], 1); assert_eq!(s.execute("table.goToRow", &json!({"row": 20})).unwrap()["page"], 2); + let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0); + assert_eq!(frame, b["id"].as_u64(), "the caret is in the frame that shows the row"); // The header row repeats on page 2; the row itself is the one on page 1. assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index e4a111a8b..352eb3a58 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2255,6 +2255,8 @@ fn the_table_menu_follows_indesigns_order() { "-", "Distribute Rows Evenly", "Distribute Columns Evenly", + "-", + "Go to Row…", ]; assert_eq!(labels, expected); // Cmd+Alt+Shift+T opens the dialog, as InDesign's; the engine command has no shortcut of From cc4939569636cb2dc1fd2d40c8898d27231f0309 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:41:12 -0700 Subject: [PATCH 046/328] Tables: Go to Row names the page under the row and reads no cell text table.goToRow took the page from the frame's center, so a row in a frame that spans two pages of a spread could name the other page, and the view moved there. It now takes the page under the row's first cell. table.get takes cells: false to leave out the cells, and the Go to Row dialog uses it, so opening the dialog on a large table does not copy every cell's text. --- crates/engine/src/cmd/table/options.rs | 30 +++++++++------- crates/engine/src/cmd/table/registry.rs | 2 +- crates/engine/src/cmd/table/selection.rs | 44 +++++++++++++++++++++--- crates/ui-egui/src/dialogs.rs | 2 +- 4 files changed, 59 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/table/options.rs b/crates/engine/src/cmd/table/options.rs index 7f9ed7786..867c7b87d 100644 --- a/crates/engine/src/cmd/table/options.rs +++ b/crates/engine/src/cmd/table/options.rs @@ -70,19 +70,23 @@ pub(super) fn get(s: &mut Session, p: &Value) -> Result { let g = target(s, p, "table.get")?; let st = s.doc()?; let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad("table.get", "no table"))?; - let owners = t.owners(); - let cells: Vec = (0..t.nrows()) - .flat_map(|r| (0..t.ncols()).map(move |c| (r, c))) - .filter(|&(r, c)| owners[r * t.ncols() + c] == (r, c)) - .filter_map(|(r, c)| { - let cell = t.cell(r, c)?; - Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill, - "insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style})) - }) - .collect(); - Ok(json!({ + let mut out = json!({ "story": g.story.0, "table": g.table, "anchor": st.doc.story(g.story).and_then(|x| x.table_anchor(g.table)), "rows": t.rows, "columns": t.columns, "headerRows": t.header_rows(), "footerRows": t.footer_rows(), - "cells": cells, "options": t.options, "range": g.range, "style": t.style, - })) + "options": t.options, "range": g.range, "style": t.style, + }); + if p.get("cells").and_then(Value::as_bool) != Some(false) { + let owners = t.owners(); + let cells: Vec = (0..t.nrows()) + .flat_map(|r| (0..t.ncols()).map(move |c| (r, c))) + .filter(|&(r, c)| owners[r * t.ncols() + c] == (r, c)) + .filter_map(|(r, c)| { + let cell = t.cell(r, c)?; + Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill, + "insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style})) + }) + .collect(); + out["cells"] = json!(cells); + } + Ok(out) } diff --git a/crates/engine/src/cmd/table/registry.rs b/crates/engine/src/cmd/table/registry.rs index 43c32f292..c42470681 100644 --- a/crates/engine/src/cmd/table/registry.rs +++ b/crates/engine/src/cmd/table/registry.rs @@ -416,6 +416,6 @@ fn table_specs() -> Vec { in_cell, |s, _| toggle_selection(s) ), - cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get), + cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?, cells?: bool (false leaves out the cells)} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get), ] } diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index f29b3ca58..c6f3d31ae 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -72,14 +72,17 @@ pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result { let cells: Vec<(usize, usize)> = owners.get(start..start.saturating_add(nc)).map(<[_]>::to_vec).unwrap_or_default(); let st = s.doc()?; let cs = s.cache.get(&st.doc, g.story, None); - let frame = cs.frames.iter().find_map(|ft| { + let placed = cs.frames.iter().find_map(|ft| { ft.tables .iter() .filter(|t| t.table == g.table) - .any(|t| t.cells.iter().any(|c| !c.repeated && cells.contains(&(c.row, c.col)))) - .then_some(ft.frame) + .flat_map(|t| t.cells.iter()) + .find(|c| !c.repeated && cells.contains(&(c.row, c.col))) + .map(|c| (ft.frame, c.rect.center())) }); - let page = frame.and_then(|f| st.doc.page_of_item(f)).map(|p| p + 1); + let frame = placed.map(|(f, _)| f); + // The page under the row's first cell: a frame can span two pages of a spread. + let page = placed.and_then(|(f, at)| page_under(&st.doc, f, at)).map(|p| p + 1); // The caret is shown in the frame that shows the row. if let Some(f) = frame && let Some(t) = s.doc_mut()?.selection.text.as_mut() @@ -89,6 +92,15 @@ pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result { Ok(json!({"story": r["story"], "table": r["table"], "range": r["range"], "page": page})) } +/// The page (from 0) under `at`, a point in the inner space of text frame `frame`. +fn page_under(doc: &designcraft_doc::Document, frame: designcraft_doc::ItemId, at: designcraft_geom::Point) -> Option { + let loc = doc.find(frame)?; + let designcraft_doc::SpreadRef::Doc(si) = loc.spread else { return None }; + let it = doc.item_at(&loc)?; + let p = doc.parent_xf(&loc) * doc.text_xf(it) * at; + Some(doc.first_page_of_spread(si) + doc.spread(loc.spread)?.page_at_x(p.x).unwrap_or(0)) +} + /// Move the caret to the next/previous cell (Tab / Shift-Tab), selecting its text. Tab in the last /// cell adds a row. pub(crate) fn step_cell(s: &mut Session, forward: bool) -> Result { @@ -292,4 +304,28 @@ mod go_to_row_tests { // The header row repeats on page 2; the row itself is the one on page 1. assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); } + + #[test] + fn table_get_without_cells_reads_the_rows_alone() { + // The Go to Row dialog reads the row counts and the selection, not every cell's text. + let mut s = session(); + s.execute("table.goToRow", &json!({"row": 2})).unwrap(); + let t = s.execute("table.get", &json!({"cells": false})).unwrap(); + assert!(t.get("cells").is_none(), "{t}"); + assert_eq!((t["headerRows"].clone(), t["footerRows"].clone(), t["range"]["r0"].clone()), (json!(1), json!(1), json!(2))); + assert_eq!(t["rows"].as_array().map(Vec::len), Some(5)); + assert_eq!(s.execute("table.get", &json!({})).unwrap()["cells"].as_array().map(Vec::len), Some(10)); + } + + #[test] + fn go_to_row_names_the_page_under_the_row_in_a_frame_across_the_spine() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 3, "facingPages": true})).unwrap(); + // Pages 2 and 3 meet at x = 612; the frame's center is on page 3, the narrow table on page 2. + let f = s.execute("frame.create", &json!({"spread": 1, "rect": [400, 72, 900, 400], "content": "text", "text": ""})).unwrap(); + s.execute("text.select", &json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap(); + s.execute("table.setColumnWidth", &json!({"cols": [0, 1], "width": 50})).unwrap(); + assert_eq!(s.execute("table.goToRow", &json!({"row": 2})).unwrap()["page"], 2); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index dae827fb2..79343e9ed 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1506,7 +1506,7 @@ fn doc_unit(app: &DesignApp) -> Unit { /// Table › Go to Row…: opens on the target table's first selected row, numbered within its header, /// body or footer rows. pub fn open_go_to_row(app: &mut DesignApp) { - let Ok(t) = app.run("table.get", json!({})) else { return }; + let Ok(t) = app.run("table.get", json!({"cells": false})) else { return }; let (h, f, r) = (count_at(&t, "headerRows"), count_at(&t, "footerRows"), count_at(&t["range"], "r0")); let nr = t["rows"].as_array().map_or(0, Vec::len); let (section, n) = if r < h { From 327b9cc7a34e9e72264b12f4e84bd756aae18d83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 21:46:49 -0700 Subject: [PATCH 047/328] Tables: selecting a row puts the caret in the merged cell that covers it table.select and table.goToRow put the caret at the range's first grid position, which has no cell of its own when a merged cell from the row above covers it, so the caret was not drawn. The caret now goes in the cell that covers that position. --- crates/engine/src/cmd/table/selection.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index c6f3d31ae..8c23d698a 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -24,11 +24,13 @@ pub(super) fn select(s: &mut Session, p: &Value) -> Result { _ => {} } let st = s.doc_mut()?; + // The caret goes in the cell that covers the range's first position, a merged one included. + let (row, col) = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).map_or((r.r0, r.c0), |t| t.owner(r.r0, r.c0)); // The caret's frame is kept only within the same story. let frame = st.selection.text.filter(|t| t.story == g.story).and_then(|t| t.frame); st.selection = Selection { cells: Some(TableSel { story: g.story, table: g.table, range: r }), - text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }) }), + text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row, col }) }), ..Default::default() }; st.bump_revision(); @@ -305,6 +307,16 @@ mod go_to_row_tests { assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); } + #[test] + fn go_to_row_puts_the_caret_in_a_merged_cell_that_covers_the_row() { + let mut s = session(); + // Body rows 1 and 2 (table rows 1 and 2) share one merged cell in column 0. + s.execute("table.merge", &json!({"rows": [1, 2], "col": 0})).unwrap(); + s.execute("table.goToRow", &json!({"row": 2})).unwrap(); + assert_eq!(selected(&s), CellRange { r0: 2, c0: 0, r1: 2, c1: 1 }); + assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.cell).map(|c| (c.row, c.col)), Some((1, 0))); + } + #[test] fn table_get_without_cells_reads_the_rows_alone() { // The Go to Row dialog reads the row counts and the selection, not every cell's text. From 2ba27b840bb1a5342b75b1199050af22f71ec1d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:28:48 -0700 Subject: [PATCH 048/328] Tables: Go to Row scrolls the row to the middle of the view Go to Row's OK moved the view only when the row's page was not the page at the center of the view, and then centered that page. When zoomed in, a row on the page in view stayed off screen, and a row on another page could stay off screen too. The view now scrolls so the row is in the middle of the view from top to bottom, at the same zoom, on the page in view or another. It scrolls sideways only when no part of the row is in view across. table.goToRow also returns the spread that shows the row, a document or parent spread, and the row's bounds on that spread. A composed table fragment lists its rows with their top and bottom, so a row inside cells merged across several rows is bounded by its own height. A row in an anchored text frame is found where the host story places the frame. --- ROADMAP.md | 2 +- crates/compose/src/cache.rs | 7 ++ crates/compose/src/table.rs | 8 ++ crates/engine/src/cmd/table/registry.rs | 2 +- crates/engine/src/cmd/table/selection.rs | 131 ++++++++++++++++++++--- crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/canvas/view.rs | 21 ++++ crates/ui-egui/src/dialogs.rs | 13 ++- crates/ui-egui/src/dialogs/tests.rs | 43 ++++++++ 9 files changed, 205 insertions(+), 25 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9b9c7d284..ac0849624 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -429,7 +429,7 @@ Newest first. - **2026-10-24** · A guide pulled out of a ruler keeps the resize cursor across it until it is dropped; the tool's cursor took over as soon as the pointer left the ruler, so the drag looked as if it had stopped. No readiness percentage change. - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change. - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change. -- **2026-10-25** · Table › Go to Row… (`table.goToRow {row, section?}`): as in InDesign, a dialog takes a row number and, when the table has header or footer rows, the section is chosen from a menu. The menu lists Body Rows and those of Header Rows and Footer Rows that the table has. DesignCraft counts the row from 1 within its section and selects it, and the view moves to the row's page when that page is not the one at the center of the view. A row number past the section's last row is refused. No readiness percentage change. +- **2026-10-25** · Table › Go to Row… (`table.goToRow {row, section?}`): as in InDesign, a dialog takes a row number and, when the table has header or footer rows, the section is chosen from a menu. The menu lists Body Rows and those of Header Rows and Footer Rows that the table has. DesignCraft counts the row from 1 within its section and selects it, and the view scrolls the row to its middle at the same zoom, on the page in view or another. A row number past the section's last row is refused. No readiness percentage change. - **2026-10-22** · Paragraph Style Options › Paragraph Shading and Paragraph Border are laid out as InDesign's: headed with the page's name; Tint is a spinner with InDesign's presets and has Overprint beside it (shading, border and gap; a new attribute each, kept through IDML; PDF export warns it doesn't overprint yet); Corner Size and Shape is InDesign's two-by-two grid of corner icons, sizes and shape menus showing each shape's glyph, with the link in the middle; offsets and weights have spinners. Found in the Learn Skills Daily course, chapter 41. No readiness percentage change. - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change. - **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change. diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 66122ccf4..88421ceb5 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -103,6 +103,13 @@ impl Cache { self.get_with(doc, sid, on, true, 0) } + /// Where the host story places anchored text frame `fid`, one of story `sid`'s frames; `None` for + /// a frame on a spread. + pub fn placement(&self, doc: &Document, sid: StoryId, fid: designcraft_doc::ItemId) -> Option { + let placed = crate::placed::placements(doc, sid, &mut |host| self.get_with(doc, host, ShownOn::Own, true, 1)); + placed.into_iter().find_map(|(id, p)| (id == fid).then_some(p)) + } + /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for /// a story `depth` hosts down from the story asked for. fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize) -> Arc { diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index dc579d8a7..f0c6fb59b 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -52,6 +52,9 @@ pub struct TableFrag { pub column: u32, pub rect: Rect, pub cells: Vec, + /// The table rows in the fragment, each with its top and bottom; repeated header and footer + /// rows are left out. + pub rows: Vec<(usize, f64, f64)>, pub strokes: Vec, /// Index of the fragment's (glyph-less) line in the frame's lines. pub line: usize, @@ -88,6 +91,10 @@ impl TableFrag { c.clip = c.clip + v; c.origin += v; } + for r in &mut self.rows { + r.1 += dy; + r.2 += dy; + } for s in &mut self.strokes { s.a += v; s.b += v; @@ -492,6 +499,7 @@ fn emit( column: cur.col as u32, rect: Rect::new(x0, top, right, bottom), cells, + rows: rows.iter().filter(|r| !r.2).map(|&(r, y, _)| (r, y, y + heights[r])).collect(), strokes, line, first, diff --git a/crates/engine/src/cmd/table/registry.rs b/crates/engine/src/cmd/table/registry.rs index c42470681..04b4dee30 100644 --- a/crates/engine/src/cmd/table/registry.rs +++ b/crates/engine/src/cmd/table/registry.rs @@ -401,7 +401,7 @@ fn table_specs() -> Vec { "Go to Row…", ["Table"], None, - "{row: number (from 1, counted within the section), section?: header|body|footer (default: body), story?, table?}: selects the row → {story, table, range, page: the page showing the row (from 1), or null when the row is overset}", + "{row: number (from 1, counted within the section), section?: header|body|footer (default: body), story?, table?}: selects the row → {story, table, range, page: the document page showing the row (from 1), spread: {kind: doc|parent, index} of the spread showing it, rowBounds: [x0, y0, x1, y1] of the row on that spread; each null when the row is overset, and page on a parent spread}", in_table_or_ids, go_to_row ), diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index 8c23d698a..524106373 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -74,33 +74,63 @@ pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result { let cells: Vec<(usize, usize)> = owners.get(start..start.saturating_add(nc)).map(<[_]>::to_vec).unwrap_or_default(); let st = s.doc()?; let cs = s.cache.get(&st.doc, g.story, None); + // The part of the table that shows the row, its frame, and the cells that cover the row there. let placed = cs.frames.iter().find_map(|ft| { - ft.tables - .iter() - .filter(|t| t.table == g.table) - .flat_map(|t| t.cells.iter()) - .find(|c| !c.repeated && cells.contains(&(c.row, c.col))) - .map(|c| (ft.frame, c.rect.center())) + ft.tables.iter().filter(|t| t.table == g.table).find_map(|t| { + let covering: Vec = + t.cells.iter().filter(|c| !c.repeated && cells.contains(&(c.row, c.col))).map(|c| c.rect).collect(); + (!covering.is_empty()).then_some((ft.frame, t, covering)) + }) }); - let frame = placed.map(|(f, _)| f); - // The page under the row's first cell: a frame can span two pages of a spread. - let page = placed.and_then(|(f, at)| page_under(&st.doc, f, at)).map(|p| p + 1); + let frame = placed.as_ref().map(|(f, _, _)| *f); + let on_spread = frame.and_then(|f| frame_on_spread(&st.doc, &s.cache, g.story, f)); + // The document page under the row's first cell: a frame can span two pages of a spread. + let page = placed.as_ref().zip(on_spread).and_then(|((_, _, covering), (spread, xf))| { + let designcraft_doc::SpreadRef::Doc(si) = spread else { return None }; + let at = xf * covering.first()?.center(); + Some(st.doc.first_page_of_spread(si) + st.doc.spreads.get(si)?.page_at_x(at.x).unwrap_or(0) + 1) + }); + // The row on its spread: across, the cells that cover it; from top to bottom, the row alone, also + // inside cells merged across several rows. + let bounds = placed.as_ref().zip(on_spread).and_then(|((_, t, covering), (_, xf))| { + let across = covering.iter().copied().reduce(|a, b| a.union(b))?; + let &(_, top, bottom) = t.rows.iter().find(|r| r.0 == index)?; + Some(xf.transform_rect_bbox(designcraft_geom::Rect::new(across.x0, top, across.x1, bottom))) + }); + let spread = on_spread.map(|(si, _)| si); // The caret is shown in the frame that shows the row. if let Some(f) = frame && let Some(t) = s.doc_mut()?.selection.text.as_mut() { t.frame = Some(f); } - Ok(json!({"story": r["story"], "table": r["table"], "range": r["range"], "page": page})) + Ok(json!({ + "story": r["story"], + "table": r["table"], + "range": r["range"], + "page": page, + "spread": spread, + "rowBounds": bounds.map(|b| [b.x0, b.y0, b.x1, b.y1]), + })) } -/// The page (from 0) under `at`, a point in the inner space of text frame `frame`. -fn page_under(doc: &designcraft_doc::Document, frame: designcraft_doc::ItemId, at: designcraft_geom::Point) -> Option { - let loc = doc.find(frame)?; - let designcraft_doc::SpreadRef::Doc(si) = loc.spread else { return None }; - let it = doc.item_at(&loc)?; - let p = doc.parent_xf(&loc) * doc.text_xf(it) * at; - Some(doc.first_page_of_spread(si) + doc.spread(loc.spread)?.page_at_x(p.x).unwrap_or(0)) +/// The spread (a document or parent spread) that text frame `frame` of story `sid` is on, and the +/// transform from the frame's inner space to that spread's coordinates. An anchored frame is where +/// its host story places it. +fn frame_on_spread( + doc: &designcraft_doc::Document, + cache: &designcraft_compose::Cache, + sid: StoryId, + frame: designcraft_doc::ItemId, +) -> Option<(designcraft_doc::SpreadRef, designcraft_geom::Affine)> { + let (spread, parent, it) = match doc.find(frame) { + Some(loc) => (loc.spread, doc.parent_xf(&loc), doc.item_at(&loc)?), + None => { + let p = cache.placement(doc, sid, frame)?; + (p.spread, p.xf, doc.anchored_item(frame)?) + } + }; + Some((spread, parent * doc.text_xf(it))) } /// Move the caret to the next/previous cell (Tab / Shift-Tab), selecting its text. Tab in the last @@ -303,6 +333,11 @@ mod go_to_row_tests { assert_eq!(s.execute("table.goToRow", &json!({"row": 20})).unwrap()["page"], 2); let frame = s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0); assert_eq!(frame, b["id"].as_u64(), "the caret is in the frame that shows the row"); + // The row on its spread: one row tall, in the frame on the second spread. + let r = s.execute("table.goToRow", &json!({"row": 20})).unwrap(); + assert_eq!(r["spread"], json!({"kind": "doc", "index": 1})); + let at: Vec = r["rowBounds"].as_array().map(|a| a.iter().filter_map(serde_json::Value::as_f64).collect()).unwrap_or_default(); + assert!(at.len() == 4 && (at[3] - at[1] - 20.0).abs() < 1e-6 && at[0] >= 72.0 && at[2] <= 401.0 && at[1] >= 72.0 && at[3] <= 600.0, "{at:?}"); // The header row repeats on page 2; the row itself is the one on page 1. assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); } @@ -317,6 +352,68 @@ mod go_to_row_tests { assert_eq!(s.doc().unwrap().selection.text.and_then(|t| t.cell).map(|c| (c.row, c.col)), Some((1, 0))); } + #[test] + fn go_to_row_bounds_a_row_inside_cells_merged_across_rows() { + let mut s = session(); + for (row, height) in [20, 10, 40, 20, 20].into_iter().enumerate() { + s.execute("table.setRowHeight", &json!({"row": row, "height": height, "mode": "exactly"})).unwrap(); + } + // Every column's cell covers body rows 1 to 3 (table rows 1 to 3), so no cell starts in body row 2. + s.execute("table.merge", &json!({"rows": [1, 3], "cols": [0, 0]})).unwrap(); + s.execute("table.merge", &json!({"rows": [1, 3], "cols": [1, 1]})).unwrap(); + let bounds = |s: &mut Session, p: serde_json::Value| -> Vec { + let r = s.execute("table.goToRow", &p).unwrap(); + r["rowBounds"].as_array().map(|a| a.iter().filter_map(serde_json::Value::as_f64).collect()).unwrap_or_default() + }; + let header = bounds(&mut s, json!({"row": 1, "section": "header"})); + let row = bounds(&mut s, json!({"row": 2})); + assert_eq!((header.len(), row.len()), (4, 4)); + assert!((row[1] - (header[3] + 10.0)).abs() < 1e-6 && (row[3] - row[1] - 40.0).abs() < 1e-6, "{header:?} {row:?}"); + assert_eq!((row[0], row[2]), (header[0], header[2]), "the row spans the table across"); + } + + #[test] + fn go_to_row_finds_a_row_in_an_anchored_text_frame() { + use designcraft_doc::{AnchorPosition, AnchoredObject, Content, Item, ItemId, Shape, Story, StoryId, TextFrame}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let host = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": "Host text"})).unwrap(); + // A text frame anchored in the host's text, its own story holding the table. + let sid = { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let (fid, sid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(sid, "", Default::default()); + story.frames.push(fid); + d.stories.insert(sid, std::sync::Arc::new(story)); + let layer = d.item(ItemId(host["id"].as_u64().unwrap())).unwrap().layer; + let mut it = + Item::new(fid, layer, Shape::Rectangle, designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(0.0, 0.0, 200.0, 100.0))); + it.content = Content::Text(TextFrame { story: sid, options: Default::default() }); + let host_story = StoryId(host["story"].as_u64().unwrap()); + d.story_mut(host_story).unwrap().insert_object(4, AnchoredObject::new(it, AnchorPosition::default())); + sid + }; + s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap(); + let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap(); + assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(1), json!({"kind": "doc", "index": 0})), "{r}"); + assert_eq!(r["rowBounds"].as_array().map(Vec::len), Some(4), "{r}"); + } + + #[test] + fn go_to_row_finds_a_row_on_a_parent_spread() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let f = s + .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 72, 400, 400], "content": "text", "text": ""})) + .unwrap(); + s.execute("text.select", &json!({"story": f["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap(); + let r = s.execute("table.goToRow", &json!({"row": 2})).unwrap(); + assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(null), json!({"kind": "parent", "index": 0})), "{r}"); + assert_eq!(r["rowBounds"].as_array().map(Vec::len), Some(4), "{r}"); + } + #[test] fn table_get_without_cells_reads_the_rows_alone() { // The Go to Row dialog reads the row counts and the selection, not every cell's text. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ed207c34b..565454f91 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -62,7 +62,8 @@ pub(crate) use view::page_in_view; use view::present_fit; pub use view::{ PageBox, apply_view_request, can_go_through_history, current_page, current_parent_page, current_slot, current_spread, current_spread_page, - drop_point, fit, go_through_history, go_to_page, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, zoom_at, + drop_point, fit, go_through_history, go_to_page, go_to_spread_rect, page_box, page_box_go, set_zoom, show_spread, step_spread, view_centre, + zoom_at, }; pub const RULER: f32 = 15.0; diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index 2ba0876a1..d1fe151d2 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -218,6 +218,27 @@ fn centre_page(app: &mut DesignApp, abs: usize) { } } +/// Scroll so `r`, a rectangle on spread `spread` as the canvas lays it out now, is in the middle of +/// the view from top to bottom, and from side to side when no part of it is in view across (keeps +/// zoom). A jump Go Back can return from. +pub fn go_to_spread_rect(app: &mut DesignApp, spread: SpreadRef, r: DRect) { + note_jump(app, false); + centre_spread_rect(app, spread, r); + note_jump(app, true); +} + +fn centre_spread_rect(app: &mut DesignApp, spread: SpreadRef, r: DRect) { + let Some(st) = app.session.active() else { return }; + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let Some(b) = layout.slot(spread).map(|s| s.xf.transform_rect_bbox(r)) else { return }; + let Some(rect) = app.canvas_rect else { return }; + if let Some(v) = app.view_mut() { + let (w, h) = (rect.width() as f64 / v.zoom, rect.height() as f64 / v.zoom); + let x = if b.x1 > v.origin.x && b.x0 < v.origin.x + w { v.origin.x } else { b.center().x - w / 2.0 }; + v.origin = Point::new(x, b.center().y - h / 2.0); + } +} + /// The document's pages by id, in page order. fn page_ids(doc: &Document) -> Vec { doc.spreads.iter().flat_map(|s| s.pages.iter().map(|p| p.id)).collect() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 79343e9ed..b3f18834f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4298,11 +4298,14 @@ fn confirm_part1(app: &mut DesignApp, d: Dialog) -> Result { let r = app.run("table.goToRow", p); match &r { Ok(v) => { - // The view moves when the row's page is not the page at the center of the view. - if let Some(page) = v["page"].as_u64().and_then(|p| usize::try_from(p).ok()).and_then(|p| p.checked_sub(1)) - && crate::canvas::current_page(app) != Some(page) - { - crate::canvas::go_to_page(app, page); + // The view scrolls the row to its middle, at the same zoom, on the row's page or another. + let spread = serde_json::from_value::(v["spread"].clone()).ok(); + let bounds = v["rowBounds"].as_array().and_then(|a| { + let n: Vec = a.iter().filter_map(Value::as_f64).collect(); + (n.len() == 4).then(|| designcraft_geom::Rect::new(n[0], n[1], n[2], n[3])) + }); + if let (Some(spread), Some(b)) = (spread, bounds) { + crate::canvas::go_to_spread_rect(app, spread, b); } } Err(e) => { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 0b6179060..1a65b9f9d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -3750,6 +3750,49 @@ fn go_to_row_dialog_selects_the_row_and_shows_its_page() { assert_eq!(crate::canvas::current_page(&app), Some(1), "the view goes to the page that shows the row"); } +/// Go to Row's OK scrolls the row to the middle of the view at the same zoom: a row off screen on the +/// page in view, and a row on another page away from that page's center. +#[test] +fn go_to_row_dialog_scrolls_the_row_to_the_middle_of_the_view() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 2, "facingPages": false})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + let a = app.run("frame.create", json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap(); + let b = app.run("frame.create", json!({"spread": 1, "rect": [72, 72, 400, 600], "content": "unassigned"})).unwrap(); + app.run("text.thread", json!({"from": a["id"], "to": b["id"]})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap(); + app.run("table.insert", json!({"rows": 20, "cols": 2, "headerRows": 1})).unwrap(); + for row in 0..21 { + app.run("table.setRowHeight", json!({"row": row, "height": 20, "mode": "exactly"})).unwrap(); + } + app.run("table.select", json!({"rows": [1, 1]})).unwrap(); + crate::canvas::go_to_page(&mut app, 0); + crate::canvas::set_zoom(&mut app, 4.0); + // The row's middle and the view's middle, from top to bottom, on the canvas. + let middles = |app: &mut DesignApp, row: u64| { + let r = app.run("table.goToRow", json!({"row": row})).unwrap(); + let spread: designcraft_doc::SpreadRef = serde_json::from_value(r["spread"].clone()).unwrap(); + let n: Vec = r["rowBounds"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let st = app.session.active().unwrap(); + let slot = designcraft_tools::CanvasLayout::new(&st.doc, false).slot(spread).unwrap().xf; + let row_y = slot.transform_rect_bbox(designcraft_geom::Rect::new(n[0], n[1], n[2], n[3])).center().y; + let (v, rect) = (app.view().unwrap(), app.canvas_rect.unwrap()); + (row_y, v.origin.y + rect.height() as f64 / 2.0 / v.zoom) + }; + let x = app.view().unwrap().origin.x; + for row in ["3", "20"] { + crate::menus::activate(&mut app, "table.goToRow", &Value::Null); + ctl(&mut app, "ui.dialog.set", json!({"field": "row", "value": row})); + assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true); + let (row_y, view_y) = middles(&mut app, row.parse().unwrap()); + assert!((row_y - view_y).abs() < 0.5, "row {row} is in the middle of the view: {row_y} against {view_y}"); + let v = app.view().unwrap(); + assert!((v.zoom - 4.0).abs() < 1e-9, "the zoom stays"); + assert!((v.origin.x - x).abs() < 1e-9, "the row was in view across, so the view does not scroll sideways"); + } + assert_eq!(crate::canvas::current_page(&app), Some(1)); +} + /// Go to Row's OK goes to the row of the table in the document the dialog was opened for, even /// when another document became active meanwhile; when that document has closed, nothing is selected. #[test] From 5b0e0295b3535411dadcbda1d03bc767b82b9bea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 2 Nov 2026 08:48:57 -0800 Subject: [PATCH 049/328] =?UTF-8?q?i18n:=20Swedish=20row=20for=20Go=20to?= =?UTF-8?q?=20Row=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Swedish became a complete-menu language on main, so the Table menu's Go to Row… item and the dialog title need Swedish rows. --- crates/ui-egui/src/i18n/sv.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 1a7550a35..4f7488ff6 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -102,6 +102,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Numbering & Section Options…", "Numrerings- och avsnittsalternativ…"), ("Go to Page…", "Gå till sida…"), ("Go to Page", "Gå till sida"), + ("Go to Row…", "Gå till rad…"), + ("Go to Row", "Gå till rad"), ("Next Page", "Nästa sida"), ("Previous Page", "Föregående sida"), ("First Page", "Första sidan"), From 8b109879d2f5b96ff84ea23a32fe0eeeac35f901 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:55:22 +0000 Subject: [PATCH 050/328] Apply review fixes - crates/ui-egui/src/menus/invoke.rs --- crates/ui-egui/src/menus/invoke.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 45120484a..33096849d 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -147,8 +147,8 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param return; } // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change) - // the character would land at the canvas caret, not where the person is typing. - if params.is_null() && ctx.text_edit_focused() && TEXT_INSERTS.contains(&id) { + // or a dialog open, the character would land at the canvas caret behind it. + if params.is_null() && (ctx.text_edit_focused() || app.ui.dialog.is_some()) && TEXT_INSERTS.contains(&id) { return; } // The canvas text editor is not an egui TextEdit, so its clipboard events must pass through From db8e1b63644f226cd7846d960f52cf4fc690b482 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 13:48:13 -0800 Subject: [PATCH 051/328] Docs: leave gap 16 of docs/gaps.md as it is on main The Go to Row change only removes Go to Row from gap 12. --- docs/gaps.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index 7010c807b..398288062 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -178,10 +178,13 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Estimate:** 30–50 h. ### 16. Menu items still missing (U) -- **Missing:** 147 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes +- **Missing:** 149 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes +- **Missing:** 150 of 482 in-scope items of InDesign 21.6's menu dump have no match (measured 2026-10-10; some exist under other labels): Type ▸ Notes and Track Changes submenus (the panels and commands exist), hyperlink and cross-reference + update commands, Convert Bullets/Numbering to Text, Convert Variable to Text, Object ▸ Clear + Effects / Clear All Transparency / Rotate 180° / Reverse Path, update commands, Convert Bullets/Numbering to Text, Object ▸ Clear - Effects / Clear All Transparency / Rotate 180°, + Effects / Clear All Transparency / Rotate 180° / Reverse Path, Layout ▸ Go Back/Forward, Window ▸ Arrange (2-up … 6-up), Trap Presets, Overlays, Edit ▸ Assign Profiles / Convert to Profile / Edit Original, File ▸ Open PDF / Document and Print Presets / User Settings, Type ▸ Size presets, Table ▸ Table Options / Cell Options submenus, Paste Before/After, From c51f02ee67516169e6fa449a8b8474f3d15822c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 14:18:43 -0800 Subject: [PATCH 052/328] Copy: tables inside copied table cells and notes get ids of their own A copied story's tables got new ids, but tables in the stories of its table cells and notes kept the original's, so a duplicate or paste left two tables with one id. They now get new ids from the destination document down to the same nesting limit, and the cell paragraphs follow. --- crates/engine/src/cmd/object.rs | 67 ++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 85c9e530d..1a9769b1b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1171,8 +1171,9 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut } /// Give the text anchors and tables of `st`, a new copy of a story of `src`, ids of their own (anchors from the story's -/// id, tables from `dst`). Cross-references in `st` and in the copies `stories` already lists point at the copies of -/// their destinations where those are copied, and the copy's paragraphs follow its tables. +/// id, tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] +/// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their +/// destinations where those are copied, and the copy's paragraphs follow its tables. fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) { let base = st.id.0 << 24; let mut anchors = HashMap::new(); @@ -1192,6 +1193,13 @@ fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap= MAX_COPY_DEPTH { + return; + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + renumber_tables(dst, &mut c.text, depth + 1); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_tables(dst, &mut Arc::make_mut(n).text, depth + 1); + } } /// Point the cross-references in `st`, and in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] @@ -5471,6 +5490,50 @@ mod copy_ids_tests { assert_own_marks(&mut s, sid, copy); } + #[test] + fn copied_text_gives_tables_in_its_cells_ids_of_their_own() { + use std::sync::Arc; + + fn table_ids(st: &designcraft_doc::Story, out: &mut Vec) { + for (id, t) in &st.tables { + out.push(*id); + for c in &t.cells { + table_ids(&c.text, out); + } + } + } + let cell = |st: &designcraft_doc::Story| st.tables.values().next().unwrap().cells[0].text.clone(); + let mut s = crate::Session::new(); + let (f, sid) = marked_frame(&mut s); + // The table's first cell holds a table. + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let inner = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let st = d.story_mut(sid).unwrap(); + let text = &mut Arc::make_mut(st.tables.values_mut().next().unwrap()).cells[0].text; + text.insert_table(text.len(), inner); + for copy_cmd in ["edit.duplicate", "edit.paste"] { + if copy_cmd == "edit.paste" { + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + } + let copy = s.execute(copy_cmd, &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let csid = d.item(designcraft_doc::ItemId(copy)).unwrap().text_frame().unwrap().story; + let (o, c) = (d.story(sid).unwrap(), d.story(csid).unwrap()); + let (oc, cc) = (cell(o), cell(c)); + let (oi, ci) = (*oc.tables.keys().next().unwrap(), *cc.tables.keys().next().unwrap()); + assert_ne!(oi, ci, "{copy_cmd}: the copied cell's table has an id of its own"); + assert_eq!(cc.tables[&ci].id, ci); + assert_eq!(cc.paras.iter().filter_map(|pf| pf.table).collect::>(), [ci], "the cell's paragraph holds the copied table"); + let mut ids = Vec::new(); + for st in d.stories.values() { + table_ids(st, &mut ids); + } + let unique: std::collections::HashSet<_> = ids.iter().collect(); + assert_eq!(unique.len(), ids.len(), "{copy_cmd}: no two tables share an id: {ids:?}"); + } + } + #[test] fn groups_nested_too_deeply_are_not_copied() { let mut s = crate::Session::new(); From 240f423392c17a88a4b22c58198cec9817be8cbd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 15:41:31 -0800 Subject: [PATCH 053/328] Tables: Go to Row leaves no caret frame for an overset row When no frame showed the row, the caret kept an earlier frame of the story, so frame commands acted on a frame that does not show the row. --- crates/engine/src/cmd/table/selection.rs | 26 +++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/table/selection.rs b/crates/engine/src/cmd/table/selection.rs index 524106373..320b21350 100644 --- a/crates/engine/src/cmd/table/selection.rs +++ b/crates/engine/src/cmd/table/selection.rs @@ -98,11 +98,9 @@ pub(super) fn go_to_row(s: &mut Session, p: &Value) -> Result { Some(xf.transform_rect_bbox(designcraft_geom::Rect::new(across.x0, top, across.x1, bottom))) }); let spread = on_spread.map(|(si, _)| si); - // The caret is shown in the frame that shows the row. - if let Some(f) = frame - && let Some(t) = s.doc_mut()?.selection.text.as_mut() - { - t.frame = Some(f); + // The caret is shown in the frame that shows the row, and in no frame when the row is overset. + if let Some(t) = s.doc_mut()?.selection.text.as_mut() { + t.frame = frame; } Ok(json!({ "story": r["story"], @@ -342,6 +340,24 @@ mod go_to_row_tests { assert_eq!(s.execute("table.goToRow", &json!({"row": 1, "section": "header"})).unwrap()["page"], 1); } + #[test] + fn go_to_row_leaves_no_caret_frame_for_an_overset_row() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": ""})).unwrap(); + s.execute("text.select", &json!({"story": a["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("table.insert", &json!({"rows": 20, "cols": 2})).unwrap(); + for row in 0..20 { + s.execute("table.setRowHeight", &json!({"row": row, "height": 20, "mode": "exactly"})).unwrap(); + } + let frame = |s: &Session| s.doc().unwrap().selection.text.and_then(|t| t.frame).map(|f| f.0); + s.execute("table.goToRow", &json!({"row": 1})).unwrap(); + assert_eq!(frame(&s), a["id"].as_u64()); + let r = s.execute("table.goToRow", &json!({"row": 20})).unwrap(); + assert_eq!((r["page"].clone(), r["spread"].clone()), (json!(null), json!(null)), "{r}"); + assert_eq!(frame(&s), None, "no frame shows the overset row"); + } + #[test] fn go_to_row_puts_the_caret_in_a_merged_cell_that_covers_the_row() { let mut s = session(); From d890289a92be8cbb60a0bd20c4b20b85a74b568b Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:43:44 -0500 Subject: [PATCH 054/328] Place: several images load the place cursor, with a thumbnail, count and grid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split out of #2073. Port of #1307, #1392 (grid) and #1432 (thumbnail and count). - File › Place takes several files; images load the place cursor in the order chosen (`place.load` `files`, `append`), after the ones it holds. A multi-page PDF or an alert stops the batch, and a file that can't be placed returns its error to `app.placeDialog`. - Each click places the next image; arrow keys while dragging lay out a grid (`place.grid`) and are handled even at a limit; Escape unloads the rest (`place.cancel`). Undo of a loaded image's asset cancels the queue. - The cursor shows how many images are loaded. - On the web, Place picks several files and the inbox loads consecutive images for the same document as one batch. --- ROADMAP.md | 1 + apps/designcraft-web/src/web.rs | 15 +- crates/engine/src/cmd/file/place.rs | 221 ++++++++++++++++-- crates/engine/src/cmd/file/registry.rs | 21 +- crates/engine/src/lib.rs | 9 + crates/engine/src/tests.rs | 117 ++++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/nav.rs | 75 +++++- crates/tools/src/tests.rs | 17 ++ crates/ui-egui/src/app/file_dialogs.rs | 40 ++++ crates/ui-egui/src/app/files.rs | 267 ++++++++++++++++++++-- crates/ui-egui/src/canvas.rs | 2 + crates/ui-egui/src/canvas/place_cursor.rs | 34 +++ crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/table.rs | 20 ++ crates/ui-egui/src/menus/run.rs | 15 +- crates/ui-egui/src/menus/ui_commands.rs | 7 +- docs/multi-image-placement.md | 26 +++ 18 files changed, 836 insertions(+), 54 deletions(-) create mode 100644 crates/ui-egui/src/canvas/place_cursor.rs create mode 100644 docs/multi-image-placement.md diff --git a/ROADMAP.md b/ROADMAP.md index a13912f7c..57c143340 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 19bc3a122..8b23ef6b7 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -402,11 +402,18 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { - return; + // Place takes several files, loaded into the place cursor in the order chosen. + let handles = if request.purpose == "place" { + dialog.pick_files().await.unwrap_or_default() + } else { + dialog.pick_file().await.into_iter().collect() }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); + let mut files = Vec::with_capacity(handles.len()); + for file in handles { + let bytes = file.read().await; + files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); + } + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); }); })), diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index a3ae11df1..ba9e0827a 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -116,7 +116,7 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh)); + return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); @@ -235,35 +235,96 @@ pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, comm Ok(()) } +/// Decode and validate the complete batch before replacing the placement cursor. pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { - let (bytes, name, link) = read_source(p)?; - let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; - let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); - let mime = designcraft_render::image_mime(&bytes).to_string(); - let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; - load_cursor(s, asset, natural) + let append = p.get("append").and_then(Value::as_bool) == Some(true); + if p.get("files").is_none() { + let (bytes, name, link) = read_source(p)?; + let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; + let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); + let mime = designcraft_render::image_mime(&bytes).to_string(); + let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; + return load_cursor(s, asset, natural, append); + } + let sources = p.get("files").and_then(Value::as_array).ok_or_else(|| bad("place.load", "files must be an array"))?; + if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { + return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); + } + let mut images = Vec::with_capacity(sources.len()); + for source in sources { + let (bytes, name, link) = read_source(source)?; + let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", format!("unsupported or corrupt image: {name}")))?; + let size = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); + validate_placement(size, Rect::new(0.0, 0.0, size.0, size.1), Affine::IDENTITY, "place.load")?; + let mime = designcraft_render::image_mime(&bytes).to_string(); + images.push((Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }, size)); + } + let queue = s.edit(|d, _| { + let mut queue = std::collections::VecDeque::with_capacity(images.len()); + for (mut asset, size) in images { + asset.id = AssetId(d.alloc()); + queue.push_back(crate::LoadedGraphic { asset: d.add_asset(asset), size }); + } + Ok(queue) + })?; + if append && s.loaded.is_some() { + s.loaded_queue.extend(queue); + } else { + s.loaded_queue = queue; + s.loaded = s.loaded_queue.pop_front(); + } + s.set_tool("placeGun"); + Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Adds `asset` to the document (with a fresh id) and loads it into the place cursor. -fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result { +/// Most images one `place.load` takes. +const MAX_LOADED_IMAGES: usize = 1000; + +/// How many images the place cursor holds: the current one and those queued after it. +fn loaded_count(s: &Session) -> usize { + s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) +} + +/// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with +/// `append` and an image already loaded, queued after it). +fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { asset.id = AssetId(d.alloc()); Ok(d.add_asset(asset)) })?; - s.loaded = Some(crate::LoadedGraphic { asset: aid, size }); + let image = crate::LoadedGraphic { asset: aid, size }; + if append && s.loaded.is_some() { + s.loaded_queue.push_back(image); + } else { + s.loaded_queue.clear(); + s.loaded = Some(image); + } s.set_tool("placeGun"); Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true})) } -pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { - let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; - // Undo can remove the loaded graphic's asset. - if !s.doc()?.doc.assets.contains_key(&aid) { - s.loaded = None; - return Err(bad("place.drop", "the loaded graphic is no longer in the document")); +/// Cancel every pending image if Undo removed an asset used by the cursor. +fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { + // An empty cursor is its own error, and leaves the tool as it is. + if s.loaded.is_none() { + return Err(bad(command, "nothing loaded in the place cursor")); } + let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); + if !valid { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + return Err(bad(command, "the loaded graphic is no longer in the document")); + } + Ok(()) +} + +/// Place the current image and advance the cursor only after success. +pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { + validate_place_cursor(s, "place.drop")?; + let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; let sr = crate::cmd::spread_param(p, "place.drop")?; let lid = s.doc()?.active_layer; let frame = crate::cmd::id_param(p, "frame"); @@ -321,11 +382,121 @@ pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { *sel = Selection::items(vec![id]); Ok(json!({"id": id.0})) })?; - s.loaded = None; - s.set_tool("selection"); + advance_place_cursor(s); Ok(r) } +/// Advance in file order, returning to selection when the queue is exhausted. +fn advance_place_cursor(s: &mut Session) { + s.loaded = s.loaded_queue.pop_front(); + if s.loaded.is_none() { + s.set_tool("selection"); + } +} + +/// Validate bounded grid dimensions and a finite nonnegative gutter. +fn grid_dimensions(p: &Value, command: &str, default_columns: usize, default_rows: usize) -> Result<(usize, usize, f64)> { + let dimension = |key, default| -> Result { + match p.get(key) { + None => Ok(default), + Some(v) => v + .as_u64() + .filter(|n| (1..=100).contains(n)) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad(command, "rows and columns must be integers between 1 and 100")), + } + }; + let gutter = crate::cmd::f64_or(p, "gutter", 6.0); + if !gutter.is_finite() || gutter < 0.0 { + return Err(bad(command, "gutter must be finite and nonnegative")); + } + Ok((dimension("columns", default_columns)?, dimension("rows", default_rows)?, gutter)) +} + +/// Calculate row-major cells, rejecting gutters that leave no usable space. +fn grid_cells(rect: Rect, columns: usize, rows: usize, gutter: f64, command: &str) -> Result> { + let (columns, rows) = (columns.max(1), rows.max(1)); + let w = (rect.width() - gutter * columns.saturating_sub(1) as f64) / columns as f64; + let h = (rect.height() - gutter * rows.saturating_sub(1) as f64) / rows as f64; + if ![rect.x0, rect.y0, rect.x1, rect.y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(bad(command, "the grid area is too small for its rows, columns and gutter")); + } + Ok((0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + gutter); + let y = rect.y0 + row as f64 * (h + gutter); + Rect::new(x, y, x + w, y + h) + }) + }) + .collect()) +} + +/// Insert a proportionally fitted image into one grid cell. +fn insert_grid_image( + d: &mut designcraft_doc::Document, + spread: designcraft_doc::SpreadRef, + layer: designcraft_doc::LayerId, + image: crate::LoadedGraphic, + rect: Rect, + command: &str, +) -> Result { + let crate::LoadedGraphic { asset, size: (nw, nh) } = image; + if !d.assets.contains_key(&asset) { + return Err(bad(command, "a loaded image is no longer in the document")); + } + let k = (rect.width() / nw).min(rect.height() / nh); + let xf = Affine::translate((rect.x0 + (rect.width() - nw * k) / 2.0, rect.y0 + (rect.height() - nh * k) / 2.0)) * Affine::scale(k); + validate_placement((nw, nh), rect, xf, command)?; + let id = ItemId(d.alloc()); + let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect)); + item.object_style = d.styles.default_graphic_frame.clone(); + if let Some(effects) = d.styles.object_effects(&item.object_style) { + item.effects = effects.clone(); + } + item.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: designcraft_doc::Fitting::FitProportionally, + fit_align: 4, + crop: [0.0; 4], + clip: None, + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(spread, item, None)?; + Ok(id) +} + +/// Place a row-major grid as one undoable edit. +pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.grid"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 1, 1)?; + let rect = crate::cmd::rect_param(p, "rect").ok_or_else(|| bad(ID, "missing rect"))?; + let cells = grid_cells(rect, columns, rows, gutter, ID)?; + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().take(cells.len()).collect(); + if images.is_empty() { + return Err(bad(ID, "nothing loaded in the place cursor")); + } + let layer = s.doc()?.active_layer; + let spread = crate::cmd::spread_param(p, ID)?; + let ids = s.edit(|d, sel| { + let mut ids = Vec::with_capacity(images.len()); + for (image, rect) in images.iter().zip(cells) { + ids.push(insert_grid_image(d, spread, layer, *image, rect, ID)?); + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result { @@ -395,6 +566,20 @@ pub(super) mod image_place_tests { Ok(file) } + /// With nothing in the place cursor, placing says so and leaves the tool as it is (the + /// cursor's graphic gone from the document is another error). + #[test] + fn an_empty_place_cursor_says_so_and_keeps_the_tool() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangleFrame"); + for (cmd, p) in [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]}))] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("nothing loaded"), "{cmd}: {e}"); + assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); + } + } + #[test] fn consecutive_path_placements_create_distinct_graphics() { let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()]; diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index c1f522956..57aa1a5a6 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -3,7 +3,7 @@ use super::EngineError; use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_load, read_source}; +use super::place::{file_place, place_drop, place_grid, place_load, read_source}; use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -123,17 +123,32 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{path | base64, name?} — load a graphic into the place cursor (then click/drag with the placeGun tool)", + "{path | base64, name?, files?: [{path | base64, name?}], append? (keep the images already loaded and queue these after them)} — load up to 1000 images into the place cursor, in order (then click/drag with the placeGun tool)", has_doc, place_load ), cmd!("place.drop", "Place Loaded Graphic", [], None, "{spread?, x, y, rect?: [x0,y0,x1,y1], frame?: id}", has_doc, place_drop), + cmd!( + "place.grid", + "Place Image Grid", + [], + None, + "{spread?, rect: [x0,y0,x1,y1], columns?: 1, rows?: 1, gutter?: 6} — place queued images in row order", + has_doc, + place_grid + ), + cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{}", has_doc, |s, _| { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + ok() + }), cmd!( "file.place", "Place…", ["File"], Some("Cmd+D"), - "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", + "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), append? (with loadCursor: queue the image after those already loaded instead of replacing them), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", has_doc, file_place ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 19c50b7c0..397be3203 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -411,6 +411,8 @@ pub struct Session { pub ui_requests: Vec, /// Graphic loaded in the place cursor. pub loaded: Option, + /// Remaining graphics, in source-selection order, after `loaded`. + pub loaded_queue: std::collections::VecDeque, pub(crate) untitled: u32, /// Transforms applied to the current selection, oldest first (Transform Again / Sequence /// Again), with the selection they were applied to and whether the last one came from a @@ -474,6 +476,7 @@ impl Session { image_link_checks: Default::default(), ui_requests: vec![], loaded: None, + loaded_queue: Default::default(), transforms: Default::default(), text_drag: false, text_unit: None, @@ -549,6 +552,8 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); + self.loaded = None; + self.loaded_queue.clear(); self.active = Some(i); } } @@ -558,6 +563,8 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); + self.loaded = None; + self.loaded_queue.clear(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -580,6 +587,8 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { + self.loaded = None; + self.loaded_queue.clear(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7cdcd5e02..564e42605 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2010,6 +2010,123 @@ fn direct_selection_on_a_selected_frame_deletes_only_its_image() { assert!(st.selection.content && st.selection.items == [designcraft_doc::ItemId(holder)], "the pasted-in items are selected: {:?}", st.selection); } +fn load_test_images(s: &mut Session, count: usize) { + let sources: Vec<_> = (0..count) + .map(|i| { + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![(i % 255) as u8; 40 * 20 * 4] }.to_png(); + json!({"base64": cmd::base64_encode(&png), "name": format!("{i}.png")}) + }) + .collect(); + s.execute("place.load", &json!({"files": sources})).unwrap(); +} + +#[test] +fn image_queue_places_in_order_and_retains_remainder() { + let mut s = session(); + load_test_images(&mut s, 5); + let first = s.loaded.unwrap().asset; + s.execute("place.drop", &json!({"x": 10, "y": 20})).unwrap(); + assert_eq!(s.tool_id(), "placeGun"); + let item = s.doc().unwrap().doc.spreads[0].items.last().unwrap(); + assert!(matches!(&item.content, designcraft_doc::Content::Graphic(g) if g.asset == first)); + let r = s.execute("place.grid", &json!({"rect": [0, 0, 206, 50], "columns": 2, "rows": 1})).unwrap(); + assert_eq!(r["remaining"], 2); + let id = designcraft_doc::ItemId(r["ids"][1].as_u64().unwrap()); + let item = s.doc().unwrap().doc.item(id).unwrap(); + assert_eq!(item.bounds(), designcraft_geom::Rect::new(106.0, 0.0, 206.0, 50.0)); + if let designcraft_doc::Content::Graphic(g) = &item.content { + assert_eq!(s.doc().unwrap().doc.assets[&g.asset].name, "2.png"); + } else { + panic!("expected graphic"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.item(id).is_none(), "the whole grid is one undo step"); + s.execute("place.cancel", &json!({})).unwrap(); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty()); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn image_grid_and_load_fail_atomically() { + let mut s = session(); + load_test_images(&mut s, 3); + let before = s.doc().unwrap().doc.clone(); + let first = s.loaded.unwrap().asset; + assert!(s.execute("place.load", &json!({"files": [{"base64": "bad"}]})).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(s.loaded.unwrap().asset, first); + for params in [json!({"columns": 0}), json!({"columns": 101}), json!({"rows": 1.5}), json!({"gutter": -1}), json!({"columns": 3, "gutter": 1000})] + { + let mut p = params; + p["rect"] = json!([0, 0, 100, 100]); + assert!(s.execute("place.grid", &p).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(s.loaded_queue.len(), 2); + } +} + +#[test] +fn place_drag_arrows_make_three_by_four_grid_and_escape_cancels() { + use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + load_test_images(&mut s, 13); + let v = ViewInfo::at_zoom(1.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + for key in [ToolKey::Right, ToolKey::Right, ToolKey::Up, ToolKey::Up, ToolKey::Up] { + s.tool_key(key, Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 500.0, 600.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 500.0, 600.0), v).unwrap(); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), 12); + assert!(s.loaded.is_some() && s.loaded_queue.is_empty()); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert!(s.loaded.is_none()); +} + +/// With several images loaded, a release under the drag threshold is still a click: arrows set +/// no grid then, and the next queued image lands at actual size where the press was. +#[test] +fn a_place_click_with_a_queue_places_the_next_image_without_a_grid() { + use designcraft_tools::{Cursor, Mods, Overlay, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + load_test_images(&mut s, 3); + let v = ViewInfo::at_zoom(1.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 500.0), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 101.0, 501.0), v).unwrap(); + assert!(s.overlays(v).is_empty(), "no frame or grid under the threshold"); + assert_eq!(s.cursor(designcraft_geom::Point::new(101.0, 501.0), Mods::default(), v), Cursor::LoadedGraphic); + s.pointer(&PointerEvent::new(PointerKind::Up, 101.0, 501.0), v).unwrap(); + let items = &s.doc().unwrap().doc.spreads[0].items; + assert_eq!(items.len(), 1); + assert_eq!(items[0].bounds(), designcraft_geom::Rect::new(100.0, 500.0, 140.0, 520.0), "actual size at the press"); + assert_eq!(s.loaded_queue.len(), 1, "the next image is loaded"); + // Past the threshold the arrows' grid shows, one cell per column. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 306.0, 150.0), v).unwrap(); + assert_eq!(s.overlays(v).iter().filter(|o| matches!(o, Overlay::Marquee(_))).count(), 2); + assert_eq!(s.cursor(designcraft_geom::Point::new(306.0, 150.0), Mods::default(), v), Cursor::Crosshair); +} + +#[test] +fn undoing_loaded_assets_cancels_every_placement_cursor() { + for command in ["place.drop", "place.grid"] { + let mut s = session(); + load_test_images(&mut s, 3); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let params = json!({"rect": [0, 0, 200, 200]}); + assert!(s.execute(command, ¶ms).is_err(), "{command}"); + assert!(s.loaded.is_none(), "{command}"); + assert!(s.loaded_queue.is_empty(), "{command}"); + assert_eq!(s.tool_id(), "selection"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + load_test_images(&mut s, 2); + assert!(s.execute("place.drop", &json!({"x": 0, "y": 0})).is_ok()); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 2badc3a17..6dfd23703 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -74,6 +74,7 @@ impl Session { // Any other tool unloads the place cursor. if id != "placeGun" { self.loaded = None; + self.loaded_queue.clear(); } // Leaving the Type tool keeps the text frame selected. if id != "type" diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index 1748c9cfb..2b84010d1 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -112,6 +112,8 @@ impl Tool for ZoomTool { pub struct PlaceGun { start: Option, cur: Point, + columns: usize, + rows: usize, } impl Tool for PlaceGun { @@ -122,6 +124,8 @@ impl Tool for PlaceGun { match ev.kind { PointerKind::Down => { self.start = Some(ev.pos); + self.columns = 1; + self.rows = 1; self.cur = ev.pos; vec![] } @@ -140,10 +144,19 @@ impl Tool for PlaceGun { { return vec![Action::Exec("place.drop".into(), json!({"frame": id.0}))]; } - // Under the drag threshold it's a click, as the overlay shows: actual size there. + // Under the drag threshold it's a click, as the overlay shows: actual size there + // (the next queued image, with several loaded). if click { return vec![Action::Exec("place.drop".into(), json!({"spread": crate::spread_json(sr), "x": sa.x, "y": sa.y}))]; } + // Arrow keys during the drag set a grid: the queued images fill its cells. + if self.columns > 1 || self.rows > 1 { + let r = designcraft_geom::Rect::from_points(sa, b); + return vec![Action::Exec( + "place.grid".into(), + json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), + )]; + } // The frame the drag drew: at the graphic's proportions from where it started. let r = cx.loaded.map_or_else(|| designcraft_geom::Rect::from_points(sa, b), |size| proportional(sa, b, size).0); vec![Action::Exec( @@ -154,14 +167,41 @@ impl Tool for PlaceGun { _ => vec![], } } + fn busy(&self) -> bool { + self.start.is_some() + } + fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { + use crate::ToolKey; + if key == ToolKey::Escape { + self.start = None; + return vec![Action::Exec("place.cancel".into(), json!({}))]; + } + // During a drag the arrow keys change the grid, and are handled even when it is already + // at its limit, so they don't go on to nudge the selection. + if self.start.is_some() { + match key { + ToolKey::Right => self.columns = (self.columns + 1).min(100), + ToolKey::Left => self.columns = self.columns.saturating_sub(1).max(1), + ToolKey::Up => self.rows = (self.rows + 1).min(100), + ToolKey::Down => self.rows = self.rows.saturating_sub(1).max(1), + _ => return vec![], + } + return vec![Action::Handled]; + } + vec![] + } fn overlays(&self, cx: &ToolContext) -> Vec { let Some(a) = self.start else { return vec![] }; + // Under the drag threshold the release is a click (actual size where it was pressed): + // no frame is drawn yet, the loaded cursor shows what lands. + let click = (self.cur - a).hypot() < cx.tol(3.0); + if !click && (self.columns > 1 || self.rows > 1) { + return grid_overlays(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + } let Some(size) = cx.loaded else { return vec![crate::Overlay::Marquee(designcraft_geom::Rect::from_points(a, self.cur))]; }; - // Under the drag threshold the release is a click (actual size where it was pressed): - // no frame is drawn yet, the loaded cursor shows what lands. - if (self.cur - a).hypot() < cx.tol(3.0) { + if click { return vec![]; } // As InDesign: the frame the graphic will fill, and its scale beside the pointer. @@ -178,13 +218,6 @@ Y: {pct}" }, ] } - fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { - match key { - // Escape unloads the place cursor. - crate::ToolKey::Escape => vec![Action::SwitchTool("selection".into())], - _ => vec![], - } - } fn cursor(&self, cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { // Drawing the frame: the crosshair (the loaded graphic's thumbnail would hide the frame). // Under the drag threshold no frame is drawn yet (the release is a click), so the @@ -195,6 +228,26 @@ Y: {pct}" } } +/// The cells of a `columns` × `rows` place grid drawn over `rect`, 6 pt apart, as `place.grid` +/// lays them out; the whole rect when the cells would vanish. +fn grid_overlays(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { + let (columns, rows) = (columns.clamp(1, 100), rows.clamp(1, 100)); + let w = (rect.width() - 6.0 * (columns - 1) as f64) / columns as f64; + let h = (rect.height() - 6.0 * (rows - 1) as f64) / rows as f64; + if !(w > 0.0 && h > 0.0) { + return vec![crate::Overlay::Marquee(rect)]; + } + (0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + 6.0); + let y = rect.y0 + row as f64 * (h + 6.0); + crate::Overlay::Marquee(designcraft_geom::Rect::new(x, y, x + w, y + h)) + }) + }) + .collect() +} + /// A dragged frame `place.drop` takes only when it is wider and taller than this, in points; /// a thinner one places the graphic at its natural size instead. pub const PLACE_DRAG_MIN: f64 = 2.0; diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 3970f1910..28cfecf01 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2352,3 +2352,20 @@ fn direct_selection_marquee_selects_points_of_several_frames_and_drags_them_toge assert!(want.x.abs() < 1e-9 && (want.y.abs() - inc).abs() < 1e-9, "a quarter turn: {want:?}"); assert!(moves(p).iter().all(|&(x, y)| (x - want.x).abs() < 1e-9 && (y - want.y).abs() < 1e-9), "{p}"); } + +/// While the place cursor drags out a grid, the arrow keys change it and are handled, even at a +/// limit, so the session doesn't try them elsewhere; other keys and keys before a drag aren't. +#[test] +fn place_gun_grid_arrow_keys_are_handled_during_a_drag() { + let d = Document::new(&NewDocument::default()); + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let mut t = create("placeGun"); + assert!(t.key(&cx, ToolKey::Right, Mods::default()).is_empty(), "no drag yet"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 110.0, 60.0)); + for key in [ToolKey::Right, ToolKey::Up, ToolKey::Left, ToolKey::Left, ToolKey::Down, ToolKey::Down] { + assert_eq!(t.key(&cx, key, Mods::default()), vec![Action::Handled], "{key:?}"); + } + assert!(t.key(&cx, ToolKey::Delete, Mods::default()).is_empty()); +} diff --git a/crates/ui-egui/src/app/file_dialogs.rs b/crates/ui-egui/src/app/file_dialogs.rs index 9f1271389..42a47fe32 100644 --- a/crates/ui-egui/src/app/file_dialogs.rs +++ b/crates/ui-egui/src/app/file_dialogs.rs @@ -16,6 +16,10 @@ use super::{DesignApp, Value, json}; #[cfg(not(target_arch = "wasm32"))] pub(crate) type Then = Box Result>; +/// What runs with the files chosen in a dialog that takes several, in the order chosen. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) type ThenMany = Box) -> Result>; + /// Whether an answer still needs the document that was active when the dialog was asked for. #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Bound { @@ -64,6 +68,8 @@ pub(crate) struct Held { enum Step { /// Open: run `then` with the file chosen. Open(Then), + /// Open several: run `then` with the files chosen. + OpenMany(ThenMany), /// Save: `ext` is added to a name typed without it, then `then` runs, after the replace-file /// question when the added extension names a file that exists. Save { ext: Option, then: Then }, @@ -118,6 +124,31 @@ impl DesignApp { } } + /// [`Self::ask_open`] for a dialog that takes several files: `then` runs with their paths, + /// in the order chosen. + #[track_caller] + pub(crate) fn ask_open_many( + &mut self, + purpose: &str, + bound: Bound, + then: impl FnOnce(&mut DesignApp, Vec) -> Result + 'static, + ) -> Result { + #[cfg(not(target_arch = "wasm32"))] + { + let mut dialog = craft_dialogs::FileDialog::open_many(); + for filter in open_filters(purpose) { + dialog = dialog.filter(filter.name, filter.extensions); + } + self.ask_file(dialog, bound, Step::OpenMany(Box::new(then))); + Ok(Value::Null) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (purpose, bound, then); + Err(NO_PICKER.into()) + } + } + /// Ask where to save `name`: beside the active document once it has been saved, else in the /// folder of the last file saved or exported (#1653). `then` runs with the path on a later /// frame; Cancel runs nothing. In a browser the name is the download's and `then` runs now. @@ -232,6 +263,15 @@ impl DesignApp { self.continue_in(Held { doc, dialog, then, path: path.to_string_lossy().to_string() }); } } + (Step::OpenMany(then), Answer::Paths(paths)) => { + let paths: Vec = paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect(); + if let Some(first) = paths.first().cloned() { + // Held as one answer: it waits for a dialog in its way and returns to its + // document as a single file's does. + let then: Then = Box::new(move |app, _| then(app, paths)); + self.continue_in(Held { doc, dialog, then, path: first }); + } + } (Step::Save { ext, then }, Answer::Paths(paths)) => { let Some(picked) = paths.into_iter().next() else { continue }; let path = picked_save_path(picked.clone(), ext.as_deref()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3c90d8c59..3df85b504 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -16,27 +16,82 @@ impl DesignApp { open(request); return Ok(Value::Null); } - let bound = if purpose == "place" { file_dialogs::Bound::Document } else { file_dialogs::Bound::App }; + // File › Place takes several files: they load the place cursor in the order chosen. + if purpose == "place" { + return self.ask_open_many(purpose, file_dialogs::Bound::Document, |app, paths| match paths.as_slice() { + [path] => app.open_picked("place", path.clone()), + _ => app.place_paths(paths).map(|()| Value::Null), + }); + } let purpose_owned = purpose.to_string(); - self.ask_open(purpose, bound, move |app, path| app.open_picked(&purpose_owned, path)) + self.ask_open(purpose, file_dialogs::Bound::App, move |app, path| app.open_picked(&purpose_owned, path)) } /// Open (`open`) or place (`place`) the file at `path`, chosen in a dialog or passed by a script. pub(crate) fn open_picked(&mut self, purpose: &str, path: String) -> Result { + if purpose == "place" { + return self.place_path(&path, false); + } + self.open_file("file.open", json!({"path": path})) + } + + /// File › Place of the file at `path`, asking a multi-page PDF's Image Import Options first. + /// With `append`, an image that loads the cursor queues after the ones already loaded rather + /// than replacing them. + fn place_path(&mut self, path: &str, append: bool) -> Result { // Image Import Options: a multi-page PDF asks which page. - if purpose == "place" && path.to_ascii_lowercase().ends_with(".pdf") { + if path.to_ascii_lowercase().ends_with(".pdf") { let target = self.session.active().map(|d| d.uid); - let pages = self.services.read.as_mut().and_then(|r| r(&path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); + let pages = self.services.read.as_mut().and_then(|r| r(path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); if pages > 1 { self.ui.dialog = Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target}))); return Ok(Value::Null); } - return self.place_file(json!({"path": path})); } - if purpose == "place" { - return self.place_file(json!({"path": path})); + self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) + } + + /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when + /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; + /// every file that loads the cursor adds to what the earlier ones loaded, in the order the + /// files were chosen (images in a row load together, before the file after them). A file that + /// can't be placed gets an alert and stops the batch; its error is returned, so automation + /// doesn't carry on as if the batch had loaded. + pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { + let mut images = Vec::new(); + // Images already in the place cursor stay: the batch queues after them. + let mut loaded = self.session.loaded.is_some(); + // `None` at the end loads the images left. + for path in paths.into_iter().map(Some).chain([None]) { + if let Some(p) = &path + && is_cursor_image(p) + { + images.push(json!({"path": p})); + continue; + } + if path.is_none() && images.is_empty() { + break; + } + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); + return Ok(()); + } + if !images.is_empty() { + let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + } + if let Some(p) = path { + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + } } - self.open_file("file.open", json!({"path": path})) + Ok(()) + } + + /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images + /// already loaded when `append`. An image that can't be read gets an alert, as a placed one does. + fn load_place_cursor(&mut self, files: Vec, append: bool) -> Result { + self.open_named_file("place.load", json!({"files": files, "append": append}), String::new()) } /// Load Styles: ask the host for a document whose styles to load; `kind` is `paragraph`, @@ -106,11 +161,49 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); - for file in files { + let cursor_image = |file: &ImportedFile| { + file.request.purpose == "place" + && !file.name.to_ascii_lowercase().ends_with(".pdf") + && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) + }; + // In the order they came: consecutive images for the same document load the place + // cursor together; after the first placement into it, the later ones are added to it. + let mut append = false; + let mut files = files.into_iter().peekable(); + while let Some(file) = files.next() { if file.request.purpose == "shortcuts" { shortcut_import::import_delivered(self, &file.bytes); continue; } + let placing = file.request.purpose == "place"; + let mut group = vec![]; + if cursor_image(&file) { + while let Some(next) = + files.next_if(|n| cursor_image(n) && n.request.target == file.request.target && n.request.purpose == file.request.purpose) + { + group.push(next); + } + } + // Several images: into the place cursor. + if !group.is_empty() { + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Image import cancelled while a dialog is open")); + continue; + } + if self.activate_import_target(&file.request).is_err() { + continue; + } + let sources: Vec<_> = std::iter::once(file) + .chain(group) + .map(|f| json!({"name": f.name, "base64": designcraft_engine::cmd::base64_encode(&f.bytes)})) + .collect(); + // They queue after images already in the cursor, as a native batch's do. + let queue_after = append || self.session.loaded.is_some(); + if self.load_place_cursor(sources, queue_after).is_ok() { + append = true; + } + continue; + } if self.ui.dialog.is_some() { self.status( crate::i18n::tr(&self.ui.language, "{name}: import cancelled while a dialog is open; choose the file again") @@ -119,13 +212,16 @@ impl DesignApp { continue; } let name = file.name.clone(); - if let Err(e) = self.import_file(file) { - self.status(format!("{name}: {e}")); + match self.import_file(file, append) { + Ok(_) if placing => append = true, + Ok(_) => {} + Err(e) => self.status(format!("{name}: {e}")), } } } - fn import_file(&mut self, file: ImportedFile) -> Result { + /// Imports `file`; a placed one is added to the place cursor when `append`. + fn import_file(&mut self, file: ImportedFile, append: bool) -> Result { let lower = file.name.to_ascii_lowercase(); if let Some(kind) = file.request.purpose.strip_prefix("styles") { self.activate_import_target(&file.request)?; @@ -157,7 +253,7 @@ impl DesignApp { if lower.ends_with(".ase") || file.request.purpose == "swatches" { self.run("swatch.load", json!({"base64": b64})) } else if file.request.purpose == "place" { - self.place_file(json!({"name": file.name, "base64": b64})) + self.place_file(json!({"name": file.name, "base64": b64, "append": append})) } else if place { self.open_file("file.place", json!({"name": file.name, "base64": b64})) } else { @@ -270,7 +366,7 @@ impl DesignApp { pub fn open_named_file(&mut self, cmd: &str, params: Value, file: String) -> Result { let r = self.run(cmd, params); if let Err(e) = &r { - let title = if cmd == "file.place" { "Can't Place the File" } else { "Can't Open the File" }; + let title = if cmd == "file.place" || cmd == "place.load" { "Can't Place the File" } else { "Can't Open the File" }; if self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") { self.session.reset_find_scope(); } @@ -311,6 +407,14 @@ impl DesignApp { } } +/// Graphics that can wait in the place cursor, several at a time: raster images, SVG, PSD and +/// EPS. A PDF can't (it may ask which page), nor can text, media or documents. +pub(crate) fn is_cursor_image(name: &str) -> bool { + std::path::Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!(e.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "svg" | "psd" | "eps") + }) +} + /// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft, /// IDML, and InDesign documents and templates (converted to IDML on open). pub fn opens_as_document(name: &str) -> bool { @@ -761,6 +865,141 @@ pub(crate) mod browser_import_tests { assert!(app.pending_pdf.is_none()); assert!(app.session.doc().unwrap().doc.assets.is_empty()); } + + fn png(v: u8) -> Vec { + designcraft_render::Rendered { width: 10, height: 10, pixels: vec![v; 400] }.to_png() + } + + /// The names of the images in the place cursor, the one a click places first. + fn loaded_names(app: &DesignApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + app.session.loaded.iter().chain(app.session.loaded_queue.iter()).map(|g| doc.assets[&g.asset].name.clone()).collect() + } + + #[test] + fn multi_image_inbox_loads_one_queue_on_its_original_document() { + let mut app = app(); + let request = app.import_request("place"); + app.run("file.new", json!({"title": "B"})).unwrap(); + for i in 0..3 { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: format!("{i}.png"), + bytes: png(200), + }); + } + app.drain_inbox(); + assert_eq!(app.session.doc().unwrap().uid, request.target.unwrap()); + assert_eq!(app.session.tool_id(), "placeGun"); + assert_eq!(app.session.loaded_queue.len(), 2); + assert!(app.session.documents()[1].doc.assets.is_empty()); + } + + /// Files dropped together are placed in the order they came: images around a PDF go into the + /// place cursor before and after it, and each adds to the cursor rather than replacing it. + #[test] + fn inbox_places_images_and_a_pdf_in_their_order_into_one_cursor() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("one.pdf", pdf_pages(1)), ("b.png", png(90))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); + } + + #[test] + fn batch_cancel_status_uses_the_interface_language() { + let mut app = app(); + app.ui.language = "de".into(); + app.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": "t", "message": "m"}))); + let request = app.import_request("place"); + for name in ["one.png", "two.png"] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes: png(200) }); + } + app.drain_inbox(); + assert_eq!(app.ui.status, "Bildimport bei geöffnetem Dialog abgebrochen"); + assert!(app.ui.dialog.is_some()); + assert!(app.session.loaded.is_none()); + } + + #[test] + fn native_batch_stops_when_a_dialog_is_open_and_appends_to_the_cursor() { + let mut app = app(); + app.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": "t", "message": "m"}))); + let _ = app.place_paths(vec!["one.pdf".into(), "two.png".into()]); + assert_eq!(app.ui.status, "Place cancelled while a dialog is open"); + assert!(app.session.loaded.is_none()); + app.ui.dialog = None; + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("place.load", json!({"base64": b64, "name": "a.svg"})).unwrap(); + let first = app.session.loaded.as_ref().unwrap().asset; + let files = json!([{"base64": b64, "name": "b.svg"}, {"base64": b64, "name": "c.svg"}]); + app.run("place.load", json!({"files": files, "append": true})).unwrap(); + assert_eq!(app.session.loaded.as_ref().unwrap().asset, first); + assert_eq!(app.session.loaded_queue.len(), 2); + app.run("place.load", json!({"files": files})).unwrap(); + assert_eq!(app.session.loaded_queue.len(), 1); + } + + /// Images around a single-page PDF load into the cursor in the order they were chosen. + #[test] + fn native_batch_keeps_the_chosen_order() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + // A second batch queues after what the cursor still holds. + std::fs::write(path("c.svg"), image()).unwrap(); + app.place_paths(vec![path("c.svg"), path("a.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); + } + + /// File › Place with several files chosen in the dialog loads them all into the place + /// cursor, in the order chosen; with one, it is placed as before. + #[test] + fn place_dialog_with_several_files_loads_them_all() { + let dir = tempfile::tempdir().unwrap(); + let paths: Vec = ["b.svg", "a.svg", "c.svg"].iter().map(|n| dir.path().join(n)).collect(); + for p in &paths { + std::fs::write(p, image()).unwrap(); + } + let mut app = app(); + let answer = paths.clone(); + app.answer_dialogs(move |_| craft_dialogs::Answer::Paths(answer.clone())); + app.run("app.placeDialog", json!({})).unwrap(); + app.settle_dialogs(); + assert_eq!(loaded_names(&app), ["b.svg", "a.svg", "c.svg"]); + assert_eq!(app.session.tool_id(), "placeGun"); + // The same through the command's `paths`, as the control channel gives them. + let mut scripted = self::app(); + let paths: Vec = paths.iter().map(|p| p.to_string_lossy().to_string()).collect(); + scripted.run("app.placeDialog", json!({"paths": paths})).unwrap(); + assert_eq!(loaded_names(&scripted), ["b.svg", "a.svg", "c.svg"]); + } + + #[test] + fn multi_image_inbox_cancels_when_original_document_closed() { + let mut app = app(); + let request = app.import_request("place"); + app.run("file.new", json!({"title": "B"})).unwrap(); + app.run("file.close", json!({"index": 0})).unwrap(); + for i in 0..2 { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: format!("{i}.png"), + bytes: png(200), + }); + } + app.drain_inbox(); + assert!(app.session.loaded.is_none()); + assert!(app.session.doc().unwrap().doc.assets.is_empty()); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f544f5bf5..72132250c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -20,6 +20,7 @@ mod guides; mod ime; mod input; mod page_decor; +mod place_cursor; mod render; mod rulers; mod scroll; @@ -413,6 +414,7 @@ fn draw_loaded_thumbnail(app: &DesignApp, painter: &egui::Painter, p: Pos2, t: & vec![pos2(inner.min.x, inner.max.y), pos2(inner.min.x + 3.5, inner.min.y + 2.5), pos2(inner.max.x, inner.max.y)], ink, )); + place_cursor::draw_loaded_count(app, painter, badge); } /// The loaded graphic's thumbnail texture, cached per image data. diff --git a/crates/ui-egui/src/canvas/place_cursor.rs b/crates/ui-egui/src/canvas/place_cursor.rs new file mode 100644 index 000000000..69b17571c --- /dev/null +++ b/crates/ui-egui/src/canvas/place_cursor.rs @@ -0,0 +1,34 @@ +//! The loaded place cursor's image count, drawn beside the thumbnail's badge. + +use super::{Color32, DesignApp, Pos2, Rect, pos2, vec2}; + +/// Several images loaded: how many, beside the thumbnail's image `badge` ("(6)"), navy with a +/// white rim so it reads over any picture. +pub(super) fn draw_loaded_count(app: &DesignApp, painter: &egui::Painter, badge: Rect) { + let loaded = app.session.loaded.is_some().then(|| app.session.loaded_queue.len().saturating_add(1)); + let Some(label) = loaded_count_label(loaded) else { return }; + let at: Pos2 = pos2(badge.max.x + 6.0, badge.center().y); + let font = crate::theme::semibold(15.0); + for d in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, -1.0), vec2(0.0, 1.0)] { + painter.text(at + d, egui::Align2::LEFT_CENTER, &label, font.clone(), Color32::WHITE); + } + painter.text(at, egui::Align2::LEFT_CENTER, label, font, Color32::from_rgb(25, 35, 100)); +} + +/// The count the loaded place cursor shows, as InDesign's "(6)": only when more than one image +/// is loaded. +pub(super) fn loaded_count_label(loaded: Option) -> Option { + loaded.filter(|n| *n > 1).map(|n| format!("({n})")) +} + +#[cfg(test)] +mod tests { + /// The loaded cursor counts the images as InDesign's "(6)", and shows no count for the last + /// one or with nothing loaded. + #[test] + fn the_loaded_cursor_counts_several_images() { + assert_eq!(super::loaded_count_label(Some(6)).as_deref(), Some("(6)")); + assert_eq!(super::loaded_count_label(Some(1)), None); + assert_eq!(super::loaded_count_label(None), None); + } +} diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b89840044..87fae4392 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -25,6 +25,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "ასლის შენახვა…"), ("Revert", "წინა ვერსიაზე დაბრუნება"), ("Place…", "განთავსება…"), + ("Image import cancelled while a dialog is open", "გამოსახულებების იმპორტი გაუქმდა, რადგან დიალოგი გახსნილია"), + ("Place cancelled while a dialog is open", "განთავსება გაუქმდა, რადგან დიალოგი ღიაა"), ("Export PDF…", "PDF ექსპორტი…"), ("Print…", "დაბეჭდვა…"), ("Document Setup…", "დოკუმენტის პარამეტრები…"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 27f5cf389..7e8ccdddc 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -146,6 +146,26 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Save a Copy…", ["Kopie speichern …", "Enregistrer une copie…", "Guardar una copia…", "コピーを保存…", "保存副本…"]), ("Revert", ["Zurück zur letzten Version", "Version précédente", "Volver a la versión guardada", "復帰", "恢复到上次保存"]), ("Place…", ["Platzieren …", "Importer…", "Colocar…", "配置…", "置入…"]), + ( + "Image import cancelled while a dialog is open", + [ + "Bildimport bei geöffnetem Dialog abgebrochen", + "Importation des images annulée car une boîte de dialogue est ouverte", + "Importación de imágenes cancelada mientras hay un diálogo abierto", + "ダイアログが開いているため画像の読み込みをキャンセルしました", + "对话框打开时已取消图像导入", + ], + ), + ( + "Place cancelled while a dialog is open", + [ + "Platzieren bei geöffnetem Dialog abgebrochen", + "Importation annulée car une boîte de dialogue est ouverte", + "Colocación cancelada mientras hay un diálogo abierto", + "ダイアログが開いているため配置をキャンセルしました", + "对话框打开时已取消置入", + ], + ), ("Export PDF…", ["PDF exportieren …", "Exporter en PDF…", "Exportar PDF…", "PDF を書き出し…", "导出PDF…"]), ("Print…", ["Drucken …", "Imprimer…", "Imprimir…", "プリント…", "打印…"]), ("Document Setup…", ["Dokument einrichten …", "Format de document…", "Ajustar documento…", "ドキュメント設定…", "文档设置…"]), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 717e1332e..b49b8c7f4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -135,9 +135,18 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option match p.get("path").and_then(Value::as_str) { - Some(path) => app.open_picked("place", path.to_string()), - None => app.pick_and_open("place"), + "app.placeDialog" => match (p.get("path").and_then(Value::as_str), p.get("paths").and_then(Value::as_array)) { + (Some(path), _) => app.open_picked("place", path.to_string()), + // Several files, as chosen together in the dialog: in their order. One is placed as the + // dialog places one (filling the selected frame). Every entry must be a path. + (None, Some(paths)) => match paths.iter().map(|v| v.as_str().map(str::to_string)).collect::>>() { + None => Err("app.placeDialog: every entry of paths must be a string".into()), + Some(paths) => match <[String; 1]>::try_from(paths) { + Ok([path]) => app.open_picked("place", path), + Err(paths) => app.place_paths(paths).map(|()| Value::Null), + }, + }, + (None, None) => app.pick_and_open("place"), }, "app.placeWithOptions" => { // Word/RTF Import Options: style mapping and conflicts before the text lands. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f24d1d548..0fbdaca45 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -15,7 +15,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("app.newDocumentDialog", "New Document…", Some("Cmd+N"), "{}"), ("app.openDialog", "Open…", Some("Cmd+O"), "{path?} — without a path, choose the file in a dialog"), ("app.openRecent", "Open Recent File", None, "{index} — file.openRecent, with an alert when the file can't be opened"), - ("app.placeDialog", "Place…", Some("Cmd+D"), "{path?} — without a path, choose the file in a dialog"), + ( + "app.placeDialog", + "Place…", + Some("Cmd+D"), + "{path?, paths?: [path] (several, loaded into the place cursor in order)} — without either, choose the files in a dialog", + ), ("app.saveDialog", "Save As…", Some("Cmd+Shift+S"), "{path?} — without a path, choose where in a dialog"), ("app.save", "Save", Some("Cmd+S"), "{}"), ("app.quit", "Quit DesignCraft", Some("Cmd+Q"), "{} — close the window; each document with unsaved changes asks first"), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md new file mode 100644 index 000000000..997414bcd --- /dev/null +++ b/docs/multi-image-placement.md @@ -0,0 +1,26 @@ +# Multiple images + +Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). + +- Click to place the next image at its natural size. +- Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. +- Click an existing graphic frame to replace its contents. +- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. +- Press Escape or select another tool to cancel the remaining placement. + +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. + +Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. + +## Automation + +All placement behavior is available through the engine, CLI, control channel and MCP: + +```json +{"command":"place.load","params":{"files":[{"path":"/images/one.png"},{"path":"/images/two.jpg"}]}} +{"command":"place.load","params":{"files":[{"path":"/images/three.png"}],"append":true}} +{"command":"place.grid","params":{"rect":[36,36,576,756],"columns":3,"rows":4,"gutter":6}} +{"command":"place.cancel","params":{}} +``` + +Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit. Undo removes placed frames together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. From e2d85026362a22fc4c7ec97003f93b5c93c398f5 Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:54:22 -0500 Subject: [PATCH 055/328] =?UTF-8?q?Place:=20File=20=E2=80=BA=20Place=20Con?= =?UTF-8?q?tact=20Sheet=E2=80=A6=20puts=20the=20loaded=20images=20on=20new?= =?UTF-8?q?=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split out of #2073. Port of #1392's contact sheet. - `place.contactSheet` places every image in the place cursor on new pages after the last one, in a grid of equal frames (columns, rows, gutter, page margin), as one undo step; a bad grid or margin changes nothing. - The dialog reads bare numbers in the document's unit, from the menu and from `ui.dialog.open` alike; a mistake keeps it open with what was typed and why. Its fields have accessible names; strings in every language. --- ROADMAP.md | 1 + crates/engine/src/cmd/file/place.rs | 42 +++++++++++++++++++++- crates/engine/src/cmd/file/registry.rs | 11 +++++- crates/engine/src/tests.rs | 30 ++++++++++++++-- crates/ui-egui/src/app/files.rs | 38 ++++++++++++++++++++ crates/ui-egui/src/control.rs | 18 +++++++++- crates/ui-egui/src/dialogs.rs | 47 +++++++++++++++++++++++++ crates/ui-egui/src/i18n/ka.rs | 4 +++ crates/ui-egui/src/i18n/sv.rs | 4 +++ crates/ui-egui/src/i18n/table.rs | 19 ++++++++++ crates/ui-egui/src/menus/run.rs | 4 +++ crates/ui-egui/src/menus/tables.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 1 + docs/multi-image-placement.md | 9 +++-- 14 files changed, 221 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 57c143340..40cce6b26 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · File › Place Contact Sheet… puts every image loaded in the place cursor on new pages, in a grid of equal frames (`place.contactSheet`), as one undo step. Ported from #1392; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ba9e0827a..819f18ef1 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -497,6 +497,44 @@ pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) } +/// Place all queued images on new pages as one undoable edit. +pub(super) fn place_contact_sheet(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.contactSheet"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 3, 4)?; + let margin = crate::cmd::f64_or(p, "margin", 36.0); + if !margin.is_finite() || margin < 0.0 { + return Err(bad(ID, "invalid margin")); + } + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().collect(); + if images.is_empty() { + return Err(bad(ID, "load images first using File > Place")); + } + let layer = s.doc()?.active_layer; + let per_page = columns.saturating_mul(rows).max(1); + let count = images.len().div_ceil(per_page); + let ids = s.edit(|d, sel| { + let after = d.page_count().saturating_sub(1); + d.insert_pages(Some(after), count, None)?; + let mut ids = Vec::with_capacity(images.len()); + for (page_offset, chunk) in images.chunks(per_page).enumerate() { + let index = after.saturating_add(1).saturating_add(page_offset); + let (si, pi) = d.page_loc(index).ok_or_else(|| bad(ID, "missing page"))?; + let b = d.spreads.get(si).and_then(|sp| sp.pages.get(pi)).ok_or_else(|| bad(ID, "missing page"))?.bounds(); + let cells = grid_cells(Rect::new(b.x0 + margin, b.y0 + margin, b.x1 - margin, b.y1 - margin), columns, rows, gutter, ID)?; + for (image, rect) in chunk.iter().zip(cells) { + ids.push(insert_grid_image(d, designcraft_doc::SpreadRef::Doc(si), layer, *image, rect, ID)?); + } + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"pages": count, "images": ids.len()})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result { @@ -573,7 +611,9 @@ pub(super) mod image_place_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.set_tool("rectangleFrame"); - for (cmd, p) in [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]}))] { + for (cmd, p) in + [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]})), ("place.contactSheet", json!({}))] + { let e = s.execute(cmd, &p).unwrap_err().to_string(); assert!(e.contains("nothing loaded"), "{cmd}: {e}"); assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index 57aa1a5a6..194cfe2ec 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -3,7 +3,7 @@ use super::EngineError; use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_grid, place_load, read_source}; +use super::place::{file_place, place_contact_sheet, place_drop, place_grid, place_load, read_source}; use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_doc, place_grid ), + cmd!( + "place.contactSheet", + "Place Contact Sheet", + ["File"], + None, + "{columns?: 3, rows?: 4, gutter?: 6, margin?: 36} — place all loaded images on new pages", + has_doc, + place_contact_sheet + ), cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{}", has_doc, |s, _| { s.loaded = None; s.loaded_queue.clear(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..b8228976b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2063,6 +2063,32 @@ fn image_grid_and_load_fail_atomically() { assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); assert_eq!(s.loaded_queue.len(), 2); } + assert!(s.execute("place.contactSheet", &json!({"margin": 10000})).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); +} + +#[test] +fn contact_sheet_adds_pages_and_undoes_as_one_edit() { + let mut s = session(); + load_test_images(&mut s, 25); + let pages = s.doc().unwrap().doc.page_count(); + let r = s.execute("place.contactSheet", &json!({"columns": 3, "rows": 4})).unwrap(); + assert_eq!(r["pages"], 3); + assert_eq!(r["images"], 25); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.page_count(), pages + 3); + for page_index in pages..pages + 3 { + let (si, pi) = doc.page_loc(page_index).unwrap(); + let bounds = doc.spreads[si].pages[pi].bounds(); + let items: Vec<_> = doc.spreads[si].items.iter().filter(|i| bounds.contains(i.bounds().center())).collect(); + assert_eq!(items.len(), if page_index == pages + 2 { 1 } else { 12 }); + for item in items { + assert!(bounds.contains(item.bounds().origin())); + } + } + assert!(s.loaded.is_none() && s.loaded_queue.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.page_count(), pages); } #[test] @@ -2111,12 +2137,12 @@ fn a_place_click_with_a_queue_places_the_next_image_without_a_grid() { #[test] fn undoing_loaded_assets_cancels_every_placement_cursor() { - for command in ["place.drop", "place.grid"] { + for command in ["place.drop", "place.grid", "place.contactSheet"] { let mut s = session(); load_test_images(&mut s, 3); s.execute("edit.undo", &json!({})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let params = json!({"rect": [0, 0, 200, 200]}); + let params = if command == "place.contactSheet" { json!({}) } else { json!({"rect": [0, 0, 200, 200]}) }; assert!(s.execute(command, ¶ms).is_err(), "{command}"); assert!(s.loaded.is_none(), "{command}"); assert!(s.loaded_queue.is_empty(), "{command}"); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..65097d2ef 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -893,6 +893,10 @@ pub(crate) mod browser_import_tests { assert_eq!(app.session.tool_id(), "placeGun"); assert_eq!(app.session.loaded_queue.len(), 2); assert!(app.session.documents()[1].doc.assets.is_empty()); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let result = dialogs::confirm(&mut app).unwrap(); + assert_eq!(result["images"], 3); + assert_eq!(result["pages"], 1); } /// Files dropped together are placed in the order they came: images around a PDF go into the @@ -983,6 +987,40 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&scripted), ["b.svg", "a.svg", "c.svg"]); } + #[test] + fn contact_sheet_measures_use_the_document_unit() { + let mut app = app(); + app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.unit, designcraft_geom::Unit::Millimeters); + assert_eq!(d.s("gutter"), "6pt"); + } + + #[test] + fn contact_sheet_validation_preserves_fields_and_pending_images() { + let mut app = app(); + let request = app.import_request("place"); + deliver(&mut app, request, "image.png", png(200)); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + for (field, value) in [("rows", "bad"), ("rows", "0"), ("rows", "4"), ("margin", "999999pt")] { + app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value)); + if field == "rows" && value == "4" { + continue; + } + assert!(dialogs::confirm(&mut app).is_err()); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.s(field), value); + assert!(!dialog.s("status").is_empty()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); + assert!(app.session.loaded.is_some()); + } + app.ui.dialog.as_mut().unwrap().fields.insert("margin".into(), json!("36pt")); + assert!(dialogs::confirm(&mut app).is_ok()); + assert!(app.ui.dialog.is_none()); + } + #[test] fn multi_image_inbox_cancels_when_original_document_closed() { let mut app = app(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d70a79695..efa2cbd8a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -390,7 +390,11 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest app.session.reset_find_scope(); } let fields = p.get("fields").cloned().unwrap_or(Value::Null); - let d = if id == "frameSize" { crate::dialogs::frame_size_dialog(app, fields) } else { crate::dialogs::Dialog::new(id, fields) }; + let d = match id { + "frameSize" => crate::dialogs::frame_size_dialog(app, fields), + "contactSheet" => crate::dialogs::contact_sheet_dialog(app, fields), + _ => crate::dialogs::Dialog::new(id, fields), + }; let v = serde_json::to_value(&d).unwrap_or_default(); app.ui.dialog = Some(d); ok(v) @@ -517,6 +521,18 @@ mod automation_contract_tests { app.run("style.paragraph.edit", json!({"name":designcraft_doc::BASIC_PARAGRAPH,"chars":{"size":18}})).unwrap(); assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); } + /// `ui.dialog.open` opens Place Contact Sheet as the menu does: bare numbers are in the + /// document's ruler unit, so `1` on an inch document is an inch, not a pica. + #[test] + fn a_contact_sheet_opened_over_the_control_channel_uses_the_document_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + app.run("document.preferences", json!({"horizontalUnits": "inches"})).unwrap(); + let response = call(&mut app, &ctx, "ui.dialog.open", json!({"id": "contactSheet", "fields": {"margin": "1"}})); + assert_eq!(response["ok"], true, "{response}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.unit, designcraft_geom::Unit::Inches); + } fn app() -> DesignApp { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", &json!({"pages":2})).unwrap(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7662c0cb0..a0a00c15c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -36,6 +36,7 @@ impl Dialog { }; let defaults = match id { "newDocument" => crate::new_document::defaults(), + "contactSheet" => json!({"columns": 3, "rows": 4, "gutter": "6pt", "margin": "36pt"}), "goToPage" => json!({"page": "1"}), "epubExport" => json!({"split": false, "mode": "style", "style": designcraft_doc::BASIC_PARAGRAPH, "coverImage": ""}), "qrCode" => json!({"type": "url", "content": "https://", "color": "[Black]"}), @@ -1526,6 +1527,20 @@ fn doc_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas) } +/// File › Place Contact Sheet…: bare numbers typed in the dialog are in the document's ruler unit +/// (the defaults keep their explicit `pt`). +pub fn open_contact_sheet(app: &mut DesignApp) { + app.ui.dialog = Some(contact_sheet_dialog(app, json!({}))); +} + +/// The Place Contact Sheet dialog with `fields`, its bare numbers in the document's ruler unit, +/// for the menu and for `ui.dialog.open` alike. +pub fn contact_sheet_dialog(app: &DesignApp, fields: Value) -> Dialog { + let mut d = Dialog::new("contactSheet", fields); + d.unit = doc_unit(app); + d +} + /// The document's vertical ruler unit: what a bare number means in a height field. fn doc_vertical_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.vertical_units).unwrap_or(Unit::Picas) @@ -2948,6 +2963,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "qrCode" => crate::i18n::tr(&app.ui.language, "Generate QR Code"), "preferences" => crate::i18n::tr(&app.ui.language, "Preferences"), "print" => crate::i18n::tr(&app.ui.language, "Print"), + "contactSheet" => crate::i18n::tr(&app.ui.language, "Place Contact Sheet"), "pdfImport" => crate::i18n::tr(&app.ui.language, "Place PDF"), "pdfExport" => crate::i18n::tr(&app.ui.language, "Export PDF"), "epubExport" => crate::i18n::tr(&app.ui.language, "EPUB Export Options"), @@ -3330,6 +3346,19 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { crate::package_dialog::INSTRUCTIONS => crate::package_dialog::show_instructions(app, ui, &mut d), "preferences" => preferences(app, ui, &mut d, body_height), "print" => print_dialog(app, ui, &mut d), + "contactSheet" => { + if !d.s("status").is_empty() { + ui.label(d.s("status")); + } + ui.label(crate::i18n::tr(&app.ui.language, "Place loaded images on new pages, in file order.")); + for (label, key) in [("Columns", "columns"), ("Rows", "rows"), ("Gutter", "gutter"), ("Page margin", "margin")] { + let label = crate::i18n::tr(&app.ui.language, label); + ui.horizontal(|ui| { + ui.add_sized([95.0, 20.0], egui::Label::new(label)); + text_field_named(ui, &mut d, key, 80.0, label); + }); + } + } "pdfImport" => { ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0)); ui.horizontal(|ui| { @@ -4611,6 +4640,24 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { app.canvas.shown = None; Ok(r) } + "contactSheet" => { + let result = (|| { + let params = json!({ + "columns": d.s("columns").trim().parse::().map_err(|_| "Columns must be a whole number")?, + "rows": d.s("rows").trim().parse::().map_err(|_| "Rows must be a whole number")?, + "gutter": d.m("gutter").ok_or("Enter a valid gutter")?, + "margin": d.m("margin").ok_or("Enter a valid margin")?, + }); + app.run("place.contactSheet", params) + })(); + // A mistake keeps the dialog, with what was typed and why it can't be placed. + if let Err(error) = &result { + let mut d = d; + d.fields.insert("status".into(), json!(error)); + app.ui.dialog = Some(d); + } + result + } "pdfImport" => { let crop = d.s("crop"); // One page number, 1 or more; a blank field is page 1. A range or list ("4-5", "2,5"), a diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 87fae4392..0c2ce3dc9 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "ასლის შენახვა…"), ("Revert", "წინა ვერსიაზე დაბრუნება"), ("Place…", "განთავსება…"), + ("Place Contact Sheet…", "საკონტაქტო ფურცლის განთავსება…"), + ("Place Contact Sheet", "საკონტაქტო ფურცლის განთავსება"), + ("Place loaded images on new pages, in file order.", "ჩატვირთული გამოსახულებების ახალ გვერდებზე განთავსება, ფაილების თანმიმდევრობით."), + ("Page margin", "გვერდის ველი"), ("Image import cancelled while a dialog is open", "გამოსახულებების იმპორტი გაუქმდა, რადგან დიალოგი გახსნილია"), ("Place cancelled while a dialog is open", "განთავსება გაუქმდა, რადგან დიალოგი ღიაა"), ("Export PDF…", "PDF ექსპორტი…"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 8d7c46e15..40b0b2488 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -21,6 +21,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Spara en kopia…"), ("Revert", "Återgå"), ("Place…", "Placera…"), + ("Place Contact Sheet…", "Placera kontaktark…"), + ("Place Contact Sheet", "Placera kontaktark"), + ("Place loaded images on new pages, in file order.", "Placera inlästa bilder på nya sidor, i filordning."), + ("Page margin", "Sidmarginal"), ("Export PDF…", "Exportera PDF…"), ("Print…", "Skriv ut…"), ("Print", "Skriv ut"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 7e8ccdddc..60cba865d 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -146,6 +146,25 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Save a Copy…", ["Kopie speichern …", "Enregistrer une copie…", "Guardar una copia…", "コピーを保存…", "保存副本…"]), ("Revert", ["Zurück zur letzten Version", "Version précédente", "Volver a la versión guardada", "復帰", "恢复到上次保存"]), ("Place…", ["Platzieren …", "Importer…", "Colocar…", "配置…", "置入…"]), + ( + "Place Contact Sheet…", + ["Kontaktbogen platzieren…", "Importer une planche-contact…", "Colocar hoja de contactos…", "コンタクトシートを配置…", "置入联系表…"], + ), + ( + "Place Contact Sheet", + ["Kontaktbogen platzieren", "Importer une planche-contact", "Colocar hoja de contactos", "コンタクトシートを配置", "置入联系表"], + ), + ( + "Place loaded images on new pages, in file order.", + [ + "Geladene Bilder in Dateireihenfolge auf neuen Seiten platzieren.", + "Importer les images chargées sur de nouvelles pages, dans l’ordre des fichiers.", + "Colocar las imágenes cargadas en páginas nuevas, en el orden de los archivos.", + "読み込んだ画像をファイル順に新しいページに配置します。", + "按文件顺序将载入的图像置入新页面。", + ], + ), + ("Page margin", ["Seitenrand", "Marge de page", "Margen de página", "ページマージン", "页边距"]), ( "Image import cancelled while a dialog is open", [ diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b49b8c7f4..5228d3c60 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -148,6 +148,10 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option app.pick_and_open("place"), }, + "app.contactSheetDialog" => { + crate::dialogs::open_contact_sheet(app); + Ok(Value::Null) + } "app.placeWithOptions" => { // Word/RTF Import Options: style mapping and conflicts before the text lands. let Some(path) = p.get("path").and_then(Value::as_str) else { return Some(rerun_with_path(app, "place", id, p, "path")) }; diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index e7907e7da..50904af4f 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -16,6 +16,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ "cmd:file.revert", "-", "ui:app.placeDialog", + "ui:app.contactSheetDialog", "ui:app.placeWithOptions", "-", "ui:app.exportPdf", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 0fbdaca45..db6d9eb54 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -21,6 +21,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ Some("Cmd+D"), "{path?, paths?: [path] (several, loaded into the place cursor in order)} — without either, choose the files in a dialog", ), + ("app.contactSheetDialog", "Place Contact Sheet…", None, "{} — place the images loaded in the place cursor on new pages"), ("app.saveDialog", "Save As…", Some("Cmd+Shift+S"), "{path?} — without a path, choose where in a dialog"), ("app.save", "Save", Some("Cmd+S"), "{}"), ("app.quit", "Quit DesignCraft", Some("Cmd+Q"), "{} — close the window; each document with unsaved changes asks first"), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..ea5ee549b 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -1,4 +1,4 @@ -# Multiple images +# Multiple images and contact sheets Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). @@ -8,7 +8,9 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. - Press Escape or select another tool to cancel the remaining placement. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. + +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. @@ -20,7 +22,8 @@ All placement behavior is available through the engine, CLI, control channel and {"command":"place.load","params":{"files":[{"path":"/images/one.png"},{"path":"/images/two.jpg"}]}} {"command":"place.load","params":{"files":[{"path":"/images/three.png"}],"append":true}} {"command":"place.grid","params":{"rect":[36,36,576,756],"columns":3,"rows":4,"gutter":6}} +{"command":"place.contactSheet","params":{"columns":3,"rows":4,"gutter":6,"margin":36}} {"command":"place.cancel","params":{}} ``` -Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit. Undo removes placed frames together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. +Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit; `place.contactSheet` consumes the entire queue. Undo removes placed frames/pages together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. From a10e288a581d2fda01275b0a07c2f148852f5f76 Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:54:43 -0500 Subject: [PATCH 056/328] Place: dropped images load the place cursor, in the order they came Split out of #2073. Port of #1307's drops and #1666. - Several images dropped together load the place cursor in the order they came, each run of them where it comes among the other files, after the images it already holds; click to place them one by one. - One image dropped off a frame that takes it loads the place cursor instead of being placed at once; on such a frame it still fills it. - A drop is handled in its order, each file at its own pointer, and a dialog (a multi-page PDF's Import Options, an alert) cancels the rest. - On the web, files dropped together are read as one batch (none if one can't be read), and a single dropped image loads the place cursor. --- ROADMAP.md | 1 + apps/designcraft-web/src/browser_policy.rs | 39 ++++++- apps/designcraft-web/src/web.rs | 23 +++- crates/ui-egui/src/app/files.rs | 97 ++++++++++++---- crates/ui-egui/src/app/input.rs | 9 +- crates/ui-egui/src/tests.rs | 128 ++++++++++++++++++++- docs/multi-image-placement.md | 10 +- 7 files changed, 269 insertions(+), 38 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 3cef01494..8aedbe1f0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · Dropping images from the file manager works as in InDesign: images dropped together load the place cursor in the order they came, and one image dropped off a frame that takes it loads the place cursor instead of being placed at once (on a frame it still fills it). Documents and text files dropped keep opening and flowing as before. Ported from #1307 and #1666; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). diff --git a/apps/designcraft-web/src/browser_policy.rs b/apps/designcraft-web/src/browser_policy.rs index 524df6cc5..ca82c71ca 100644 --- a/apps/designcraft-web/src/browser_policy.rs +++ b/apps/designcraft-web/src/browser_policy.rs @@ -1,4 +1,4 @@ -//! Pure browser startup and download metadata policies. +//! Browser startup, download metadata, and atomic import policies. /// Query flags are case-sensitive decoded keys. Values are ignored: `?sample=false` /// still enables sample startup, and repeated keys have the same presence semantics. @@ -65,3 +65,40 @@ mod tests { } } } + +/// Read a drop in order, publishing nothing unless every file can be read. +pub(crate) async fn read_batch(files: impl IntoIterator, mut read: F) -> Result, E> +where + F: FnMut(T) -> Fut, + Fut: std::future::Future>, +{ + let mut result = Vec::new(); + for file in files { + result.push(read(file).await?); + } + Ok(result) +} + +#[cfg(test)] +mod batch_tests { + #[test] + fn failed_read_aborts_the_whole_batch() { + use std::{ + future::Future, + task::{Context, Poll, Waker}, + }; + let mut seen = Vec::new(); + let result = { + let future = super::read_batch([1, 2, 3], |n| { + seen.push(n); + std::future::ready(if n == 2 { Err("read failed") } else { Ok(n) }) + }); + let mut future = std::pin::pin!(future); + future.as_mut().poll(&mut Context::from_waker(Waker::noop())) + }; + assert_eq!(result, Poll::Ready(Err("read failed"))); + assert_eq!(seen, [1, 2]); + let mut success = std::pin::pin!(super::read_batch([3, 1], |n| std::future::ready(Ok::<_, ()>(n)))); + assert_eq!(success.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Ready(Ok(vec![3, 1]))); + } +} diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 8b23ef6b7..c87581e32 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -357,18 +357,29 @@ impl eframe::App for WebShell { let _ = self.graphics.run_if_healthy(|| { // Dropped files belong to this host iteration's raw input, not to stale logic input: // read them here once, before the batch is saved as pending for a hidden pass. - for f in std::mem::take(&mut raw.dropped_files) { + // Files dropped together arrive together, in their order, so several images load the + // place cursor as one batch. + let dropped = std::mem::take(&mut raw.dropped_files); + if !dropped.is_empty() { let request = self.app.import_request("drop"); let inbox = self.inbox.clone(); let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes }); + let files = crate::browser_policy::read_batch(dropped, |f| { + let request = request.clone(); + async move { + let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); + let bytes = f.bytes_async().await.map_err(|e| format!("couldn't read dropped file {name}: {e}"))?; + Ok::<_, String>(ImportedFile { request, name, bytes }) + } + }) + .await; + match files { + Ok(files) => { + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), + Err(error) => log::error!("{error}"), } }); } diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..bb0a20661 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -162,7 +162,7 @@ impl DesignApp { let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); let cursor_image = |file: &ImportedFile| { - file.request.purpose == "place" + matches!(file.request.purpose.as_str(), "place" | "drop") && !file.name.to_ascii_lowercase().ends_with(".pdf") && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) }; @@ -175,7 +175,7 @@ impl DesignApp { shortcut_import::import_delivered(self, &file.bytes); continue; } - let placing = file.request.purpose == "place"; + let placing = matches!(file.request.purpose.as_str(), "place" | "drop"); let mut group = vec![]; if cursor_image(&file) { while let Some(next) = @@ -184,8 +184,9 @@ impl DesignApp { group.push(next); } } - // Several images: into the place cursor. - if !group.is_empty() { + // Several images, or one dropped (a browser drop has no position to place it at or + // frame to fill): into the place cursor. + if !group.is_empty() || (file.request.purpose == "drop" && cursor_image(&file)) { if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Image import cancelled while a dialog is open")); continue; @@ -262,9 +263,9 @@ impl DesignApp { } /// A file dropped on the window: documents open, the swatches in a swatch exchange (.ase) file - /// are loaded, and anything else is placed on the spread in view (a parent spread while parents - /// are being edited). A file without an extension opens when its content is a DesignCraft or - /// IDML document. + /// are loaded, an image loads into the place cursor, and anything else is placed on the spread + /// in view (a parent spread while parents are being edited). A file without an extension + /// opens when its content is a DesignCraft or IDML document. pub fn open_dropped(&mut self, path: &str) -> Result { self.open_dropped_at(path, None) } @@ -273,18 +274,48 @@ impl DesignApp { /// window's coordinates. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_dropped_files(&mut self, files: &[egui::DroppedFileHandle], pointer: Option) { + let drops = files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).map(|p| (p, pointer)).collect(); + self.open_dropped_batch(drops); + } + + /// Files dropped on the window together, each with the pointer it was dropped at, handled in + /// the order they came. Each that isn't an image opens or is placed as + /// [`Self::open_dropped_at`] does at its own pointer. One image is dropped as that does too + /// (filling the frame under the pointer, else loading the place cursor); several load the place + /// cursor, each run of them where it came in the order, after any images it already holds, + /// whatever is under the pointer: click to place them one by one, drag with the arrow keys for + /// a grid. The rest of the drop is cancelled once a file opens a dialog (a multi-page PDF's + /// Import Options, an alert), as File › Place with several chosen is. + pub fn open_dropped_batch(&mut self, drops: Vec<(String, Option)>) { + let several = drops.iter().filter(|(p, _)| is_cursor_image(p)).count() > 1; + // Only the first graphic of a drop fills the frame under the pointer. let mut frame_free = true; - for f in files { - let p = f.path().to_string_lossy().to_string(); - if !p.is_empty() { - let _ = self.place_dropped(&p, pointer, &mut frame_free); + let mut images = Vec::new(); + // `None` at the end flushes the images left. + for drop in drops.into_iter().map(Some).chain([None]) { + if several + && let Some((path, _)) = &drop + && is_cursor_image(path) + { + images.push(path.clone()); + continue; } + // A file that can't be placed has its alert, which cancels the rest below. + if !images.is_empty() { + let _ = self.place_paths(std::mem::take(&mut images)); + } + let Some((path, pointer)) = drop else { break }; + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); + return; + } + let _ = self.place_dropped(&path, pointer, &mut frame_free); } } /// [`Self::open_dropped`] at the pointer: a graphic dropped on an empty or graphic frame fills - /// it, elsewhere its top left lands where the file was dropped on the canvas; text goes to a - /// new frame on the document page there. + /// it; elsewhere an image loads into the place cursor, and another graphic's top left lands + /// where the file was dropped on the canvas; text goes to a new frame on the document page there. pub fn open_dropped_at(&mut self, path: &str, pointer: Option) -> Result { self.place_dropped(path, pointer, &mut true) } @@ -303,13 +334,22 @@ impl DesignApp { if document { return self.open_file("file.open", json!({"path": path})); } - let mut params = json!({"path": path}); - // A graphic dropped on an empty or graphic frame fills it, as File > Place does. Text keeps + // A graphic dropped on a frame that takes one fills it, as File > Place does. Text keeps // getting a frame of its own, so it never replaces the image in a graphic frame. let frame = if *frame_free && !designcraft_textimport::is_text_file(path) { canvas::drop_frame(self, pointer) } else { None }; - if let (Some(frame), Some(o)) = (frame, params.as_object_mut()) { - o.insert("frame".into(), json!(frame.0)); + if let Some(frame) = frame { + let placed = self.open_file("file.place", json!({"path": path, "frame": frame.0})); + if placed.is_ok() { + *frame_free = false; + } + return placed; } + // An image dropped anywhere else waits in the place cursor, after any it already holds. + if is_cursor_image(path) { + let append = self.session.loaded.is_some(); + return self.open_file("place.load", json!({"path": path, "append": append})); + } + let mut params = json!({"path": path}); if let (Some((sr, at)), Some(o)) = (canvas::drop_point(self, pointer), params.as_object_mut()) { o.insert("spread".into(), serde_json::to_value(sr).unwrap_or(Value::Null)); o.insert("x".into(), json!(at.x)); @@ -319,11 +359,7 @@ impl DesignApp { o.insert("page".into(), json!(st.doc.first_page_of_spread(si) + pi + 1)); } } - let placed = self.open_file("file.place", params); - if frame.is_some() && placed.is_ok() { - *frame_free = false; - } - placed + self.open_file("file.place", params) } /// Queue files the operating system asked the app to open. They can arrive before the window @@ -908,6 +944,23 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A browser drop of one image (it has no position or frame under it) loads the place + /// cursor; images dropped together load it at once, after what it holds. + #[test] + fn browser_dropped_images_load_the_place_cursor() { + let mut app = app(); + let request = app.import_request("drop"); + deliver(&mut app, request, "one.png", png(200)); + assert_eq!(app.session.tool_id(), "placeGun"); + assert!(app.session.doc().unwrap().doc.spreads[0].items.is_empty(), "nothing placed yet"); + let request = app.import_request("drop"); + for (name, v) in [("two.png", 90), ("three.png", 60)] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes: png(v) }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["one.png", "two.png", "three.png"]); + } + #[test] fn batch_cancel_status_uses_the_interface_language() { let mut app = app(); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2682478c4..2281d3643 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -154,13 +154,10 @@ impl DesignApp { if drops.is_empty() { return; } - // Each file keeps the pointer it was dropped at; the system is asked once, for those - // that came without one. + // Dropped together, they go together: several images load the place cursor at once. Each + // file keeps the pointer it was dropped at. let system = drops.iter().any(|d| d.pointer.is_none()).then(|| self.system_pointer(ctx)).flatten(); - let mut frame_free = true; - for drop in drops { - let _ = self.place_dropped(&drop.path, drop.pointer.or(system), &mut frame_free); - } + self.open_dropped_batch(drops.into_iter().map(|d| (d.path, d.pointer.or(system))).collect()); } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e53e603a1..1f8cedf68 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -884,10 +884,20 @@ fn a_graphic_dropped_on_a_frame_fills_it() { let r = app.open_dropped_at(&path.to_string_lossy(), Some(inside)); let _ = std::fs::remove_file(&path); assert_eq!(r.unwrap()["id"].as_u64(), Some(frame), "the frame under the pointer is filled"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); let d = &app.session.doc().unwrap().doc; assert_eq!(d.spreads[0].items.len(), 1, "no new object"); assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); assert!(canvas::drop_frame(&app, Some(outside)).is_none(), "an empty spot on the page is no frame"); + // Dropped again, it replaces the image there rather than loading the place cursor. + let path = dropped_png("dropframe-again"); + app.open_dropped_at(&path.to_string_lossy(), Some(inside)).unwrap(); + let _ = std::fs::remove_file(&path); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "still no new object"); + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { panic!("a graphic frame") }; + assert!(d.assets[&g.asset].name.contains("dropframe-again"), "the frame shows the new image"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); // Text dropped there gets a frame of its own and leaves the image in place. let text = std::env::temp_dir().join(format!("designcraft-ui-{}-dropframe.txt", std::process::id())); std::fs::write(&text, "Dropped words").unwrap(); @@ -920,6 +930,7 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe ctx.run_ui(raw, |ui| app.take_pending_drops(ui.ctx())).textures_delta.clear(); let _ = std::fs::remove_file(&path); assert!(app.pending_drops.is_empty()); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor at {zoom}"); let d = &app.session.doc().unwrap().doc; assert_eq!(d.spreads[0].items.len(), 1, "no new object at {zoom}"); let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { @@ -940,7 +951,8 @@ fn a_locked_frame_is_not_a_drop_target() { r.unwrap(); let d = &app.session.doc().unwrap().doc; assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned), "the locked frame stays empty"); - assert_eq!(d.spreads[0].items.len(), 2, "the graphic became a new object"); + assert_eq!(d.spreads[0].items.len(), 1, "no new object yet"); + assert!(app.session.loaded.is_some(), "the image waits in the place cursor"); } #[test] @@ -954,8 +966,10 @@ fn only_the_first_graphic_of_a_drop_fills_the_frame() { let _ = (std::fs::remove_file(&first), std::fs::remove_file(&second)); assert_eq!(a.unwrap()["id"].as_u64(), Some(frame)); assert_ne!(b.unwrap()["id"].as_u64(), Some(frame), "the second graphic doesn't replace the first"); + // An image dropped off a frame that takes it waits in the place cursor. + assert!(app.session.loaded.is_some(), "the second image waits in the place cursor"); let d = &app.session.doc().unwrap().doc; - assert_eq!(d.spreads[0].items.len(), 2, "the second graphic is a new object"); + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); } @@ -971,11 +985,121 @@ fn a_file_dropped_while_a_parent_is_open_lands_on_the_parent() { let r = app.open_dropped(&path.to_string_lossy()); let _ = std::fs::remove_file(&path); r.unwrap(); + // The image waits in the place cursor; a click on the parent spread places it there. + assert!(app.session.loaded.is_some()); + let st = app.session.active().unwrap(); + let at = designcraft_tools::CanvasLayout::new(&st.doc, st.editing_parents) + .slot(designcraft_doc::SpreadRef::Parent(0)) + .unwrap() + .to_canvas(designcraft_geom::Point::new(50.0, 50.0)); + let v = designcraft_engine::ViewInfo::at_zoom(1.0); + for kind in [designcraft_tools::PointerKind::Down, designcraft_tools::PointerKind::Up] { + app.session.pointer(&designcraft_tools::PointerEvent::new(kind, at.x, at.y), v).unwrap(); + } let d = &app.session.doc().unwrap().doc; assert_eq!(d.parents[0].items.len(), 1, "the graphic is on the parent spread"); assert!(d.spreads.iter().all(|s| s.items.is_empty()), "no document page gets it"); } +/// The names of the images in the place cursor, the one a click places first. +fn loaded_names(app: &DesignApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + app.session.loaded.iter().chain(app.session.loaded_queue.iter()).map(|g| doc.assets[&g.asset].name.clone()).collect() +} + +/// One image dropped where no frame can take it loads the place cursor instead of being placed: +/// the next click places it. A frame selected doesn't take it, and another image dropped +/// meanwhile queues after it. +#[test] +fn a_single_image_dropped_off_a_frame_loads_the_place_cursor() { + let (mut app, frame, _, outside) = app_with_drop_frame(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let first = dropped_png("drop-loads-a"); + let second = dropped_png("drop-loads-b"); + app.open_dropped_at(&first.to_string_lossy(), Some(outside)).unwrap(); + assert_eq!(app.session.tool_id(), "placeGun"); + assert_eq!(loaded_names(&app).len(), 1); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), 1, "nothing placed yet"); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + app.open_dropped_at(&second.to_string_lossy(), Some(outside)).unwrap(); + let _ = (std::fs::remove_file(&first), std::fs::remove_file(&second)); + let names = loaded_names(&app); + assert_eq!(names.len(), 2, "{names:?}"); + assert!(names[0].contains("drop-loads-a") && names[1].contains("drop-loads-b"), "{names:?}"); + let d = &app.session.doc().unwrap().doc; + assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned)); + app.run("place.drop", json!({"x": 300, "y": 300})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), 2, "the click placed the first"); + assert_eq!(app.session.tool_id(), "placeGun", "the second is still loaded"); +} + +/// Several images dropped together load the place cursor in the order they came, even over a +/// frame; a file that isn't an image keeps its own drop behaviour (text gets a frame). +#[test] +fn several_dropped_images_load_the_place_cursor_in_order() { + let (mut app, frame, inside, _) = app_with_drop_frame(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let a = dropped_png("drop-many-a"); + let b = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-many-b.svg", std::process::id())); + std::fs::write(&b, br##""##).unwrap(); + let c = dropped_png("drop-many-c"); + let text = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-many.txt", std::process::id())); + std::fs::write(&text, "Dropped words").unwrap(); + let paths = [&a, &text, &b, &c].map(|p| p.to_string_lossy().to_string()); + app.open_dropped_batch(paths.iter().map(|p| (p.clone(), Some(inside))).collect()); + for p in [&a, &b, &c, &text] { + let _ = std::fs::remove_file(p); + } + let names = loaded_names(&app); + assert_eq!(names.len(), 3, "{names:?}"); + for (name, want) in names.iter().zip(["drop-many-a", "drop-many-b", "drop-many-c"]) { + assert!(name.contains(want), "{names:?}"); + } + assert_eq!(app.session.tool_id(), "placeGun"); + let d = &app.session.doc().unwrap().doc; + assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned), "the frame isn't filled"); + assert_eq!(d.spreads[0].items.len(), 2, "the text got a frame of its own"); + // Clicks place them one by one; Escape unloads the rest. + app.run("place.drop", json!({"x": 300, "y": 300})).unwrap(); + assert_eq!(app.session.loaded_queue.len(), 1); + let mods = designcraft_tools::Mods::default(); + app.session.tool_key(designcraft_tools::ToolKey::Escape, mods, designcraft_engine::ViewInfo::at_zoom(1.0)).unwrap(); + assert!(app.session.loaded.is_none() && app.session.loaded_queue.is_empty()); + assert_eq!(app.session.tool_id(), "selection"); +} + +/// A drop is handled in the order its files came, each at its own pointer: an image dropped on a +/// frame before a document fills that frame in the document that was open, not in the one the +/// drop opens after it. +#[test] +fn a_mixed_drop_keeps_its_order() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let mut other = DesignApp::new(Session::new(), Services::default()); + other.run("file.new", json!({})).unwrap(); + let document = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-mixed.designcraft", std::process::id())); + other.run("file.saveAs", json!({"path": document})).unwrap(); + let image = dropped_png("drop-mixed"); + let text = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-mixed.txt", std::process::id())); + std::fs::write(&text, "Dropped words").unwrap(); + let drops = vec![ + (image.to_string_lossy().to_string(), Some(inside)), + (text.to_string_lossy().to_string(), Some(outside)), + (document.to_string_lossy().to_string(), Some(outside)), + ]; + app.open_dropped_batch(drops); + for p in [&image, &text, &document] { + let _ = std::fs::remove_file(p); + } + assert_eq!(app.session.documents().len(), 2, "the document opened last"); + let d = &app.session.documents()[0].doc; + assert!( + matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_)), + "the image filled the frame in the document open before the drop" + ); + assert_eq!(d.spreads[0].items.len(), 2, "the text got a frame of its own"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); +} + #[test] fn file_open_failures_show_an_alert() { let path = unreadable_file("open.designcraft"); diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..6281de637 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -1,6 +1,6 @@ # Multiple images -Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). +Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a selection of images from your file manager onto the document. Multiple images load into a placement cursor in the order supplied by the file picker (or the drop). The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). - Click to place the next image at its natural size. - Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. @@ -10,6 +10,14 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +## Dropping files + +- One image dropped on an empty or graphic frame fills it, or replaces the image in it. +- One image dropped anywhere else loads into the place cursor, as File > Place does with nothing selected: the next click or drag places it. +- Several images dropped together load into the place cursor in the order they came, wherever they are dropped. +- Images dropped while the cursor already holds some queue after them. +- DesignCraft, IDML and InDesign documents open; text files (.txt, .docx, .rtf, .md) and spreadsheets go into a new frame where they are dropped; a PDF is placed where it is dropped (or fills the frame under it); swatch exchange (.ase) files load their swatches. + Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. ## Automation From cb97fcb0bdcccea9a192b5eeedfc6b533bb4f667 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 10:31:22 -0500 Subject: [PATCH 057/328] Place: a grid drag too small for its cells previews and places one frame The place cursor's grid preview fell back to the raw drag rectangle when the cells had no positive size, while the release still sent `place.grid`, which rejected the area. Both now use the same cell calculation (`grid_cells`), and a grid with no room for its cells shows and places the single proportional frame of an ordinary drag. --- crates/tools/src/nav.rs | 41 +++++++++++++++++++++++------------ crates/tools/src/tests.rs | 31 ++++++++++++++++++++++++++ docs/multi-image-placement.md | 2 +- 3 files changed, 59 insertions(+), 15 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index 2b84010d1..762a4f0f3 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -149,9 +149,10 @@ impl Tool for PlaceGun { if click { return vec![Action::Exec("place.drop".into(), json!({"spread": crate::spread_json(sr), "x": sa.x, "y": sa.y}))]; } - // Arrow keys during the drag set a grid: the queued images fill its cells. - if self.columns > 1 || self.rows > 1 { - let r = designcraft_geom::Rect::from_points(sa, b); + // Arrow keys during the drag set a grid: the queued images fill its cells. A drag + // too small for the grid's cells places one frame instead, as the overlay shows. + let r = designcraft_geom::Rect::from_points(sa, b); + if !grid_cells(r, self.columns, self.rows).is_empty() { return vec![Action::Exec( "place.grid".into(), json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), @@ -195,8 +196,13 @@ impl Tool for PlaceGun { // Under the drag threshold the release is a click (actual size where it was pressed): // no frame is drawn yet, the loaded cursor shows what lands. let click = (self.cur - a).hypot() < cx.tol(3.0); - if !click && (self.columns > 1 || self.rows > 1) { - return grid_overlays(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + // A grid draws its cells; one too small for them falls back to the single frame, as the + // release does. + if !click { + let cells = grid_cells(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + if !cells.is_empty() { + return cells.into_iter().map(crate::Overlay::Marquee).collect(); + } } let Some(size) = cx.loaded else { return vec![crate::Overlay::Marquee(designcraft_geom::Rect::from_points(a, self.cur))]; @@ -228,21 +234,28 @@ Y: {pct}" } } -/// The cells of a `columns` × `rows` place grid drawn over `rect`, 6 pt apart, as `place.grid` -/// lays them out; the whole rect when the cells would vanish. -fn grid_overlays(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { +/// The gutter between place-grid cells, in points: `place.grid`'s default. +const PLACE_GRID_GUTTER: f64 = 6.0; + +/// The cells of a `columns` × `rows` place grid drawn over `rect`, [`PLACE_GRID_GUTTER`] apart, as +/// `place.grid` lays them out. None for a 1 × 1 grid, or when `rect` is too small for the cells to +/// have a positive size: then the drag places one frame. +fn grid_cells(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { let (columns, rows) = (columns.clamp(1, 100), rows.clamp(1, 100)); - let w = (rect.width() - 6.0 * (columns - 1) as f64) / columns as f64; - let h = (rect.height() - 6.0 * (rows - 1) as f64) / rows as f64; + if columns == 1 && rows == 1 { + return vec![]; + } + let w = (rect.width() - PLACE_GRID_GUTTER * (columns - 1) as f64) / columns as f64; + let h = (rect.height() - PLACE_GRID_GUTTER * (rows - 1) as f64) / rows as f64; if !(w > 0.0 && h > 0.0) { - return vec![crate::Overlay::Marquee(rect)]; + return vec![]; } (0..rows) .flat_map(|row| { (0..columns).map(move |column| { - let x = rect.x0 + column as f64 * (w + 6.0); - let y = rect.y0 + row as f64 * (h + 6.0); - crate::Overlay::Marquee(designcraft_geom::Rect::new(x, y, x + w, y + h)) + let x = rect.x0 + column as f64 * (w + PLACE_GRID_GUTTER); + let y = rect.y0 + row as f64 * (h + PLACE_GRID_GUTTER); + designcraft_geom::Rect::new(x, y, x + w, y + h) }) }) .collect() diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 28cfecf01..790b3c7f8 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2369,3 +2369,34 @@ fn place_gun_grid_arrow_keys_are_handled_during_a_drag() { } assert!(t.key(&cx, ToolKey::Delete, Mods::default()).is_empty()); } + +/// A place-cursor grid drag too thin for its cells shows and places the single frame an ordinary +/// drag would; one with room shows its cells and places the grid. +#[test] +fn place_gun_grid_too_small_for_its_cells_previews_and_places_one_frame() { + let d = Document::new(&NewDocument::default()); + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let mut cx = ctx(&d, &s, &c, &l); + cx.loaded = Some((40.0, 20.0)); + // Drag from (10, 10) to `to`, pressing ↑ (two rows) when `grid`: the overlay before release, + // and the release. + let drag = |to: (f64, f64), grid: bool| { + let mut t = create("placeGun"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)); + if grid { + assert_eq!(t.key(&cx, ToolKey::Up, Mods::default()), vec![Action::Handled]); + } + let shown = t.overlays(&cx); + (shown, t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1))) + }; + // 100 × 8 pt: two rows 6 pt apart leave each a 1 pt cell; 100 × 4 pt leaves none. + let (shown, out) = drag((110.0, 18.0), true); + assert_eq!(shown.len(), 2, "{shown:?}"); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["rows"] == 2), "{out:?}"); + let (shown, out) = drag((110.0, 14.0), true); + let (single_shown, single_out) = drag((110.0, 14.0), false); + assert_eq!(shown, single_shown); + assert_eq!(out, single_out); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, _)] if cmd == "place.drop"), "{out:?}"); +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..da8f180bf 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -5,7 +5,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Click to place the next image at its natural size. - Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. - Click an existing graphic frame to replace its contents. -- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. +- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. A drag too small for the grid's cells shows and places one frame instead, as an ordinary drag does. - Press Escape or select another tool to cancel the remaining placement. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From a93885877568e05c40eb16d6e117b5c42ffa2de7 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 10:44:31 -0500 Subject: [PATCH 058/328] Place: contact sheet strings in every interface language; Spanish grid labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Arabic, Czech, Hungarian, Italian, Polish, Portuguese (Brazil), Russian and Ukrainian read only their own catalogs, so File › Place Contact Sheet… and its dialog showed in English there. They now have the four new strings. - Spanish Columns, Rows and Gutter were still English in the shared table: Columnas, Filas, Medianil, as the Spanish catalog already says for "Columns:", "Rows:" and "Gutter:". --- crates/ui-egui/src/i18n/ar.rs | 4 ++++ crates/ui-egui/src/i18n/cs.rs | 4 ++++ crates/ui-egui/src/i18n/hu.rs | 4 ++++ crates/ui-egui/src/i18n/it.rs | 4 ++++ crates/ui-egui/src/i18n/pl.rs | 4 ++++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++++ crates/ui-egui/src/i18n/ru.rs | 4 ++++ crates/ui-egui/src/i18n/table.rs | 6 +++--- crates/ui-egui/src/i18n/tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/i18n/uk.rs | 4 ++++ 10 files changed, 57 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 651b748f9..a5b8c9ce5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,6 +22,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "حفظ نسخة…"), ("Revert", "استعادة"), ("Place…", "وضع…"), + ("Place Contact Sheet…", "وضع ورقة مصغّرات…"), + ("Place Contact Sheet", "وضع ورقة مصغّرات"), + ("Place loaded images on new pages, in file order.", "وضع الصور المحمّلة على صفحات جديدة، بترتيب الملفات."), + ("Page margin", "هامش الصفحة"), ("Export PDF…", "تصدير PDF…"), ("Print…", "طباعة…"), ("Print", "طباعة"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b6459bc36..6b8caa4be 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Uložit kopii…"), ("Revert", "Vrátit k uložené verzi"), ("Place…", "Umístit…"), + ("Place Contact Sheet…", "Umístit kontaktní arch…"), + ("Place Contact Sheet", "Umístit kontaktní arch"), + ("Place loaded images on new pages, in file order.", "Umístit načtené obrázky na nové stránky v pořadí souborů."), + ("Page margin", "Okraj stránky"), ("Export PDF…", "Exportovat PDF…"), ("Print…", "Tisk…"), ("Document Setup…", "Nastavení dokumentu…"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index 890959761..b3a32ca3e 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1223,6 +1223,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Place with Import Options", "Elhelyezés importálási beállításokkal"), ("Place with Import Options…", "Elhelyezés importálási beállításokkal…"), ("Place…", "Elhelyezés…"), + ("Place Contact Sheet…", "Kontaktlap elhelyezése…"), + ("Place Contact Sheet", "Kontaktlap elhelyezése"), + ("Place loaded images on new pages, in file order.", "A betöltött képek elhelyezése új oldalakon, fájlsorrendben."), + ("Page margin", "Oldalmargó"), ("Plain", "Egyszerű"), ("Plain Text", "Egyszerű szöveg"), ("Play on Page Load", "Lejátszás az oldal betöltésekor"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 70d08085e..183891a57 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Salva una copia…"), ("Revert", "Ripristina"), ("Place…", "Inserisci…"), + ("Place Contact Sheet…", "Inserisci provino…"), + ("Place Contact Sheet", "Inserisci provino"), + ("Place loaded images on new pages, in file order.", "Inserisci le immagini caricate in nuove pagine, nell'ordine dei file."), + ("Page margin", "Margine pagina"), ("Export PDF…", "Esporta PDF…"), ("Print…", "Stampa…"), ("Document Setup…", "Impostazione documento…"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index fcdb3718e..155e5f3eb 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -23,6 +23,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Zapisz kopię…"), ("Revert", "Przywróć"), ("Place…", "Umieść…"), + ("Place Contact Sheet…", "Umieść stykówkę…"), + ("Place Contact Sheet", "Umieść stykówkę"), + ("Place loaded images on new pages, in file order.", "Umieść wczytane obrazy na nowych stronach, w kolejności plików."), + ("Page margin", "Margines strony"), ("Export PDF…", "Eksportuj PDF…"), ("Print…", "Drukuj…"), ("Document Setup…", "Ustawienia dokumentu…"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0ef8fa755..f104fd8de 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -26,6 +26,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Salvar uma cópia…"), ("Revert", "Reverter"), ("Place…", "Inserir…"), + ("Place Contact Sheet…", "Inserir folha de contato…"), + ("Place Contact Sheet", "Inserir folha de contato"), + ("Place loaded images on new pages, in file order.", "Inserir as imagens carregadas em novas páginas, na ordem dos arquivos."), + ("Page margin", "Margem da página"), ("Export PDF…", "Exportar PDF…"), ("Print…", "Imprimir…"), ("Print", "Imprimir"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 8b933fe60..22533a4ff 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -27,6 +27,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Сохранить копию…"), ("Revert", "Восстановить сохраненную версию"), ("Place…", "Поместить…"), + ("Place Contact Sheet…", "Поместить контактный лист…"), + ("Place Contact Sheet", "Поместить контактный лист"), + ("Place loaded images on new pages, in file order.", "Поместить загруженные изображения на новые страницы в порядке файлов."), + ("Page margin", "Поле страницы"), ("Export PDF…", "Экспорт в PDF…"), ("Print…", "Печать…"), ("Document Setup…", "Настройка документа…"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 60cba865d..e83665438 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -1190,7 +1190,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ), ("Color Settings", ["Color Settings", "Réglages des couleurs", "Color Settings", "Color Settings", "颜色设置"]), ("Color:", ["Color:", "Couleur :", "Color:", "Color:", "颜色:"]), - ("Columns", ["Columns", "Colonnes", "Columns", "Columns", "栏"]), + ("Columns", ["Columns", "Colonnes", "Columnas", "Columns", "栏"]), ("Composer:", ["Composer:", "Compositeur :", "Composer:", "Composer:", "排版器:"]), ("Copies:", ["Copies:", "Copies :", "Copies:", "Copies:", "份数:"]), ("Count", ["Count", "Compter", "Count", "Count", "数量"]), @@ -1292,7 +1292,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Generate QR Code", ["Generate QR Code", "Générer un code QR", "Generate QR Code", "Generate QR Code", "生成二维码"]), ("Go To", ["Go To", "Atteindre", "Go To", "Go To", "转到"]), ("Go to Page", ["Go to Page", "Atteindre la page", "Go to Page", "Go to Page", "转到页面"]), - ("Gutter", ["Gutter", "Gouttière", "Gutter", "Gutter", "栏间距"]), + ("Gutter", ["Gutter", "Gouttière", "Medianil", "Gutter", "栏间距"]), ("Header Rows", ["Header Rows", "Lignes d'en-tête", "Header Rows", "Header Rows", "表头行"]), ("Height", ["Height", "Hauteur", "Height", "Height", "高度"]), ("Height:", ["Height:", "Hauteur :", "Height:", "Height:", "高度:"]), @@ -3723,7 +3723,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ), ("Rotate 180°", ["180° drehen", "Rotation à 180°", "Girar 180°", "180°回転", "旋转 180°"]), ("Rotation Angle", ["Rotation Angle", "Angle de rotation", "Rotation Angle", "Rotation Angle", "旋转角度"]), - ("Rows", ["Rows", "Lignes", "Rows", "Rows", "行数"]), + ("Rows", ["Rows", "Lignes", "Filas", "Rows", "行数"]), ("Run", ["Run", "Exécuter", "Run", "Run", "运行"]), ("Scale X Percentage", ["Scale X Percentage", "Échelle X en pourcentage", "Scale X Percentage", "Scale X Percentage", "水平缩放百分比"]), ("Scale Y Percentage", ["Scale Y Percentage", "Échelle Y en pourcentage", "Scale Y Percentage", "Scale Y Percentage", "垂直缩放百分比"]), diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b676a0c5f..a10f61438 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -249,6 +249,28 @@ fn arrangement_accessible_name_is_localized_in_every_interface_language() { } } +/// File › Place Contact Sheet… and its dialog read in every interface language, including those +/// whose own catalog is all `tr` looks in. +#[test] +fn contact_sheet_strings_are_translated_in_every_interface_language() { + let strings = [ + "Place Contact Sheet…", + "Place Contact Sheet", + "Place loaded images on new pages, in file order.", + "Columns", + "Rows", + "Gutter", + "Page margin", + ]; + for (code, name) in LANGUAGES.iter().filter(|(code, _)| !code.is_empty()) { + for s in strings { + let text = tr(code, s); + assert!(text != s && !text.trim().is_empty(), "{name}: {s:?} is still English"); + } + } + assert_eq!(["Columns", "Rows", "Gutter"].map(|s| tr("es", s)), ["Columnas", "Filas", "Medianil"]); +} + /// Checks language-specific context precedence and fallback to the plain translation. #[test] fn context_captions_come_from_their_context_or_the_plain_translation() { diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 03918520f..f902cd236 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -26,6 +26,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Зберегти копію…"), ("Revert", "Повернути збережену версію"), ("Place…", "Розмістити…"), + ("Place Contact Sheet…", "Розмістити аркуш мініатюр…"), + ("Place Contact Sheet", "Розмістити аркуш мініатюр"), + ("Place loaded images on new pages, in file order.", "Розмістити завантажені зображення на нових сторінках у порядку файлів."), + ("Page margin", "Поле сторінки"), ("Export PDF…", "Експортувати PDF…"), ("Print…", "Друк…"), ("Document Setup…", "Параметри документа…"), From 0ea2a72a091e96833783dee24669bc7ea6b3a0f4 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:05:45 -0500 Subject: [PATCH 059/328] Place: switching, opening or closing a document leaves the place cursor's tool Review fix for #2309: set_active, add_document and close_document emptied the place cursor but kept the placeGun tool, so the next canvas click failed with 'nothing loaded in the place cursor'. One helper, Session::unload_place_cursor, empties the cursor and its queue and goes back to the Selection tool when the place cursor's tool is active; validate_place_cursor uses it too. Test: changing_documents_unloads_the_place_cursor_and_its_tool. --- ROADMAP.md | 2 +- crates/engine/src/cmd/file/place.rs | 4 +--- crates/engine/src/lib.rs | 9 +++------ crates/engine/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 10 ++++++++++ docs/multi-image-placement.md | 1 + 6 files changed, 43 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8aedbe1f0..0395fb926 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -406,7 +406,7 @@ Newest first. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. - **2026-10-30** · Dropping images from the file manager works as in InDesign: images dropped together load the place cursor in the order they came, and one image dropped off a frame that takes it loads the place cursor instead of being placed at once (on a frame it still fills it). Documents and text files dropped keep opening and flowing as before. Ported from #1307 and #1666; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. -- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). Switching, opening or closing a document unloads it too, back to the Selection tool. A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ba9e0827a..dd7313776 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -313,9 +313,7 @@ fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { } let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); if !valid { - s.loaded = None; - s.loaded_queue.clear(); - s.set_tool("selection"); + s.unload_place_cursor(); return Err(bad(command, "the loaded graphic is no longer in the document")); } Ok(()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 397be3203..33af11c42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -552,8 +552,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.active = Some(i); } } @@ -563,8 +562,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -587,8 +585,7 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..a2751de72 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2127,6 +2127,33 @@ fn undoing_loaded_assets_cancels_every_placement_cursor() { } } +/// Switching, opening or closing a document empties the place cursor and leaves its tool: a click +/// on the canvas then selects, instead of failing with nothing loaded. Another tool stays. +#[test] +fn changing_documents_unloads_the_place_cursor_and_its_tool() { + let changes: [fn(&mut Session); 3] = [ + |s| s.set_active(0), + |s| { + s.execute("file.new", &json!({})).unwrap(); + }, + |s| s.close_document(1), + ]; + for (n, change) in changes.into_iter().enumerate() { + let mut s = session(); + s.execute("file.new", &json!({})).unwrap(); + load_test_images(&mut s, 3); + assert_eq!(s.tool_id(), "placeGun"); + change(&mut s); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty(), "change {n}"); + assert_eq!(s.tool_id(), "selection", "change {n}"); + // Holding another tool, the change keeps it. + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangle"); + s.set_active(0); + assert_eq!(s.tool_id(), "rectangle", "change {n}"); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 6dfd23703..9bde0acfd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -87,6 +87,16 @@ impl Session { } } + /// Empty the place cursor (its graphic and the ones queued after it). Holding the place + /// cursor's tool, go back to the Selection tool: with nothing loaded, a click would only fail. + pub(crate) fn unload_place_cursor(&mut self) { + self.loaded = None; + self.loaded_queue.clear(); + if self.tool_id() == "placeGun" { + self.set_tool("selection"); + } + } + pub fn layout(&self) -> CanvasLayout { match self.active() { Some(st) => CanvasLayout::new(&st.doc, st.editing_parents), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 6281de637..13119cf64 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -7,6 +7,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Click an existing graphic frame to replace its contents. - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. - Press Escape or select another tool to cancel the remaining placement. +- Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From f02e13318b0c870e09f4c791047e69db7681f2b1 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:02:26 -0500 Subject: [PATCH 060/328] Place: a drop without pointer events keeps the system pointer of its own input Review fixes for #2304: - Each pointer-less drop asks the system where the pointer is when its raw input arrives, and converts it with that input's window rect and the UI scale, instead of one sample taken at the later UI pass for the whole batch. Drops with pointer events keep their own pointer, and the system is still only asked when a drop brought none. - system_pointer is cfg'd off on wasm with its only caller; Services::pointer's docs say a drop without a pointer lands in the middle of the view. - pointer.rs: the AppKit flip is a pure function with a test, documenting why it flips against the main display only (winit's window positions use the same origin). - Test: a filled compound path takes a dropped image through its ring, not its hole. --- apps/designcraft/src/pointer.rs | 29 +++++++++++- crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/input.rs | 46 ++++++++++--------- crates/ui-egui/src/lib.rs | 4 ++ crates/ui-egui/src/services.rs | 2 +- crates/ui-egui/src/tests.rs | 78 ++++++++++++++++++++++++++++++--- 6 files changed, 132 insertions(+), 29 deletions(-) diff --git a/apps/designcraft/src/pointer.rs b/apps/designcraft/src/pointer.rs index 14bf9599a..3725cfbaa 100644 --- a/apps/designcraft/src/pointer.rs +++ b/apps/designcraft/src/pointer.rs @@ -11,6 +11,33 @@ pub fn screen_position() -> Option { // AppKit's origin is the bottom left of the first screen, the one with the menu bar. let height = NSScreen::screens(mtm).firstObject()?.frame().size.height; let at = NSEvent::mouseLocation(); - let (x, y) = (at.x, height - at.y); + from_appkit(at.x, at.y, height) +} + +/// A point in AppKit's global coordinates (origin at the bottom left of the main display, the one +/// with the menu bar, y up) in winit's (origin at its top left, y down), given that display's +/// height. Only the main display's height: winit flips window positions the same way +/// (`flip_window_screen_coordinates`, against `CGMainDisplayID`), whatever display the window is +/// on, so a display left of or above the main one gives negative coordinates in both. +fn from_appkit(x: f64, y: f64, main_height: f64) -> Option { + let y = main_height - y; (x.is_finite() && y.is_finite()).then(|| egui::pos2(x as f32, y as f32)) } + +#[cfg(test)] +mod tests { + use super::from_appkit; + + #[test] + fn appkit_points_flip_against_the_main_display_only() { + // The main display is 1000 points high: its top left is (0, 0), its bottom left (0, 1000). + assert_eq!(from_appkit(0.0, 1000.0, 1000.0), Some(egui::pos2(0.0, 0.0))); + assert_eq!(from_appkit(200.0, 100.0, 1000.0), Some(egui::pos2(200.0, 900.0))); + // A second display above the main one, and one to its left: negative, as winit reports a + // window there. + assert_eq!(from_appkit(300.0, 1200.0, 1000.0), Some(egui::pos2(300.0, -200.0))); + assert_eq!(from_appkit(-800.0, 500.0, 1000.0), Some(egui::pos2(-800.0, 500.0))); + assert_eq!(from_appkit(f64::NAN, 0.0, 1000.0), None); + assert_eq!(from_appkit(0.0, 0.0, f64::INFINITY), None); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..55a257dd3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -206,7 +206,7 @@ impl DesignApp { // must not replay shortcuts or dropped files from stale input. if ctx.current_pass_index() == 0 { #[cfg(not(target_arch = "wasm32"))] - self.take_pending_drops(&ctx); + self.take_pending_drops(); menus::shortcuts(self, &ctx); } let t0 = now_ms(); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2682478c4..27049a1a7 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -59,10 +59,13 @@ impl DesignApp { _ => None, }); let generation = self.input_generation(); + // A drop without pointer events (dragged in from another application) asks the + // system now, while the pointer is still where the files were let go. + let system = if pointer.is_none() && !raw.dropped_files.is_empty() { self.system_pointer(ctx, raw) } else { None }; for file in std::mem::take(&mut raw.dropped_files) { let path = file.path().to_string_lossy().to_string(); if !path.is_empty() { - self.pending_drops.push(PendingDrop { path, pointer, generation }); + self.pending_drops.push(PendingDrop { path, pointer, system, generation }); } } } @@ -144,37 +147,29 @@ impl DesignApp { /// Open or place the files dropped since the last UI pass, at the pointer. Files dropped /// without pointer events (dragged in from another application) are placed where the system - /// says the pointer is, so one dropped on a frame still fills it. + /// said the pointer was when they arrived, so one dropped on a frame still fills it. #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn take_pending_drops(&mut self, ctx: &egui::Context) { + pub(crate) fn take_pending_drops(&mut self) { // Sample the generation once for the whole batch: placing the first valid file must not // suppress later files that belong to the same captured batch. let current = self.input_generation(); - let drops: Vec<_> = std::mem::take(&mut self.pending_drops).into_iter().filter(|d| d.generation == current).collect(); - if drops.is_empty() { - return; - } - // Each file keeps the pointer it was dropped at; the system is asked once, for those - // that came without one. - let system = drops.iter().any(|d| d.pointer.is_none()).then(|| self.system_pointer(ctx)).flatten(); let mut frame_free = true; - for drop in drops { - let _ = self.place_dropped(&drop.path, drop.pointer.or(system), &mut frame_free); + for drop in std::mem::take(&mut self.pending_drops) { + if drop.generation == current { + let _ = self.place_dropped(&drop.path, drop.pointer.or(drop.system), &mut frame_free); + } } } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), /// for files dropped without pointer events: dragged in from another application, they bring - /// none. `None` when the system doesn't say or the window's place isn't known. - pub(crate) fn system_pointer(&self, ctx: &egui::Context) -> Option { + /// none. Converted with the window's place in `raw` (that input's own viewport info, else the + /// last pass's). `None` when the system doesn't say or the window's place isn't known. + #[cfg(not(target_arch = "wasm32"))] + fn system_pointer(&self, ctx: &egui::Context, raw: &egui::RawInput) -> Option { let at = (self.services.pointer.as_ref()?)()?; - // The system's points are unscaled; egui's (the window's rect too) are divided by the - // UI scale. - let zoom = ctx.zoom_factor(); - let at = if zoom.is_finite() && zoom > 0.0 { at / zoom } else { at }; - let inner = ctx.input(|i| i.viewport().inner_rect)?; - let local = at - inner.min.to_vec2(); - (local.x.is_finite() && local.y.is_finite()).then_some(local) + let inner = raw.viewports.get(&raw.viewport_id).and_then(|v| v.inner_rect).or_else(|| ctx.input(|i| i.viewport().inner_rect))?; + screen_to_window(at, ctx.zoom_factor(), inner) } /// The current state an injected batch belongs to. @@ -224,3 +219,12 @@ impl DesignApp { self.control_input_frame.store(false, std::sync::atomic::Ordering::Relaxed); } } + +/// A point on the screen in the system's unscaled points, in the window whose content is `inner` +/// (egui's points, divided by the UI scale `zoom`). `None` when the result isn't finite. +#[cfg(not(target_arch = "wasm32"))] +fn screen_to_window(at: egui::Pos2, zoom: f32, inner: egui::Rect) -> Option { + let at = if zoom.is_finite() && zoom > 0.0 { at / zoom } else { at }; + let local = at - inner.min.to_vec2(); + (local.x.is_finite() && local.y.is_finite()).then_some(local) +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c780d632a..531a8dbe7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -111,6 +111,10 @@ struct InputGeneration { struct PendingDrop { path: String, pointer: Option, + /// Where the system said the pointer was in the window when this drop's raw input arrived, + /// for a drop that brought no pointer events ([`crate::Services::pointer`]). Each drop keeps + /// its own, converted with the window's place and the UI scale of that input. + system: Option, generation: InputGeneration, } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 107e9e775..32d7e4599 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -47,6 +47,6 @@ pub struct Services { /// The pointer's place on the screen, asked when a file is dropped: a file dragged in from /// another application brings no pointer events with it (winit reports none during a drag on /// macOS), so without it a drop can't tell which frame it landed on. `None`: a drop without - /// pointer events loads the place cursor. + /// pointer events lands in the middle of the view (`canvas::drop_point`), filling no frame. pub pointer: Option, } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e53e603a1..46c3ce3e2 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -899,6 +899,15 @@ fn a_graphic_dropped_on_a_frame_fills_it() { assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); } +/// The raw input of a drop without pointer events, with the window's content at `inner`. +#[cfg(not(target_arch = "wasm32"))] +fn pointerless_drop(path: &std::path::Path, inner: egui::Rect) -> egui::RawInput { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, inner.size())), ..Default::default() }; + raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(inner), ..Default::default() }); + raw.dropped_files.push(dropped_file(path)); + raw +} + /// A file dragged in from the Finder brings no pointer events (winit sends none during a drag on /// macOS): the drop asks the system where the pointer is, so one dropped on a frame fills it. #[cfg(not(target_arch = "wasm32"))] @@ -911,13 +920,13 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe let window = egui::vec2(300.0, 200.0); app.services.pointer = Some(Box::new(move || Some(((inside + window).to_vec2() * zoom).to_pos2()))); let path = dropped_png("drop-system-pointer"); - app.pending_drops.push(crate::PendingDrop { path: path.to_string_lossy().into_owned(), pointer: None, generation: app.input_generation() }); let ctx = egui::Context::default(); ctx.set_zoom_factor(zoom); - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO + window, egui::vec2(1400.0, 900.0)); - let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, rect.size())), ..Default::default() }; - raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(rect), ..Default::default() }); - ctx.run_ui(raw, |ui| app.take_pending_drops(ui.ctx())).textures_delta.clear(); + // The zoom takes effect from the next pass, as it has by the time the system drops a file. + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let mut raw = pointerless_drop(&path, egui::Rect::from_min_size(egui::Pos2::ZERO + window, egui::vec2(1400.0, 900.0))); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |_| app.take_pending_drops()).textures_delta.clear(); let _ = std::fs::remove_file(&path); assert!(app.pending_drops.is_empty()); let d = &app.session.doc().unwrap().doc; @@ -929,6 +938,65 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe } } +/// A drop without pointer events keeps the place the system gave when its input arrived, +/// converted with that input's window: the pointer and the window moving before the UI pass that +/// places it don't move the drop. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_pointerless_drop_keeps_the_system_pointer_of_its_own_input() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let at = std::rc::Rc::new(std::cell::Cell::new(inside)); + let reported = at.clone(); + app.services.pointer = Some(Box::new(move || Some(reported.get()))); + let ctx = egui::Context::default(); + let window = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let path = dropped_png("drop-own-input"); + let mut raw = pointerless_drop(&path, window); + app.raw_input_hook(&ctx, &mut raw); + // Before the pass that places it, the window moves and the pointer leaves the frame; a later + // input with no drop doesn't ask the system again. + let moved = window.translate(egui::vec2(50.0, 40.0)); + at.set(outside + moved.min.to_vec2()); + let mut later = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, moved.size())), ..Default::default() }; + later.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(moved), ..Default::default() }); + app.raw_input_hook(&ctx, &mut later); + ctx.run_ui(later, |_| app.take_pending_drops()).textures_delta.clear(); + let _ = std::fs::remove_file(&path); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { + panic!("the file fills the frame it was dropped on") + }; + assert!(d.assets[&g.asset].name.contains("drop-own-input")); +} + +/// A filled compound path (Object > Compound Paths > Make) is a frame a dropped image fills, as +/// in InDesign, through its ring and not its hole. +#[test] +fn a_graphic_dropped_on_a_compound_path_fills_it() { + let (mut app, frame, _, _) = app_with_drop_frame(); + let hole = app.run("frame.create", json!({"rect": [66, 66, 106, 106]})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(app.run("object.makeCompoundPath", json!({"ids": [frame, hole]})).unwrap()["id"].as_u64(), Some(frame)); + app.run("object.fill", json!({"ids": [frame], "swatch": "[Black]"})).unwrap(); + let (view, rect) = (app.view().unwrap(), app.canvas_rect.unwrap()); + let st = app.session.active().unwrap(); + let layout = designcraft_tools::CanvasLayout::new(&st.doc, false); + let slot = layout.slot(designcraft_doc::SpreadRef::Doc(0)).unwrap(); + let screen = |x, y| canvas::Xf::new(rect, view).to_screen(slot.to_canvas(designcraft_geom::Point::new(x, y))); + // On the ring, between the outer edge (36) and the hole (66); the hole's middle is no frame. + let ring = screen(50.0, 50.0); + assert!(canvas::drop_frame(&app, Some(screen(86.0, 86.0))).is_none(), "the hole"); + let path = dropped_png("drop-compound"); + let r = app.open_dropped_at(&path.to_string_lossy(), Some(ring)); + let _ = std::fs::remove_file(&path); + assert_eq!(r.unwrap()["id"].as_u64(), Some(frame), "the compound path under the pointer is filled"); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); + let it = d.item(designcraft_doc::ItemId(frame)).unwrap(); + assert!(matches!(it.content, designcraft_doc::Content::Graphic(_))); + assert_eq!(it.path.subpaths.len(), 2, "it keeps its hole"); +} + #[test] fn a_locked_frame_is_not_a_drop_target() { let (mut app, frame, inside, _) = app_with_drop_frame(); From 90f3d39ff0711cfe26461bad382149a3546d1b1b Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 4 Nov 2026 19:17:06 +0100 Subject: [PATCH 061/328] i18n: drop this branch's rows main's catalogues now have Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/table.rs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 6b1d2eeba..0158ec53a 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -45,16 +45,6 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Reset To Base", ["Auf Basis zurücksetzen", "Rétablir la base", "Restablecer a base", "基準に戻す", "重置为基准"]), ("New Paragraph Style", ["Neues Absatzformat", "Nouveau style de paragraphe", "Nuevo estilo de párrafo", "新規段落スタイル", "新建段落样式"]), ("New Character Style", ["Neues Zeichenformat", "Nouveau style de caractère", "Nuevo estilo de carácter", "新規文字スタイル", "新建字符样式"]), - ( - "Apply Style to Selection", - [ - "Format auf Auswahl anwenden", - "Appliquer le style à la sélection", - "Aplicar estilo a la selección", - "選択範囲にスタイルを適用", - "将样式应用于选区", - ], - ), ( "Clear Frame Fitting Options", [ From 6052a504bfc451f2b6eae495241d48a15801426c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 11:50:50 -0800 Subject: [PATCH 062/328] Copy: nested anchored stories keep cross-references to each other's copies A story anchored in a copied story is copied before its host story enters the document, so cross-references between the two kept the original anchors. After a copied story is stored with the stories anchored in it, the cross-references of every copy so far are pointed at the copied anchors again. A copy whose table cells nest tables or notes deeper than 64 levels is now refused, as deeply nested groups are, instead of keeping the original's table ids below that depth. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/object.rs | 128 +++++++++++++++++++++++++++----- 2 files changed, 112 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 166aa2c18..00e197514 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -109,7 +109,7 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< .map(|orig| { let mut i = orig.clone(); if !super::object::renumber(d, &items, &mut i, &mut stories) { - return Err(designcraft_doc::DocError::Invalid(format!("{} nests groups too deeply to copy", orig.id))); + return Err(designcraft_doc::DocError::Invalid(format!("{} nests groups or tables too deeply to copy", orig.id))); } if d.layer(i.layer).is_none() { i.layer = d.default_layer(); diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index cb4dad95d..c6b234dda 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1086,7 +1086,7 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp let mut copy = it.clone(); copy.xf = Affine::translate(off) * copy.xf; if !renumber(dst, src, &mut copy, &mut story_map) { - return Err(designcraft_doc::DocError::Invalid(format!("{id} nests groups too deeply to copy")).into()); + return Err(designcraft_doc::DocError::Invalid(format!("{id} nests groups or tables too deeply to copy")).into()); } if dst.layer(copy.layer).is_none() { copy.layer = dst.default_layer(); @@ -1098,7 +1098,7 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp Ok(out) } -/// Groups nesting deeper than this are not copied: [`renumber`] reports them. +/// Groups, and tables and notes in table cells, nesting deeper than this are not copied: [`renumber`] reports them. const MAX_COPY_DEPTH: usize = 64; /// The id to reference in `dst` for asset `id` of `src`. When `src` lacks the asset (a missing graphic), the reference @@ -1109,8 +1109,9 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { } /// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. `stories` maps -/// the stories of `src` copied so far to their copies. False when its groups nest deeper than [`MAX_COPY_DEPTH`]: the -/// items below that keep their ids, and the copy must not be used. +/// the stories of `src` copied so far to their copies. False when its groups, or the tables and notes in the table cells +/// of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below that keep their ids, and the copy +/// must not be used. pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { renumber_in(dst, src, it, stories, 0, true) } @@ -1135,7 +1136,7 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut let n = StoryId(dst.alloc()); let mut st = src.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); st.id = n; - renumber_marks(dst, src, stories, &mut st); + let marked = renumber_marks(dst, src, stories, &mut st); let mut assets = HashMap::new(); for a in designcraft_doc::story_asset_refs(&st) { let na = adopt_or_dangle(dst, src, a); @@ -1147,8 +1148,14 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. stories.insert(tf.story, n); - complete = renumber_anchored(dst, src, &mut st, stories, depth + 1); + let copied = stories.len(); + complete = renumber_anchored(dst, src, &mut st, stories, depth + 1) && marked; dst.stories.insert(n, Arc::new(st)); + // The stories anchored in this one were copied while it was not yet in `dst`. + if stories.len() > copied { + let anchors = copied_anchors(dst, src, stories); + retarget_copies(dst, src, stories, &anchors); + } n } }; @@ -1181,33 +1188,46 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut /// Give the text anchors and tables of `st`, a new copy of a story of `src`, ids of their own (anchors from the story's /// id, tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] /// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their -/// destinations where those are copied, and the copy's paragraphs follow its tables. -fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) { +/// destinations where those are copied, and the copy's paragraphs follow its tables. False when tables or notes in +/// table cells nest deeper than [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. +fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) -> bool { let base = st.id.0 << 24; let mut anchors = HashMap::new(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { anchors.insert(a.id, base + k); Arc::make_mut(a).id = base + k; } + anchors.extend(copied_anchors(dst, src, stories)); + retarget_copies(dst, src, stories, &anchors); + remap_xrefs(st, &anchors, 0); + renumber_tables(dst, st, 0) +} + +/// The anchor ids of the stories of `src` that `stories` maps, each to the id of its copy's anchor in `dst`. +fn copied_anchors(dst: &Document, src: &Document, stories: &HashMap) -> HashMap { + let mut anchors = HashMap::new(); for (old, new) in stories { if let (Some(o), Some(n)) = (src.story(*old), dst.story(*new)) { anchors.extend(o.anchors.iter().zip(&n.anchors).map(|(a, b)| (a.id, b.id))); } } - // An earlier copy's targets are found again from its original: a new anchor id can be another original's. + anchors +} + +/// Point the cross-references in the copies in `dst` that `stories` lists at the anchors `anchors` gives for their +/// targets. Each copy's targets are found again from its original: a new anchor id can be another original's. +fn retarget_copies(dst: &mut Document, src: &Document, stories: &HashMap, anchors: &HashMap) { for (old, new) in stories { if let (Some(o), Some(copy)) = (src.story(*old), dst.story_mut(*new)) { - retarget_xrefs(copy, o, &anchors, 0); + retarget_xrefs(copy, o, anchors, 0); } } - remap_xrefs(st, &anchors, 0); - renumber_tables(dst, st, 0); } /// Give the tables of `st`, and those in the stories of their cells and of the notes of `st` down to /// [`MAX_COPY_DEPTH`] levels, new ids from `dst`, each story's in the order of their old ids, and point the stories' -/// paragraphs at them. -fn renumber_tables(dst: &mut Document, st: &mut Story, depth: usize) { +/// paragraphs at them. False when the stories below that depth hold tables or notes. +fn renumber_tables(dst: &mut Document, st: &mut Story, depth: usize) -> bool { let mut tables = HashMap::new(); for (old, mut table) in std::mem::take(&mut st.tables) { let id = dst.alloc(); @@ -1219,16 +1239,20 @@ fn renumber_tables(dst: &mut Document, st: &mut Story, depth: usize) { pf.table = pf.table.map(|t| tables.get(&t).copied().unwrap_or(t)); } if depth >= MAX_COPY_DEPTH { - return; + // The stories below keep the ids of their tables, so the copy is incomplete when they hold tables or notes. + let leaf = |s: &Story| s.tables.is_empty() && s.notes.is_empty() && s.endnotes.is_empty(); + return st.tables.values().all(|t| t.cells.iter().all(|c| leaf(&c.text))) && st.notes.iter().chain(&st.endnotes).all(|n| leaf(&n.text)); } + let mut complete = true; for t in st.tables.values_mut() { for c in &mut Arc::make_mut(t).cells { - renumber_tables(dst, &mut c.text, depth + 1); + complete &= renumber_tables(dst, &mut c.text, depth + 1); } } for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - renumber_tables(dst, &mut Arc::make_mut(n).text, depth + 1); + complete &= renumber_tables(dst, &mut Arc::make_mut(n).text, depth + 1); } + complete } /// Point the cross-references in `st`, and in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] @@ -5620,6 +5644,41 @@ mod copy_ids_tests { assert_eq!(s.doc().unwrap().doc, before, "nothing is pasted"); } + #[test] + fn tables_nested_too_deeply_in_cells_are_not_copied() { + use std::sync::Arc; + + // The first cell of the story's table holds `n` tables, each in the first cell of the one before. + fn nested(n: usize) -> crate::Session { + let mut s = crate::Session::new(); + let (f, sid) = marked_frame(&mut s); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut chain: Option = None; + for _ in 0..n { + let mut t = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + if let Some(inner) = chain.take() { + t.cells[0].text.insert_table(0, inner); + } + chain = Some(t); + } + let st = d.story_mut(sid).unwrap(); + let text = &mut Arc::make_mut(st.tables.values_mut().next().unwrap()).cells[0].text; + text.insert_table(text.len(), chain.unwrap()); + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + s + } + let mut s = nested(super::MAX_COPY_DEPTH); + s.execute("edit.duplicate", &json!({})).unwrap(); + let mut s = nested(super::MAX_COPY_DEPTH + 1); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("edit.duplicate", &json!({})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing is copied"); + s.execute("edit.copy", &json!({})).unwrap(); + assert!(s.execute("edit.paste", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().doc, before, "nothing is pasted"); + } + #[test] fn pasted_cross_references_follow_the_pasted_anchors_of_other_stories() { let mut s = crate::Session::new(); @@ -6395,4 +6454,39 @@ mod anchored_copy_tests { assert_eq!(d.story(inner_sid).unwrap().frames, [inner]); assert_reopens(&d); } + + // Each story refers to an anchor in the story anchored in it, which is copied after it. + #[test] + fn cross_references_into_anchored_stories_follow_their_copies() { + let mut d = Document::new(&designcraft_doc::build::NewDocument::default()); + let layer = d.default_layer(); + let mut frame = + |text: &str| d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 50.0, 50.0), layer, text, ParaFormat::default()).unwrap(); + let (host, host_sid) = frame("Host "); + let (inner, inner_sid) = frame("Inner "); + let (deep, deep_sid) = frame("Deep"); + for (into, (id, sid)) in [(inner_sid, (deep, deep_sid)), (host_sid, (inner, inner_sid))] { + let target = d.story_mut(sid).unwrap().insert_anchor(0, "Here"); + let st = d.story_mut(into).unwrap(); + st.insert_xref(st.len(), designcraft_doc::CrossRef { target, ..Default::default() }); + let item = d.item(id).unwrap().clone(); + let story = d.stories.get(&sid).unwrap().clone(); + d.remove_item(id).unwrap(); + d.stories.insert(sid, story); + d.story_mut(into).unwrap().insert_object(0, AnchoredObject { item, position: Default::default() }); + } + d.check().unwrap(); + let src = d.clone(); + let copy = duplicate_from(&mut d, &src, &[host], SpreadRef::Doc(0), Vec2::new(10.0, 10.0)).unwrap(); + let anchored = |sid: StoryId| d.story(sid).unwrap().objects[0].item.text_frame().unwrap().story; + let host_copy = d.item(copy[0]).unwrap().text_frame().unwrap().story; + let inner_copy = anchored(host_copy); + let deep_copy = anchored(inner_copy); + for (refers, dest) in [(host_copy, inner_copy), (inner_copy, deep_copy)] { + let target = d.story(refers).unwrap().xrefs[0].target; + assert_eq!(target, d.story(dest).unwrap().anchors[0].id, "the copied cross-reference points at the copied anchor"); + assert_eq!(d.find_anchor(target).map(|(at, _)| at), Some(dest)); + } + assert_reopens(&d); + } } From 09832b12e8128a02593b52cc347ab581a59b2660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 12:02:45 -0800 Subject: [PATCH 063/328] Copy: skip cross-reference passes for stories without anchors or cross-references Copying many text frames no longer walks every earlier copy for each new story: earlier copies are revisited only when the new story brings text anchors, and the new story's cross-references are mapped only when it holds any. --- crates/engine/src/cmd/object.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index c6b234dda..149a4eab1 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1197,12 +1197,28 @@ fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap bool { + if !st.xrefs.is_empty() { + return true; + } + depth < MAX_COPY_DEPTH + && (st.tables.values().any(|t| t.cells.iter().any(|c| has_xrefs(&c.text, depth + 1))) + || st.notes.iter().chain(&st.endnotes).any(|n| has_xrefs(&n.text, depth + 1))) +} + /// The anchor ids of the stories of `src` that `stories` maps, each to the id of its copy's anchor in `dst`. fn copied_anchors(dst: &Document, src: &Document, stories: &HashMap) -> HashMap { let mut anchors = HashMap::new(); From e4f82e243eaa96591f3d88cb00b341a1b42ef0b3 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:05:45 -0500 Subject: [PATCH 064/328] Place: switching, opening or closing a document leaves the place cursor's tool Review fix for #2309: set_active, add_document and close_document emptied the place cursor but kept the placeGun tool, so the next canvas click failed with 'nothing loaded in the place cursor'. One helper, Session::unload_place_cursor, empties the cursor and its queue and goes back to the Selection tool when the place cursor's tool is active; validate_place_cursor uses it too. Test: changing_documents_unloads_the_place_cursor_and_its_tool. --- ROADMAP.md | 2 +- crates/engine/src/cmd/file/place.rs | 4 +--- crates/engine/src/lib.rs | 9 +++------ crates/engine/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 10 ++++++++++ docs/multi-image-placement.md | 1 + 6 files changed, 43 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index df9b5fea0..b080dfc9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -408,7 +408,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. -- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). Switching, opening or closing a document unloads it too, back to the Selection tool. A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ddad5ba96..081e3bd27 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -313,9 +313,7 @@ fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { } let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); if !valid { - s.loaded = None; - s.loaded_queue.clear(); - s.set_tool("selection"); + s.unload_place_cursor(); return Err(bad(command, "the loaded graphic is no longer in the document")); } Ok(()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 397be3203..33af11c42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -552,8 +552,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.active = Some(i); } } @@ -563,8 +562,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -587,8 +585,7 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..a2751de72 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2127,6 +2127,33 @@ fn undoing_loaded_assets_cancels_every_placement_cursor() { } } +/// Switching, opening or closing a document empties the place cursor and leaves its tool: a click +/// on the canvas then selects, instead of failing with nothing loaded. Another tool stays. +#[test] +fn changing_documents_unloads_the_place_cursor_and_its_tool() { + let changes: [fn(&mut Session); 3] = [ + |s| s.set_active(0), + |s| { + s.execute("file.new", &json!({})).unwrap(); + }, + |s| s.close_document(1), + ]; + for (n, change) in changes.into_iter().enumerate() { + let mut s = session(); + s.execute("file.new", &json!({})).unwrap(); + load_test_images(&mut s, 3); + assert_eq!(s.tool_id(), "placeGun"); + change(&mut s); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty(), "change {n}"); + assert_eq!(s.tool_id(), "selection", "change {n}"); + // Holding another tool, the change keeps it. + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangle"); + s.set_active(0); + assert_eq!(s.tool_id(), "rectangle", "change {n}"); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 6dfd23703..9bde0acfd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -87,6 +87,16 @@ impl Session { } } + /// Empty the place cursor (its graphic and the ones queued after it). Holding the place + /// cursor's tool, go back to the Selection tool: with nothing loaded, a click would only fail. + pub(crate) fn unload_place_cursor(&mut self) { + self.loaded = None; + self.loaded_queue.clear(); + if self.tool_id() == "placeGun" { + self.set_tool("selection"); + } + } + pub fn layout(&self) -> CanvasLayout { match self.active() { Some(st) => CanvasLayout::new(&st.doc, st.editing_parents), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index da8f180bf..ca0d38415 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -7,6 +7,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Click an existing graphic frame to replace its contents. - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. A drag too small for the grid's cells shows and places one frame instead, as an ordinary drag does. - Press Escape or select another tool to cancel the remaining placement. +- Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From d721ef9f62176f0317ca176b7ae1075e2f5c1c2a Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:36:38 -0500 Subject: [PATCH 065/328] Place: a grid previews the cells it places on a rotated spread The preview divided the dragged rectangle on the canvas and the release divided it on the spread, so on a rotated spread two columns previewed across the canvas and landed down it. The preview now takes the release's cells and shows each where it lands on the canvas. --- crates/tools/src/nav.rs | 13 +++++++++---- crates/tools/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index d4925009f..c86fc4fec 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -197,11 +197,16 @@ impl Tool for PlaceGun { // no frame is drawn yet, the loaded cursor shows what lands. let click = (self.cur - a).hypot() < cx.tol(3.0); // A grid draws its cells; one too small for them falls back to the single frame, as the - // release does. - if !click { - let cells = grid_cells(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + // release does. The cells are the release's, worked out on the spread: on a rotated spread + // its columns don't run across the canvas. + if !click && let Some((sr, sa)) = cx.layout.spread_at(a) { + let cells = grid_cells(designcraft_geom::Rect::from_points(sa, cx.layout.to_spread(sr, self.cur)), self.columns, self.rows); if !cells.is_empty() { - return cells.into_iter().map(crate::Overlay::Marquee).collect(); + let on_canvas = |x: f64, y: f64| cx.layout.to_canvas(sr, Point::new(x, y)); + return cells + .into_iter() + .map(|c| crate::Overlay::Marquee(designcraft_geom::Rect::from_points(on_canvas(c.x0, c.y0), on_canvas(c.x1, c.y1)))) + .collect(); } } let Some(size) = cx.loaded else { diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 6fb3a6af7..9fd67fdd8 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2441,3 +2441,40 @@ fn place_gun_grid_too_small_for_its_cells_previews_and_places_one_frame() { assert_eq!(out, single_out); assert!(matches!(out.as_slice(), [Action::Exec(cmd, _)] if cmd == "place.drop"), "{out:?}"); } + +/// On a rotated spread a place-cursor grid previews the cells it places: worked out on the spread, +/// then shown on the canvas, so two columns on the spread don't preview as two across the canvas. +#[test] +fn place_gun_grid_preview_matches_the_release_on_a_rotated_spread() { + let mut d = Document::new(&NewDocument::default()); + std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = 1; + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let (start, end) = (Point::new(10.0, 10.0), Point::new(210.0, 110.0)); + let (spread, a) = l.spread_at(start).unwrap(); + let b = l.to_spread(spread, end); + let mut t = create("placeGun"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, start.x, start.y)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, end.x, end.y)); + assert_eq!(t.key(&cx, ToolKey::Right, Mods::default()), vec![Action::Handled]); + let shown = t.overlays(&cx); + let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, end.x, end.y)); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2), "{out:?}"); + // Two columns on the spread, 6 pt apart, each shown where its corners land on the canvas. + let r = Rect::from_points(a, b); + let w = (r.width() - 6.0) / 2.0; + let expected: Vec = [r.x0, r.x0 + w + 6.0] + .into_iter() + .map(|x| Overlay::Marquee(Rect::from_points(l.to_canvas(spread, Point::new(x, r.y0)), l.to_canvas(spread, Point::new(x + w, r.y1))))) + .collect(); + assert_eq!(shown.len(), 2, "{shown:?}"); + for (got, want) in shown.iter().zip(&expected) { + let (Overlay::Marquee(got), Overlay::Marquee(want)) = (got, want) else { panic!("{got:?}") }; + for (g, w) in [(got.x0, want.x0), (got.y0, want.y0), (got.x1, want.x1), (got.y1, want.y1)] { + assert!((g - w).abs() < 1e-6, "{shown:?} against {expected:?}"); + } + } + // A quarter turn: the columns stack down the canvas. + let (Overlay::Marquee(first), Overlay::Marquee(second)) = (&shown[0], &shown[1]) else { panic!("{shown:?}") }; + assert!((first.x0 - second.x0).abs() < 1e-6, "{shown:?}"); +} From 92d3e74a3979598137c0dad4d59bf9827aef10a4 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:36:38 -0500 Subject: [PATCH 066/328] Place: a multi-page PDF in a batch keeps the images loaded before it Confirming the PDF's Import Options placed it without append, so in a batch such as [a.png, b.png, multi.pdf] it replaced the images already in the cursor. The dialog now carries append, on both the native and the delivered-file paths. A single multi-page PDF still replaces what the cursor holds. --- crates/ui-egui/src/app/files.rs | 62 +++++++++++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 6 ++-- docs/multi-image-placement.md | 2 +- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..8b1682d83 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -44,7 +44,8 @@ impl DesignApp { let target = self.session.active().map(|d| d.uid); let pages = self.services.read.as_mut().and_then(|r| r(path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); if pages > 1 { - self.ui.dialog = Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target}))); + self.ui.dialog = + Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target, "append": append}))); return Ok(Value::Null); } } @@ -135,10 +136,12 @@ impl DesignApp { self.pending_pdf = None; } - pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String) -> Result { + /// Import Options confirmed for the delivered PDF; a placed one is added to the place cursor + /// when `append`, so the images loaded before it stay. + pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String, append: bool) -> Result { let file = self.pending_pdf.take().ok_or("PDF import cancelled: no pending file")?; self.activate_import_target(&file.request)?; - let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop}); + let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop, "append": append}); if file.request.purpose == "place" { self.place_file(params) } else { self.open_file("file.place", params) } } @@ -243,8 +246,10 @@ impl DesignApp { if place && lower.ends_with(".pdf") { let pages = designcraft_render::pdf_page_count(&file.bytes).unwrap_or(1); if pages > 1 { - self.ui.dialog = - Some(dialogs::Dialog::new("pdfImport", json!({"async": true, "name": file.name.clone(), "page": "1", "pages": pages}))); + self.ui.dialog = Some(dialogs::Dialog::new( + "pdfImport", + json!({"async": true, "name": file.name.clone(), "page": "1", "pages": pages, "append": append}), + )); self.pending_pdf = Some(file); return Ok(Value::Null); } @@ -770,7 +775,7 @@ pub(crate) mod browser_import_tests { app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!(page.to_string())); // The native dialog clamps zero to one; positive invalid pages must fail. if page == 0 { - assert!(app.confirm_pdf_import(page, "crop".into()).is_err()); + assert!(app.confirm_pdf_import(page, "crop".into(), false).is_err()); } else { assert!(dialogs::confirm(&mut app).is_err()); } @@ -908,6 +913,51 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A multi-page PDF after images in a native batch asks which page, then queues after them. + #[test] + fn native_batch_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(vec![path("a.svg"), path("b.svg"), path("three.pdf")]).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "b.svg", "three.pdf"]); + } + + /// The same for files delivered by the host (a browser's Place): the images stay. + #[test] + fn inbox_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("b.png", png(90)), ("three.pdf", pdf_pages(3))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); + } + + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. + #[test] + fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("three.pdf").to_string_lossy().to_string(); + std::fs::write(&path, pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("place.load", json!({"base64": b64, "name": "a.svg"})).unwrap(); + app.open_picked("place", path).unwrap(); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["three.pdf"]); + } + #[test] fn batch_cancel_status_uses_the_interface_language() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7662c0cb0..460a4bc71 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4630,12 +4630,14 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { }, }; if d.b("async") { - return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }); + return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }, d.b("append")); } if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file(json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }})) + app.place_file( + json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), + ) } "print" => { let pages = if d.s("range") == "all" { Value::Null } else { json!(d.s("pages")) }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index ca0d38415..cae08a519 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 267917b8de223df327e336e79c4ca646eda4de1e Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:56:22 -0500 Subject: [PATCH 067/328] Place: drops that arrive before one UI pass stay separate All pending drops went into one batch, so two single images counted as several: both queued and neither filled the frame it was dropped on. Files of one raw input now share a batch, and each batch is opened on its own. --- crates/ui-egui/src/app/input.rs | 13 +++++++------ crates/ui-egui/src/lib.rs | 3 +++ crates/ui-egui/src/tests.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 465eeaaff..fe5fb673b 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -62,10 +62,11 @@ impl DesignApp { // A drop without pointer events (dragged in from another application) asks the // system now, while the pointer is still where the files were let go. let system = if pointer.is_none() && !raw.dropped_files.is_empty() { self.system_pointer(ctx, raw) } else { None }; + let batch = self.pending_drops.last().map_or(0, |d| d.batch.wrapping_add(1)); for file in std::mem::take(&mut raw.dropped_files) { let path = file.path().to_string_lossy().to_string(); if !path.is_empty() { - self.pending_drops.push(PendingDrop { path, pointer, system, generation }); + self.pending_drops.push(PendingDrop { path, pointer, system, batch, generation }); } } } @@ -154,12 +155,12 @@ impl DesignApp { // suppress later files that belong to the same captured batch. let current = self.input_generation(); let drops: Vec<_> = std::mem::take(&mut self.pending_drops).into_iter().filter(|d| d.generation == current).collect(); - if drops.is_empty() { - return; - } // Dropped together, they go together: several images load the place cursor at once. Each - // file keeps the pointer it was dropped at, or the system's from when it arrived. - self.open_dropped_batch(drops.into_iter().map(|d| (d.path, d.pointer.or(d.system))).collect()); + // file keeps the pointer it was dropped at, or the system's from when it arrived. Separate + // drops stay separate, so a single image still fills the frame it was dropped on. + for batch in drops.chunk_by(|a, b| a.batch == b.batch) { + self.open_dropped_batch(batch.iter().map(|d| (d.path.clone(), d.pointer.or(d.system))).collect()); + } } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 531a8dbe7..239127c3b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -115,6 +115,9 @@ struct PendingDrop { /// for a drop that brought no pointer events ([`crate::Services::pointer`]). Each drop keeps /// its own, converted with the window's place and the UI scale of that input. system: Option, + /// Which drop this file came with: files of one raw input share it, so drops that arrive + /// before the same UI pass stay separate. + batch: u64, generation: InputGeneration, } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 5692ba7fe..39534b0eb 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1011,6 +1011,37 @@ fn a_pointerless_drop_keeps_the_system_pointer_of_its_own_input() { assert!(d.assets[&g.asset].name.contains("drop-own-input")); } +/// Two drops that arrive before one UI pass stay separate: the first still fills the frame it was +/// dropped on, and the second, off any frame, loads the place cursor. Merged, they'd both queue. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn separate_drops_before_one_pass_are_not_one_batch() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let at = std::rc::Rc::new(std::cell::Cell::new(inside)); + let reported = at.clone(); + app.services.pointer = Some(Box::new(move || Some(reported.get()))); + let ctx = egui::Context::default(); + let window = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let (first, second) = (dropped_png("separate-drop-a"), dropped_png("separate-drop-b")); + let mut raw = pointerless_drop(&first, window); + app.raw_input_hook(&ctx, &mut raw); + at.set(outside); + let mut raw = pointerless_drop(&second, window); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 2); + ctx.run_ui(raw, |_| app.take_pending_drops()).textures_delta.clear(); + let _ = std::fs::remove_file(&first); + let _ = std::fs::remove_file(&second); + let d = &app.session.doc().unwrap().doc; + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { + panic!("the first drop fills the frame it was dropped on") + }; + assert!(d.assets[&g.asset].name.contains("separate-drop-a")); + let loaded = app.session.loaded.as_ref().expect("the second drop loads the place cursor"); + assert!(d.assets[&loaded.asset].name.contains("separate-drop-b")); + assert!(app.session.loaded_queue.is_empty()); +} + /// A filled compound path (Object > Compound Paths > Make) is a frame a dropped image fills, as /// in InDesign, through its ring and not its hole. #[test] From 391e0881b4e75294694916c1a8aa01f1e400bb08 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:56:42 -0500 Subject: [PATCH 068/328] Place: the grid tool sends the gutter it previews The preview's 6 pt duplicated place.grid's default, so changing one would leave the preview out of step with what lands. The tool now sends its gutter with the command. --- crates/tools/src/nav.rs | 5 +++-- crates/tools/src/tests.rs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index c86fc4fec..456c73ba9 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -155,7 +155,7 @@ impl Tool for PlaceGun { if !grid_cells(r, self.columns, self.rows).is_empty() { return vec![Action::Exec( "place.grid".into(), - json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), + json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows, "gutter": PLACE_GRID_GUTTER}), )]; } // The frame the drag drew: at the graphic's proportions from where it started. @@ -239,7 +239,8 @@ Y: {pct}" } } -/// The gutter between place-grid cells, in points: `place.grid`'s default. +/// The gutter between place-grid cells, in points. The tool sends it with `place.grid`, so the +/// preview and what lands can't disagree if the command's default changes. const PLACE_GRID_GUTTER: f64 = 6.0; /// The cells of a `columns` × `rows` place grid drawn over `rect`, [`PLACE_GRID_GUTTER`] apart, as diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 9fd67fdd8..4949e20e4 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2459,7 +2459,7 @@ fn place_gun_grid_preview_matches_the_release_on_a_rotated_spread() { assert_eq!(t.key(&cx, ToolKey::Right, Mods::default()), vec![Action::Handled]); let shown = t.overlays(&cx); let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, end.x, end.y)); - assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2), "{out:?}"); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2 && p["gutter"] == 6.0), "{out:?}"); // Two columns on the spread, 6 pt apart, each shown where its corners land on the canvas. let r = Rect::from_points(a, b); let w = (r.width() - 6.0) / 2.0; From 078b8bdcd2b1c87ada6e299a47e1d3dc37d145d7 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 5 Nov 2026 12:15:32 +0500 Subject: [PATCH 069/328] Data Merge: a field in a table cell goes into the cell and is filled (#2315) With the insertion point in a table cell, data.placeholder.add took the selection's offsets, which are the cell's, as offsets into the table's own story, so the marker landed outside the table. The fill only read each story's own text, so a field in a cell, inserted or converted from text, was left as its marker. A field inserted in a cell now goes into the cell's text as its marker, and the fill replaces the markers in the table cells and footnotes of the stories it fills. --- crates/engine/src/cmd/datamerge.rs | 14 +++++++ crates/engine/src/cmd/datamerge/fill.rs | 39 ++++++++++++++++++ crates/engine/src/cmd/datamerge/tests.rs | 52 ++++++++++++++++++++++++ 3 files changed, 105 insertions(+) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 4d3cd5dd6..e834127fd 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -482,6 +482,20 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); } + // The insertion point is in a table cell: the field goes into the cell's text as its + // marker, which the merge fills as it fills a typed one. A cell's text is a story of its + // own that a placeholder can't name, and the selection's offsets are the cell's, so they + // used to put the marker in the table's story instead (#2315). + if !explicit_story && let Some(t) = sel.text.filter(|t| t.cell.is_some()) { + if role != PlaceholderRole::Text { + return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell; insert it as text")); + } + let marker = format!("<<{name}>>"); + let st = d.text_story_mut(t.story, t.cell).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; + let at = designcraft_doc::floor_char_boundary(&st.text, t.range().start.min(st.text.len())); + st.replace(at..at, &marker); + return Ok(json!({"cell": true, "marker": marker})); + } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; if d.story(story).is_none() { return Err(bad("data.placeholder.add", "no story")); diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 825179ac9..288dbf44f 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -228,6 +228,7 @@ pub fn fill_row( let Pending { mut reps, links, parent, mut report } = pending; typed_reps(doc, fields, row, maps, &placeholders, &mut reps); apply_reps(doc, &reps); + fill_nested_markers(doc, fields, row, maps); for (anchor, dest, field) in links { let anchor = match anchor { PlaceholderAnchor::Text { story, start, end } => { @@ -331,6 +332,44 @@ fn typed_reps( } } +/// The `<>` markers in the table cells and footnotes of the stories being filled. A cell's +/// or a footnote's text is a story of its own inside its story, which no placeholder can name and +/// `typed_reps` doesn't read, so a field in a table was left as its marker (#2315). Only a table +/// or note that holds a marker is copied. +fn fill_nested_markers(doc: &mut designcraft_doc::Document, fields: &[DataField], row: &[String], maps: &Maps) { + let fill = |st: &mut Story| { + let found: Vec<(usize, usize, String)> = + find_markers(&st.text).into_iter().filter(|(_, _, name)| fields.iter().any(|f| f.name == *name)).collect(); + for (start, end, name) in found.into_iter().rev() { + st.replace(start..end, cell_of(fields, row, &name)); + } + }; + let has = |st: &Story| find_markers(&st.text).iter().any(|(_, _, name)| fields.iter().any(|f| f.name == *name)); + let mut mapped: Vec = maps.stories.values().copied().collect(); + mapped.sort(); + mapped.dedup(); + for sid in mapped { + let Some(st) = doc.story_mut(sid) else { continue }; + for t in st.tables.values_mut() { + if t.cells.iter().any(|c| nested_has(&c.text, &has)) { + for c in &mut Arc::make_mut(t).cells { + c.text.for_each_text_mut(&mut |x| fill(x)); + } + } + } + for n in &mut st.notes { + if nested_has(&n.text, &has) { + Arc::make_mut(n).text.for_each_text_mut(&mut |x| fill(x)); + } + } + } +} + +/// Whether `st` or a text inside it (its table cells and notes) satisfies `has`. +fn nested_has(st: &Story, has: &impl Fn(&Story) -> bool) -> bool { + has(st) || st.tables.values().any(|t| t.cells.iter().any(|c| nested_has(&c.text, has))) || st.notes.iter().any(|n| nested_has(&n.text, has)) +} + fn find_markers(text: &str) -> Vec<(usize, usize, String)> { let mut out = Vec::new(); let mut i = 0; diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index e2c76a90f..66eaea7de 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1285,3 +1285,55 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +/// The cell texts of the first table in the active document's first story that has one. +fn cell_texts(s: &Session) -> Vec { + let doc = &s.documents()[s.active_index().unwrap()].doc; + let t = doc.stories.values().find_map(|st| st.tables.values().next().cloned()).expect("a table"); + t.cells.iter().map(|c| c.text.text.clone()).collect() +} + +/// A field inserted with the insertion point in a table cell goes into that cell, and the +/// preview and the merge fill it. The cell's offsets used to put the marker in the table's own +/// story, outside the table, and the merge never read a cell's text (#2315). +#[test] +fn a_field_inserted_in_a_table_cell_goes_there_and_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\nGrace,Arlington\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + let story_text = |s: &Session| s.documents()[s.active_index().unwrap()].doc.stories.values().next().unwrap().text.clone(); + let before = story_text(&s); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + let r = exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "the marker is in the cell with the caret"); + assert_eq!(story_text(&s), before, "and not in the table's story"); + + exec(&mut s, "data.preview", json!({"record": 2})); + assert_eq!(cell_texts(&s), ["Who", "ArlingtonWhere"], "the preview fills the cell"); + exec(&mut s, "data.preview.stop", json!({})); + assert_eq!(cell_texts(&s), ["Who", "<>Where"], "stopping it puts the marker back"); + exec(&mut s, "data.merge", json!({})); + let merged = &s.documents()[s.active_index().unwrap()].doc; + let mut cities: Vec = + merged.stories.values().flat_map(|st| st.tables.values().map(|t| t.cells[1].text.text.clone()).collect::>()).collect(); + cities.sort(); + assert_eq!(cities, ["ArlingtonWhere", "LondonWhere"], "one table per record, filled"); +} + +/// A field typed (or inserted) in text that is then converted to a table is filled in its cell. +#[test] +fn a_field_converted_into_a_table_is_filled_in_its_cell() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "Name\t<>", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 13})); + exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"})); + assert_eq!(cell_texts(&s), ["Name", "<>"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Name", "Ada"], "the field is filled in its cell"); +} From 3eb83555820ebaf8df105e3284b273a619234b4e Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:42:43 +0000 Subject: [PATCH 070/328] Apply review fixes - crates/engine/src/cmd/datamerge/fill.rs --- crates/engine/src/cmd/datamerge/fill.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 288dbf44f..fdde21825 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -349,6 +349,11 @@ fn fill_nested_markers(doc: &mut designcraft_doc::Document, fields: &[DataField] mapped.sort(); mapped.dedup(); for sid in mapped { + if !doc.story(sid).is_some_and(|st| { + st.tables.values().any(|t| t.cells.iter().any(|c| nested_has(&c.text, &has))) || st.notes.iter().any(|n| nested_has(&n.text, &has)) + }) { + continue; + } let Some(st) = doc.story_mut(sid) else { continue }; for t in st.tables.values_mut() { if t.cells.iter().any(|c| nested_has(&c.text, &has)) { From d22331c60f3c7518fdb7d9c861805a0bdc240da0 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 07:50:55 +0000 Subject: [PATCH 071/328] Apply review fixes - crates/engine/src/cmd/datamerge.rs --- crates/engine/src/cmd/datamerge.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index e834127fd..28c3be75f 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -434,7 +434,7 @@ fn overset_count(doc: &Document) -> usize { .count() } -fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> Result { +fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) -> Result { let (source_id, field) = { let source = d.data_merge.sources.first().ok_or_else(|| bad("data.placeholder.add", "select a data source"))?; let field = @@ -490,10 +490,21 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> if role != PlaceholderRole::Text { return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell; insert it as text")); } + if name.contains(['<', '>', '\n']) { + return Err(bad("data.placeholder.add", "this field's name can't be used in a table cell")); + } let marker = format!("<<{name}>>"); - let st = d.text_story_mut(t.story, t.cell).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; + let cell = t.cell.map(|c| { + d.story(t.story).and_then(|st| st.tables.get(&c.table)).map_or(c, |tb| { + let (row, col) = tb.owner(c.row, c.col); + designcraft_doc::CellAddr { row, col, ..c } + }) + }); + let st = d.text_story_mut(t.story, cell).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; let at = designcraft_doc::floor_char_boundary(&st.text, t.range().start.min(st.text.len())); st.replace(at..at, &marker); + let caret = at + marker.len(); + *sel = Selection::text(designcraft_doc::TextSel { anchor: caret, focus: caret, cell, ..t }); return Ok(json!({"cell": true, "marker": marker})); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; From 12106c76000f1a11858f89798853f29a734be39e Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 5 Nov 2026 12:54:12 +0500 Subject: [PATCH 072/328] Data Merge: a field in a cell leaves the caret after it, goes into a merged cell, refuses a name a marker can't hold; endnotes are filled; the walk is bounded From review: after inserting a field in a cell the cell selection stayed, so the next keystroke replaced the cell; the caret now follows the field. A covered position resolves to its merged cell. A field name with < > or a line break can't be read back from a marker, so it isn't inserted in a cell. Endnote texts are filled like footnotes, and nested texts are followed to MAX_NESTED_DEPTH (32). --- crates/engine/src/cmd/datamerge.rs | 47 ++++++---- crates/engine/src/cmd/datamerge/fill.rs | 80 ++++++++++------ crates/engine/src/cmd/datamerge/tests.rs | 113 +++++++++++++++++++++++ 3 files changed, 195 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 28c3be75f..28855d8ea 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -482,29 +482,40 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); } - // The insertion point is in a table cell: the field goes into the cell's text as its - // marker, which the merge fills as it fills a typed one. A cell's text is a story of its - // own that a placeholder can't name, and the selection's offsets are the cell's, so they - // used to put the marker in the table's story instead (#2315). - if !explicit_story && let Some(t) = sel.text.filter(|t| t.cell.is_some()) { + // The insertion point is in a table cell or a footnote: the field goes into that text as + // its marker, which the merge fills as it fills a typed one. Such a text is a story of its + // own that a placeholder can't name, and the selection's offsets are its own, so they used + // to put the marker in the table's story instead (#2315). + if !explicit_story + && let Some(t) = sel.text + && let Some(pressed) = t.cell + { if role != PlaceholderRole::Text { - return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell; insert it as text")); + return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell or a note; insert it as text")); } - if name.contains(['<', '>', '\n']) { - return Err(bad("data.placeholder.add", "this field's name can't be used in a table cell")); + // The merge finds a marker by its name, so a name that can't be read back out of one + // would stay a marker: say so rather than insert it. + if name.is_empty() || name.contains(['<', '>', '\n']) { + return Err(bad( + "data.placeholder.add", + format!("the field \"{name}\" can't be inserted in a table cell or a note: its name holds < > or a line break"), + )); } - let marker = format!("<<{name}>>"); - let cell = t.cell.map(|c| { - d.story(t.story).and_then(|st| st.tables.get(&c.table)).map_or(c, |tb| { - let (row, col) = tb.owner(c.row, c.col); - designcraft_doc::CellAddr { row, col, ..c } - }) + // A position a merged cell covers is the merged cell's: the field goes where it shows. + let cell = d.story(t.story).and_then(|st| st.tables.get(&pressed.table)).map_or(pressed, |tab| { + let (row, col) = tab.owner(pressed.row, pressed.col); + designcraft_doc::CellAddr { row, col, ..pressed } }); - let st = d.text_story_mut(t.story, cell).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; - let at = designcraft_doc::floor_char_boundary(&st.text, t.range().start.min(st.text.len())); + let marker = format!("<<{name}>>"); + let st = d.text_story_mut(t.story, Some(cell)).ok_or_else(|| bad("data.placeholder.add", "no table cell there"))?; + let at = if cell == pressed { t.range().start.min(st.text.len()) } else { st.text.len() }; + let at = designcraft_doc::floor_char_boundary(&st.text, at); st.replace(at..at, &marker); - let caret = at + marker.len(); - *sel = Selection::text(designcraft_doc::TextSel { anchor: caret, focus: caret, cell, ..t }); + // The caret goes after the field, in that text, as after typing; a cell selection + // would have the next keystroke replace the whole cell, field and all. + let end = at + marker.len(); + sel.cells = None; + sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, cell: Some(cell), ..t }); return Ok(json!({"cell": true, "marker": marker})); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index fdde21825..38da7eada 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -332,47 +332,73 @@ fn typed_reps( } } -/// The `<>` markers in the table cells and footnotes of the stories being filled. A cell's -/// or a footnote's text is a story of its own inside its story, which no placeholder can name and -/// `typed_reps` doesn't read, so a field in a table was left as its marker (#2315). Only a table -/// or note that holds a marker is copied. +/// How deep the merge follows texts inside texts (a table in a cell of a table, a note in a cell). +/// Documents don't come anywhere near it; a file that goes deeper is filled down to here instead of +/// exhausting the stack. +pub(super) const MAX_NESTED_DEPTH: usize = 32; + +/// The `<>` markers in the table cells, footnotes and endnotes of the stories being filled. +/// Those texts are stories inside their story, which no placeholder can name and `typed_reps` +/// doesn't read, so a field in a table was left as its marker (#2315). A story, table or note is +/// copied only when something inside it holds a marker of a known field. fn fill_nested_markers(doc: &mut designcraft_doc::Document, fields: &[DataField], row: &[String], maps: &Maps) { - let fill = |st: &mut Story| { - let found: Vec<(usize, usize, String)> = - find_markers(&st.text).into_iter().filter(|(_, _, name)| fields.iter().any(|f| f.name == *name)).collect(); - for (start, end, name) in found.into_iter().rev() { - st.replace(start..end, cell_of(fields, row, &name)); - } - }; - let has = |st: &Story| find_markers(&st.text).iter().any(|(_, _, name)| fields.iter().any(|f| f.name == *name)); let mut mapped: Vec = maps.stories.values().copied().collect(); mapped.sort(); mapped.dedup(); for sid in mapped { - if !doc.story(sid).is_some_and(|st| { - st.tables.values().any(|t| t.cells.iter().any(|c| nested_has(&c.text, &has))) || st.notes.iter().any(|n| nested_has(&n.text, &has)) - }) { + if !doc.story(sid).is_some_and(|st| inner_has(st, fields, 0)) { continue; } let Some(st) = doc.story_mut(sid) else { continue }; - for t in st.tables.values_mut() { - if t.cells.iter().any(|c| nested_has(&c.text, &has)) { - for c in &mut Arc::make_mut(t).cells { - c.text.for_each_text_mut(&mut |x| fill(x)); - } + fill_inner(st, fields, row, 0); + } +} + +/// Whether `st`'s own text holds a marker of a known field. +fn own_has(st: &Story, fields: &[DataField]) -> bool { + find_markers(&st.text).iter().any(|(_, _, name)| fields.iter().any(|f| f.name == *name)) +} + +/// Whether a text inside `st` (a table cell, footnote or endnote, or one inside those), not `st`'s +/// own text, holds a marker of a known field. +fn inner_has(st: &Story, fields: &[DataField], depth: usize) -> bool { + if depth >= MAX_NESTED_DEPTH { + return false; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + st.tables.values().any(|t| t.cells.iter().any(|c| holds(&c.text))) || st.notes.iter().chain(&st.endnotes).any(|n| holds(&n.text)) +} + +/// Fill the known fields' markers in the texts inside `st`, not in its own text. +fn fill_inner(st: &mut Story, fields: &[DataField], row: &[String], depth: usize) { + if depth >= MAX_NESTED_DEPTH { + return; + } + let holds = |t: &Story| own_has(t, fields) || inner_has(t, fields, depth + 1); + for t in st.tables.values_mut() { + if t.cells.iter().any(|c| holds(&c.text)) { + for c in &mut Arc::make_mut(t).cells { + fill_own(&mut c.text, fields, row); + fill_inner(&mut c.text, fields, row, depth + 1); } } - for n in &mut st.notes { - if nested_has(&n.text, &has) { - Arc::make_mut(n).text.for_each_text_mut(&mut |x| fill(x)); - } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + if holds(&n.text) { + let n = Arc::make_mut(n); + fill_own(&mut n.text, fields, row); + fill_inner(&mut n.text, fields, row, depth + 1); } } } -/// Whether `st` or a text inside it (its table cells and notes) satisfies `has`. -fn nested_has(st: &Story, has: &impl Fn(&Story) -> bool) -> bool { - has(st) || st.tables.values().any(|t| t.cells.iter().any(|c| nested_has(&c.text, has))) || st.notes.iter().any(|n| nested_has(&n.text, has)) +/// Replace the markers of known fields in `st`'s own text with the record's values. +fn fill_own(st: &mut Story, fields: &[DataField], row: &[String]) { + let found: Vec<(usize, usize, String)> = + find_markers(&st.text).into_iter().filter(|(_, _, name)| fields.iter().any(|f| f.name == *name)).collect(); + for (start, end, name) in found.into_iter().rev() { + st.replace(start..end, cell_of(fields, row, &name)); + } } fn find_markers(text: &str) -> Vec<(usize, usize, String)> { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 66eaea7de..119e159d2 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1337,3 +1337,116 @@ fn a_field_converted_into_a_table_is_filled_in_its_cell() { exec(&mut s, "data.preview", json!({"record": 1})); assert_eq!(cell_texts(&s), ["Name", "Ada"], "the field is filled in its cell"); } + +/// A table `Who⇥Where` with the caret in its second cell, and a source with `Name` and `City`. +fn table_with_caret_in_cell(s: &mut Session, csv: &str) -> Value { + new_doc(s, 1); + select_csv(s, csv); + let made = text_frame(s, [36.0, 36.0, 400.0, 200.0], "Who\tWhere", None); + exec(s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 9})); + exec(s, "table.convertFromText", json!({"columnSeparator": "tab"})); + exec(s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + made +} + +/// After a field goes into a cell the caret is after it, in that cell, and the cell selection is +/// gone: typing goes on after the field instead of replacing the cell, field and all. +#[test] +fn typing_after_a_field_inserted_in_a_cell_goes_on_after_it() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let sel = &s.documents()[s.active_index().unwrap()].selection; + assert!(sel.cells.is_none(), "no cell selection left"); + exec(&mut s, "text.insert", json!({"text": ", "})); + assert_eq!(cell_texts(&s), ["Who", "<>, Where"]); +} + +/// A position that a merged cell covers is the merged cell's: the field goes into the merged cell, +/// where it shows, not into the hidden one under it. +#[test] +fn a_field_inserted_in_a_merged_cell_goes_where_it_shows() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Name,City\nAda,London\n"); + exec(&mut s, "table.merge", json!({"story": made["story"], "rows": [0, 0], "cols": [0, 1]})); + exec(&mut s, "table.select", json!({"story": made["story"], "rows": [0, 0], "cols": [1, 1]})); + exec(&mut s, "data.placeholder.add", json!({"field": "City"})); + let cells = cell_texts(&s); + assert!(cells[0].contains("<>"), "in the merged cell: {cells:?}"); + assert!(!cells[1].contains("<>"), "not in the covered one: {cells:?}"); + exec(&mut s, "data.preview", json!({"record": 1})); + assert!(cell_texts(&s)[0].contains("London"), "and filled: {:?}", cell_texts(&s)); +} + +/// A field whose name a marker can't hold (it has `<` or `>`) can't be filled from a cell, so it +/// isn't inserted there; in body text it still becomes an anchored placeholder. +#[test] +fn a_field_named_with_angle_brackets_is_refused_in_a_cell() { + let mut s = Session::new(); + let made = table_with_caret_in_cell(&mut s, "Customer ,City\n7,London\n"); + let e = s.execute("data.placeholder.add", &json!({"field": "Customer "})).expect_err("refused").to_string(); + assert!(e.contains("can't be inserted in a table cell"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + let other = text_frame(&mut s, [36.0, 300.0, 400.0, 400.0], "No. ", None); + exec(&mut s, "text.select", json!({"story": other["story"], "anchor": 4, "focus": 4})); + assert!(exec(&mut s, "data.placeholder.add", json!({"field": "Customer "}))["id"].is_u64(), "body text still takes it"); + let _ = made; +} + +/// Endnote text is filled too: it is a text inside its story, like a footnote's. +#[test] +fn a_field_in_an_endnote_is_filled() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "See the note", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 12, "focus": 12})); + exec(&mut s, "endnote.insert", json!({"text": "From <>"})); + let endnotes = |s: &Session| -> Vec { + s.documents()[s.active_index().unwrap()].doc.stories.values().flat_map(|st| st.endnotes.iter().map(|e| e.text.text.clone())).collect() + }; + assert_eq!(endnotes(&s), ["From <>"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(endnotes(&s), ["From London"]); +} + +/// Tables nested in cells far deeper than any document goes are filled down to the merge's depth +/// limit, and the preview returns instead of exhausting the stack. +#[test] +fn deeply_nested_tables_are_filled_down_to_the_limit_without_overflowing() { + use designcraft_doc::{Cell, ParaFormat, Table}; + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City\nAda,London\n"); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 200.0], "x", None); + let sid = StoryId(made["story"].as_u64().unwrap()); + // `depth` tables, each in the one cell of the next, each cell's own text `<>`. + let nest = |depth: usize| { + let mut inner: Option = None; + for i in 0..depth { + let mut t = Table::new(1000 + i as u64, 1, 1, 0, 0, 100.0); + t.cells[0] = Cell::with_text("<>", ParaFormat::default()); + if let Some(child) = inner.take() { + t.cells[0].text.insert_table(0, child); + } + inner = Some(t); + } + inner.unwrap() + }; + s.edit(|d, _| { + d.story_mut(sid).unwrap().insert_table(0, nest(500)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "data.preview", json!({"record": 1})); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let mut t = doc.story(sid).unwrap().tables.values().next().unwrap().clone(); + let mut filled = Vec::new(); + for _ in 0..40 { + filled.push(t.cells[0].text.text.contains("Ada")); + let Some(next) = t.cells[0].text.tables.values().next().cloned() else { break }; + t = next; + } + assert!(filled[..super::fill::MAX_NESTED_DEPTH].iter().all(|f| *f), "filled down to the limit: {filled:?}"); + assert!(!filled[super::fill::MAX_NESTED_DEPTH], "and not past it"); +} From 72877fae246ca6c206835488ebd22b1571f4fc81 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 08:09:17 +0000 Subject: [PATCH 073/328] Apply review fixes - crates/engine/src/cmd/datamerge.rs --- crates/engine/src/cmd/datamerge.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 28855d8ea..f8d6d12a3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -60,7 +60,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder)", has_doc, placeholder_add ), From 1191a1df52fc6e0003b41f347521cdb35add46c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 5 Nov 2026 05:35:51 -0800 Subject: [PATCH 074/328] Reject ambiguous table targets --- crates/engine/src/cmd/table/registry.rs | 2 +- crates/engine/src/cmd/table/target.rs | 25 ++++++++-- crates/engine/src/tests/table.rs | 63 +++++++++++++++++++++++++ crates/ui-egui/src/panels/table.rs | 11 +++-- docs/mcp.md | 6 +++ 5 files changed, 96 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/table/registry.rs b/crates/engine/src/cmd/table/registry.rs index 0a8166f89..aca8b2cd4 100644 --- a/crates/engine/src/cmd/table/registry.rs +++ b/crates/engine/src/cmd/table/registry.rs @@ -407,6 +407,6 @@ fn table_specs() -> Vec { in_cell, |s, _| toggle_selection(s) ), - cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options", in_table_or_ids, get), + cmd!(query "table.get", "Get Table", [], None, "{story?, table?, rows?: [a,b] | row?, cols?: [a,b] | col?} → rows, columns, cells (text, spans, fill), options. Supplied `story` and `table` values must be nonnegative integer IDs. When a table ID occurs in multiple stories, supply `story` with `table`.", in_table_or_ids, get), ] } diff --git a/crates/engine/src/cmd/table/target.rs b/crates/engine/src/cmd/table/target.rs index 2e1784560..9f3d08bfc 100644 --- a/crates/engine/src/cmd/table/target.rs +++ b/crates/engine/src/cmd/table/target.rs @@ -41,8 +41,20 @@ pub(super) struct Tgt { pub(super) range: CellRange, } -fn find_table(doc: &Document, id: u64) -> Option { - doc.stories.iter().find(|(_, s)| s.tables.contains_key(&id)).map(|(k, _)| *k) +fn find_table(doc: &Document, id: u64, cmd: &str) -> Result { + let mut stories = doc.stories.iter().filter(|(_, story)| story.tables.contains_key(&id)).map(|(sid, _)| *sid); + let first = stories.next().ok_or_else(|| bad(cmd, format!("no table {id}")))?; + if stories.next().is_some() { + return Err(bad(cmd, format!("table {id} exists in multiple stories; specify `story`"))); + } + Ok(first) +} + +fn id_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None => Ok(None), + Some(value) => value.as_u64().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a nonnegative integer"))), + } } fn pair(p: &Value, many: &str, one: &str) -> Option<(usize, usize)> { @@ -57,10 +69,13 @@ fn pair(p: &Value, many: &str, one: &str) -> Option<(usize, usize)> { pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result { let st = s.doc()?; let doc = &st.doc; - let explicit_table = p.get("table").and_then(Value::as_u64); - let explicit_story = p.get("story").and_then(Value::as_u64).map(StoryId); + let explicit_table = id_param(p, "table", cmd)?; + let explicit_story = id_param(p, "story", cmd)?.map(StoryId); let (story, table, range) = if let Some(tid) = explicit_table { - let sid = explicit_story.or_else(|| find_table(doc, tid)).ok_or_else(|| bad(cmd, format!("no table {tid}")))?; + let sid = match explicit_story { + Some(sid) => sid, + None => find_table(doc, tid, cmd)?, + }; (sid, tid, None) } else if let Some(c) = st.selection.cells { (c.story, c.table, Some(c.range)) diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 77bcb9bfd..3ccc66789 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -17,6 +17,69 @@ fn check(s: &Session) { s.doc().unwrap().doc.check().unwrap(); } +#[test] +fn table_id_without_story_rejects_multiple_matching_stories() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let first = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap(); + let first_story = first["story"].as_u64().unwrap(); + let shared_id = s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap()["table"].as_u64().unwrap(); + let second = s.execute("frame.create", &json!({"rect": [320, 36, 580, 200], "content": "text"})).unwrap(); + let second_story = second["story"].as_u64().unwrap(); + let second_id = s.execute("table.insert", &json!({"rows": 2, "cols": 1})).unwrap()["table"].as_u64().unwrap(); + s.edit(|d, _| { + let story = d.story_mut(doc::StoryId(second_story)).unwrap(); + let mut table = (*story.tables.remove(&second_id).unwrap()).clone(); + table.id = shared_id; + story.tables.insert(shared_id, std::sync::Arc::new(table)); + for para in &mut story.paras { + if para.table == Some(second_id) { + para.table = Some(shared_id); + } + } + Ok(()) + }) + .unwrap(); + check(&s); + + let error = s.execute("table.get", &json!({"table": shared_id})).unwrap_err(); + assert!(error.to_string().contains("multiple stories"), "{error}"); + assert!(error.to_string().contains("story"), "{error}"); + assert_eq!(s.execute("table.get", &json!({"story": first_story, "table": shared_id})).unwrap()["rows"].as_array().unwrap().len(), 1); + assert_eq!(s.execute("table.get", &json!({"story": second_story, "table": shared_id})).unwrap()["rows"].as_array().unwrap().len(), 2); +} + +#[test] +fn table_target_rejects_wrong_typed_story_and_table_ids() { + let (mut s, story, _) = session_with_frame(); + let table = s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap()["table"].as_u64().unwrap(); + for (key, value) in [ + ("story", json!("other")), + ("story", json!("")), + ("story", json!(-1)), + ("story", json!(1.5)), + ("story", Value::Null), + ("table", json!("other")), + ("table", json!("")), + ("table", json!(-1)), + ("table", json!(1.5)), + ("table", Value::Null), + ] { + let mut params = json!({"story": story, "table": table}); + params[key] = value; + let error = s.execute("table.get", ¶ms).unwrap_err(); + assert!(error.to_string().contains(&format!("`{key}`")), "{key}: {error}"); + } + let undo = s.doc().unwrap().history.undo.len(); + let error = s.execute("table.setCell", &json!({"story": null, "table": table, "insets": 7})).unwrap_err(); + assert!(error.to_string().contains("`story`"), "{error}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + for params in [json!({"story": story, "table": u64::MAX}), json!({"story": u64::MAX, "table": table})] { + let error = s.execute("table.get", ¶ms).unwrap_err(); + assert!(error.to_string().contains("no table"), "{error}"); + } +} + #[test] fn table_text_replacement_floors_utf8_selection_and_allows_quote_typing() { for (original, (a, b), replacement, (after_a, after_b), quoted) in [ diff --git a/crates/ui-egui/src/panels/table.rs b/crates/ui-egui/src/panels/table.rs index 90cf274ea..ef99bcce3 100644 --- a/crates/ui-egui/src/panels/table.rs +++ b/crates/ui-egui/src/panels/table.rs @@ -26,6 +26,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let cols = info["columns"].as_array().cloned().unwrap_or_default(); let range = info["range"].clone(); let (r0, c0) = (range["r0"].as_u64().unwrap_or(0) as usize, range["c0"].as_u64().unwrap_or(0) as usize); + let sid = info["story"].clone(); let tid = info["table"].clone(); let cell = info["cells"].as_array().and_then(|cs| cs.iter().find(|c| c["row"] == r0 && c["col"] == c0)).cloned().unwrap_or(Value::Null); let run = |app: &mut DesignApp, id: &str, p: Value| { @@ -72,7 +73,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let combo = craft_ui::ComboBox::from_id_salt(("tp_style", kind)).selected_text(&cur).width(130.0).show_ui(ui, |ui| { for n in &names { if ui.selectable_label(*n == cur, n).clicked() { - run(app, &format!("style.{kind}.apply"), json!({"name": n, "table": tid})); + run(app, &format!("style.{kind}.apply"), json!({"name": n, "story": sid, "table": tid})); } } }); @@ -103,10 +104,10 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { run( app, "table.insertRow", - json!({"table": tid, "rows": [rows.len() - 1, rows.len() - 1], "where": "below", "count": n - rows.len()}), + json!({"story": sid, "table": tid, "rows": [rows.len() - 1, rows.len() - 1], "where": "below", "count": n - rows.len()}), ); } else if n < rows.len() { - run(app, "table.deleteRow", json!({"table": tid, "rows": [n, rows.len() - 1]})); + run(app, "table.deleteRow", json!({"story": sid, "table": tid, "rows": [n, rows.len() - 1]})); } } caption(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table")); @@ -116,10 +117,10 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { run( app, "table.insertColumn", - json!({"table": tid, "cols": [cols.len() - 1, cols.len() - 1], "where": "right", "count": n - cols.len()}), + json!({"story": sid, "table": tid, "cols": [cols.len() - 1, cols.len() - 1], "where": "right", "count": n - cols.len()}), ); } else if n < cols.len() { - run(app, "table.deleteColumn", json!({"table": tid, "cols": [n, cols.len() - 1]})); + run(app, "table.deleteColumn", json!({"story": sid, "table": tid, "cols": [n, cols.len() - 1]})); } } ui.end_row(); diff --git a/docs/mcp.md b/docs/mcp.md index 61e59df4d..365d2bd9f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -185,6 +185,12 @@ In connected mode every tool maps to a control-channel method (`engine.execute`, what the agent does shows up live in the window. A failed request is not resent: the operation may have completed, so inspect the document before retrying. The next request re-establishes the connection. +## Table targets + +Table IDs can repeat across stories. For `execute` commands that target an existing table, supply `story` with `table` +when an ID repeats. An ambiguous table-only request returns an error. Supplied `story` and `table` values must be +nonnegative integers; `null` and values of other types return an error. + ## Coordinates Points (1/72 in), y down, in **spread** space: on a single-page spread the page's top-left is (0, 0); on a facing From f238a9a51ea44606d78cc29dd8eba4aeec2d81bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 5 Nov 2026 05:48:40 -0800 Subject: [PATCH 075/328] Fix MCP temporary directory build on Windows --- crates/mcp/src/tools.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 08659f202..7f38036e3 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -565,7 +565,10 @@ fn screenshot(b: &mut dyn Backend, a: &Args) -> Result { fn private_temp_dir(prefix: &str) -> Result { let nanos = std::time::SystemTime::UNIX_EPOCH.elapsed().map_or(0, |d| d.as_nanos()); let dir = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id())); + #[cfg(unix)] let mut builder = std::fs::DirBuilder::new(); + #[cfg(not(unix))] + let builder = std::fs::DirBuilder::new(); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; From 00d7f0e1910cfd7b8c331576e68a40b9b95b4a89 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 14:03:44 +0000 Subject: [PATCH 076/328] Apply review fixes - crates/ui-egui/src/panels/table.rs --- crates/ui-egui/src/panels/table.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/table.rs b/crates/ui-egui/src/panels/table.rs index ef99bcce3..6d2213ba4 100644 --- a/crates/ui-egui/src/panels/table.rs +++ b/crates/ui-egui/src/panels/table.rs @@ -73,7 +73,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let combo = craft_ui::ComboBox::from_id_salt(("tp_style", kind)).selected_text(&cur).width(130.0).show_ui(ui, |ui| { for n in &names { if ui.selectable_label(*n == cur, n).clicked() { - run(app, &format!("style.{kind}.apply"), json!({"name": n, "story": sid, "table": tid})); + run(app, &format!("style.{kind}.apply"), json!({"name": n, "story": sid, "table": tid, "rows": [range["r0"], range["r1"]], "cols": [range["c0"], range["c1"]]})); } } }); From 8f2451bc6642d4cf7d8995e4cfa0e25e417f3106 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 077/328] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 081e3bd27..5ecd31268 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 8b1682d83..48ca90e26 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1010,6 +1010,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From e2b21cb3db126feb09e4bc4f6253c7c895ea01eb Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 078/328] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 081e3bd27..5ecd31268 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index d98fba286..ba5b23105 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1063,6 +1063,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From 64cc0c072dc11f6b2776d9b34aaf3fdf3712f647 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 079/328] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index f80d9d69f..6bf3d263d 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index e0bc04e22..ee576ccec 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1014,6 +1014,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From 5868b6036584aff4d155ee181c9124e5ec12f08b Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 080/328] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 5ecd31268..5ac886618 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1067,3 +1078,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index cae08a519..bb58b600a 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 15eeacc8456af6d9e194647b6d11c9b40c40b907 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 081/328] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 48ca90e26..6f5368ad8 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -943,6 +948,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4633620f3..b104a0ae1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1562,6 +1562,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4711,9 +4714,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index bb58b600a..a99b4e144 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 68a2030614404b8c59d4bc93243e72346b3f9a3d Mon Sep 17 00:00:00 2001 From: francesco fantoni Date: Tue, 3 Nov 2026 23:30:53 +0100 Subject: [PATCH 082/328] fix(engine): write automatic recovery off the interface thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 30 s timer ran file.recovery.save on the UI thread, and designcraft_format::save() deflated the entire package — every linked placed file included — into a Vec in RAM: 3.6 GB and 30-100 s of zlib inside DesignApp::ui() per autosave on a 190-page catalogue with 4.2 GB of links. - file.recovery.save {background: true} snapshots the dirty documents (Arc clones; no bytes copied) and queues them on one "designcraft-recovery" thread, skipping a document whose previous write is still in flight. file.recovery.progress reports {written, busy, errors}; the app's timer uses it and polls from ui_frame_end while a write is outstanding. The synchronous command is unchanged for MCP, scripts and tests, and the web build still writes inline (it has one thread). - designcraft_format gains write(), streaming the package to any Write + Seek, so a large save needs no second copy of the archive. - A snapshot still queued or running when its document is saved, reverted or closed is cancelled before its atomic rename; a write that lands after the poll is discarded, so a crash cannot offer back a copy older than the saved file. A panicking write is the job's error instead of ending the thread and leaving the document stuck as running. Tests: the_recovery_timer_writes_off_the_interface_thread; recovery::a_background_save_writes_recovery_data_the_app_can_recover, a_saved_document_is_not_written_in_the_background, a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove, a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove, a_write_cancelled_midway_publishes_nothing, only_a_queued_write_is_cancelled, a_panicking_recovery_write_is_an_error_and_the_writer_keeps_going; format::writing_to_a_stream_makes_the_same_file_as_saving_in_memory. Gates: cargo fmt --all --check; clippy -p designcraft-engine -p designcraft-format -p designcraft-ui-egui --all-targets -D warnings; cargo test -p designcraft-engine -p designcraft-format. Part of #1923, split for review: leaving linked placed files out of snapshots is a separate pull request on top of this one. --- ROADMAP.md | 6 + crates/engine/src/cmd/file/registry.rs | 12 +- crates/engine/src/recovery.rs | 424 +++++++++++++++++++++++-- crates/engine/src/recovery/tests.rs | 188 +++++++++++ crates/format/src/lib.rs | 22 +- crates/format/src/tests.rs | 18 ++ crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/frame.rs | 40 ++- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/tests.rs | 29 ++ docs/architecture.md | 7 +- docs/gaps.md | 8 +- 12 files changed, 711 insertions(+), 47 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 963b8b855..34ce00129 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -13,6 +13,12 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. - **2026-10-30** · Document Fonts lookup treats a bare document filename's empty parent as the current directory (#2014), preserving case-insensitive discovery and automation read-root checks. No readiness percentage change. +- **2026-10-27** · Automatic recovery writes off the interface thread, straight to disk: on a + 190-page catalogue with 4.2 GB of placed files an autosave was 3.6 GB deflated in RAM on the + interface thread, which stopped the window answering for 30-100 s after an edit. It is now a + background write (`file.recovery.save {background}`, `file.recovery.progress`), the caller + blocked for 109 ms instead, and Save, Close and Revert cancel a snapshot still being written. + No readiness percentage change. - **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in the next column or frame when needed (#1901). Cell-local footnotes contribute to row height and sit inside the cell rather than outside its measuring frame. Vertical justification keeps diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index c1f522956..e3a21213e 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -67,10 +67,20 @@ pub fn specs() -> Vec { let dir = recovery_dir(s, p, FolderAccess::Read)?; Ok(Value::Array(crate::recovery::list(&dir).into_iter().map(|(uid, mut m)| { m["uid"] = json!(uid); m }).collect())) }), - cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?} — write every unsaved document to the recovery folder (the app does this on a timer)", always, |s, p| { + cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, + "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved}` or {queued}", + always, |s, p| { let dir = recovery_dir(s, p, FolderAccess::Write)?; + if p.get("background").and_then(Value::as_bool).unwrap_or(false) { + return Ok(json!({"queued": crate::recovery::start_tracked(s, &dir)?})); + } Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?})) }), + cmd!(query "file.recovery.progress", "Recovery Progress", [], None, + "{} → {written, busy, errors} recovery data queued in the background has been written", always, |s, _| { + let done = crate::recovery::finished(s); + Ok(json!({"written": done.written, "busy": done.busy, "errors": done.errors})) + }), cmd!(noundo "file.recovery.open", "Recover Documents", [], None, "{dir?} — reopen documents left in the recovery folder (unsaved)", always, |s, p| { // Reopening removes the entries it read. let dir = recovery_dir(s, p, FolderAccess::ReadWrite)?; diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index eb6d99886..4598ae397 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -477,6 +477,9 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio if !s.docs.iter().enumerate().any(|(other_index, owner)| { other_index != index && owner.recovery_entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) }) { + // A write of it still running must not publish its snapshot after this point. + #[cfg(not(target_arch = "wasm32"))] + worker::cancel(&dir, uid); discard(&dir, uid); } } @@ -528,7 +531,10 @@ pub fn save(s: &Session, dir: &Path) -> Result { discard(dir, d.uid); continue; } - write_entry(&access, dir, d)?; + // The caller asked for this write now: nothing has cancelled it. + if let Some(e) = write_snapshot(&Snapshot::of(&access, dir, d), || false).error { + return Err(e); + } n += 1; } Ok(n) @@ -537,14 +543,7 @@ pub fn save(s: &Session, dir: &Path) -> Result { /// Command-path checkpointing also records explicitly selected directories, without configuring /// automatic recovery. The immutable public helper remains available for fixtures and callers. pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { - // Reject the complete batch before writing rather than silently losing old ownership records. - for document in &s.docs { - if document.is_dirty() && !has_checkpoint(document, dir) && document.recovery_entries.len() >= MAX_RECOVERY_ENTRIES { - return Err(EngineError::Other( - "too many recovery checkpoints; save or close the document before choosing another recovery folder".into(), - )); - } - } + reject_overfull_checkpoints(s, dir)?; let access = prepare_save(s, dir)?; let mut n = 0; let preview = s.new_document_preview(); @@ -557,34 +556,361 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { discard_document(s, index, Some(dir)); continue; } - let Some(document) = s.docs.get_mut(index) else { continue }; - let (doc, meta) = files(dir, document.uid); - let bytes = designcraft_format::save(document.preview_stash.as_deref().unwrap_or(document.doc.as_ref())) - .map_err(|e| EngineError::Other(e.to_string()))?; - // An entry this run did not write is never replaced, even one made since it checked. - let replace = access.owns(document.uid); - publish_recovery_file(&doc, &bytes, replace)?; - access.record(document.uid); - // The primary is useful even if optional metadata fails next. Track it immediately. - if !has_checkpoint(document, dir) { + let Some(document) = s.docs.get(index) else { continue }; + let entry = Snapshot::of(&access, dir, document); + let written = write_snapshot(&entry, || false); + // The primary is the recovery data; its metadata is optional. Track the primary before + // returning a metadata error, so Save and Close remove the snapshot this run wrote. + if written.published + && let Some(document) = s.docs.get_mut(index) + && !has_checkpoint(document, dir) + { document.recovery_entries.push((dir.to_path_buf(), document.uid)); } - let metadata = json!({"path": document.path, "title": document.title(), "saved": designcraft_doc::vars::now()}); - publish_recovery_file(&meta, metadata.to_string().as_bytes(), replace)?; + if let Some(e) = written.error { + return Err(e); + } n += 1; } Ok(n) } -/// Publish a document's recovery entry before its optional metadata. -fn write_entry(access: &Access, dir: &Path, d: &DocState) -> Result<()> { - let (doc, meta) = files(dir, d.uid); - let bytes = designcraft_format::save(d.preview_stash.as_deref().unwrap_or(d.doc.as_ref())).map_err(|e| EngineError::Other(e.to_string()))?; - let replace = access.owns(d.uid); - publish_recovery_file(&doc, &bytes, replace)?; - access.record(d.uid); - let metadata = json!({"path": d.path, "title": d.title(), "saved": designcraft_doc::vars::now()}); - publish_recovery_file(&meta, metadata.to_string().as_bytes(), replace) +/// Reject a complete batch before writing rather than silently losing old ownership records. +fn reject_overfull_checkpoints(s: &Session, dir: &Path) -> Result<()> { + for document in &s.docs { + if document.is_dirty() && !has_checkpoint(document, dir) && document.recovery_entries.len() >= MAX_RECOVERY_ENTRIES { + return Err(EngineError::Other( + "too many recovery checkpoints; save or close the document before choosing another recovery folder".into(), + )); + } + } + Ok(()) +} + +/// A document's recovery write, copied so a background thread can write it while the interface +/// stays responsive: no deflate, no copy of the placed files, happens on the interface thread. +struct Snapshot { + dir: PathBuf, + uid: u64, + /// The document as it was when the write started (data-merge previews save the unfilled one). + doc: std::sync::Arc, + path: Option, + title: String, + /// Whether this run may replace an entry already in the folder. + own: bool, + /// The folder's canonical key, for recording that a shared entry is this run's now. + key: PathBuf, +} + +impl Snapshot { + fn of(access: &Access, dir: &Path, d: &DocState) -> Self { + Snapshot { + dir: dir.to_path_buf(), + uid: d.uid, + doc: d.preview_stash.clone().unwrap_or_else(|| d.doc.clone()), + path: d.path.clone(), + title: d.title(), + // An entry this run did not write is never replaced, even one made since it checked. + own: access.owns(d.uid), + key: access.key.clone(), + } + } +} + +/// What one recovery write left in the folder: whether the primary document was published, and +/// the error that stopped it or the optional metadata written after it. The primary is the +/// recovery data (see the module docs: metadata may be missing or stale), so a metadata failure +/// must not lose the checkpoint that lets Save and Close remove what this run wrote. +struct Written { + published: bool, + error: Option, +} + +/// Publish a document's recovery entry before its optional metadata. `cancelled` says whether the +/// document was saved, reverted or closed since the write started: its snapshot is then dropped +/// instead of published, so a crash cannot offer back a copy older than the saved file. +fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { + let (doc, meta) = files(&entry.dir, entry.uid); + let published = publish_recovery_written( + &doc, + entry.own, + |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), + &cancelled, + ); + match published { + Ok(true) => {} + // Cancelled while writing: no snapshot and no metadata for it. + Ok(false) => return Written { published: false, error: None }, + Err(e) => return Written { published: false, error: Some(e) }, + } + // Written: in a folder that is not this run's own, the entry is now this run's to replace and + // remove (Save and Close must clean up the snapshot they wrote). + if !entry.own { + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); + } + let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); + Written { published: true, error: publish_recovery_file(&meta, metadata.to_string().as_bytes(), entry.own).err() } +} + +/// Write recovery entries for dirty documents on a background thread and drop clean checkpoints +/// now. The interface thread only snapshots what to write: `designcraft_format::write` deflates +/// and copies placed files, which takes minutes on a catalogue with gigabytes of links. Returns +/// how many documents were queued. +pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { + reject_overfull_checkpoints(s, dir)?; + let access = prepare_save(s, dir)?; + // Nothing runs on the web's single thread: it would freeze the page just the same. + #[cfg(target_arch = "wasm32")] + { + let _ = access; + return save_tracked(s, dir); + } + #[cfg(not(target_arch = "wasm32"))] + { + let mut queued = 0; + let preview = s.new_document_preview(); + for index in 0..s.docs.len() { + if s.docs.get(index).is_some_and(|document| preview == Some(document.uid)) { + continue; + } + if s.docs.get(index).is_some_and(|document| !document.is_dirty()) { + discard_document(s, index, Some(dir)); + continue; + } + let Some(document) = s.docs.get(index) else { continue }; + let entry = Snapshot::of(&access, dir, document); + // A write still running for this document already holds a snapshot of it; the next + // timer tick catches up with the edits made since. + match worker::submit(entry) { + Some(true) => queued += 1, + Some(false) => {} + None => { + // No thread: write this one here rather than lose the recovery data. + let written = write_snapshot(&Snapshot::of(&access, dir, document), || false); + if written.published { + record_checkpoint(s, dir.to_path_buf(), document.uid); + } + if let Some(e) = written.error { + return Err(e); + } + queued += 1; + } + } + } + Ok(queued) + } +} + +/// Apply one finished background write: record the checkpoint of a document still open and +/// unsaved, or drop the snapshot of one saved, reverted or closed while its write ran. Returns +/// whether a checkpoint was recorded. +#[cfg(not(target_arch = "wasm32"))] +fn record_checkpoint(s: &mut Session, dir: PathBuf, uid: u64) -> bool { + match s.docs.iter_mut().find(|doc| doc.uid == uid) { + Some(doc) if doc.is_dirty() => { + if !has_checkpoint(doc, &dir) { + doc.recovery_entries.push((dir, uid)); + } + true + } + // Saved, reverted or closed while being written: its snapshot must not come back after a + // crash, and the timer writes only when a document is dirty, so nothing else would + // remove it. + Some(_) | None => { + discard(&dir, uid); + false + } + } +} + +/// Apply finished background writes. Returns what was written and what failed. +pub(crate) struct Finished { + pub written: usize, + pub errors: Vec, + pub busy: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn finished(s: &mut Session) -> Finished { + let mut out = Finished { written: 0, errors: Vec::new(), busy: false }; + let Some(w) = worker::started() else { return out }; + let Ok(done) = w.done.lock() else { + out.busy = w.busy(); + return out; + }; + while let Ok(d) = done.try_recv() { + // A primary that landed belongs to this run even if its optional metadata failed: record + // it, so Save and Close remove the snapshot instead of leaving it in the folder for ever. + if d.published && record_checkpoint(s, d.dir, d.uid) { + out.written += 1; + } + if let Some(e) = d.error { + out.errors.push(e); + } + } + // After draining: the worker delivers a result before it clears the document as running, so + // "not busy" means every result is already in the channel, not on its way. + out.busy = w.busy(); + out +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn finished(_s: &mut Session) -> Finished { + // Nothing is written in the background on the web. + Finished { written: 0, errors: Vec::new(), busy: false } +} + +/// Automatic recovery's writer: one thread with its own queue, so an unsaved document with +/// gigabytes of placed files is written without stopping the interface. +#[cfg(not(target_arch = "wasm32"))] +mod worker { + use std::collections::BTreeSet; + use std::sync::mpsc::{Receiver, Sender}; + use std::sync::{Mutex, OnceLock}; + + use super::{Path, PathBuf, Result, Snapshot, write_snapshot}; + + /// One document written, for the interface thread to record. + pub(super) struct Done { + pub(super) dir: PathBuf, + pub(super) uid: u64, + pub(super) error: Option, + /// The primary document reached the folder (its optional metadata may have failed): the + /// checkpoint must still be recorded, or Save and Close could not remove it. + pub(super) published: bool, + } + + pub(super) struct Writer { + jobs: Sender, + pub(super) done: Mutex>, + /// Documents queued or being written: a second write of one still holds nothing newer. + running: Mutex>, + /// A document saved, reverted or closed while its write was queued or running: the + /// snapshot it is producing must not be published. + cancelled: Mutex>, + } + + static WRITER: OnceLock> = OnceLock::new(); + + impl Writer { + pub(super) fn busy(&self) -> bool { + self.running.lock().is_ok_and(|running| !running.is_empty()) + } + + fn finish(&self, dir: &Path, uid: u64) { + let key = (dir.to_path_buf(), uid); + if let Ok(mut running) = self.running.lock() { + running.remove(&key); + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.remove(&key); + } + } + + /// Do not publish the snapshot being written for `dir`/`uid`: the document was saved, + /// reverted or closed. Only a write that is queued or running is marked, so the set stays + /// as small as the work in flight. + fn cancel(&self, dir: &Path, uid: u64) { + let key = (dir.to_path_buf(), uid); + if !self.running.lock().is_ok_and(|running| running.contains(&key)) { + return; + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.insert(key); + } + } + + fn cancelled(&self, dir: &Path, uid: u64) -> bool { + self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&(dir.to_path_buf(), uid))) + } + } + + /// The writer, started on first use (a thread that can't start leaves recovery synchronous). + fn writer() -> Option<&'static Writer> { + WRITER + .get_or_init(|| { + let (jobs, job_rx) = std::sync::mpsc::channel::(); + let (done_tx, done_rx) = std::sync::mpsc::channel::(); + let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { + while let Ok(job) = job_rx.recv() { + let (published, error) = guarded_write(&job); + let (dir, uid) = (job.dir, job.uid); + // The result before the document reads as idle: a writer that is not busy + // has already delivered it, so the interface never stops polling with an + // answer still on its way. + let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published }).is_ok(); + if let Some(w) = WRITER.get().and_then(Option::as_ref) { + w.finish(&dir, uid); + } + if !sent { + break; + } + } + }); + spawned.ok().map(|_| Writer { + jobs, + done: Mutex::new(done_rx), + running: Mutex::new(BTreeSet::new()), + cancelled: Mutex::new(BTreeSet::new()), + }) + }) + .as_ref() + } + + /// The writer if it has been started. + pub(super) fn started() -> Option<&'static Writer> { + WRITER.get().and_then(Option::as_ref) + } + + /// Do not publish the snapshot being written for `dir`/`uid` (see [`Writer::cancel`]). + pub(super) fn cancel(dir: &Path, uid: u64) { + if let Some(w) = started() { + w.cancel(dir, uid); + } + } + + /// Whether that write is already marked as cancelled (see [`Writer::cancelled`]). + pub(super) fn cancelled(dir: &Path, uid: u64) -> bool { + started().is_some_and(|w| w.cancelled(dir, uid)) + } + + /// Write one snapshot, turning a panic into its error: a panic that ended this thread would + /// leave the document marked as running for ever (so it is never written again) and the + /// interface asking for frames for ever. A safety net: a writer still must not panic. + fn guarded_write(job: &Snapshot) -> (bool, Option) { + match guarded(|| Ok(write_snapshot(job, || cancelled(&job.dir, job.uid)))) { + // A primary that landed is this run's to remove, even if its metadata failed. + Ok(written) => (written.published, written.error.map(|e| e.to_string())), + Err(e) => (false, Some(e.to_string())), + } + } + + /// [`guarded_write`]'s guard, for any write on this thread. + pub(super) fn guarded(write: impl FnOnce() -> Result) -> Result { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(write)).unwrap_or_else(|payload| { + Err(crate::EngineError::Other(format!("recovery writer panicked: {}", crate::guard::panic_message(payload.as_ref())))) + }) + } + + /// Queue a document's write. `None`: no writer thread (the caller writes it itself); + /// `Some(false)`: one for this document is still queued or running. + pub(super) fn submit(entry: Snapshot) -> Option { + let w = writer()?; + let mut running = w.running.lock().ok()?; + let key = (entry.dir.clone(), entry.uid); + if !running.insert(key.clone()) { + return Some(false); + } + // A write is wanted again: whatever cancelled the last one does not apply to this one. + if let Ok(mut cancelled) = w.cancelled.lock() { + cancelled.remove(&key); + } + if w.jobs.send(entry).is_err() { + running.remove(&key); + return None; + } + Some(true) + } } #[cfg(not(target_arch = "wasm32"))] @@ -632,6 +958,21 @@ fn secure_recovery_dir(_dir: &Path) -> Result { #[cfg(not(target_arch = "wasm32"))] fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> { + publish_recovery_written(path, replace, |out| out.write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display()))), || false) + .map(|_| ()) +} + +/// [`publish_recovery_file`], with `write` filling the temporary file: a large document is written +/// straight to disk instead of being built in memory first. Returns whether it was published; +/// `cancelled` is asked after the bytes are written and before the rename, so a document saved or +/// closed meanwhile leaves nothing behind. +#[cfg(not(target_arch = "wasm32"))] +fn publish_recovery_written( + path: &Path, + replace: bool, + write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, + cancelled: impl Fn() -> bool, +) -> Result { let Some(dir) = path.parent() else { return Err(EngineError::Other(format!("{} has no parent folder", path.display()))); }; @@ -646,15 +987,24 @@ fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> use std::os::unix::fs::PermissionsExt; tmp.as_file().set_permissions(std::fs::Permissions::from_mode(0o600)).map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; } - tmp.as_file_mut().write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; + { + let mut out = std::io::BufWriter::new(tmp.as_file_mut()); + write(&mut out)?; + out.flush().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; + } tmp.as_file_mut().sync_all().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; + // Last moment: the document was saved, reverted or closed while the bytes were written. The + // temporary file is dropped, so nothing of the stale snapshot stays. + if cancelled() { + return Ok(false); + } // Validate the non-followed leaf again immediately before renaming the randomized temporary // file to its fixed sibling destination. validate_recovery_dir(dir)?; let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; sync_recovery_dir(dir)?; - Ok(()) + Ok(true) } #[cfg(not(target_arch = "wasm32"))] @@ -712,6 +1062,16 @@ fn publish_recovery_file(_path: &Path, _bytes: &[u8], _replace: bool) -> Result< Err(EngineError::Other("recovery files are unavailable on the web".into())) } +#[cfg(target_arch = "wasm32")] +fn publish_recovery_written( + _path: &Path, + _replace: bool, + _write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, + _cancelled: impl Fn() -> bool, +) -> Result { + Err(EngineError::Other("recovery files are unavailable on the web".into())) +} + /// Canonical keys are only for alias comparison; operational paths stay unchanged so run /// ownership checks still find the directory registered by the native profile. fn directory_key(dir: &Path) -> Result { diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 395e8385b..89feb2873 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -126,6 +126,194 @@ fn recovery_data_is_private_to_the_user() { } } +/// The recovery writer is one thread for the whole process, and its results go to whichever +/// session polls it: tests that submit to it take turns, so one test's write or error is never +/// drained by another. +static BACKGROUND: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn background() -> std::sync::MutexGuard<'static, ()> { + BACKGROUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Poll `file.recovery.progress` until the background writer has nothing left, as the app does at +/// the end of a frame. +fn finished_writes(s: &mut Session) -> usize { + let mut written = 0; + for _ in 0..1200 { + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["errors"], json!([]), "{v}"); + written += v["written"].as_u64().unwrap_or(0) as usize; + if !v["busy"].as_bool().unwrap_or(false) { + return written; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the background writer did not finish"); +} + +#[test] +fn a_background_save_writes_recovery_data_the_app_can_recover() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + // The timer's call: the interface thread does not wait for the deflate or the file writes. + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + assert_eq!(finished_writes(&mut s), 1); + assert_eq!(list(dir.path()).len(), 1); + assert!(s.docs[0].recovery_entries.iter().any(|(d, _)| same_directory(d, dir.path())), "the checkpoint is recorded"); + // Recovering it gives the unsaved edits back. + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 1); + assert!(reopened.doc().unwrap().is_dirty()); + discard(dir.path(), reopened.doc().unwrap().uid); +} + +#[test] +fn a_snapshot_that_finishes_after_the_save_is_dropped() { + // A write of a large document runs for seconds: the user can save while it does. The saved + // document's checkpoint is consumed then, and the write must not put a stale snapshot back. + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + // The snapshot the writer took before the save. + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + let saved = dir.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!s.docs[0].is_dirty()); + // The write lands after the save. + let written = write_snapshot(&entry, || false); + assert!(written.published && written.error.is_none(), "the snapshot landed"); + let (file, _) = files(dir.path(), uid); + assert!(file.exists()); + assert!(!record_checkpoint(&mut s, dir.path().to_path_buf(), uid), "a saved document records no checkpoint"); + assert!(!file.exists(), "its snapshot is not left to be recovered"); + assert!(list(dir.path()).is_empty()); + // A document still unsaved does record one. + s.execute("frame.create", &json!({"rect": [10, 10, 50, 50]})).unwrap(); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + let written = write_snapshot(&entry, || false); + assert!(written.published && written.error.is_none(), "the second snapshot landed"); + assert!(record_checkpoint(&mut s, dir.path().to_path_buf(), uid)); + assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && d == dir.path())); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { + // The primary document is the recovery data; its metadata is optional. A metadata failure + // must not leave the published snapshot untracked, or Save and Close would not remove it and + // it would stay in the folder for ever. + let root = tempfile::tempdir().unwrap(); + let dir = run_dir(root.path()).unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.clone()); + let uid = s.docs[0].uid; + let (document, metadata) = files(&dir, uid); + // The folder is this run's own, so the entry is its own; a folder takes the metadata's name, + // which makes the optional write fail after the primary landed. + std::fs::create_dir(&metadata).unwrap(); + let err = save_tracked(&mut s, &dir).unwrap_err(); + assert!(err.to_string().contains(&metadata.display().to_string()), "{err}"); + assert!(document.exists(), "the primary landed"); + assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, &dir)), "and is tracked"); + // Saving the document removes the snapshot this run wrote. + let saved = root.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!document.exists(), "Save removed the snapshot"); + assert!(s.docs[0].recovery_entries.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { + // The background writer's result must be applied the same way: a published primary is the + // document's snapshot even when its optional metadata fails. + let _turn = background(); + let root = tempfile::tempdir().unwrap(); + let dir = run_dir(root.path()).unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.clone()); + let uid = s.docs[0].uid; + let (document, metadata) = files(&dir, uid); + std::fs::create_dir(&metadata).unwrap(); + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + let mut reported = None; + for _ in 0..1200 { + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + if let Some(first) = v["errors"].as_array().and_then(|errors| errors.first()) { + reported = first.as_str().map(str::to_string); + } + if !v["busy"].as_bool().unwrap_or(false) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let reported = reported.expect("the metadata failure is reported"); + assert!(reported.contains(&metadata.display().to_string()), "{reported}"); + assert!(document.exists(), "the primary landed"); + assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, &dir)), "and is tracked"); + // Saving the document removes the snapshot this run wrote. + let saved = root.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!document.exists(), "Save removed the snapshot"); +} + +#[test] +fn a_write_cancelled_midway_publishes_nothing() { + // Save/Revert/Close during a write marks it cancelled; the snapshot must not land after it, + // even if the app crashes before the next interface frame discards it. + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + let written = write_snapshot(&entry, || true); + assert!(!written.published && written.error.is_none(), "a cancelled write is not an error"); + assert!(list(dir.path()).is_empty(), "a cancelled write leaves no snapshot"); + assert!(!files(dir.path(), entry.uid).0.exists(), "nor its document"); + assert!(!files(dir.path(), entry.uid).1.exists(), "nor its metadata"); + // The temporary file it was written to is dropped, not left behind. + assert!( + std::fs::read_dir(dir.path()).unwrap().all(|e| e.is_ok_and(|e| !e.file_name().to_string_lossy().starts_with(".designcraft-recovery-"))), + "no temporary file is left" + ); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn only_a_queued_write_is_cancelled() { + // A mark for a document with no write in flight would stay in the writer's set for ever. + let dir = tempfile::tempdir().unwrap(); + worker::cancel(dir.path(), 7); + assert!(!worker::cancelled(dir.path(), 7), "nothing was queued for it"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_panicking_recovery_write_is_an_error_and_the_writer_keeps_going() { + let err = worker::guarded(|| -> Result<()> { panic!("boom") }).unwrap_err(); + assert!(err.to_string().contains("panicked") && err.to_string().contains("boom"), "{err}"); + assert_eq!(worker::guarded(|| Ok(7)).unwrap(), 7, "the next write still runs"); +} + +#[test] +fn a_saved_document_is_not_written_in_the_background() { + // The autosave writes unsaved documents only. + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let saved = dir.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 0, "{queued}"); + assert_eq!(finished_writes(&mut s), 0); + assert!(list(dir.path()).is_empty()); +} + #[test] fn existing_recovery_directory_is_used() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 09bdfe334..126c9470a 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -86,6 +86,23 @@ fn required_version(doc: &Document) -> u32 { } fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_entry: usize) -> Result, FormatError> { + let mut buf = Cursor::new(Vec::new()); + write_with_large_entries_from(&mut buf, doc, preview, large_entry)?; + Ok(buf.into_inner()) +} + +/// Write the package to `out` instead of returning it in memory: a document with gigabytes of +/// placed files needs no second copy in RAM (recovery snapshots, large saves). +pub fn write(out: &mut W, doc: &Document, preview: Option<&[u8]>) -> Result<(), FormatError> { + write_with_large_entries_from(out, doc, preview, LARGE_ENTRY) +} + +fn write_with_large_entries_from( + out: &mut W, + doc: &Document, + preview: Option<&[u8]>, + large_entry: usize, +) -> Result<(), FormatError> { // JSON writes infinity and NaN as null, which no load accepts: the file would not open. if let Some(id) = doc.non_finite_item() { return Err(FormatError::Unsaveable(format!("object {} has a position or size that is not a finite number", id.0))); @@ -94,9 +111,8 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en compact.compact_assets(); let doc = &compact; let io = |e: zip::result::ZipError| FormatError::Io(e.to_string()); - let mut buf = Cursor::new(Vec::new()); { - let mut z = zip::ZipWriter::new(&mut buf); + let mut z = zip::ZipWriter::new(out); let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); z.start_file("mimetype", stored).map_err(io)?; @@ -124,7 +140,7 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en } z.finish().map_err(io)?; } - Ok(buf.into_inner()) + Ok(()) } /// The file name extension of a DesignCraft document. diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index a95bee160..8820eabda 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -577,6 +577,24 @@ fn saved_tab_lists_load_sanitized() { assert_eq!(tabs.last().map(|t| t.position), Some(3960.0), "the first stops by position"); } +#[test] +fn writing_to_a_stream_makes_the_same_file_as_saving_in_memory() { + // A save that streams needs no copy of the archive in RAM; it must write the same package. + let mut d = Document::new(&NewDocument::default()); + let a = png_asset(&mut d, b"streamed bytes"); + place(&mut d, a, 0.0); + let png = b"\x89PNG streamed".to_vec(); + let saved = save_with_preview(&d, Some(&png)).unwrap(); + let mut out = Cursor::new(Vec::new()); + write(&mut out, &d, Some(&png)).unwrap(); + let streamed = out.into_inner(); + assert_eq!(saved.len(), streamed.len()); + assert_eq!(asset_entries(&streamed), 1); + let back = load(&streamed).unwrap(); + assert_eq!(back.assets.len(), 1); + assert_eq!(read_preview(Cursor::new(&streamed)), Some(png)); +} + #[test] fn the_preview_is_read_back_without_the_document() { let d = Document::new(&NewDocument::default()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..43071f366 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -108,6 +108,7 @@ impl DesignApp { shortcut_answers: Default::default(), last_time: now, last_recovery: now, + recovery_writing: false, egui_ctx: None, in_control: false, object_clip_text: None, diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index ceeb28743..985ede0f5 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -83,14 +83,28 @@ impl DesignApp { /// uses the monotonic clock, so a wall-clock/NTP jump cannot postpone or advance it. pub(super) fn ui_frame_end(&mut self, ctx: &egui::Context) { let now = now_ms() / 1000.0; - // Crash recovery: unsaved documents are written to the recovery folder every 30 s. + // Crash recovery: unsaved documents are written to the recovery folder every 30 s, on a + // background thread — writing a catalogue with gigabytes of placed files took minutes, and + // on the interface thread the window stopped answering for all of it. #[cfg(not(target_arch = "wasm32"))] - if self.session.recovery_dir.is_some() && now - self.last_recovery > (self.session.prefs.recovery_minutes * 60.0).max(5.0) { - self.last_recovery = now; - if self.session.documents().iter().any(|d| d.is_dirty()) - && let Err(e) = self.session.execute("file.recovery.save", &json!({})) - { - self.status(crate::i18n::tr(&self.ui.language, "Couldn't write recovery data: {error}").replace("{error}", &e.to_string())); + { + if self.session.recovery_dir.is_some() && now - self.last_recovery > (self.session.prefs.recovery_minutes * 60.0).max(5.0) { + self.last_recovery = now; + if self.session.documents().iter().any(|d| d.is_dirty()) { + match self.session.execute("file.recovery.save", &json!({"background": true})) { + Ok(v) if v["queued"].as_u64().unwrap_or(0) > 0 => self.recovery_writing = true, + Ok(_) => {} + Err(e) => self + .status(crate::i18n::tr(&self.ui.language, "Couldn't write recovery data: {error}").replace("{error}", &e.to_string())), + } + } + } + if self.recovery_writing { + self.poll_recovery(); + // Keep the frames coming while the writer works; it has no interface to ask. + if self.recovery_writing { + ctx.request_repaint_after(std::time::Duration::from_millis(150)); + } } } let dt = now - self.last_time; @@ -101,6 +115,18 @@ impl DesignApp { self.issue_screenshots(ctx); } + /// Take what the background recovery writer finished: its checkpoints, and what failed. + #[cfg(not(target_arch = "wasm32"))] + fn poll_recovery(&mut self) { + let Ok(v) = self.session.execute("file.recovery.progress", &json!({})) else { return }; + self.recovery_writing = v["busy"].as_bool().unwrap_or(false); + let errors: Vec = v["errors"].as_array().into_iter().flatten().filter_map(|e| e.as_str().map(str::to_string)).collect(); + for e in errors { + let message = crate::i18n::tr(&self.ui.language, "Couldn't write recovery data: {error}").replace("{error}", &e); + self.status(message); + } + } + /// The document area: the start screen, or the document tabs over one or two canvas panes. pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui, presenting: bool) { let t = theme::Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6775c7755..751f8ccca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,6 +242,9 @@ pub struct DesignApp { last_time: f64, /// When recovery data was last written (seconds on the monotonic clock; see [`now_ms`]). pub last_recovery: f64, + /// Recovery data is being written in the background: poll for it, and keep repainting. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) recovery_writing: bool, /// The egui context (set by the first UI pass): copied text goes to the system clipboard through it. egui_ctx: Option, /// A control-channel request is being handled: commands it runs never read or write the diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 5b3871bbf..08b709505 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -140,6 +140,35 @@ fn app_with_unsaved_document() -> DesignApp { app } +/// The recovery timer wrote the whole document on the interface thread: on a catalogue with +/// gigabytes of linked files the window stopped answering for minutes after every edit. +#[test] +fn the_recovery_timer_writes_off_the_interface_thread() { + let ctx = egui::Context::default(); + let mut app = app_with_unsaved_document(); + let dir = tempfile::tempdir().unwrap(); + app.session.recovery_dir = Some(dir.path().to_path_buf()); + app.last_recovery = -1.0e9; + let uid = app.session.documents()[0].uid; + let entry = dir.path().join(format!("{uid}.designcraft")); + let mut written = false; + for _ in 0..600 { + shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); + // The timer fired and the write finished: the file is there and nothing is still queued. + if entry.exists() && !app.recovery_writing { + written = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(written, "the timer's background write published the document"); + assert!(app.last_recovery > 0.0, "the timer restarted its interval"); + // The checkpoint is the document's: saving it removes the recovery entry. + let saved = dir.path().join("saved.designcraft"); + app.run("file.saveAs", json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!dir.path().join(format!("{uid}.designcraft")).exists()); +} + /// File ▸ Close (and its shortcut) closed a document with unsaved changes without asking, and /// closing discards the document's recovery data too. #[test] diff --git a/docs/architecture.md b/docs/architecture.md index 7b86388a9..c0b7ac7a5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # DesignCraft architecture -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (shared PDF writing) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (recovery writes on a background thread, streamed to disk) · **Target:** Adobe InDesign 2026 How DesignCraft is built today. The design notes behind it are in `plan/architecture.md` (local, gitignored); this file describes what the code on `main` does. Agents: AGENTS.md has the @@ -58,7 +58,9 @@ panels, zoom, dialogs) are `UI_COMMANDS` in `crates/ui-egui/src/menus/ui_command Tool gestures emit Begin/Preview/Commit commands so a drag is one undo step. Every journaled command is replayable as a script. Escaped panics during a command or an import/export become an error (`engine/src/guard.rs`), never a lost document; native recovery is written periodically -into each running app's locked folder. Orderly native shutdown finalizes complete, current quit +into each running app's locked folder, on a background thread and straight to disk, so an +autosave of a catalogue with gigabytes of placed files no longer stops the window answering. +Orderly native shutdown finalizes complete, current quit approvals and writes the remaining documents' latest recovery state, including clean-document cleanup after Undo. Unavailable or failed recovery is reported. The desktop opts into a pinned winit 0.30 patch that cancels AppKit termination and queues ordinary window close requests, @@ -110,6 +112,7 @@ builds (on manifest changes), packaging lint and the release workflow; `xtask ci | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | Recovery writes off the interface thread, streamed to disk; a snapshot still being written when its document is saved, reverted or closed is cancelled | | 2026-10-12 | minor | Documented cancelable Dock Quit through the native event-loop boundary | | 2026-10-12 | minor | Documented orderly native exit recovery and the remaining cancelable Dock Quit gap | | 2026-10-10 | major | Created from the code on main (92649ff) and `plan/architecture.md` | diff --git a/docs/gaps.md b/docs/gaps.md index d74de3b04..b83dbdb2b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where DesignCraft falls short of InDesign -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (gap 20: automatic recovery moved off the interface thread; placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6) Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops an InDesign professional from doing real work. This is the work list: agents pick from the top. @@ -234,7 +234,11 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Missing:** incremental composition (recompose from the edited paragraph; 8 ms keystroke budget), benchmarks against InDesign on long books and image-heavy catalogues. - **Have:** compose 300k characters ~38 ms warm, damage-region repaint (< 1 ms while typing), - parallel story composition. + parallel story composition. Automatic recovery writes on a background thread and streams to + disk, so an autosave of that catalogue no longer blocks the interface thread for 30-100 s + (`file.recovery.save {background}`, `file.recovery.progress`). A snapshot still being written + when its document is saved, reverted or closed is cancelled before it is published, so a crash + cannot offer back a copy older than the saved file. - **Estimate:** 40–80 h. ### 26. Autoflow flows into the primary text frame of the pages that follow (F) From ba2237f8d5e13a910135bca16416ec8e4ce9bd59 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 083/328] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 5ecd31268..5ac886618 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1067,3 +1078,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 50061c8c0..478ad6755 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. ## Dropping files From 3111d4086a0b216e01545529508b4e900476d2b7 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 084/328] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ba5b23105..4cd29d214 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -996,6 +1001,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4633620f3..b104a0ae1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1562,6 +1562,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4711,9 +4714,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 478ad6755..e64a26fbc 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. ## Dropping files From 5e1cb976f9fc3aeaded864cc5952851ac6e81306 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 085/328] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 6bf3d263d..c462fe773 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1107,3 +1118,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 99e8c809d..58cbdb60b 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -11,7 +11,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From dd311b88031dcae02e0e2223883517cc6a134eb0 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 086/328] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ee576ccec..bf9ce5e7b 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -947,6 +952,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e6f6311b2..6730c3590 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1563,6 +1563,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4758,9 +4761,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 58cbdb60b..8086650f5 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -11,7 +11,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From a66355b6ca2f44fa526b01b2b547a2636e6d1e49 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:45:45 -0500 Subject: [PATCH 087/328] Place: say what a dropped batch does at a multi-page PDF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Place now carries on after the PDF's options; a drop still cancels the rest. --- crates/ui-egui/src/app/files.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4cd29d214..730b6e222 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -295,7 +295,8 @@ impl DesignApp { /// cursor, each run of them where it came in the order, after any images it already holds, /// whatever is under the pointer: click to place them one by one, drag with the arrow keys for /// a grid. The rest of the drop is cancelled once a file opens a dialog (a multi-page PDF's - /// Import Options, an alert), as File › Place with several chosen is. + /// Import Options, an alert): unlike File › Place with several chosen, nothing waits for a + /// PDF's options to be confirmed. pub fn open_dropped_batch(&mut self, drops: Vec<(String, Option)>) { let several = drops.iter().filter(|(p, _)| is_cursor_image(p)).count() > 1; // Only the first graphic of a drop fills the frame under the pointer. From fea50adfafe5bb1290edde8a6e15c3cca86ad0cb Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:58:57 -0500 Subject: [PATCH 088/328] Place: contact sheet numbers mean the document unit however they arrive A number sent over ui.dialog.open or ui.dialog.set showed as 2 in the field but was sent as 2 points, while a typed 2 meant the ruler unit. --- crates/ui-egui/src/app/files.rs | 34 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 7 +++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index bf9ce5e7b..38d7f137a 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1124,6 +1124,40 @@ pub(crate) mod browser_import_tests { assert_eq!(d.s("gutter"), "6pt"); } + /// A bare number in a field means the document's ruler unit, whether it was typed or came as + /// a number over `ui.dialog.open` or `ui.dialog.set`. + #[test] + fn contact_sheet_numbers_are_in_the_document_unit_however_they_came() { + let frames = |margin: Value, gutter: Value, set: bool| { + let mut app = app(); + app.run("document.preferences", json!({"horizontalUnits": "inches"})).unwrap(); + let request = app.import_request("place"); + for name in ["one.png", "two.png"] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: name.into(), + bytes: png(200), + }); + } + app.drain_inbox(); + let fields = json!({"columns": 2, "rows": 1, "gutter": gutter, "margin": margin}); + app.ui.dialog = Some(dialogs::contact_sheet_dialog(&app, if set { json!({"columns": 2, "rows": 1}) } else { fields.clone() })); + if set { + let d = app.ui.dialog.as_mut().unwrap(); + d.set_field("gutter", fields["gutter"].clone()); + d.set_field("margin", fields["margin"].clone()); + } + dialogs::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + doc.spreads.last().unwrap().items.iter().map(|item| item.bounds()).collect::>() + }; + let typed = frames(json!("1"), json!("0.5"), false); + assert_eq!(typed.len(), 2); + assert_eq!(frames(json!(1), json!(0.5), false), typed, "numbers over ui.dialog.open"); + assert_eq!(frames(json!(1), json!(0.5), true), typed, "numbers over ui.dialog.set"); + assert_eq!(frames(json!("72pt"), json!("36pt"), false), typed, "an explicit unit still says what it means"); + } + #[test] fn contact_sheet_validation_preserves_fields_and_pending_images() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6730c3590..f6a15386b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4721,11 +4721,14 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { } "contactSheet" => { let result = (|| { + // A bare number means the ruler unit, as typed or as a JSON number (`Dialog::m` + // takes the latter as points). + let measure = |k: &str| parse_measure(&d.s(k), d.unit).ok(); let params = json!({ "columns": d.s("columns").trim().parse::().map_err(|_| "Columns must be a whole number")?, "rows": d.s("rows").trim().parse::().map_err(|_| "Rows must be a whole number")?, - "gutter": d.m("gutter").ok_or("Enter a valid gutter")?, - "margin": d.m("margin").ok_or("Enter a valid margin")?, + "gutter": measure("gutter").ok_or("Enter a valid gutter")?, + "margin": measure("margin").ok_or("Enter a valid margin")?, }); app.run("place.contactSheet", params) })(); From 6444c76202d1d5b325cd208899850d3493c29af6 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:04:52 +0000 Subject: [PATCH 089/328] Apply review fixes - crates/engine/src/cmd/file/registry.rs - crates/engine/src/recovery.rs --- crates/engine/src/cmd/file/registry.rs | 2 +- crates/engine/src/recovery.rs | 17 ++++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index e3a21213e..a9d14892c 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { Ok(Value::Array(crate::recovery::list(&dir).into_iter().map(|(uid, mut m)| { m["uid"] = json!(uid); m }).collect())) }), cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, - "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved}` or {queued}", + "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved} or {queued}", always, |s, p| { let dir = recovery_dir(s, p, FolderAccess::Write)?; if p.get("background").and_then(Value::as_bool).unwrap_or(false) { diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 4598ae397..877759f8f 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -532,6 +532,9 @@ pub fn save(s: &Session, dir: &Path) -> Result { continue; } // The caller asked for this write now: nothing has cancelled it. + // A background write of an older state must not land over this one. + #[cfg(not(target_arch = "wasm32"))] + worker::cancel(dir, d.uid); if let Some(e) = write_snapshot(&Snapshot::of(&access, dir, d), || false).error { return Err(e); } @@ -557,6 +560,9 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { continue; } let Some(document) = s.docs.get(index) else { continue }; + // A background write of an older state must not land over this one. + #[cfg(not(target_arch = "wasm32"))] + worker::cancel(dir, document.uid); let entry = Snapshot::of(&access, dir, document); let written = write_snapshot(&entry, || false); // The primary is the recovery data; its metadata is optional. Track the primary before @@ -734,10 +740,9 @@ pub(crate) struct Finished { pub(crate) fn finished(s: &mut Session) -> Finished { let mut out = Finished { written: 0, errors: Vec::new(), busy: false }; let Some(w) = worker::started() else { return out }; - let Ok(done) = w.done.lock() else { - out.busy = w.busy(); - return out; - }; + // Before draining: the worker sends a result before it clears the document as running, so a writer idle now has every result in the channel already. + let busy = w.busy(); + let done = w.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); while let Ok(d) = done.try_recv() { // A primary that landed belongs to this run even if its optional metadata failed: record // it, so Save and Close remove the snapshot instead of leaving it in the folder for ever. @@ -748,9 +753,7 @@ pub(crate) fn finished(s: &mut Session) -> Finished { out.errors.push(e); } } - // After draining: the worker delivers a result before it clears the document as running, so - // "not busy" means every result is already in the channel, not on its way. - out.busy = w.busy(); + out.busy = busy; out } From d5bb8a378c8c3ccb676885c19b2bc1feb49672ca Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 18:40:41 -0500 Subject: [PATCH 090/328] Place: a browser batch waits for a PDF's options; a PDF first joins the cursor Files delivered after a multi-page PDF were dropped when its Import Options opened, with a status asking to choose them again, and choosing them again replaced the cursor. They now wait with the PDF and carry on when it is confirmed; Cancel ends the batch, as a native one's does. A batch starting with a single-page PDF, or in a browser with one image before a PDF, filled the selected frame instead of entering the place cursor. A browser delivers one Place's files together, so several in one delivery now count as a batch. One file alone still fills the frame. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/files.rs | 145 ++++++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 2 + docs/multi-image-placement.md | 2 +- 4 files changed, 142 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..0048a8c4e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -39,6 +39,7 @@ impl DesignApp { let dialog_wake = std::sync::Arc::new(std::sync::OnceLock::new()); DesignApp { pending_pdf: None, + pending_pdf_rest: Vec::new(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::new_dialogs(dialog_wake.clone()), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 6f5368ad8..712f2b500 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -61,6 +61,8 @@ impl DesignApp { /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); + // Several files go to the place cursor, even a PDF first with a frame selected. + let batch = paths.len() > 1; // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); let mut paths = paths.into_iter(); @@ -85,7 +87,7 @@ impl DesignApp { loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } let Some(p) = path else { return Ok(()) }; - let r = self.place_path(&p, loaded)?; + let r = self.place_path(&p, batch || loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); @@ -138,16 +140,28 @@ impl DesignApp { } pub(crate) fn cancel_pdf_import(&mut self) { + self.release_pending_pdf(); + } + + fn release_pending_pdf(&mut self) { self.pending_pdf = None; + self.pending_pdf_rest = Vec::new(); } /// Import Options confirmed for the delivered PDF; a placed one is added to the place cursor - /// when `append`, so the images loaded before it stay. + /// when `append`, so the images loaded before it stay. The files of its batch that waited for + /// the options carry on; if it can't be placed, the batch ends, as a native one does. pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String, append: bool) -> Result { let file = self.pending_pdf.take().ok_or("PDF import cancelled: no pending file")?; + let rest = std::mem::take(&mut self.pending_pdf_rest); self.activate_import_target(&file.request)?; let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop, "append": append}); - if file.request.purpose == "place" { self.place_file(params) } else { self.open_file("file.place", params) } + if file.request.purpose != "place" { + return self.open_file("file.place", params); + } + let placed = self.place_file(params)?; + self.import_delivered(rest, true); + Ok(placed) } /// A single unresolved PDF owns its bytes. Later deliveries cancel explicitly rather than @@ -158,7 +172,7 @@ impl DesignApp { let owns_dialog = self.ui.dialog.as_ref().is_some_and(|d| d.id == "pdfImport" && d.fields.get("async").and_then(Value::as_bool) == Some(true)); if !target_exists || !owns_dialog { - self.pending_pdf = None; + self.release_pending_pdf(); if !target_exists { if owns_dialog { self.ui.dialog = None; @@ -169,14 +183,23 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + // A browser delivers one Place's files together. Several go to the place cursor, even a + // PDF first with a frame selected, as a native batch's do. + let batch = files.iter().filter(|f| f.request.purpose == "place").count() > 1; + self.import_delivered(files, batch); + } + + /// Imports `files` in the order they came; placed ones are added to the place cursor when + /// `append`, and after the first that loads it. A multi-page PDF's Import Options pause a + /// Place: the files after it wait with it and carry on when it is confirmed, and Cancel ends + /// the batch. + fn import_delivered(&mut self, files: Vec, mut append: bool) { let cursor_image = |file: &ImportedFile| { file.request.purpose == "place" && !file.name.to_ascii_lowercase().ends_with(".pdf") && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) }; - // In the order they came: consecutive images for the same document load the place - // cursor together; after the first placement into it, the later ones are added to it. - let mut append = false; + // Consecutive images for the same document load the place cursor together. let mut files = files.into_iter().peekable(); while let Some(file) = files.next() { if file.request.purpose == "shortcuts" { @@ -220,11 +243,17 @@ impl DesignApp { continue; } let name = file.name.clone(); + let target = file.request.target; match self.import_file(file, append) { Ok(_) if placing => append = true, Ok(_) => {} Err(e) => self.status(format!("{name}: {e}")), } + if placing && self.pending_pdf.is_some() { + while let Some(next) = files.next_if(|n| n.request.purpose == "place" && n.request.target == target) { + self.pending_pdf_rest.push(next); + } + } } } @@ -918,6 +947,108 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A graphic frame, holding a picture and selected, with an empty place cursor; the frame's id. + fn select_a_graphic_frame(app: &mut DesignApp) -> u64 { + let frame = app.run("frame.create", json!({"rect": [10, 10, 100, 100]})).unwrap()["id"].as_u64().unwrap(); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("file.place", json!({"base64": b64, "name": "old.svg", "frame": frame})).unwrap(); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + assert!(app.session.loaded.is_none()); + frame + } + + fn frame_asset(app: &DesignApp, frame: u64) -> String { + let doc = &app.session.active().unwrap().doc; + let designcraft_doc::Content::Graphic(g) = &doc.item(designcraft_doc::ItemId(frame)).unwrap().content else { panic!("a graphic") }; + doc.assets[&g.asset].name.clone() + } + + /// A PDF first in a native batch joins the cursor like the rest; the selected frame keeps its + /// picture. A PDF alone still fills it. + #[test] + fn native_batch_starting_with_a_pdf_leaves_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("a.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let frame = select_a_graphic_frame(&mut app); + app.place_paths(vec![path("one.pdf"), path("a.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["one.pdf", "a.svg"]); + assert_eq!(frame_asset(&app, frame), "old.svg"); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let frame = select_a_graphic_frame(&mut app); + app.place_paths(vec![path("one.pdf")]).unwrap(); + assert!(app.session.loaded.is_none()); + assert_eq!(frame_asset(&app, frame), "one.pdf"); + } + + /// The same for files a host delivers (a browser's Place), with a PDF or an image first. + #[test] + fn inbox_batch_leaves_the_selected_frame() { + for names in [["one.pdf", "a.png"], ["a.png", "one.pdf"]] { + let mut app = app(); + let frame = select_a_graphic_frame(&mut app); + let request = app.import_request("place"); + for name in names { + let bytes = if name.ends_with(".pdf") { pdf_pages(1) } else { png(200) }; + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), names); + assert_eq!(frame_asset(&app, frame), "old.svg"); + } + // One file alone still fills it. + let mut app = app(); + let frame = select_a_graphic_frame(&mut app); + let request = app.import_request("place"); + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: "one.pdf".into(), bytes: pdf_pages(1) }); + app.drain_inbox(); + assert_eq!(frame_asset(&app, frame), "one.pdf"); + } + + /// The files a host delivered after a multi-page PDF wait for its Import Options, through a + /// second such PDF too, keep their order and don't replace what the cursor holds. + #[test] + fn inbox_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let mut app = app(); + let request = app.import_request("place"); + let files = + [("a.png", png(200)), ("three.pdf", pdf_pages(3)), ("b.png", png(90)), ("c.png", png(40)), ("two.pdf", pdf_pages(2)), ("d.png", png(20))]; + for (name, bytes) in files { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["a.png"], "waiting for the first PDF's options"); + assert_eq!(app.pending_pdf_rest.len(), 4); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.png", "three.pdf", "b.png", "c.png"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.png", "three.pdf", "b.png", "c.png", "two.pdf", "d.png"]); + assert!(app.pending_pdf.is_none() && app.pending_pdf_rest.is_empty()); + } + + /// Cancel ends a delivered batch, as a native one's does: what it loaded stays, the waiting + /// files are released. + #[test] + fn inbox_batch_ends_when_a_multi_page_pdf_is_cancelled() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("three.pdf", pdf_pages(3)), ("b.png", png(90))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(app.pending_pdf_rest.len(), 1); + dialogs::cancel(&mut app); + assert!(app.pending_pdf.is_none() && app.pending_pdf_rest.is_empty()); + assert_eq!(loaded_names(&app), ["a.png"]); + } + /// A multi-page PDF after images in a native batch asks which page, then queues after them. #[test] fn native_batch_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6775c7755..ef7b7b0a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -131,6 +131,8 @@ struct ShotRequest { pub struct DesignApp { pending_pdf: Option, + /// The files of the batch after `pending_pdf`, which wait for its Import Options. + pending_pdf_rest: Vec, /// File and message dialogs: asked for during a frame, shown by the host at its end, answered /// on a later frame (see `app/file_dialogs.rs`). #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index a99b4e144..c6b719584 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Several files go to the place cursor whatever is selected, even with a PDF first. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From b18506e3b5c8991b4ce5562a08e436ae455f05fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 10 Nov 2026 19:31:41 -0800 Subject: [PATCH 091/328] Anchored text frames: place a frame anchored inside another anchored frame placed::locate only looked for an anchored frame in host frames that sit on a spread. When the host frame was itself anchored, the inner frame got no placement and composed where it is stored, on no page. The host frame is now placed through its own host first, up to MAX_DEPTH hosts out. --- crates/compose/src/placed.rs | 40 +++++++++++++++++++++++--------- crates/compose/src/tests.rs | 44 ++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs index 33e4ff73c..0207f3af4 100644 --- a/crates/compose/src/placed.rs +++ b/crates/compose/src/placed.rs @@ -36,24 +36,42 @@ pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(Stor continue; } let items = anchored.get_or_insert_with(|| doc.anchored_items()); - // A frame anchored in its own story would need its own composition to place it. - let Some(owner) = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid) else { continue }; - let composed = hosts.entry(owner).or_insert_with(|| host(owner)); - if let Some(p) = locate(doc, composed, fid) { + if let Some(p) = locate(doc, items, sid, fid, &mut hosts, host, 0) { out.push((fid, p)); } } out } -/// Where `cs` (a host story's composition) places item `fid`: in its frames' anchored objects, -/// footnotes and table cells. -fn locate(doc: &Document, cs: &ComposedStory, fid: ItemId) -> Option { +/// Where the host story of `fid`, an anchored frame of story `sid`, places it: in its frames' +/// anchored objects, footnotes and table cells. A host frame that is itself anchored is placed +/// the same way first, up to [`MAX_DEPTH`] hosts out. `items` is [`Document::anchored_items`]. +fn locate( + doc: &Document, + items: &[(StoryId, &Item)], + sid: StoryId, + fid: ItemId, + hosts: &mut HashMap>, + host: &mut dyn FnMut(StoryId) -> Arc, + depth: usize, +) -> Option { + if depth > MAX_DEPTH { + return None; + } + // A frame anchored in its own story would need its own composition to place it. + let owner = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid)?; + let cs = hosts.entry(owner).or_insert_with(|| host(owner)).clone(); cs.frames.iter().find_map(|ft| { - let loc = doc.find(ft.frame)?; - let frame = doc.item_at(&loc)?; - let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; - Some(Placement { spread: loc.spread, xf }) + if let Some(loc) = doc.find(ft.frame) { + let frame = doc.item_at(&loc)?; + let xf = in_frame(ft, doc.parent_xf(&loc) * doc.text_xf(frame), fid, 0)?; + return Some(Placement { spread: loc.spread, xf }); + } + // The host frame is anchored too: find `fid` in it before placing the frame. + let local = in_frame(ft, Affine::IDENTITY, fid, 0)?; + let frame = items.iter().find_map(|(_, it)| (it.id == ft.frame).then_some(*it))?; + let outer = locate(doc, items, owner, ft.frame, hosts, host, depth + 1)?; + Some(Placement { spread: outer.spread, xf: outer.xf * doc.text_xf(frame) * local }) }) } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..e56095312 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8566,6 +8566,50 @@ fn anchored_frames_in_one_host_compose_it_once() { assert_eq!(Cache::new().get(&d, nsid, None).frames.len(), compose_story(&d, nsid, &ComposeOptions::default()).frames.len()); } +/// A text frame anchored in a text frame that is itself anchored in a frame on page 1 is placed +/// through both hosts: on page 1, at the inner object's spot in the outer anchored frame. +#[test] +fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + let frame = |d: &mut Document, text: &str, w: f64, h: f64| { + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) + }; + let (outer, osid) = frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + + let placed = placed::placements(&d, isid, &mut |h| Arc::new(compose_story(&d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner_id, SpreadRef::Doc(0))); + // The body frame's object, then the outer frame's object, each at its composed origin. + let host = compose_story(&d, sid, &ComposeOptions::default()); + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.item(bf).unwrap().xf + * Affine::translate(o1.origin.to_vec2()) + * d.anchored_item(outer_id).unwrap().xf + * Affine::translate(o2.origin.to_vec2()); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(&d, isid, &placed)[0].page, Some(0)); + // The cache places it the same way. + assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, From 9f4bc29c3e9e654f67463bc63b6e61e40f4f9c53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 13:31:04 -0800 Subject: [PATCH 092/328] Tables: a malformed table id is refused with nothing in a table selected With nothing in a table selected, a table command given a `table` that is not a nonnegative integer (`null`, a string, a negative number) was refused as disabled, since the enablement check read it as no table. It is now refused with "`table` must be a nonnegative integer", as it is with a table selected. --- crates/engine/src/cmd.rs | 12 ++++++++---- crates/engine/src/lib.rs | 4 ++-- crates/engine/src/tests/table.rs | 9 +++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..b9bc2b9c2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -332,12 +332,16 @@ pub(crate) fn named_targets(spec: &CommandSpec, p: &Value) -> Option } /// The table a call names with `table`, for a command whose params document an optional `table`. -/// `None` when the call names no table. [`table_story`] reads the `story` that goes with it. -pub(crate) fn named_table(spec: &CommandSpec, p: &Value) -> Option { +/// `None` when the call names no table. A `table` that is present but not a non-negative integer, +/// `null` included, is an error. [`table_story`] reads the `story` that goes with it. +pub(crate) fn named_table(spec: &CommandSpec, p: &Value, cmd: &str) -> Result> { if !spec.params.split(|c: char| !c.is_ascii_alphanumeric() && c != '?').any(|w| w == "table?") { - return None; + return Ok(None); + } + match p.get("table") { + None => Ok(None), + Some(v) => v.as_u64().map(Some).ok_or_else(|| bad(cmd, "`table` must be a nonnegative integer")), } - p.get("table").and_then(Value::as_u64) } /// The `story` a table command's call names alongside `table`, or `None` when the call has no diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3d43a80e0..716068c89 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -686,8 +686,8 @@ impl Session { // A table command that takes `story` and `table` acts on the table the call names, so // the selection doesn't matter: with nothing selected, the caret outside a table, or // selected rows the command can't act on, `{"table": 3}` still runs. - if let Some(table) = cmd::named_table(spec, params) - && cmd::has_doc(self).is_ok() + if cmd::has_doc(self).is_ok() + && let Some(table) = cmd::named_table(spec, params, id)? { let story = cmd::table_story(params, id)?; let st = self.doc()?; diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 2546fa667..7626005f4 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -78,6 +78,15 @@ fn table_target_rejects_wrong_typed_story_and_table_ids() { let error = s.execute("table.get", ¶ms).unwrap_err(); assert!(error.to_string().contains("no table"), "{error}"); } + // With nothing in a table selected, a malformed `table` is refused as such, not as disabled. + s.execute("edit.deselectAll", &json!({})).unwrap(); + for id in ["table.selectTable", "table.insertRow"] { + for value in [json!("other"), json!(-1), Value::Null] { + let error = s.execute(id, &json!({ "table": value })).unwrap_err(); + assert!(!matches!(error, crate::EngineError::Disabled(..)) && error.to_string().contains("`table`"), "{id} {value}: {error}"); + } + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); } #[test] From 27d8eabb103f8cc4baaaf6a2304260693a65d38e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 19:33:50 -0500 Subject: [PATCH 093/328] Render: clamp the blur size before the filter planner squares it (#2640) * Render: a blur size is clamped to 1,000,000 pt before the filter planner squares it * address review: bound effect extents and sigma before spread, padding and reach arithmetic --- crates/render/src/fx.rs | 67 ++++++++++++++++++++++++++++++----------- 1 file changed, 50 insertions(+), 17 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index af3c0227c..7c7c91fe1 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -29,6 +29,7 @@ use designcraft_compose::ShownOn; /// Shadow offset (spread units) for an InDesign angle (degrees, light direction) and distance. pub(crate) fn offset(angle: f64, distance: f64) -> Vec2 { let a = angle.to_radians(); + let distance = bound(distance); Vec2::new(-a.cos() * distance, a.sin() * distance) } @@ -37,33 +38,43 @@ pub(crate) fn outset(it: &Item) -> f64 { let e = &it.effects; let mut o: f64 = 0.0; if e.drop_shadow.on { - o = o.max(e.drop_shadow.distance.abs() + e.drop_shadow.size.abs() * 1.6 + 1.0); + o = o.max(bound(e.drop_shadow.distance).abs() + bound(e.drop_shadow.size).abs() * 1.6 + 1.0); } if e.outer_glow.on { - o = o.max(e.outer_glow.size.abs() * 1.6 + 1.0); + o = o.max(bound(e.outer_glow.size).abs() * 1.6 + 1.0); } o } /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { - let size = size.max(0.0); + let size = bound(size).max(0.0); let p = (pct / 100.0).clamp(0.0, 1.0); (size * (1.0 - p) / 2.0, size * p) } +/// Largest blur standard deviation handed to the filter planner, in points: far wider than any +/// page, so a larger one looks the same. Its planner squares the value in f32, so an unbounded +/// finite size would overflow to infinity there and never finish. +const MAX_SIGMA: f64 = 1.0e6; + +/// Largest effect extent (size, distance, feather width) used for geometry, in points: twice the +/// largest blur, so a size of any finite value, or infinity, cannot overflow later arithmetic +/// (`sigma * 3.0`, padding, reach). NaN is 0. +fn bound(v: f64) -> f64 { + if v.is_nan() { 0.0 } else { v.clamp(-2.0 * MAX_SIGMA, 2.0 * MAX_SIGMA) } +} + +fn std_dev(sigma: f64) -> f32 { + if sigma.is_nan() { 0.0 } else { sigma.clamp(0.0, MAX_SIGMA) as f32 } +} + fn blur(sigma: f64) -> Filter { - Filter::from_primitive(FilterPrimitive::GaussianBlur { std_deviation: sigma.max(0.0) as f32, edge_mode: EdgeMode::None }) + Filter::from_primitive(FilterPrimitive::GaussianBlur { std_deviation: std_dev(sigma), edge_mode: EdgeMode::None }) } fn shadow(sigma: f64, color: peniko::Color) -> Filter { - Filter::from_primitive(FilterPrimitive::DropShadowOnly { - dx: 0.0, - dy: 0.0, - std_deviation: sigma.max(0.0) as f32, - color, - edge_mode: EdgeMode::None, - }) + Filter::from_primitive(FilterPrimitive::DropShadowOnly { dx: 0.0, dy: 0.0, std_deviation: std_dev(sigma), color, edge_mode: EdgeMode::None }) } /// Keep what was drawn in the current layer as much as `it`'s gradient feather says. Cover the @@ -150,7 +161,7 @@ impl Renderer { // fade); Sharp and Rounded corners follow the inset shape more tightly than Diffused. if e.feather > 0.0 && it.path.is_closed() { let fo = &e.feather_options; - let w = e.feather * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); + let w = bound(e.feather) * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); let (sigma, join) = match fo.corners { designcraft_doc::FeatherCorners::Diffused => (w / 4.0, kurbo::Join::Round), designcraft_doc::FeatherCorners::Rounded => (w / 3.0, kurbo::Join::Round), @@ -266,7 +277,7 @@ impl Renderer { c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); c.set_transform(fr.view * xf); c.set_paint(peniko::Color::BLACK); - c.set_stroke(kurbo::Stroke::new((g.size - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); + c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); c.stroke_path(bp); c.pop_layer(); c.pop_layer(); @@ -281,7 +292,7 @@ impl Renderer { { let st = &e.satin; let off = offset(st.angle, st.distance / 2.0); - let sigma = st.size.max(0.0) / 2.0; + let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { @@ -309,8 +320,8 @@ impl Renderer { // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. if e.bevel.on { let b = &e.bevel; - let off = offset(doc.light_angle(b.angle, b.global_light), b.size * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); - let sigma = b.size.max(0.0) / 2.0; + let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); + let sigma = bound(b.size).max(0.0) / 2.0; if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { // The inverse shape moved away from the light lights the edges facing it. self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen, painted); @@ -340,6 +351,8 @@ impl Renderer { mix: Mix, painted: Option<(&Item, ShownOn)>, ) { + let sigma = bound(sigma).max(0.0); + let choke = bound(choke); if let Some((it, page)) = painted { self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; @@ -425,8 +438,9 @@ impl Renderer { clip: Option<(&BezPath, Affine)>, draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), ) { + let sigma = bound(sigma).max(0.0); // 3σ of the Gaussian in pixels, plus a pixel of antialiasing. - let spread = sigma.max(0.0) * 3.0 / f.px + 2.0; + let spread = sigma * 3.0 / f.px + 2.0; if !f.mt && spread <= MAX_BLUR_SPREAD { push_clip(ctx, f, clip); draw(self, ctx, f); @@ -498,6 +512,25 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option Date: Wed, 11 Nov 2026 17:30:21 -0800 Subject: [PATCH 094/328] Type: type.align without a value is an error (#2645) type.align with no `align` key applied Align Left, so a call that misspelled the key, or passed a bare string, changed the paragraphs to left alignment instead of failing. The command now returns an error, leaves the text unchanged and records no undo step. A named value still applies, and `align: null` still removes the override. --- crates/engine/src/cmd/text.rs | 5 +++-- crates/engine/src/cmd/text/format.rs | 31 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bee08c167..4bcbd6cc4 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -238,8 +238,9 @@ pub fn specs() -> Vec { has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), - cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…}", has_text_or_frames, |s, p| { - format_paras(s, &json!({"align": p.get("align").cloned().unwrap_or(json!("left"))})) + cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…|null} (required)", has_text_or_frames, |s, p| { + let align = p.get("align").cloned().ok_or_else(|| bad("type.align", "`align` required"))?; + format_paras(s, &json!({ "align": align })) }), cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "left"}))), cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| format_paras( diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index d915da91d..10bce4841 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -1074,6 +1074,37 @@ mod pick_up_format_tests { } } +#[cfg(test)] +mod align_param_tests { + use serde_json::json; + + use crate::Session; + + /// `type.align` with no `align` applied Align Left, so a script that misspelled the key + /// (`{"alignment": "center"}`) changed the paragraph to the opposite of what it asked for. + #[test] + fn type_align_without_a_value_is_refused_and_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world"})).unwrap(); + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 5})).unwrap(); + s.execute("type.align", &json!({"align": "right"})).unwrap(); + let align = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone(); + assert_eq!(align(&mut s), json!("right")); + let steps = s.doc().unwrap().history.undo.len(); + for params in [json!({}), json!({"alignment": "center"}), json!("center"), json!({"align": "middle"})] { + assert!(s.execute("type.align", ¶ms).is_err(), "{params}"); + assert_eq!(align(&mut s), json!("right"), "{params}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{params}: no undo step"); + } + // A named value still applies, and null removes the override. + s.execute("type.align", &json!({"align": "center"})).unwrap(); + assert_eq!(align(&mut s), json!("center")); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(align(&mut s), json!("left")); + } +} + #[cfg(test)] mod size_bounds_tests { use serde_json::json; From 54652717c041cc03105a876dcfa5b94ff6e181ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:30:44 -0800 Subject: [PATCH 095/328] Text Frame Options: a non-rectangular frame shows one Inset field For an oval, a polygon or a frame with corner options, Inset Spacing dims Top, Left, Bottom, Right and the link and shows one Inset field. OK sends it as `object.textFrameOptions {inset: }`, which sets all four sides; compose keeps that inset from the frame's outline. Rectangular frames keep the four fields. --- crates/ui-egui/src/dialogs.rs | 57 ++++++++++++++--- crates/ui-egui/src/dialogs/tests.rs | 94 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/cs.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/hu.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ka.rs | 1 + crates/ui-egui/src/i18n/pl.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/ru.rs | 1 + crates/ui-egui/src/i18n/sv.rs | 1 + crates/ui-egui/src/i18n/table.rs | 1 + crates/ui-egui/src/i18n/uk.rs | 1 + docs/target-app-parity.md | 1 + 16 files changed, 155 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..158b9d07d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,6 +1005,23 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { + let shaped = || { + let st = app.session.active()?; + let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; + let item = st.doc.item(fid)?; + if item.text_frame()?.options.path.is_some() { + return Some(false); + } + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) + }; + shaped().unwrap_or(false) +} + /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, /// so OK sends only the fields the user changed. Fields given when the dialog opened count as /// changed. @@ -1032,7 +1049,7 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { }; designcraft_doc::FrameBaselineGrid { start: g.start, increment: g.increment, relative_to } }); - let shown = json!({ + let mut shown = json!({ "columns": o.columns, "gutter": fm(o.gutter), "columnsKind": kind(serde_json::to_value(o.columns_kind).unwrap_or_default()), "columnWidth": fm(width), "balanceColumns": o.balance_columns, "ignoreWrap": o.ignore_wrap, @@ -1051,6 +1068,12 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { "customGrid": o.baseline_grid.is_some(), "gridStart": fm(grid.start), "gridIncrement": fm(grid.increment), "gridRelativeTo": grid.relative_to.name(), }); + // A non-rectangular frame shows one Inset (its top inset, the one kept from the outline). + let shaped = selected_frame_is_shaped(app); + if shaped && let Value::Object(m) = &mut shown { + m.insert("inset".into(), fm(o.inset[0])); + } + d.fields.insert("_shaped".into(), json!(shaped)); if let Value::Object(m) = &shown { for (k, v) in m { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); @@ -1218,8 +1241,9 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { } /// Text Frame Options › General, as InDesign's: Columns (kind, number and width, gutter and -/// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right), Vertical -/// Justification (align, paragraph spacing limit) and Ignore Text Wrap. +/// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right; one Inset +/// for a non-rectangular frame), Vertical Justification (align, paragraph spacing limit) and +/// Ignore Text Wrap. fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { let tr = |s: &'static str| crate::i18n::tr(lang, s); let (cap, field, cap2) = (64.0, 110.0, 70.0); @@ -1243,8 +1267,10 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { // Fixed Number: each column's width, from the frame, the insets and the gutter. let frame = d.fields.get("_frameWidth").and_then(Value::as_f64); let n = d.n("columns").unwrap_or(1.0).max(1.0); + // A non-rectangular frame keeps its sides until its one Inset is changed. + let (left, right) = if d.b("_shaped") && edited(d, "inset") { ("inset", "inset") } else { ("insetLeft", "insetRight") }; let width = frame.map(|w| { - let inner = w - d.m("insetLeft").unwrap_or(0.0) - d.m("insetRight").unwrap_or(0.0); + let inner = w - d.m(left).unwrap_or(0.0) - d.m(right).unwrap_or(0.0); ((inner - d.m("gutter").unwrap_or(0.0) * (n - 1.0)) / n).max(0.0) }); let _ = crate::widgets::NumField::measure("tfo_auto_width", width, d.unit).width(field).spinner().enabled(false).show(ui); @@ -1262,6 +1288,9 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { check(ui, d, "balanceColumns", tr("Balance Columns")); }); framed(ui, Some(tr("Inset Spacing")), |ui| { + // A non-rectangular frame: the four sides are dimmed and one Inset sets the distance kept + // from the outline. + let shaped = d.b("_shaped"); // While linked, a side typed in sets all four ("Make all settings the same"). let sides = ["insetTop", "insetLeft", "insetBottom", "insetRight"]; let before: Vec = sides.iter().map(|k| d.s(k)).collect(); @@ -1270,24 +1299,32 @@ fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { { ui.horizontal(|ui| { caption_at(ui, tr(l1), cap); - spin_measure(ui, d, k1, field, true); + spin_measure(ui, d, k1, field, !shaped); ui.add_space(8.0); if r == 0 { let linked = d.b("insetLinked"); let tip = tr("Make all settings the same"); - if crate::widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, tip, egui::vec2(22.0, 21.0)) - .clicked() - { + let toggle = ui.add_enabled_ui(!shaped, |ui| { + crate::widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, tip, egui::vec2(22.0, 21.0)) + }); + if toggle.inner.clicked() { d.fields.insert("insetLinked".into(), json!(!linked)); } } else { ui.add_space(22.0 + ui.spacing().item_spacing.x); } caption_at(ui, tr(l2), cap2 - 30.0); - spin_measure(ui, d, k2, field, true); + spin_measure(ui, d, k2, field, !shaped); }); } - if d.b("insetLinked") + if shaped { + ui.horizontal(|ui| { + caption_at(ui, tr("Inset:"), cap); + spin_measure(ui, d, "inset", field, true); + }); + } + if !shaped + && d.b("insetLinked") && let Some(k) = sides.iter().zip(&before).find(|(k, b)| d.s(k) != **b).map(|(k, _)| *k) { let v = d.fields.get(k).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..a11bd2f3f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1436,6 +1436,100 @@ fn text_frame_options_set_a_custom_baseline_grid_relative_to() { assert_eq!(grid(&app), None); } +/// A non-rectangular frame (an oval, or a rectangle with rounded corners) shows one Inset, the +/// distance kept from its outline, and OK sends it as one value for all four sides. A rectangle +/// keeps the four side fields. +#[test] +fn text_frame_options_set_one_inset_for_a_non_rectangular_frame() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let oval = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 300, 336, 500], "content": "text", "text": "Hello"})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let open = |app: &mut DesignApp, id: designcraft_doc::ItemId| { + app.run("selection.set", json!({"ids": [id.0]})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d + }; + // The oval shows its top inset as the one Inset. + let d = open(&mut app, oval); + assert!(d.b("_shaped")); + assert_eq!(d.s("inset"), "0p6"); + // OK without edits changes nothing, and adds no undo step. + let undo = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog = Some(d); + assert_eq!(confirm(&mut app).unwrap(), Value::Null); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + // Inset set to 1p0: all four sides take it. + let mut d = open(&mut app, oval); + d.fields.insert("inset".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, oval).inset, [12.0; 4]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + // A value that isn't a measure is refused and the frame keeps its inset. + let mut d = open(&mut app, oval); + d.fields.insert("inset".into(), json!("not a measure")); + app.ui.dialog = Some(d); + assert!(confirm(&mut app).unwrap_err().to_string().contains("the inset is not a measure")); + assert_eq!(opts(&app, oval).inset, [12.0; 4]); + // A rectangle shows the four sides; with rounded corners it is not rectangular either. + let d = open(&mut app, rect); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "a rectangle shows the four sides"); + app.run("object.cornerOptions", json!({"ids": [rect.0], "shape": "rounded", "size": 12})).unwrap(); + let d = open(&mut app, rect); + assert!(d.b("_shaped")); + assert_eq!(d.s("inset"), "0p6"); +} + +/// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an +/// Inset field; for a rectangle it shows no Inset field and the sides stay editable. +#[test] +fn text_frame_options_dims_the_sides_for_a_non_rectangular_frame() { + use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, + }; + for shaped in [true, false] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let shape = if shaped { "ellipse" } else { "rectangle" }; + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": shape, "content": "text", "text": "Hello"})).unwrap(); + app.run("selection.set", json!({"ids": [r["id"]]})).unwrap(); + app.ui.dialog = Some(Dialog::new("textFrameOptions", json!({}))); + // The General tab's Columns and Align dropdowns have no accessible name yet. + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("text_frame_inset_test_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + for side in ["insetTop", "insetLeft", "insetBottom", "insetRight"] { + let label = format!("Increase tfo_{side}"); + assert_eq!(h.get_by_label(&label).accesskit_node().is_disabled(), shaped, "{shape}: {side}"); + } + assert_eq!(h.query_by_label("Inset:").is_some(), shaped, "{shape}: the Inset caption"); + assert_eq!(h.query_by_label("Increase tfo_inset").is_some(), shaped, "{shape}: the Inset field"); + // The link toggles only for a rectangle. + let linked = |h: &Harness<'_, DesignApp>| h.state().ui.dialog.as_ref().unwrap().b("insetLinked"); + let before = linked(&h); + h.get_by_label("Make all settings the same").click(); + h.run_steps(3); + assert_eq!(linked(&h) != before, !shaped, "{shape}: the link"); + } +} + #[test] fn text_frame_options_change_only_what_was_edited() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index adf22f4fb..28dda77d0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1858,6 +1858,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "خيارات الإبقاء"), ("Span Columns", "امتداد الأعمدة"), ("Top:", "أعلى:"), + ("Inset:", "الإزاحة الداخلية:"), ("Left:", "يسار:"), ("Bottom:", "أسفل:"), ("Right:", "يمين:"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 5310e8d12..32bf1803c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1913,6 +1913,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Třetina čtverčíku"), ("Title Case", "Velká Počáteční Písmena"), ("Top:", "Nahoře:"), + ("Inset:", "Odsazení:"), ("Trademark Symbol", "Symbol ochranné známky"), ("Transform Again Individually", "Transformovat znovu jednotlivě"), ("Transform Sequence Again", "Transformovat posloupnost znovu"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2e9920126..15009e53a 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1864,6 +1864,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Drittelgeviert"), ("Title Case", "Wortanfänge groß"), ("Top:", "Oben:"), + ("Inset:", "Versatz:"), ("Trademark Symbol", "Markensymbol"), ("Transform Again Individually", "Erneut einzeln transformieren"), ("Transform Sequence Again", "Abfolge erneut transformieren"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..8ca23c858 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1727,6 +1727,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Top Margin", "Felső margó"), ("Top of Page", "Oldal teteje"), ("Top:", "Fent:"), + ("Inset:", "Belső margó:"), ("Track Changes", "Változások követése"), ("Track Changes in All Stories", "Változások követése minden szövegfolyamban"), ("Tracking", "Betűköz"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 131875d46..9f0cf29c0 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1918,6 +1918,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Opzioni di unione"), ("Span Columns", "Estendi su colonne"), ("Top:", "Superiore:"), + ("Inset:", "Rientro:"), ("Left:", "Sinistra:"), ("Bottom:", "Inferiore:"), ("Right:", "Destra:"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ae2dd653f..9c6a9772f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -2057,6 +2057,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "三分スペース"), ("Title Case", "各単語の先頭を大文字に"), ("Top:", "上:"), + ("Inset:", "フレーム内マージン:"), ("Trademark Symbol", "商標記号"), ("Transform Again Individually", "個別に再変形"), ("Transform Sequence Again", "一連の変形を再実行"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 1ba9a61a9..74b688a10 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1955,6 +1955,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "მესამედი შორისი"), ("Title Case", "ყოველი სიტყვა მთავრულით"), ("Top:", "ზემოთ:"), + ("Inset:", "შეწევა:"), ("Trademark Symbol", "სავაჭრო ნიშნის სიმბოლო"), ("Transform Again Individually", "გარდაქმნის ცალ-ცალკე გამეორება"), ("Transform Sequence Again", "გარდაქმნების მიმდევრობის გამეორება"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 7aac5d74b..b37f8de3e 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1888,6 +1888,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Trzecia firetu"), ("Title Case", "Wielkie Litery Wyrazów"), ("Top:", "Góra:"), + ("Inset:", "Margines wewnętrzny:"), ("Trademark Symbol", "Symbol znaku towarowego"), ("Transform Again Individually", "Przekształć ponownie osobno"), ("Transform Sequence Again", "Powtórz sekwencję przekształceń"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 147947dbd..a5c47c386 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1468,6 +1468,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Opções de manter"), ("Span Columns", "Abranger colunas"), ("Top:", "Superior:"), + ("Inset:", "Recuo:"), ("Left:", "Esquerda:"), ("Bottom:", "Inferior:"), ("Right:", "Direita:"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 178cc9bc3..3cfb7fff0 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1898,6 +1898,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Third Space", "Треть шпации"), ("Title Case", "Каждое слово с прописной"), ("Top:", "Сверху:"), + ("Inset:", "Отступ:"), ("Trademark Symbol", "Знак товарного знака"), ("Transform Again Individually", "Повторить трансформирование по отдельности"), ("Transform Sequence Again", "Повторить последовательность трансформирования"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..f3def92b5 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -65,6 +65,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Gutter:", "Spaltmellanrum:"), ("Fit Guides to:", "Anpassa stödlinjer till:"), ("Top:", "Överkant:"), + ("Inset:", "Infällning:"), ("Bottom:", "Nederkant:"), ("Inside:", "Inre:"), ("Outside:", "Yttre:"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index ebde2b629..0aea8e244 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -479,6 +479,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Gutter:", ["Steg:", "Gouttière :", "Medianil:", "間隔:", "栏间距:"]), ("Fit Guides to:", ["Hilfslinien einpassen in:", "Ajuster les repères à :", "Ajustar guías a:", "ガイドの適用先:", "参考线适合:"]), ("Top:", ["Oben:", "Haut :", "Superior:", "天:", "上:"]), + ("Inset:", ["Versatz:", "Marge intérieure :", "Margen interior:", "フレーム内マージン :", "内边距:"]), ("Bottom:", ["Unten:", "Bas :", "Inferior:", "地:", "下:"]), ("Inside:", ["Innen:", "Intérieur :", "Interior:", "ノド:", "内:"]), ("Outside:", ["Außen:", "Extérieur :", "Exterior:", "小口:", "外:"]), diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4b2853eae..16a983abe 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1885,6 +1885,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Keep Options", "Параметри утримання"), ("Span Columns", "Охоплення колонок"), ("Top:", "Зверху:"), + ("Inset:", "Відступ:"), ("Left:", "Ліворуч:"), ("Bottom:", "Знизу:"), ("Right:", "Праворуч:"), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..4207507dc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -352,6 +352,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. +- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. - Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame. Clipping paths saved in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path; Invert) hide the image outside the path on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (Object ▸ Clipping Path ▸ None). From 86867e8e42f0a1f8749ebf1f23359a61e51ad0f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:31:56 -0800 Subject: [PATCH 096/328] Compose: vertical Center, Bottom and Justify measure to the last baseline Vertical justification measured the free space down to the bottom of the last line's descenders, so Center set text too high (most visibly with a Cap Height first baseline) and Bottom and Justify left the descender depth empty. The last baseline is now the bottom of the text: Bottom and Justify put it on the bottom inset, and Center leaves as much room below it as above the first line. The descenders may reach into the bottom inset but not past the frame's edge; above footnotes, in vertical frames and in shaped frames they stay inside the text area. Tables keep their bottom. A shaped frame no longer tests the part of a line above its text area against the outline, so a small corner radius leaves a Cap Height first line where a rectangular frame puts it. Fixes #1999 --- crates/compose/src/lib.rs | 39 ++++++++++----- crates/compose/src/tests.rs | 98 +++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..858cf0433 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4311,9 +4311,10 @@ fn wrap_slot( #[allow(clippy::too_many_arguments)] fn free_slots(f: &FrameSpec, col: Rect, y0: f64, y1: f64, desc: f64, size: f64, rtl: bool, line_start: usize) -> Vec<(f64, f64)> { // A shaped frame: the parts of the band its outline covers (a concave one can give several), - // descenders included: they stay inside the frame. + // descenders included: they stay inside the frame. The part of the band above the column's + // top is not tested, as in a rectangular frame: a Cap Height first line reaches above it. let mut free = match &f.outline { - Some(o) => o.intervals(col.x0, col.x1, y0, y1 + desc.max(0.0)), + Some(o) => o.intervals(col.x0, col.x1, y0.max(col.y0).min(y1), y1 + desc.max(0.0)), None => vec![(col.x0, col.x1)], }; let mut cut = f.outline.is_some(); @@ -5495,23 +5496,39 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); - let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; - let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); - let bottom = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(bottom, f64::max); - let limit = ft + if idx.is_empty() { + continue; + } + let note_top = ft .notes .iter() .filter(|n| spanned || notes.span_columns || n.column == c) .map(|n| n.rect.y0 - notes.space_before) - .fold(f.area.y1, f64::min); - let space = limit - bottom; - if space <= 0.0 { + .fold(f64::INFINITY, f64::min); + let limit = note_top.min(f.area.y1); + let tables = ft.tables.iter().filter(|t| spanned || t.column == c).map(|t| t.rect.y1).fold(f64::NEG_INFINITY, f64::max); + let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); + let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); + // The bottom of the text is the last baseline, as the top is the first baseline: the + // descenders of the last line may reach into the bottom inset, but not past the frame's + // edge, and in a shaped frame not past the text area (its outline holds the descenders). + // Above footnotes, and in vertical frames, the descenders stay inside the text area, as + // when the lines are fitted. + // `space`: the room under the bottom of the text; `room`: how far its last line may move. + let (space, room) = if f.vertical || note_top <= f.area.y1 { + (limit - ink_bottom, f64::INFINITY) + } else { + let edge = if f.outline.is_some() { f.area.y1 } else { f.area.y1 + f.opts.inset[2].max(0.0) }; + (limit - last_baseline, edge - ink_bottom) + }; + if space <= 0.0 || room <= 0.0 { continue; } - let _ = a; + let center = (space / 2.0).min(room); + let space = space.min(room); let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += space / 2.0), + VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += center), VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), VerticalJustification::Justify => { // Segments of one line (beside an object) share a row and move together. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..d9e3df22e 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2300,6 +2300,104 @@ fn vertical_justification_counts_table_fragment_bottoms() { } } +/// Center, Bottom and Justify place the text between its first baseline (where Top sets it) and +/// its last baseline: Bottom and Justify put the last baseline on the bottom inset, and Center +/// leaves as much room under the last baseline as above the first line (#1999). +#[test] +fn vertical_justification_measures_to_the_last_baseline() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_inset = |mode: VerticalJustification, first: FirstBaseline, bottom_inset: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = first; + o.inset = [6.0, 6.0, bottom_inset, 6.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect::>()) + }; + let compose_with = |mode, first| compose_inset(mode, first, 9.0); + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight] { + let (area, top) = compose_with(Top, first); + assert!((area.y1 - 291.0).abs() < 1e-9, "the bottom inset bounds the text area: {area:?}"); + assert_eq!(top.len(), 2); + let last = |v: &[(f64, f64)]| v[v.len() - 1]; + + let (_, bottom) = compose_with(Bottom, first); + assert!((last(&bottom).0 - area.y1).abs() < 1e-6, "{first:?}: Bottom puts the last baseline on the inset: {bottom:?}"); + assert!(last(&bottom).0 + last(&bottom).1 > area.y1 + 1.0, "{first:?}: the descenders reach into the inset"); + assert!((bottom[1].0 - bottom[0].0 - (top[1].0 - top[0].0)).abs() < 1e-6, "{first:?}: Bottom keeps the leading"); + + let (_, justify) = compose_with(Justify, first); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{first:?}: Justify keeps the first baseline: {justify:?}"); + assert!((last(&justify).0 - area.y1).abs() < 1e-6, "{first:?}: Justify puts the last baseline on the inset: {justify:?}"); + + let (_, center) = compose_with(Center, first); + let shift = center[0].0 - top[0].0; + assert!(shift > 1.0); + assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); + assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); + + // A bottom inset smaller than the descent: the descenders end on the frame's edge. + for inset in [0.0, 1.0] { + for mode in [Bottom, Justify] { + let (area, lines) = compose_inset(mode, first, inset); + let (b, desc) = last(&lines); + assert!(desc > inset + 0.5); + assert!((b + desc - (area.y1 + inset)).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: descenders end at {}", b + desc); + } + } + } +} + +/// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top +/// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +#[test] +fn a_corner_radius_keeps_a_cap_height_line_in_place() { + use designcraft_doc::VerticalJustification::{self, Center, Top}; + use designcraft_geom::corners::{CornerOptions, CornerShape}; + let mm = 72.0 / 25.4; + let rect = Rect::new(0.0, 0.0, 29.553 * mm, 9.593 * mm); + let compose_with = |radius: f64, mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.first_baseline = FirstBaseline::CapHeight; + o.inset = [0.0; 4]; + d.story_mut(sid).unwrap().format_chars(0.."137mm".len(), |f| { + f.over.size = Some(19.0); + f.over.leading = Some(designcraft_doc::Leading::Points(19.0)); + }); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) + }; + let (square, area, top) = compose_with(0.0, Top); + let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); + assert!(!square && rounded, "only the radius gives the frame an outline"); + assert!((rounded_top - top).abs() < 1e-6, "Top: {rounded_top} with a radius, {top} without"); + let (_, _, center) = compose_with(0.0, Center); + let (_, _, rounded_center) = compose_with(0.1 * mm, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); + assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); + + // In a shaped frame the outline holds the descenders: with Bottom they end on the text area's + // bottom, not in the bottom inset. + let (mut d, sid, fid) = doc_with("gypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, 6.0); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + o.inset = [0.0, 0.0, 12.0, 0.0]; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = &cs.frames[0].lines[0]; + assert!((l.baseline + l.descent - area.y1).abs() < 1e-6, "descenders end at {}, text area at {}", l.baseline + l.descent, area.y1); +} + #[test] fn table_rows_clear_footnotes_and_continue_in_the_next_column() { for span in [false, true] { From e362820bc45f497fb4188bd98e44cf5b37fde8fc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:42:24 -0800 Subject: [PATCH 097/328] Data merge: an image field in text places the image, not its path An image field inserted at a text insertion point, or typed there as <>, merged as text, so each record showed the image's path. It now merges as an inline image at its natural size, scaled down to fit the smallest text column of the story's frames. A missing file is listed in missingImages and its marker is removed. An explicit image role at a text insertion point places an inline image too. An image path that starts with one separator (\Photos\a.jpg) is tried from the drive's root first, then beside the data file and the document. --- crates/engine/src/cmd/datamerge.rs | 18 ++- crates/engine/src/cmd/datamerge/fill.rs | 190 ++++++++++++++++++----- crates/engine/src/cmd/datamerge/parse.rs | 7 +- crates/engine/src/cmd/datamerge/tests.rs | 151 ++++++++++++++++++ docs/agents.md | 5 +- 5 files changed, 324 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 7cb332fd3..6fac73836 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image", has_doc, placeholder_add ), @@ -484,8 +484,11 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> true } else if explicit_story || role_param == Some("text") { false - } else if matches!(role_param, Some("image" | "qr")) { + } else if role_param == Some("qr") { true + } else if role_param == Some("image") { + // An image role with the insertion point in text places an inline image there. + sel.text.is_none() } else { sel.text.is_none() && !sel.items.is_empty() }; @@ -497,6 +500,9 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> DataFieldKind::Qr => PlaceholderRole::Qr, DataFieldKind::Text => return Err(bad("data.placeholder.add", "say which role to use on this frame")), } + } else if field.kind == DataFieldKind::Image { + // An image field at the insertion point places the image inline in the text. + PlaceholderRole::Image } else { PlaceholderRole::Text }; @@ -515,14 +521,14 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } PlaceholderAnchor::Item { id: item } } else { - if matches!(role, PlaceholderRole::Image | PlaceholderRole::Qr) { - return Err(bad("data.placeholder.add", "image and qr placeholders bind to a frame")); + if role == PlaceholderRole::Qr { + return Err(bad("data.placeholder.add", "qr placeholders bind to a frame")); } let (story, at, end) = text_target(p, sel).ok_or_else(|| bad("data.placeholder.add", "select text or a frame"))?; if d.story(story).is_none() { return Err(bad("data.placeholder.add", "no story")); } - if role == PlaceholderRole::Text { + if matches!(role, PlaceholderRole::Text | PlaceholderRole::Image) { let marker = format!("<<{name}>>"); let at = { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); @@ -574,7 +580,7 @@ pub(crate) fn sync_placeholders(doc: &mut Document) { } PlaceholderAnchor::Text { story, start, end } => { let text = doc.story(story).map(|st| st.text.clone()).unwrap_or_default(); - if ph.role != PlaceholderRole::Text { + if !matches!(ph.role, PlaceholderRole::Text | PlaceholderRole::Image) { if start <= end && end <= text.len() { keep.push(ph); } diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index a7b4a0ba6..caea4d67e 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -8,10 +8,10 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use designcraft_doc::{ - Asset, AssetId, Content, DataField, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, HyperlinkSource, Item, ItemId, MergeOptions, - PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, + AnchorPosition, AnchoredObject, Asset, AssetId, Content, DataField, DataFieldKind, Fill, Fitting, Graphic, Hyperlink, HyperlinkDest, + HyperlinkSource, Item, ItemId, MergeOptions, OBJECT_MARK, PlaceholderAnchor, PlaceholderRole, Shape, SpreadRef, Story, StoryId, }; -use designcraft_geom::{Affine, Rect, Vec2}; +use designcraft_geom::{Affine, Rect, Vec2, shapes}; use super::parse::image_candidates; use crate::EngineError; @@ -147,6 +147,16 @@ struct Rep { start: usize, end: usize, text: String, + /// An inline image that takes the range's place; `text` is then its object mark. + object: Option, +} + +/// An image field at a text range: the placed image goes into the text in the marker's place. +struct InlineImage { + story: StoryId, + start: usize, + end: usize, + field: String, } /// Where `fill_row` looks for linked images: the merge options and the two search folders. @@ -199,6 +209,7 @@ impl ImageCache { #[derive(Default)] struct Pending { reps: Vec, + images: Vec, links: Vec<(PlaceholderAnchor, HyperlinkDest, String)>, parent: bool, report: FillReport, @@ -225,8 +236,14 @@ pub fn fill_row( PlaceholderAnchor::Item { .. } => plan_item(doc, maps, ph, &cell, record, sources, &mut pending), } } - let Pending { mut reps, links, parent, mut report } = pending; - typed_reps(doc, fields, row, maps, &placeholders, &mut reps); + let Pending { mut reps, mut images, links, parent, mut report } = pending; + typed_reps(doc, fields, row, maps, &placeholders, &mut reps, &mut images); + for InlineImage { story, start, end, field } in images { + let cell = cell_of(fields, row, &field); + let object = inline_image(doc, story, &field, cell, record, sources, &mut report); + let text = if object.is_some() { OBJECT_MARK.to_string() } else { String::new() }; + reps.push(Rep { story, start, end, text, object }); + } apply_reps(doc, &reps); for (anchor, dest, field) in links { let anchor = match anchor { @@ -261,13 +278,14 @@ fn plan_text( return; }; match ph.role { - PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell }), + PlaceholderRole::Text => pending.reps.push(Rep { story: mapped, start, end, text: cell, object: None }), + PlaceholderRole::Image => pending.images.push(InlineImage { story: mapped, start, end, field: ph.field.clone() }), PlaceholderRole::Hyperlink => { if let Some(dest) = classify_link(&cell) { pending.links.push((PlaceholderAnchor::Text { story: mapped, start, end }, dest, ph.field.clone())); } } - PlaceholderRole::Image | PlaceholderRole::Qr => {} + PlaceholderRole::Qr => {} } } @@ -306,6 +324,7 @@ fn typed_reps( maps: &Maps, placeholders: &[designcraft_doc::Placeholder], reps: &mut Vec, + images: &mut Vec, ) { let mut stories: Vec<(StoryId, StoryId)> = maps.stories.iter().map(|(a, b)| (*a, *b)).collect(); stories.sort_by_key(|(a, _)| a.0); @@ -315,7 +334,9 @@ fn typed_reps( let covers: Vec<(usize, usize)> = placeholders .iter() .filter_map(|ph| match (&ph.role, &ph.anchor) { - (PlaceholderRole::Text, PlaceholderAnchor::Text { story, start, end }) if *story == original => Some((*start, *end)), + (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start, end }) if *story == original => { + Some((*start, *end)) + } _ => None, }) .collect(); @@ -323,10 +344,12 @@ fn typed_reps( if covers.iter().any(|(a, b)| start < *b && end > *a) { continue; } - if !fields.iter().any(|f| f.name == name) { + let Some(field) = fields.iter().find(|f| f.name == name) else { continue }; + if field.kind == DataFieldKind::Image { + images.push(InlineImage { story: mapped, start, end, field: name }); continue; } - reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string() }); + reps.push(Rep { story: mapped, start, end, text: cell_of(fields, row, &name).to_string(), object: None }); } } } @@ -367,6 +390,15 @@ fn apply_reps(doc: &mut designcraft_doc::Document, reps: &[Rep]) { for r in mine { if r.start <= r.end && r.end <= st.text.len() { st.replace(r.start..r.end, &r.text); + // The replacement made a blank object for its mark; the image takes that slot. + if let Some(obj) = &r.object + && st.text.get(r.start..).is_some_and(|t| t.starts_with(OBJECT_MARK)) + { + let k = st.text[..r.start].matches(OBJECT_MARK).count(); + if let Some(slot) = st.objects.get_mut(k) { + *slot = Arc::new(obj.clone()); + } + } } } } @@ -420,10 +452,19 @@ fn create_link(doc: &mut designcraft_doc::Document, anchor: PlaceholderAnchor, d true } -fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { - let Sources { options, data_dir, doc_dir, images } = *sources; +/// An image file named by a cell: where it was found, its bytes, its pixel size and its natural size. +struct LoadedImage { + path: PathBuf, + bytes: Arc>, + pixels: (u32, u32), + natural: (f64, f64), +} + +/// The first candidate for `cell` that reads and decodes; `None` when none does. +fn load_image(cell: &str, sources: &Sources) -> Option { + let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let found = cands.iter().find_map(|p| { + let (path, bytes) = cands.iter().find_map(|p| { // Read once per merge: many records naming one file is the normal case, and reading it // per record is the amplification (#1595). let bytes = images.get_or_read(p, || { @@ -435,23 +476,98 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c crate::io::read_file(p).ok().filter(|b| !b.is_empty()) })?; Some((p.clone(), bytes)) + })?; + let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; + Some(LoadedImage { path, bytes, pixels, natural }) +} + +fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); +} + +/// Add `image` to the document as a new asset, linked to its file when the options say so. +fn add_image_asset(doc: &mut designcraft_doc::Document, image: LoadedImage, field: &str, options: &MergeOptions) -> AssetId { + let fresh = AssetId(doc.alloc()); + let name = image.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); + let link = options.link_images.then(|| image.path.to_string_lossy().into_owned()); + doc.add_asset(Asset { + id: fresh, + name, + mime: designcraft_render::image_mime(&image.bytes).to_string(), + link, + // The cached buffer is shared with every other record naming this file, rather than + // copied per record (#1595). + data: image.bytes, + pixels: Some(image.pixels), + ..Default::default() + }) +} + +/// The image `cell` names, as an inline object for the text of `story`. It comes in at its +/// natural size, scaled down to fit the smallest text column of the story's frames (never scaled up). +fn inline_image( + doc: &mut designcraft_doc::Document, + story: StoryId, + field: &str, + cell: &str, + record: u32, + sources: &Sources, + report: &mut FillReport, +) -> Option { + let Some(image) = load_image(cell, sources) else { + report_missing(report, record, field, cell); + return None; + }; + let (nw, nh) = image.natural; + let frame = doc.story(story).and_then(|st| st.frames.first().copied()).and_then(|id| doc.item(id)); + let layer = frame.map_or_else(|| doc.default_layer(), |it| it.layer); + // The marker may flow into any of the story's frames: fit the smallest column among them. + let fit = designcraft_compose::frame_specs(doc, story) + .iter() + .flat_map(|f| f.columns()) + .map(|b| (b.width() / nw).min(b.height() / nh)) + .reduce(f64::min) + .unwrap_or(1.0); + let k = if fit.is_finite() && fit > 0.0 { fit.min(1.0) } else { 1.0 }; + let rect = Rect::new(0.0, 0.0, nw * k, nh * k); + let xf = Affine::scale(k); + if super::super::file::validate_placement((nw, nh), rect, xf, "data.merge").is_err() { + report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); + report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); + return None; + } + let asset = add_image_asset(doc, image, field, sources.options); + let mut it = Item::new(ItemId(doc.alloc()), layer, Shape::Rectangle, shapes::rectangle(rect)); + it.object_style = doc.styles.default_graphic_frame.clone(); + if let Some(e) = doc.styles.object_effects(&it.object_style) { + it.effects = e.clone(); + } + it.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + clip: None, + fill: Default::default(), }); - let Some((path, bytes)) = found else { + Some(AnchoredObject::new(it, AnchorPosition::default())) +} + +fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, cell: &str, record: u32, sources: &Sources, report: &mut FillReport) { + let options = sources.options; + let Some(image) = load_image(cell, sources) else { if let Some(it) = doc.item_mut(item) { it.content = Content::Unassigned; } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); - return; - }; - let Some(((pw, ph), (nw, nh))) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0)) else { - if let Some(it) = doc.item_mut(item) { - it.content = Content::Unassigned; - } - report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); - report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); + report_missing(report, record, field, cell); return; }; + let (nw, nh) = image.natural; let Some(inner) = doc.item(item).map(|it| it.inner_bounds()) else { report.warnings.push(format!("Record {record}, field {field}: missing image {cell}.")); report.missing.push(MissingImage { record, field: field.to_string(), path: cell.to_string() }); @@ -488,20 +604,7 @@ fn place_image(doc: &mut designcraft_doc::Document, item: ItemId, field: &str, c report.warnings.push(format!("Record {record}, field {field}: image {cell} exceeds finite geometry limits.")); return; } - let fresh = AssetId(doc.alloc()); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string()); - let link = options.link_images.then(|| path.to_string_lossy().into_owned()); - g.asset = doc.add_asset(Asset { - id: fresh, - name, - mime: designcraft_render::image_mime(&bytes).to_string(), - link, - // The cached buffer is shared with every other record naming this file, rather than - // copied per record (#1595). - data: bytes, - pixels: Some((pw, ph)), - ..Default::default() - }); + g.asset = add_image_asset(doc, image, field, options); if let Some(it) = doc.item_mut(item) { it.content = Content::Graphic(g); } @@ -662,4 +765,15 @@ mod image_path_tests { let found = image_candidates("img/x.png", Some(data), Some(doc)); assert_eq!(found, [data.join("img").join("x.png"), doc.join("img").join("x.png")]); } + + /// A path that starts with one separator is tried as it is, then beside the data file and the + /// document without the separator. Two separators still name another computer. + #[cfg(unix)] + #[test] + fn a_rooted_image_cell_is_also_tried_beside_the_data_and_the_document() { + let (data, doc) = (Path::new("/work/data"), Path::new("/work/doc")); + let found = image_candidates("/img/x.png", Some(data), Some(doc)); + assert_eq!(found, [Path::new("/img/x.png").to_path_buf(), data.join("img").join("x.png"), doc.join("img").join("x.png")]); + assert!(image_candidates("//192.0.2.1/img/x.png", Some(data), Some(doc)).is_empty()); + } } diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index dfc49e842..5b8717baa 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -288,15 +288,18 @@ fn next_slot(col: i32, row: i32, rows_first: bool, fits_col: &impl Fn(i32) -> bo /// Files to try for an image cell: an absolute path as it is, a relative one beside the data /// file, then beside the document. Relative paths are not resolved against the process working /// directory, and paths that may not be followed ([`crate::io::document_path`]: URLs, other -/// computers, devices) are not candidates. +/// computers, devices) are not candidates. A path that starts with one separator (`\Photos\x.jpg`) +/// is tried as it is first, then beside the data file and the document with that separator dropped. pub fn image_candidates(cell: &str, data_dir: Option<&Path>, doc_dir: Option<&Path>) -> Vec { let cell = cell.trim(); if cell.is_empty() { return Vec::new(); } + let below = cell.strip_prefix(['\\', '/']).filter(|rest| !rest.is_empty() && !rest.starts_with(['\\', '/'])); let found = std::iter::once(crate::io::document_path(cell, None)) .chain(data_dir.map(|dir| crate::io::folder_path(cell, dir))) - .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))); + .chain(doc_dir.map(|dir| crate::io::folder_path(cell, dir))) + .chain(below.into_iter().flat_map(|rest| [data_dir, doc_dir].into_iter().flatten().map(move |dir| crate::io::folder_path(rest, dir)))); let mut out: Vec = Vec::new(); for p in found.flatten() { if !out.contains(&p) { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..8ca5291a6 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -749,6 +749,157 @@ fn role_overrides_column_kind_qr_and_hyperlink() { assert_eq!(kinds, vec!["email:a@b.c".to_string(), "url:https://example.com".to_string()]); } +fn write_png_sized(path: &Path, width: u32, height: u32) { + let pixels = vec![255; width as usize * height as usize * 4]; + let bytes = designcraft_render::Rendered { width, height, pixels }.to_png(); + assert_eq!(designcraft_render::image_size(&bytes), Some((width, height)), "the fixture png must decode"); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, bytes).unwrap(); +} + +/// The images anchored in the stories of document `index`, as (file name, width, height), by name. +fn inline_images(s: &Session, index: usize) -> Vec<(String, f64, f64)> { + let doc = &s.documents()[index].doc; + let mut out = Vec::new(); + for st in doc.stories.values() { + for o in &st.objects { + if let Content::Graphic(g) = &o.item.content { + let name = doc.assets.get(&g.asset).map(|a| a.name.clone()).unwrap_or_default(); + let (w, h) = o.size(); + out.push((name, w, h)); + } + } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +/// An image field inserted at a text insertion point placed the path as text. It places the +/// image in the text: at its natural size, scaled down to fit the frame, with a missing file +/// reported and its marker removed. +#[test] +fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { + let dir = scratch("inline-image"); + let data = dir.join("data"); + write_png_sized(&data.join("pics").join("small.png"), 40, 20); + write_png_sized(&data.join("pics").join("wide.png"), 800, 100); + write(&data.join("cards.csv"), "Name,@Photo\nAda,pics/small.png\nGrace,pics/wide.png\nKai,pics/none.png\n"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let made = text_frame(&mut s, [36.0, 36.0, 236.0, 236.0], "Photo: ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 7, "focus": 7})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + let template = &s.documents()[0].doc; + assert_eq!(template.stories.values().next().unwrap().text, "Photo: <>"); + let width = template.item(designcraft_doc::ItemId(made["id"].as_u64().unwrap())).unwrap().inner_bounds().width(); + + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(inline_images(&s, 0).len(), 1, "the preview shows the image"); + exec(&mut s, "data.preview.stop", json!({})); + + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 3); + let missing = r["missingImages"].as_array().unwrap(); + assert_eq!(missing.len(), 1, "{missing:?}"); + assert_eq!((missing[0]["record"].as_u64(), missing[0]["path"].as_str()), (Some(3), Some("pics/none.png"))); + let mark = designcraft_doc::OBJECT_MARK; + assert_eq!(texts(&s), vec!["Photo: ".to_string(), format!("Photo: {mark}"), format!("Photo: {mark}")]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 2, "{placed:?}"); + let (small, wide) = (&placed[0], &placed[1]); + assert_eq!(small.0, "small.png"); + assert!((small.1 - 40.0).abs() < 0.01 && (small.2 - 20.0).abs() < 0.01, "a small image keeps its natural size: {small:?}"); + assert_eq!(wide.0, "wide.png"); + assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); +} + +/// A typed `<>` marker for an image column places the image too, from an absolute path; +/// an explicit text role still writes the path as text. +#[test] +fn a_typed_image_marker_places_the_image_and_a_text_role_keeps_the_path() { + let dir = scratch("typed-image"); + let pic = dir.join("pic.png"); + write_png_sized(&pic, 10, 30); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "A <> B", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0)); + assert_eq!(texts(&s), vec![format!("A {} B", designcraft_doc::OBJECT_MARK)]); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1); + assert!((placed[0].1 - 10.0).abs() < 0.01 && (placed[0].2 - 30.0).abs() < 0.01, "{placed:?}"); + + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + exec(&mut s, "data.merge", json!({})); + assert_eq!(texts(&s), vec![pic.display().to_string()]); + assert!(inline_images(&s, s.active_index().unwrap()).is_empty()); +} + +/// An explicit image role at a text insertion point places an inline image too, and in a frame +/// with two columns the image is scaled down to one column's width. +#[test] +fn an_inline_image_role_at_text_fits_one_column() { + let dir = scratch("inline-columns"); + let pic = dir.join("wide.png"); + write_png_sized(&pic, 800, 100); + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + exec(&mut s, "object.textFrameOptions", json!({"ids": [made["id"]], "columns": 2, "gutter": 20})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image"})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + // 420 pt wide, less the 20 pt gutter, gives two 200 pt columns. + assert!((placed[0].1 - 200.0).abs() < 0.01 && (placed[0].2 - 25.0).abs() < 0.01, "{placed:?}"); + + // The story threads on into a 100 pt frame: the image fits that one, wherever the marker lands. + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, &format!("@Photo\n{}\n", pic.display())); + let made = text_frame(&mut s, [36.0, 36.0, 456.0, 336.0], "", None); + let small = exec(&mut s, "frame.create", json!({"rect": [36.0, 400.0, 136.0, 500.0], "content": "unassigned"})); + exec(&mut s, "text.thread", json!({"from": made["id"], "to": small["id"]})); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 0})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + exec(&mut s, "data.merge", json!({})); + let placed = inline_images(&s, s.active_index().unwrap()); + assert_eq!(placed.len(), 1, "{placed:?}"); + assert!(placed[0].1 <= 100.0 + 0.01, "{placed:?}"); +} + +/// A cell that starts with one separator (`\pics\a.png`) and names no file from the drive's root +/// is found beside the data file. +#[test] +fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { + let dir = scratch("rooted-image"); + let data = dir.join("data"); + write_png_sized(&data.join("dc-merge-rooted-pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\n\\dc-merge-rooted-pics\\a.png\n/dc-merge-rooted-pics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["records"], 2); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); diff --git a/docs/agents.md b/docs/agents.md index 621173a85..d2f416c83 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -88,7 +88,10 @@ external PDF/X certification. `data.source.select {path, sheet?}` links a CSV/TSV/`.xlsx` file to the document (`data.source.update` re-reads it, `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` -marks text or a frame as a field (`role`: text, image, qr, hyperlink); `data.options` sets records, tiling and image +marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text +insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the +frame. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with +one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. `data.merge` now **creates a new document** and leaves the template unchanged (the old `spread` parameter, which From e90517be4512195cf54e27293d5f4330e598c7bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:50:38 -0800 Subject: [PATCH 098/328] Text: paragraph spacing and justification values are checked type.para, style.paragraph.create and style.paragraph.edit accepted any number for paragraph spacing and justification. They now refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. Each justification row needs Minimum <= Desired <= Maximum over the values the paragraph or style resolves to after the change, including the styles based on an edited style and the paragraphs, table cells and notes that use them. object.textFrameOptions refuses an inset outside 0 to 15552 pt or a list that is not four sides, and a verticalJustification, firstBaseline, autoSize or columnsKind that is not one of its names. These were applied or skipped without an error before. IDML import reads these values as before. --- crates/engine/src/cmd/object.rs | 118 ++++++++++-- crates/engine/src/cmd/style/paragraph.rs | 56 ++++++ crates/engine/src/cmd/text.rs | 5 +- crates/engine/src/cmd/text/format.rs | 234 ++++++++++++++++++++++- docs/target-app-parity.md | 1 + 5 files changed, 390 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..69e2d2b04 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2595,6 +2595,14 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { let column_width = ranged("columnWidth", 0.0, 15552.0, "a number of points")?; let first_baseline_min = ranged("firstBaselineMin", 0.0, 15552.0, "a number of points")?; let spacing_limit = ranged("paragraphSpacingLimit", 0.0, 15552.0, "a number of points")?; + let inset = frame_inset_param(p)?; + let vertical_justification: Option = + frame_choice_param(p, "verticalJustification", "top|center|bottom|justify")?; + let first_baseline: Option = + frame_choice_param(p, "firstBaseline", "ascent|capHeight|leading|xHeight|fixed|emboxHeight")?; + let auto_size: Option = + frame_choice_param(p, "autoSize", "off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally")?; + let columns_kind: Option = frame_choice_param(p, "columnsKind", "fixedNumber|fixedWidth|flexibleWidth")?; let reference = match p.get("autoSizeReference") { None | Some(Value::Null) => None, Some(v) => Some( @@ -2655,28 +2663,22 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = p.get("gutter").and_then(Value::as_f64) { o.gutter = v.max(0.0); } - match p.get("inset") { - Some(Value::Number(n)) => o.inset = [n.as_f64().unwrap_or(0.0); 4], - Some(v @ Value::Array(_)) => { - if let Ok(a) = serde_json::from_value::<[Option; 4]>(v.clone()) { - for (side, v) in o.inset.iter_mut().zip(a) { - if let Some(v) = v { - *side = v; - } - } - } + for (side, v) in o.inset.iter_mut().zip(inset.unwrap_or_default()) { + if let Some(v) = v { + *side = v; } - _ => {} } - for (k, which) in [("verticalJustification", 0), ("firstBaseline", 1), ("autoSize", 2), ("columnsKind", 3)] { - if let Some(v) = p.get(k).cloned() { - let _ = match which { - 0 => serde_json::from_value(v).map(|x| o.vertical_justification = x), - 1 => serde_json::from_value(v).map(|x| o.first_baseline = x), - 2 => serde_json::from_value(v).map(|x| o.auto_size = x), - _ => serde_json::from_value(v).map(|x| o.columns_kind = x), - }; - } + if let Some(v) = vertical_justification { + o.vertical_justification = v; + } + if let Some(v) = first_baseline { + o.first_baseline = v; + } + if let Some(v) = auto_size { + o.auto_size = v; + } + if let Some(v) = columns_kind { + o.columns_kind = v; } if let Some(v) = reference { o.auto_size_ref = v; @@ -2752,6 +2754,40 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { }) } +/// `object.textFrameOptions` Inset Spacing: one number for every side, or [top, left, bottom, +/// right] with null for a side that keeps its value; each side 0 to 15552 pt. +fn frame_inset_param(p: &Value) -> Result; 4]>> { + const ID: &str = "object.textFrameOptions"; + let side = |v: &Value| match v.as_f64() { + Some(x) if x.is_finite() && (0.0..=15552.0).contains(&x) => Ok(x), + _ => Err(bad(ID, format!("inset must be a number of points from 0 to 15552, not {v}"))), + }; + match p.get("inset") { + None | Some(Value::Null) => Ok(None), + Some(v @ Value::Number(_)) => Ok(Some([Some(side(v)?); 4])), + Some(Value::Array(a)) if a.len() == 4 => { + let mut sides = [None; 4]; + for (s, v) in sides.iter_mut().zip(a) { + if !v.is_null() { + *s = Some(side(v)?); + } + } + Ok(Some(sides)) + } + Some(v) => Err(bad(ID, format!("inset must be a number or [top, left, bottom, right], not {v}"))), + } +} + +/// An `object.textFrameOptions` choice: absent or null leaves it, a name outside `names` is an error. +fn frame_choice_param(p: &Value, key: &str, names: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => { + serde_json::from_value(v.clone()).map(Some).map_err(|_| bad("object.textFrameOptions", format!("{key} must be one of {names}, not {v}"))) + } + } +} + fn apply_custom_frame_grid( options: &mut TextFrameOptions, custom: Option, Option, Option)>>, @@ -6005,6 +6041,48 @@ mod frame_baseline_grid_tests { s.execute("object.textFrameOptions", &json!({"ids": [id.0], "baselineGrid": null})).unwrap(); assert_eq!(grid(&s), None); } + + /// A negative or huge inset, an inset list that isn't four sides, and a vertical + /// justification or first baseline that isn't one of the names were applied or skipped + /// without a word. They are refused and the frame keeps its options. + #[test] + fn text_frame_options_refuse_insets_and_names_outside_their_ranges() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + let options = |s: &Session| s.doc().unwrap().doc.item(id).and_then(|i| i.text_frame()).map(|t| t.options.clone()).unwrap(); + let before = options(&s); + for (params, says) in [ + (json!({"inset": -1}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": 15553}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": [1, 2, 3]}), "inset must be a number or [top, left, bottom, right]"), + (json!({"inset": [1, 2, 3, -4]}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": [1, "2", 3, 4]}), "inset must be a number of points from 0 to 15552"), + (json!({"inset": "6pt"}), "inset must be a number or [top, left, bottom, right]"), + (json!({"verticalJustification": "middle"}), "verticalJustification must be one of top|center|bottom|justify"), + (json!({"firstBaseline": "baseline"}), "firstBaseline must be one of"), + (json!({"autoSize": "both"}), "autoSize must be one of"), + (json!({"columnsKind": "flexible"}), "columnsKind must be one of"), + (json!({"paragraphSpacingLimit": -1}), "paragraphSpacingLimit must be a number of points from 0 to 15552"), + (json!({"firstBaselineMin": 20000}), "firstBaselineMin must be a number of points from 0 to 15552"), + ] { + let mut p = params.clone(); + p["ids"] = json!([id.0]); + let e = s.execute("object.textFrameOptions", &p).expect_err("refused").to_string(); + assert!(e.contains(says), "{params}: {e}"); + assert_eq!(options(&s), before, "{params}"); + } + // Values in range apply, the ends included, and null keeps a side. + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "inset": [0, null, 15552, 4.5], "verticalJustification": "bottom"})).unwrap(); + let o = options(&s); + assert_eq!(o.inset, [0.0, before.inset[1], 15552.0, 4.5]); + assert_eq!(o.vertical_justification, designcraft_doc::VerticalJustification::Bottom); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "inset": 6, "firstBaseline": "capHeight"})).unwrap(); + let o = options(&s); + assert_eq!(o.inset, [6.0; 4]); + assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 16671fbd8..04a3f6a8d 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -416,6 +416,51 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) { } } +/// After an edit of paragraph style `name`: Minimum ≤ Desired ≤ Maximum in `rows` for the style, +/// the styles based on it and the story paragraphs that use any of them. +fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3]) -> Result<()> { + const ID: &str = "style.paragraph.edit"; + if !rows.contains(&true) { + return Ok(()); + } + let styles = &d.styles; + let affected: Vec<&str> = styles.paragraph.iter().map(|st| st.name.as_str()).filter(|n| styles.para_based_on_cycles(name, n)).collect(); + for n in &affected { + if let Some(m) = crate::cmd::text::justification_order_error(&styles.resolve_para_style(n).0, rows) { + return Err(bad(ID, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); + } + } + for st in d.stories.values() { + let mut check = |pf: &designcraft_doc::ParaFormat| { + if affected.contains(&pf.style.as_str()) { crate::cmd::text::justification_order_error(&styles.resolve_para(pf).0, rows) } else { None } + }; + if let Some(m) = first_in_nested_paras(st, &mut check) { + return Err(bad(ID, format!("a paragraph of story {}: {m}", st.id.0))); + } + } + Ok(()) +} + +/// The first answer `f` gives for a paragraph of `story`, its table cells, footnotes or endnotes, +/// at any depth. The walk keeps its own stack, so a deeply nested document can't exhaust the +/// call stack. +fn first_in_nested_paras(story: &designcraft_doc::Story, f: &mut impl FnMut(&designcraft_doc::ParaFormat) -> Option) -> Option { + let mut pending = vec![story]; + while let Some(story) = pending.pop() { + if let Some(m) = story.paras.iter().find_map(&mut *f) { + return Some(m); + } + pending.extend(story.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text))); + pending.extend(story.notes.iter().chain(&story.endnotes).map(|n| &n.text)); + } + None +} + +/// The justification rows the `para` object of `p` sets or clears. +fn justification_rows_given(p: &Value) -> [bool; 3] { + crate::cmd::text::justification_rows_named(p.get("para").and_then(Value::as_object).into_iter().flat_map(|o| o.keys().map(String::as_str))) +} + /// The style `p[key]` names: none when absent or null; anything but a name is refused. fn style_name_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { @@ -434,6 +479,8 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.create", ¶)?; + crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; + let rows = justification_rows_given(p); let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?; // Validate caller-supplied fills, not selection fills retained after a swatch is deleted. crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?; @@ -467,6 +514,9 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { return Err(bad("style.paragraph.create", format!("no style `{n}`"))); } d.styles_mut().paragraph.push(ParagraphStyle { name: name.clone(), based_on, next_style: next, para, chars, shortcut: String::new() }); + // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to. + let (resolved, _) = d.styles.resolve_para_style(&name); + crate::cmd::text::validate_justification_order(&resolved, rows, "style.paragraph.create")?; Ok(json!({"name": name})) }) } @@ -578,9 +628,15 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.edit", ¶)?; + crate::cmd::text::validate_para_values(¶, "style.paragraph.edit")?; let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; st.para.merge(¶); st.chars.merge(&chars); + // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to: in the rows the edit + // names, or in every row when it changes Based On or resets the style. + let rows = if reset || based.is_some() { [true; 3] } else { justification_rows_given(p) }; + check_justification_after_edit(d, &name, rows)?; + let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; match next { Some(Value::String(n)) => st.next_style = Some(n), Some(Value::Null) => st.next_style = None, diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index bee08c167..421df09bc 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -25,7 +25,8 @@ pub use edit::{PLACEHOLDER, quote_marks}; use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert}; pub(crate) use format::{ Target, TypingFormat, apply_char_attrs, effective_char_format, format_chars, format_paras, format_targets, format_targets_pub, - rename_typing_swatch, validate_char_fill, + justification_order_error, justification_rows_named, rename_typing_swatch, validate_char_fill, validate_justification_order, + validate_para_values, }; use format::{break_link, kern_pair, kern_step, link_style, para_toggle, pick_up_format, step_size, swap_fill_stroke}; use opentype::{open_type, open_type_features, set_features}; @@ -234,7 +235,7 @@ pub fn specs() -> Vec { "Paragraph Formatting", [], None, - "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", + "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index d915da91d..23d84bed6 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -146,6 +146,98 @@ pub(crate) const MIN_TYPE_SIZE: f64 = 0.1; pub(crate) const MAX_TYPE_SIZE: f64 = 1296.0; +/// Space Before, Space After and Space Between Paragraphs Using Same Style: 0 to 15552 pt, the +/// limit `object.textFrameOptions` applies to its Paragraph Spacing Limit. +pub(crate) const MAX_PARA_SPACE: f64 = 15552.0; + +/// The justification rows as fractions (1.0 = 100%): key stem, label, range. +const JUSTIFICATION_ROWS: [(&str, &str, f64, f64); 3] = + [("wordSpace", "word spacing", 0.0, 10.0), ("letterSpace", "letter spacing", -1.0, 5.0), ("glyphScale", "glyph scaling", 0.5, 2.0)]; + +/// Auto Leading: 0% to 500% of the type size. +const MAX_AUTO_LEADING: f64 = 5.0; + +/// A fraction shown as a percent, without float noise (1.33 is "133"). +fn percent(v: f64) -> String { + let p = (v * 100.0 * 1000.0).round() / 1000.0; + format!("{p}") +} + +/// Checks the paragraph spacing and justification values `attrs` sets: Space Before, Space After +/// and same-style spacing 0 to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing +/// -100% to 500% and glyph scaling 50% to 200%; Auto Leading 0% to 500%; Single Word +/// Justification left, center, right or fullyJustified. [`validate_justification_order`] checks +/// the order of each row once the values are applied. +pub(crate) fn validate_para_values(attrs: &ParaAttrs, command_id: &str) -> Result<()> { + use designcraft_doc::Align; + let spaces = + [("spaceBefore", attrs.space_before), ("spaceAfter", attrs.space_after), ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten())]; + for (key, v) in spaces { + if let Some(v) = v + && !(0.0..=MAX_PARA_SPACE).contains(&v) + { + return Err(bad(command_id, format!("{key} {v}: 0 to {MAX_PARA_SPACE} pt"))); + } + } + let rows = [ + [attrs.word_space_min, attrs.word_space_desired, attrs.word_space_max], + [attrs.letter_space_min, attrs.letter_space_desired, attrs.letter_space_max], + [attrs.glyph_scale_min, attrs.glyph_scale_desired, attrs.glyph_scale_max], + ]; + for ((stem, label, lo, hi), given) in JUSTIFICATION_ROWS.into_iter().zip(rows) { + for (suffix, v) in ["Min", "Desired", "Max"].into_iter().zip(given) { + if let Some(v) = v + && !(lo..=hi).contains(&v) + { + return Err(bad(command_id, format!("{stem}{suffix} {}%: {label} is {}% to {}%", percent(v), percent(lo), percent(hi)))); + } + } + } + if let Some(v) = attrs.auto_leading + && !(0.0..=MAX_AUTO_LEADING).contains(&v) + { + return Err(bad(command_id, format!("autoLeading {}%: 0% to {}%", percent(v), percent(MAX_AUTO_LEADING)))); + } + if let Some(a) = attrs.single_word_justify + && !matches!(a, Align::Left | Align::Center | Align::Right | Align::FullyJustified) + { + return Err(bad(command_id, format!("singleWordJustify {}: left, center, right or fullyJustified", json!(a)))); + } + Ok(()) +} + +/// The justification rows (word spacing, letter spacing, glyph scaling) that attribute names in +/// `keys` set or clear. +pub(crate) fn justification_rows_named<'a>(keys: impl IntoIterator) -> [bool; 3] { + let mut rows = [false; 3]; + for key in keys { + let key = key.replace('_', "").to_ascii_lowercase(); + for (row, (stem, ..)) in rows.iter_mut().zip(JUSTIFICATION_ROWS) { + *row |= key.starts_with(&stem.to_ascii_lowercase()); + } + } + rows +} + +/// Each justification row marked in `rows` needs Minimum ≤ Desired ≤ Maximum in `resolved`, the +/// attributes of the paragraph or style after the change. +pub(crate) fn validate_justification_order(resolved: &designcraft_doc::ParaProps, rows: [bool; 3], command_id: &str) -> Result<()> { + justification_order_error(resolved, rows).map_or(Ok(()), |m| Err(bad(command_id, m))) +} + +/// What [`validate_justification_order`] refuses, as a message. +pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { + let values = [ + [resolved.word_space_min, resolved.word_space_desired, resolved.word_space_max], + [resolved.letter_space_min, resolved.letter_space_desired, resolved.letter_space_max], + [resolved.glyph_scale_min, resolved.glyph_scale_desired, resolved.glyph_scale_max], + ]; + JUSTIFICATION_ROWS.into_iter().zip(values).zip(rows).find_map(|(((_, label, ..), [min, desired, max]), checked)| { + (checked && (min > desired || desired > max)) + .then(|| format!("{label} needs Minimum ≤ Desired ≤ Maximum, not {}%, {}%, {}%", percent(min), percent(desired), percent(max))) + }) +} + /// Byte `pos` is the hidden paragraph mark of an *empty* paragraph: the only character on that /// line, and so the one a line-affecting attribute like leading can land on right away instead of /// waiting for the next typed character (otherwise an empty line could never get its own leading). @@ -315,11 +407,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result { a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?; } crate::cmd::style::check_grep_styles("type.para", &a)?; + validate_para_values(&a, "type.para")?; + let rows = justification_rows_named(obj.keys().map(String::as_str)); // `null` removes the override (back to the style's value). let cleared: Vec = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect(); let targets = format_targets(s); s.edit(|d, _| { let styles = d.styles.clone(); + // Minimum ≤ Desired ≤ Maximum holds over each paragraph's own values once they change. + let mut refused = None; for t in &targets { if let Some(st) = d.text_story_mut(t.story, t.cell) { st.format_paras(t.range.clone(), |p| { @@ -332,10 +428,15 @@ pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result { for k in &cleared { let _ = p.para.set_json(k, &Value::Null); } + if refused.is_none() + && let Err(e) = validate_justification_order(&styles.resolve_para(p).0, rows, "type.para") + { + refused = Some(e); + } }); } } - ok() + refused.map_or_else(ok, Err) }) } @@ -1076,7 +1177,7 @@ mod pick_up_format_tests { #[cfg(test)] mod size_bounds_tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::Session; @@ -1111,6 +1212,135 @@ mod size_bounds_tests { assert!(e.contains("0.1 to 1296 pt"), "{command}: {e}"); } } + + /// `type.para` set any number for paragraph spacing and justification: a negative Space + /// Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, + /// and Single Word Justification took any alignment. Values outside the ranges are refused, + /// nothing changes, and the ends of each range still apply. + #[test] + fn paragraph_spacing_and_justification_outside_their_ranges_are_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap(); + let select_all = |s: &mut Session| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 0, "focus": 18})).unwrap(); + }; + let para = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone(); + select_all(&mut s); + let before = para(&mut s); + for (attrs, says) in [ + (json!({"spaceBefore": -1}), "spaceBefore -1: 0 to 15552 pt"), + (json!({"spaceAfter": 15553}), "spaceAfter 15553: 0 to 15552 pt"), + (json!({"sameParaStyleSpacing": -2}), "sameParaStyleSpacing -2: 0 to 15552 pt"), + (json!({"wordSpaceMax": 10.5}), "wordSpaceMax 1050%: word spacing is 0% to 1000%"), + (json!({"wordSpaceMin": -0.1}), "wordSpaceMin -10%: word spacing is 0% to 1000%"), + (json!({"letterSpaceMin": -1.5}), "letterSpaceMin -150%: letter spacing is -100% to 500%"), + (json!({"letterSpaceMax": 5.5}), "letterSpaceMax 550%: letter spacing is -100% to 500%"), + (json!({"glyphScaleMin": 0.4}), "glyphScaleMin 40%: glyph scaling is 50% to 200%"), + (json!({"glyphScaleDesired": 2.1}), "glyphScaleDesired 210%: glyph scaling is 50% to 200%"), + (json!({"autoLeading": 6}), "autoLeading 600%: 0% to 500%"), + (json!({"autoLeading": -0.1}), "autoLeading -10%: 0% to 500%"), + (json!({"singleWordJustify": "leftJustified"}), "singleWordJustify \"leftJustified\": left, center, right or fullyJustified"), + // Desired word spacing is 100%, so a Minimum of 120% alone is out of order. + (json!({"wordSpaceMin": 1.2}), "word spacing needs Minimum ≤ Desired ≤ Maximum, not 120%, 100%, 133%"), + ( + json!({"glyphScaleMin": 0.9, "glyphScaleDesired": 1.1, "glyphScaleMax": 1.0}), + "glyph scaling needs Minimum ≤ Desired ≤ Maximum, not 90%, 110%, 100%", + ), + ] { + select_all(&mut s); + let e = s.execute("type.para", &json!({"attrs": attrs})).expect_err("refused").to_string(); + assert!(e.contains(says), "{attrs}: {e}"); + assert_eq!(para(&mut s), before, "{attrs}"); + } + // The ends of each range apply and read back. + for attrs in [ + json!({"spaceBefore": 0, "spaceAfter": 15552, "sameParaStyleSpacing": 15552}), + json!({"wordSpaceMin": 0, "wordSpaceDesired": 0, "wordSpaceMax": 10}), + json!({"letterSpaceMin": -1, "letterSpaceDesired": 0, "letterSpaceMax": 5}), + json!({"glyphScaleMin": 0.5, "glyphScaleDesired": 1, "glyphScaleMax": 2}), + json!({"autoLeading": 5}), + json!({"autoLeading": 0, "singleWordJustify": "center"}), + ] { + select_all(&mut s); + s.execute("type.para", &json!({"attrs": attrs})).unwrap_or_else(|e| panic!("{attrs}: {e}")); + let got = para(&mut s); + let same = |a: &Value, b: &Value| a.as_f64().zip(b.as_f64()).map_or(a == b, |(a, b)| a == b); + for (k, v) in attrs.as_object().unwrap() { + assert!(same(&got[k], v), "{k}: {} for {v}", got[k]); + } + } + // The order holds over each paragraph's own values: with Desired 300% in the second + // paragraph only, a Maximum of 200% for both is refused and neither paragraph changes. + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap(); + s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 5, "wordSpaceDesired": 3}})).unwrap(); + select_all(&mut s); + let before = para(&mut s); + let e = s.execute("type.para", &json!({"attrs": {"wordSpaceMax": 2}})).expect_err("refused").to_string(); + assert!(e.contains("not 0%, 300%, 200%"), "{e}"); + assert_eq!(para(&mut s), before); + // Clearing a value is checked too: with Minimum 250% in the second paragraph, clearing + // its Desired back to the style's 100% is refused. + let second = |s: &mut Session| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 12, "focus": 18})).unwrap(); + }; + second(&mut s); + s.execute("type.para", &json!({"attrs": {"wordSpaceMin": 2.5}})).unwrap(); + second(&mut s); + let e = s.execute("type.para", &json!({"attrs": {"wordSpaceDesired": null}})).expect_err("refused").to_string(); + assert!(e.contains("word spacing needs Minimum ≤ Desired ≤ Maximum, not 250%, 100%, 500%"), "{e}"); + second(&mut s); + assert_eq!(para(&mut s)["wordSpaceDesired"].as_f64(), Some(3.0)); + // Paragraph styles are checked the same way, over what the style resolves to. + let e = s.execute("style.paragraph.create", &json!({"name": "Loose", "para": {"autoLeading": 6}})).expect_err("refused").to_string(); + assert!(e.contains("autoLeading 600%"), "{e}"); + s.execute("style.paragraph.create", &json!({"name": "Body", "para": {"wordSpaceDesired": 1.2}})).unwrap(); + let e = s.execute("style.paragraph.create", &json!({"name": "Tight", "para": {"wordSpaceMax": 0.9}})).expect_err("refused").to_string(); + assert!(e.contains("not 80%, 100%, 90%"), "{e}"); + let e = s + .execute("style.paragraph.create", &json!({"name": "Child", "basedOn": "Body", "para": {"wordSpaceMax": 1.1}})) + .expect_err("refused") + .to_string(); + assert!(e.contains("not 80%, 120%, 110%"), "{e}"); + let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"wordSpaceMin": 1.3}})).expect_err("refused").to_string(); + assert!(e.contains("not 130%, 120%, 133%"), "{e}"); + let e = s.execute("style.paragraph.edit", &json!({"name": "Body", "para": {"spaceAfter": -3}})).expect_err("refused").to_string(); + assert!(e.contains("spaceAfter -3: 0 to 15552 pt"), "{e}"); + let style = s.doc().unwrap().doc.styles.para("Body").unwrap().para.clone(); + assert_eq!((style.word_space_min, style.space_after), (None, None)); + for name in ["Loose", "Tight", "Child"] { + assert!(s.doc().unwrap().doc.styles.para(name).is_none(), "{name}"); + } + // A new Based On is checked over every row of what the style then resolves to. + s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"wordSpaceMin": 1.2, "wordSpaceDesired": 1.3}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Narrow", "para": {"wordSpaceMax": 1.1}})).unwrap(); + let e = s.execute("style.paragraph.edit", &json!({"name": "Wide", "basedOn": "Narrow"})).expect_err("refused").to_string(); + assert!(e.contains("not 120%, 130%, 110%"), "{e}"); + assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().based_on, None); + // An edit is checked over the styles based on the edited style and the paragraphs using + // them, too. + s.execute("style.paragraph.create", &json!({"name": "Parent"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Kid", "basedOn": "Parent", "para": {"wordSpaceMax": 1.1}})).unwrap(); + let e = s.execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"wordSpaceDesired": 1.2}})).expect_err("refused").to_string(); + assert!(e.contains("paragraph style \"Kid\": word spacing needs Minimum ≤ Desired ≤ Maximum, not 80%, 120%, 110%"), "{e}"); + // A footnote paragraph with its own Maximum of 10%, under a style edit that sets Desired + // to 20%. + select_all(&mut s); + s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap(); + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": 5, "focus": 5})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note"})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Parent", "clearOverrides": true})).unwrap(); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap(); + let e = s + .execute("style.paragraph.edit", &json!({"name": "Parent", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}})) + .expect_err("refused") + .to_string(); + assert!( + e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%", f["story"])), + "{e}" + ); + assert_eq!(s.doc().unwrap().doc.styles.para("Parent").unwrap().para.letter_space_desired, None); + } } #[cfg(test)] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..63da03254 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,6 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. +- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit is also checked over the styles based on it and the paragraphs that use them. `object.textFrameOptions` refuses an inset outside 0 to 15552 pt or a list that isn't four sides, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From 9041fd315322af923a21e55e05eb7b2ee0d92cf7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 17:53:41 -0800 Subject: [PATCH 099/328] Compose: Bottom, Center and Justify ignore corner radius and descent room Bottom and Justify now put the last baseline on the bottom inset in a frame with a corner radius as in a rectangular one, so a radius no longer moves the text when the bottom inset is above 0. Center puts the last baseline halfway between where Top sets it and the bottom inset even when the frame is too short for the descenders under it, so Cap Height text in a tight frame is centered. The last line's descenders hang below its baseline, into the bottom inset and past the frame's edge when the inset is smaller than the descent. An earlier line whose descenders reach below the last baseline (tight leading) is not moved past the text area. Above footnotes and in vertical frames the descenders still stay inside the text area. --- crates/compose/src/lib.rs | 109 ++++++++++++++++++++---------------- crates/compose/src/tests.rs | 93 ++++++++++++++++++++++++------ 2 files changed, 137 insertions(+), 65 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 858cf0433..72c0f69cb 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5510,63 +5510,76 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let last_baseline = idx.iter().map(|&i| ft.lines[i].baseline).fold(tables, f64::max); let ink_bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(tables, f64::max); // The bottom of the text is the last baseline, as the top is the first baseline: the - // descenders of the last line may reach into the bottom inset, but not past the frame's - // edge, and in a shaped frame not past the text area (its outline holds the descenders). - // Above footnotes, and in vertical frames, the descenders stay inside the text area, as - // when the lines are fitted. - // `space`: the room under the bottom of the text; `room`: how far its last line may move. - let (space, room) = if f.vertical || note_top <= f.area.y1 { - (limit - ink_bottom, f64::INFINITY) - } else { - let edge = if f.outline.is_some() { f.area.y1 } else { f.area.y1 + f.opts.inset[2].max(0.0) }; - (limit - last_baseline, edge - ink_bottom) - }; - if space <= 0.0 || room <= 0.0 { + // descenders of the last line hang below it, into the bottom inset and past it, in shaped + // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders + // stay inside the text area, as when the lines are fitted. + // `space`: the room under the bottom of the text. + let space = if f.vertical || note_top <= f.area.y1 { limit - ink_bottom } else { limit - last_baseline }; + if space <= 0.0 { continue; } - let center = (space / 2.0).min(room); - let space = space.min(room); - let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); - match f.opts.vertical_justification { - VerticalJustification::Center => idx.iter().for_each(|&i| ft.lines[i].baseline += center), - VerticalJustification::Bottom => idx.iter().for_each(|&i| ft.lines[i].baseline += space), - VerticalJustification::Justify => { - // Segments of one line (beside an object) share a row and move together. - let rows: Vec = idx - .iter() - .scan((0usize, f64::NAN), |(row, prev), &i| { - let b = ft.lines[i].baseline; - if !prev.is_nan() && (b - *prev).abs() > 1e-9 { - *row += 1; - } - *prev = b; - Some(*row) - }) - .collect(); - let n = rows.last().copied().unwrap_or(0); - if n > 0 { - // Paragraph Spacing Limit: the space goes between paragraphs, up to the limit - // each; what is left spreads over every line (all of it with no limit). - let mut starts = vec![false; n + 1]; - for (&i, &k) in idx.iter().zip(&rows) { - if k > 0 && ft.lines[i].first_in_para { - starts[k] = true; - } - } - let gaps = starts.iter().filter(|s| **s).count(); - let limit = f.opts.vj_paragraph_spacing_limit.max(0.0); - let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; + // Segments of one line (beside an object) share a row and move together. + let rows: Vec = idx + .iter() + .scan((0usize, f64::NAN), |(row, prev), &i| { + let b = ft.lines[i].baseline; + if !prev.is_nan() && (b - *prev).abs() > 1e-9 { + *row += 1; + } + *prev = b; + Some(*row) + }) + .collect(); + let n = rows.last().copied().unwrap_or(0); + // Paragraph Spacing Limit: with Justify the space goes between paragraphs, up to the limit + // each; what is left spreads over every line (all of it with no limit). + let mut starts = vec![false; n + 1]; + for (&i, &k) in idx.iter().zip(&rows) { + if k > 0 && ft.lines[i].first_in_para { + starts[k] = true; + } + } + let gaps = starts.iter().filter(|s| **s).count(); + let para_limit = f.opts.vj_paragraph_spacing_limit.max(0.0); + // How far each row moves when the text takes `space` more room. + let shifts = |space: f64| -> Vec { + match f.opts.vertical_justification { + VerticalJustification::Center => vec![space / 2.0; n + 1], + VerticalJustification::Bottom => vec![space; n + 1], + VerticalJustification::Justify if n > 0 => { + let para = if gaps > 0 && para_limit > 0.0 { (space / gaps as f64).min(para_limit) } else { 0.0 }; let per = (space - para * gaps as f64) / n as f64; let mut shift = vec![0.0; n + 1]; for k in 1..=n { shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; } - for (&i, &k) in idx.iter().zip(&rows) { - ft.lines[i].baseline += shift[k]; - } + shift + } + _ => vec![0.0; n + 1], + } + }; + // Only the last row's descenders hang below the bottom of the text: an earlier line whose + // ink reaches below the last baseline (tight leading) isn't moved past the text area. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) + }; + // Every row moves no less as `space` grows, so the most room that fits is found by halving. + let mut shift = shifts(space); + if !fits(&shift) { + let (mut lo, mut hi) = (0.0, space); + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if fits(&shifts(mid)) { + lo = mid; + } else { + hi = mid; } } - _ => {} + shift = shifts(lo); + } + let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); + for (&i, &k) in idx.iter().zip(&rows) { + ft.lines[i].baseline += shift[k]; } // A drop cap moves with its line. for (&i, b) in idx.iter().zip(before) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d9e3df22e..b94d94000 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2338,27 +2338,63 @@ fn vertical_justification_measures_to_the_last_baseline() { assert!((center[1].0 - top[1].0 - shift).abs() < 1e-6, "{first:?}: Center moves every line alike"); assert!((area.y1 - last(¢er).0 - shift).abs() < 1e-6, "{first:?}: Center leaves equal room above and below: {center:?}"); - // A bottom inset smaller than the descent: the descenders end on the frame's edge. + // A bottom inset smaller than the descent: the last baseline still sits on the inset, and + // the descenders reach past the frame's edge. for inset in [0.0, 1.0] { for mode in [Bottom, Justify] { let (area, lines) = compose_inset(mode, first, inset); let (b, desc) = last(&lines); assert!(desc > inset + 0.5); - assert!((b + desc - (area.y1 + inset)).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: descenders end at {}", b + desc); + assert!((b - area.y1).abs() < 1e-6, "{first:?} {mode:?} inset {inset}: last baseline at {b}, inset at {}", area.y1); } } } } +/// With tight leading an earlier line's descenders can reach below the last baseline: Bottom keeps +/// them inside the text area, and only the last line's descenders hang into the bottom inset. +#[test] +fn vertical_justification_keeps_earlier_descenders_inside() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + let compose_with = |mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Big\nx", Rect::new(0.0, 0.0, 200.0, 300.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [6.0; 4]; + let st = d.story_mut(sid).unwrap(); + st.format_chars(0..3, |f| f.over.size = Some(48.0)); + st.format_chars(4..5, |f| f.over.leading = Some(designcraft_doc::Leading::Points(2.0))); + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec<(f64, f64)> = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + assert_eq!(lines.len(), 2); + if mode != Justify { + assert!(lines[0].0 + lines[0].1 > lines[1].0 + 1.0, "the first line's ink reaches below the last baseline: {lines:?}"); + } + (area, lines[0].0 + lines[0].1, lines[1].0) + }; + // Bottom moves both lines until the first line's ink meets the text area's bottom. + let (area, ink, _) = compose_with(Bottom); + assert!((ink - area.y1).abs() < 1e-6, "Bottom: first line's ink ends at {ink}, text area at {}", area.y1); + // Center moves both lines, as far as the first line's ink allows. + let (area, ink, _) = compose_with(Center); + assert!(ink <= area.y1 + 1e-6, "Center: first line's ink ends at {ink}, text area at {}", area.y1); + // Justify leaves the first line where it is, so the last baseline still reaches the inset. + let (area, _, last) = compose_with(Justify); + assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). +/// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in +/// a frame too short for the descenders below it. #[test] fn a_corner_radius_keeps_a_cap_height_line_in_place() { - use designcraft_doc::VerticalJustification::{self, Center, Top}; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; use designcraft_geom::corners::{CornerOptions, CornerShape}; let mm = 72.0 / 25.4; - let rect = Rect::new(0.0, 0.0, 29.553 * mm, 9.593 * mm); - let compose_with = |radius: f64, mode: VerticalJustification| { + let compose_tall = |height: f64, radius: f64, mode: VerticalJustification| { + let rect = Rect::new(0.0, 0.0, 29.553 * mm, height); let (mut d, sid, fid) = doc_with("137mm", rect, ParaAttrs::default()); let item = d.item_mut(fid).unwrap(); item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); @@ -2375,6 +2411,7 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { assert!(!cs.is_overset()); (spec.outline.is_some(), spec.area, cs.frames[0].lines[0].baseline) }; + let compose_with = |radius: f64, mode: VerticalJustification| compose_tall(9.593 * mm, radius, mode); let (square, area, top) = compose_with(0.0, Top); let (rounded, _, rounded_top) = compose_with(0.1 * mm, Top); assert!(!square && rounded, "only the radius gives the frame an outline"); @@ -2384,18 +2421,40 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "Center: the last baseline halfway between {top} and {}: {center}", area.y1); assert!((rounded_center - center).abs() < 1e-6, "Center: {rounded_center} with a radius, {center} without"); - // In a shaped frame the outline holds the descenders: with Bottom they end on the text area's - // bottom, not in the bottom inset. - let (mut d, sid, fid) = doc_with("gypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); - let item = d.item_mut(fid).unwrap(); - item.corners = CornerOptions::uniform(CornerShape::Rounded, 6.0); - let o = &mut item.text_frame_mut().unwrap().options; - o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; - o.inset = [0.0, 0.0, 12.0, 0.0]; - let area = frame_specs(&d, sid)[0].area; - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let l = &cs.frames[0].lines[0]; - assert!((l.baseline + l.descent - area.y1).abs() < 1e-6, "descenders end at {}, text area at {}", l.baseline + l.descent, area.y1); + // Frames too short for the descenders under a centered last baseline. + for height in [22.0, 20.0, 19.0] { + let (_, area, top) = compose_tall(height, 0.0, Top); + let (_, _, center) = compose_tall(height, 0.0, Center); + assert!((center - (area.y1 + top) / 2.0).abs() < 1e-6, "{height} pt: Center at {center}, Top at {top}, inset at {}", area.y1); + } + + // A corner radius doesn't change where Bottom and Justify put the last baseline: on the + // bottom inset, as in a rectangular frame, with the descenders in the inset. + for insets in [[6.0; 4], [0.0, 0.0, 12.0, 0.0]] { + for mode in [Bottom, Justify] { + let compose_frame = |radius: f64| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); + let item = d.item_mut(fid).unwrap(); + item.corners = CornerOptions::uniform(CornerShape::Rounded, radius); + let o = &mut item.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = insets; + let area = frame_specs(&d, sid)[0].area; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) + }; + let (area, square) = compose_frame(0.0); + for radius in [0.1 * mm, 6.0] { + let (_, rounded) = compose_frame(radius); + assert_eq!(rounded.len(), square.len()); + for (r, s) in rounded.iter().zip(&square) { + assert!((r - s).abs() < 1e-6, "{mode:?} insets {insets:?} radius {radius}: {rounded:?} with a radius, {square:?} without"); + } + } + let last = square[square.len() - 1]; + assert!((last - area.y1).abs() < 1e-6, "{mode:?} insets {insets:?}: last baseline at {last}, inset at {}", area.y1); + } + } } #[test] From c93e93414c1156589137b394172abb9da3882b2b Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:02:22 +0000 Subject: [PATCH 100/328] Apply review fixes - crates/ui-egui/src/dialogs.rs - docs/target-app-parity.md --- crates/ui-egui/src/dialogs.rs | 15 ++++++++++----- docs/target-app-parity.md | 2 +- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 158b9d07d..6335f8fca 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,13 +1005,14 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { - let shaped = || { - let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; + let Some(st) = app.session.active() else { return false }; + let shaped = |fid: designcraft_doc::ItemId| -> Option { let item = st.doc.item(fid)?; if item.text_frame()?.options.path.is_some() { return Some(false); @@ -1019,7 +1020,11 @@ fn selected_frame_is_shaped(app: &DesignApp) -> bool { let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) }; - shaped().unwrap_or(false) + if st.selection.items.is_empty() { + let Some(fid) = st.selection.text.and_then(|t| t.frame) else { return false }; + return shaped(fid).unwrap_or(false); + } + st.selection.items.iter().all(|&fid| shaped(fid).unwrap_or(false)) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4207507dc..f950eb12c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -352,7 +352,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. -- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). +- Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options; when every selected text frame is one, a mixed selection keeps the four sides): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. - Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame. Clipping paths saved in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path; Invert) hide the image outside the path on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (Object ▸ Clipping Path ▸ None). From 058815cd802a81877fab31fa396aa4622faebd64 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:27:32 -0500 Subject: [PATCH 101/328] Honor embedded raster resolution when placing graphics (#1991) A 600px photo saved at 600dpi places 1in wide, as in InDesign, instead of one pixel per point. Reads JFIF/EXIF (JPEG), pHYs (PNG), EXIF (WebP), pixels-per-meter (BMP) and TIFF resolution tags; insane metadata falls back to 72ppi. --- crates/engine/src/cmd/file/place.rs | 40 +++++ crates/images/src/lib.rs | 15 +- crates/images/src/resolution.rs | 236 ++++++++++++++++++++++++++++ crates/images/src/tests.rs | 228 +++++++++++++++++++++++++++ 4 files changed, 516 insertions(+), 3 deletions(-) create mode 100644 crates/images/src/resolution.rs diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index a30cb2321..29358d834 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -589,6 +589,46 @@ pub(super) mod image_place_tests { } } + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc + } + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [30, 90, 180, 255].repeat(800) }.to_png(); + assert_eq!(&png[12..16], b"IHDR"); + let mut phys = Vec::new(); + phys.extend_from_slice(&23622u32.to_be_bytes()); + phys.extend_from_slice(&23622u32.to_be_bytes()); + phys.push(1); + let mut bytes = png[..33].to_vec(); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + bytes.extend_from_slice(&png[33..]); + let file = tempfile::Builder::new().suffix(".png").tempfile().unwrap(); + std::fs::write(file.path(), bytes).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); + let document = &session.doc().unwrap().doc; + let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap(); + let b = item.bounds(); + assert!((b.x0 - 10.0).abs() < 1e-9 && (b.y0 - 20.0).abs() < 1e-9, "{b:?}"); + assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..7540eee90 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -12,6 +12,7 @@ pub mod colour; mod eps; mod jpeg; mod psd; +mod resolution; mod tone; pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size, is_eps}; pub use tone::{Tone, tone}; @@ -358,8 +359,11 @@ pub fn svg_tree(bytes: &[u8]) -> Option { usvg::Tree::from_data(&xml, svg_options()).ok() } -/// Natural size of a placed graphic in points: rasters at 72 ppi (one pixel per point), PSDs -/// likewise, SVGs from their width/height (CSS pixels), PDFs are the caller's. +pub use resolution::raster_resolution; + +/// Natural size of a placed graphic in points: rasters at their embedded resolution when sane +/// (one pixel per point, 72 ppi, without usable metadata), PSDs likewise, SVGs from their +/// width/height (CSS pixels), PDFs are the caller's. pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { if is_svg(bytes) { let s = svg_tree(bytes)?.size(); @@ -370,7 +374,12 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { return Some((bb[2] - bb[0], bb[3] - bb[1])).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); } let (w, h) = pixel_size(bytes)?; - Some((w as f64, h as f64)) + // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide, + // as in InDesign. Absurd metadata falls back to a pixel per point. + match raster_resolution(bytes) { + Some(dpi) if resolution::sane_resolution(dpi) => Some((w as f64 * 72.0 / dpi.0, h as f64 * 72.0 / dpi.1)), + _ => Some((w as f64, h as f64)), + } } /// Pixel dimensions of a raster. diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs new file mode 100644 index 000000000..ab1dc119f --- /dev/null +++ b/crates/images/src/resolution.rs @@ -0,0 +1,236 @@ +//! Embedded raster resolution: the density a placed graphic was saved with, so placing honors +//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide, +//! as in InDesign). Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution +//! tags from TIFF, and the header density from BMP. GIF, PSD and files without (usable) metadata +//! report nothing and keep the pixel-is-a-point size. + +/// Dots per inch in x and y, when the file carries usable resolution metadata. +pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + if bytes.len() < 8 { + return None; + } + if bytes.starts_with(b"\xFF\xD8\xFF") { + return jpeg_resolution(bytes); + } + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + return png_resolution(bytes); + } + if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP".as_slice()) { + return webp_resolution(bytes); + } + if bytes.starts_with(b"BM") { + return bmp_resolution(bytes); + } + if is_classic_tiff(bytes) { + return tiff_resolution(bytes); + } + None +} + +/// A parsed density is usable when both axes are finite, positive and below the absurdity cap +/// (a corrupt or hostile value falls back to 72 ppi at the call site). +pub fn sane_resolution(dpi: (f64, f64)) -> bool { + let (dx, dy) = dpi; + dx.is_finite() && dy.is_finite() && dx > 0.0 && dy > 0.0 && dx <= 100_000.0 && dy <= 100_000.0 +} + +fn is_classic_tiff(bytes: &[u8]) -> bool { + bytes.starts_with(b"II*\x00") || bytes.starts_with(b"MM\x00*") +} + +// ---------- JPEG ---------- + +/// Scan JPEG markers for a JFIF density, preferring an EXIF resolution when both are present. +/// Stops at the start of scan (entropy data can contain marker-like bytes). +fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let mut pos = 2; + let mut jfif: Option<(f64, f64)> = None; + for _ in 0..512 { + // Markers are FF-prefixed; skip fill bytes. Running out of bytes ends the scan + // (a truncated file keeps a JFIF density found before the truncation). + let Some(mut m) = bytes.get(pos).copied() else { break }; + while m == 0xFF { + pos += 1; + let Some(b) = bytes.get(pos).copied() else { break }; + m = b; + if m != 0xFF { + break; + } + } + if m == 0xFF { + break; + } + pos += 1; + // Standalone markers carry no payload; SOS starts entropy-coded data. + if m == 0xD8 || m == 0xD9 || (0xD0..=0xD7).contains(&m) || m == 0x01 { + continue; + } + if m == 0xDA { + break; + } + let Some(&a) = bytes.get(pos) else { break }; + let Some(&b) = bytes.get(pos + 1) else { break }; + let len = u16::from_be_bytes([a, b]) as usize; + if len < 2 || pos + len > bytes.len() { + break; + } + let payload = &bytes[pos + 2..pos + len]; + if m == 0xE0 && jfif.is_none() { + jfif = jfif_density(payload); + } else if m == 0xE1 && let Some(dpi) = exif_resolution(payload) { + // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a + // later APP1 can still carry the EXIF resolution. + return Some(dpi); + } + pos += len; + } + jfif +} + +/// JFIF APP0 density: version, units (0 aspect, 1 dpi, 2 dots/cm), x/y density. +fn jfif_density(payload: &[u8]) -> Option<(f64, f64)> { + if !payload.starts_with(b"JFIF\x00") || payload.len() < 14 { + return None; + } + let units = payload[7]; + let (x, y) = (u16::from_be_bytes([payload[8], payload[9]]), u16::from_be_bytes([payload[10], payload[11]])); + match (units, x, y) { + (1, 1.., 1..) => Some((x as f64, y as f64)), + (2, 1.., 1..) => Some((x as f64 * 2.54, y as f64 * 2.54)), + _ => None, + } +} + +/// EXIF APP1 payload ("Exif\0\0" + a TIFF header): the resolution tags of IFD0. +fn exif_resolution(payload: &[u8]) -> Option<(f64, f64)> { + let tiff = payload.strip_prefix(b"Exif\x00\x00")?; + if !is_classic_tiff(tiff) { + return None; + } + tiff_resolution(tiff) +} + +// ---------- TIFF (also the body of EXIF) ---------- + +/// Classic TIFF resolution tags of the first IFD: XResolution/YResolution rationals scaled by +/// ResolutionUnit (2 = inch, 3 = cm; a missing unit defaults to inch per the spec). +pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { + let le = match &tiff[..2] { + b"II" => true, + b"MM" => false, + _ => return None, + }; + let u16at = |i: usize| -> Option { + let b: [u8; 2] = tiff.get(i..i + 2)?.try_into().ok()?; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32at = |i: usize| -> Option { + let b: [u8; 4] = tiff.get(i..i + 4)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let ifd = u32at(4)? as usize; + let count = u16at(ifd)? as usize; + if count > 512 { + return None; + } + let mut xres: Option<(u32, u32)> = None; + let mut yres: Option<(u32, u32)> = None; + let mut unit: Option = None; + for n in 0..count { + let e = ifd.checked_add(2)?.checked_add(n.checked_mul(12)?)?; + let (tag, typ, cnt) = (u16at(e)?, u16at(e + 2)?, u32at(e + 4)?); + // SHORT values of count 1 live inline in the value field (low bytes LE, high bytes BE). + let short_inline = || -> Option { + let raw = u32at(e + 8)?; + Some(if le { (raw & 0xFFFF) as u16 } else { (raw >> 16) as u16 }) + }; + // RATIONAL values of count 1 live at the offset (relative to the TIFF header start). + let rational_at = || -> Option<(u32, u32)> { + if cnt != 1 { + return None; + } + let off = u32at(e + 8)? as usize; + if off.checked_add(8)? > tiff.len() { + return None; + } + Some((u32at(off)?, u32at(off + 4)?)) + }; + match (tag, typ) { + (0x011A, 5) if xres.is_none() => xres = rational_at(), + (0x011B, 5) if yres.is_none() => yres = rational_at(), + (0x0128, 3) if unit.is_none() => unit = short_inline(), + _ => {} + } + } + let num = |(n, d): (u32, u32)| (d != 0).then(|| n as f64 / d as f64); + let (x, y) = (num(xres?)?, num(yres?)?); + match unit.unwrap_or(2) { + 2 => Some((x, y)), + 3 => Some((x * 2.54, y * 2.54)), + _ => None, + } +} + +// ---------- PNG ---------- + +/// The pHYs chunk: pixels-per-unit in x and y plus the unit (1 = meter → dpi). +fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let mut pos = 8; + for _ in 0..64 { + let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; + let kind = bytes.get(pos + 4..pos + 8)?; + if kind == b"pHYs" { + let data = bytes.get(pos + 8..pos + 8 + 9)?; + let (x, y) = (u32::from_be_bytes(data[0..4].try_into().ok()?), u32::from_be_bytes(data[4..8].try_into().ok()?)); + if data[8] == 1 && x > 0 && y > 0 { + return Some((x as f64 * 0.0254, y as f64 * 0.0254)); + } + return None; + } + if kind == b"IEND" { + return None; + } + pos = pos.checked_add(8)?.checked_add(len)?.checked_add(4)?; + if pos >= bytes.len() { + return None; + } + } + None +} + +// ---------- WebP ---------- + +/// A WebP EXIF chunk carries a TIFF header: reuse the TIFF resolution tags. +fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; + let end = 12usize.checked_add(riff)?.min(bytes.len()); + let mut pos = 12; + for _ in 0..64 { + let kind = bytes.get(pos..pos + 4)?; + let size = u32::from_le_bytes(bytes.get(pos + 4..pos + 8)?.try_into().ok()?) as usize; + let data = pos.checked_add(8)?; + if data.checked_add(size)? > end { + return None; + } + if kind == b"EXIF" && is_classic_tiff(bytes.get(data..data + size.min(4)).unwrap_or_default()) { + return tiff_resolution(&bytes[data..(data + size).min(bytes.len())]); + } + pos = data.checked_add(size.checked_add(size & 1)?)?; + } + None +} + +// ---------- BMP ---------- + +/// BITMAPINFOHEADER pixels-per-meter (offset 38/42): meters → dpi. +fn bmp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + if bytes.len() < 46 || u32::from_le_bytes(bytes.get(14..18)?.try_into().ok()?) < 40 { + return None; + } + let ppm = |i: usize| -> Option { Some(i32::from_le_bytes(bytes.get(i..i + 4)?.try_into().ok()?)) }; + let (x, y) = (ppm(38)?, ppm(42)?); + if x > 0 && y > 0 { + return Some((x as f64 * 0.0254, y as f64 * 0.0254)); + } + None +} diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 3e5daf8ab..917693f87 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -432,6 +432,234 @@ fn cmyk_tiff_with_alpha_reports_its_pixel_size() { assert_eq!(pixel_size(&b), Some((2, 1))); } +// ---------- embedded resolution (#1991) ---------- + +/// A real encoder-written 600x900 JPEG with an APPn segment inserted after SOI (decoders skip +/// APPn, so the file stays fully valid and dimension readers exercise the real path). +fn jpeg_with(app: &[u8]) -> Vec { + use image::codecs::jpeg::JpegEncoder; + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([200, 30, 30, 255])); + let mut b = Vec::new(); + JpegEncoder::new_with_quality(&mut b, 90).encode_image(&img).unwrap(); + assert_eq!(&b[..2], &[0xFF, 0xD8]); + let mut out = b[..2].to_vec(); + out.extend_from_slice(app); + out.extend_from_slice(&b[2..]); + out +} + +/// JFIF APP0 with the given units (0 aspect, 1 dpi, 2 per cm) and densities. +fn jfif_app(units: u8, x: u16, y: u16) -> Vec { + let mut a = vec![0xFF, 0xE0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x02, units]; + a.extend_from_slice(&x.to_be_bytes()); + a.extend_from_slice(&y.to_be_bytes()); + a.extend_from_slice(&[0x00, 0x00]); + a +} + +/// Minimal little-endian TIFF with X/YResolution rationals and an optional ResolutionUnit. +fn tiff_bytes(x: (u32, u32), y: (u32, u32), unit: Option) -> Vec { + let mut t = vec![b'I', b'I', 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00]; + let n = if unit.is_some() { 3 } else { 2 }; + t.extend_from_slice(&(n as u16).to_le_bytes()); + let data = 8 + 2 + n * 12 + 4; + let mut entry = |tag: u16, typ: u16, val: u32| { + t.extend_from_slice(&tag.to_le_bytes()); + t.extend_from_slice(&typ.to_le_bytes()); + t.extend_from_slice(&1u32.to_le_bytes()); + t.extend_from_slice(&val.to_le_bytes()); + }; + entry(0x011A, 5, data as u32); + entry(0x011B, 5, (data + 8) as u32); + if let Some(u) = unit { + // SHORT count 1: the value sits inline in the low bytes. + t.extend_from_slice(&0x0128u16.to_le_bytes()); + t.extend_from_slice(&3u16.to_le_bytes()); + t.extend_from_slice(&1u32.to_le_bytes()); + t.extend_from_slice(&u.to_le_bytes()); + t.extend_from_slice(&[0, 0]); + } + t.extend_from_slice(&[0, 0, 0, 0]); + assert_eq!(t.len(), data); + for (num, den) in [x, y] { + t.extend_from_slice(&num.to_le_bytes()); + t.extend_from_slice(&den.to_le_bytes()); + } + t +} + +/// EXIF APP1 wrapping a TIFF header. +fn exif_app(tiff: &[u8]) -> Vec { + let mut a = vec![0xFF, 0xE1]; + a.extend_from_slice(&((tiff.len() + 8) as u16).to_be_bytes()); + a.extend_from_slice(b"Exif\x00\x00"); + a.extend_from_slice(tiff); + a +} + +/// #1991: a 600x900 px photo saved at 600 dpi places 1 x 1.5 in, not 600 x 900 pt. +#[test] +fn jpeg_jfif_density_sets_natural_size() { + let jpg = jpeg_with(&jfif_app(1, 600, 600)); + assert_eq!(pixel_size(&jpg), Some((600, 900))); + assert_eq!(raster_resolution(&jpg), Some((600.0, 600.0))); + assert_eq!(natural_size(&jpg), Some((72.0, 108.0))); + // Dots per cm convert to dpi; aspect-only JFIF (units 0) carries no density. + let cm = jpeg_with(&jfif_app(2, 100, 100)); + assert_eq!(raster_resolution(&cm), Some((254.0, 254.0))); + let aspect = jpeg_with(&jfif_app(0, 600, 600)); + assert_eq!(raster_resolution(&aspect), None); + assert_eq!(natural_size(&aspect), Some((600.0, 900.0))); +} + +#[test] +fn jpeg_exif_resolution_beats_jfif() { + // EXIF wins over a conflicting JFIF density. + let mut app = jfif_app(1, 72, 72); + app.extend_from_slice(&exif_app(&tiff_bytes((300, 1), (300, 1), Some(2)))); + let jpg = jpeg_with(&app); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0))); + assert_eq!(natural_size(&jpg), Some((600.0 * 72.0 / 300.0, 900.0 * 72.0 / 300.0))); + // A missing unit defaults to inch; per-cm scales by 2.54. + let no_unit = jpeg_with(&exif_app(&tiff_bytes((300, 1), (300, 1), None))); + assert_eq!(raster_resolution(&no_unit), Some((300.0, 300.0))); + // A non-EXIF APP1 (XMP) before the EXIF one does not stop the scan. + let mut xmp = vec![0xFF, 0xE1]; + let xmp_payload = b"http://ns.adobe.com/xap/1.0/\x00"; + xmp.extend_from_slice(&((xmp_payload.len() + 2) as u16).to_be_bytes()); + xmp.extend_from_slice(xmp_payload); + xmp.extend_from_slice(&exif_app(&tiff_bytes((300, 1), (300, 1), Some(2)))); + assert_eq!(raster_resolution(&jpeg_with(&xmp)), Some((300.0, 300.0))); + let cm = jpeg_with(&exif_app(&tiff_bytes((100, 1), (100, 1), Some(3)))); + assert_eq!(raster_resolution(&cm), Some((254.0, 254.0))); + // A zero denominator or a missing axis is unusable: back to a pixel per point. + let zero = jpeg_with(&exif_app(&tiff_bytes((300, 0), (300, 1), Some(2)))); + assert_eq!(raster_resolution(&zero), None); +} + +/// Big-endian EXIF parses too. +#[test] +fn jpeg_exif_big_endian_parses() { + let mut t = vec![b'M', b'M', 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08]; + t.extend_from_slice(&[0x00, 0x02]); + let mut entry = |tag: u16, val: u32| { + t.extend_from_slice(&tag.to_be_bytes()); + t.extend_from_slice(&5u16.to_be_bytes()); + t.extend_from_slice(&1u32.to_be_bytes()); + t.extend_from_slice(&val.to_be_bytes()); + }; + entry(0x011A, 38); + entry(0x011B, 46); + t.extend_from_slice(&[0, 0, 0, 0]); + assert_eq!(t.len(), 38); + for (num, den) in [(600u32, 2u32), (600u32, 2u32)] { + t.extend_from_slice(&num.to_be_bytes()); + t.extend_from_slice(&den.to_be_bytes()); + } + let jpg = jpeg_with(&exif_app(&t)); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0))); + assert_eq!(natural_size(&jpg), Some((144.0, 216.0))); +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &b in data { + crc ^= b as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + !crc +} + +/// A real encoder-written PNG with a pHYs chunk spliced in after IHDR (valid CRC, so the +/// file stays fully decodable and exercises the real dimension path). +fn png_with_phys(ppu: u32) -> Vec { + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([30, 200, 30, 255])); + let mut b = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap(); + // Signature (8) + IHDR chunk (length 4 + type 4 + data 13 + CRC 4). + assert_eq!(&b[..8], b"\x89PNG\r\n\x1a\n"); + assert_eq!(&b[12..16], b"IHDR"); + let mut out = b[..33].to_vec(); + let mut phys = Vec::new(); + phys.extend_from_slice(&ppu.to_be_bytes()); + phys.extend_from_slice(&ppu.to_be_bytes()); + phys.push(1); + out.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + out.extend_from_slice(b"pHYs"); + out.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + out.extend_from_slice(&crc32(&c).to_be_bytes()); + out.extend_from_slice(&b[33..]); + out +} + +#[test] +fn png_phys_sets_natural_size() { + // 23622 px/m = 600 dpi: the photo places 1 x 1.5 in. + let png = png_with_phys(23622); + assert_eq!(pixel_size(&png), Some((600, 900))); + let (dx, _) = raster_resolution(&png).unwrap(); + assert!((dx - 600.0).abs() < 0.05, "{dx}"); + let (w, h) = natural_size(&png).unwrap(); + assert!((w - 72.0).abs() < 0.01 && (h - 108.0).abs() < 0.02, "{w} x {h}"); + // No pHYs: a pixel is a point. + let plain_img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255])); + let mut plain = Vec::new(); + plain_img.write_to(&mut std::io::Cursor::new(&mut plain), image::ImageFormat::Png).unwrap(); + assert_eq!(raster_resolution(&plain), None); + assert_eq!(natural_size(&plain), Some((4.0, 4.0))); +} + +/// A real encoder-written BMP with the header pixels-per-meter patched (compression and image +/// size stay zero, as the encoder writes them). +fn bmp_with_ppm(ppm: i32) -> Vec { + let img = image::RgbaImage::from_pixel(600, 900, image::Rgba([30, 30, 200, 255])); + let mut b = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Bmp).unwrap(); + assert_eq!(&b[..2], b"BM"); + b[38..42].copy_from_slice(&ppm.to_le_bytes()); + b[42..46].copy_from_slice(&ppm.to_le_bytes()); + b +} + +#[test] +fn bmp_density_sets_natural_size() { + // 2835 px/m = 72 dpi: the bitmap keeps its pixel size in points. + let bmp = bmp_with_ppm(2835); + assert_eq!(pixel_size(&bmp), Some((600, 900))); + let (dx, _) = raster_resolution(&bmp).unwrap(); + assert!((dx - 72.0).abs() < 0.05, "{dx}"); + // 600 dpi (23622 px/m): the bitmap places 1 x 1.5 in. + let dense = bmp_with_ppm(23622); + let (w, h) = natural_size(&dense).unwrap(); + assert!((w - 72.0).abs() < 0.01 && (h - 108.0).abs() < 0.02, "{w} x {h}"); + // Zero density: no metadata, a pixel is a point. + let flat = bmp_with_ppm(0); + assert_eq!(raster_resolution(&flat), None); + assert_eq!(natural_size(&flat), Some((600.0, 900.0))); +} + +#[test] +fn tiff_resolution_tags_set_natural_size() { + use tiff::encoder::colortype::Gray8; + // A TIFF the encoder writes carries no density: pixels are points. + let mut plain = Vec::new(); + { + let mut enc = tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut plain)).unwrap(); + enc.new_image::(6, 9).unwrap().write_data(&[0u8; 54]).unwrap(); + } + assert_eq!(pixel_size(&plain), Some((6, 9))); + assert_eq!(natural_size(&plain), Some((6.0, 9.0))); + // The hand-built tag body parses (300 dpi, inch default and explicit). + for unit in [None, Some(2)] { + let t = tiff_bytes((300, 1), (300, 1), unit); + assert_eq!(resolution::tiff_resolution(&t), Some((300.0, 300.0))); + } +} + #[test] fn bmp_decodes() { let mut bmp = Vec::new(); From 581af01d88dffdabb0b96393f08dbb61868d7f49 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:42:32 +0000 Subject: [PATCH 102/328] Apply review fixes - crates/images/src/resolution.rs --- crates/images/src/resolution.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index ab1dc119f..3a04f5fef 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -31,7 +31,7 @@ pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// (a corrupt or hostile value falls back to 72 ppi at the call site). pub fn sane_resolution(dpi: (f64, f64)) -> bool { let (dx, dy) = dpi; - dx.is_finite() && dy.is_finite() && dx > 0.0 && dy > 0.0 && dx <= 100_000.0 && dy <= 100_000.0 + dx.is_finite() && dy.is_finite() && dx >= 1.0 && dy >= 1.0 && dx <= 100_000.0 && dy <= 100_000.0 } fn is_classic_tiff(bytes: &[u8]) -> bool { @@ -115,17 +115,17 @@ fn exif_resolution(payload: &[u8]) -> Option<(f64, f64)> { /// Classic TIFF resolution tags of the first IFD: XResolution/YResolution rationals scaled by /// ResolutionUnit (2 = inch, 3 = cm; a missing unit defaults to inch per the spec). pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { - let le = match &tiff[..2] { + let le = match tiff.get(..2)? { b"II" => true, b"MM" => false, _ => return None, }; let u16at = |i: usize| -> Option { - let b: [u8; 2] = tiff.get(i..i + 2)?.try_into().ok()?; + let b: [u8; 2] = tiff.get(i..i.checked_add(2)?)?.try_into().ok()?; Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) }; let u32at = |i: usize| -> Option { - let b: [u8; 4] = tiff.get(i..i + 4)?.try_into().ok()?; + let b: [u8; 4] = tiff.get(i..i.checked_add(4)?)?.try_into().ok()?; Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) }; let ifd = u32at(4)? as usize; @@ -212,8 +212,12 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { if data.checked_add(size)? > end { return None; } - if kind == b"EXIF" && is_classic_tiff(bytes.get(data..data + size.min(4)).unwrap_or_default()) { - return tiff_resolution(&bytes[data..(data + size).min(bytes.len())]); + if kind == b"EXIF" { + let exif = bytes.get(data..data + size)?; + let tiff = exif.strip_prefix(b"Exif\x00\x00").unwrap_or(exif); + if is_classic_tiff(tiff) { + return tiff_resolution(tiff); + } } pos = data.checked_add(size.checked_add(size & 1)?)?; } From 0f1f51cbd43b561e7205744e1a42f318a45eefa3 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:17:26 +0000 Subject: [PATCH 103/328] Fix failing CI check - crates/images/src/resolution.rs --- crates/images/src/resolution.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index 3a04f5fef..c4a95e8e5 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -77,7 +77,9 @@ fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let payload = &bytes[pos + 2..pos + len]; if m == 0xE0 && jfif.is_none() { jfif = jfif_density(payload); - } else if m == 0xE1 && let Some(dpi) = exif_resolution(payload) { + } else if m == 0xE1 + && let Some(dpi) = exif_resolution(payload) + { // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a // later APP1 can still carry the EXIF resolution. return Some(dpi); From d490e0fb185b472c82c5e320d77b66e7b262b8a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:14:15 -0800 Subject: [PATCH 104/328] Data merge: a QR field at a text insertion point is refused instead of written as text Insert Field with a QR column and the text cursor in a frame added a text placeholder, so a merge wrote the QR payload as plain text. It now returns "qr placeholders bind to a frame" and leaves the story unchanged. --- crates/engine/src/cmd/datamerge.rs | 3 +++ crates/engine/src/cmd/datamerge/tests.rs | 14 ++++++++++++++ docs/agents.md | 7 ++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 6fac73836..411fd545c 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -503,6 +503,9 @@ fn add_placeholder(d: &mut Document, sel: &Selection, p: &Value, name: &str) -> } else if field.kind == DataFieldKind::Image { // An image field at the insertion point places the image inline in the text. PlaceholderRole::Image + } else if field.kind == DataFieldKind::Qr { + // A QR field at the insertion point is refused below: QR codes bind to a frame. + PlaceholderRole::Qr } else { PlaceholderRole::Text }; diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 8ca5291a6..39b1988e2 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -817,6 +817,20 @@ fn an_image_field_at_the_insertion_point_merges_as_an_inline_image() { assert!((wide.1 - width).abs() < 0.01 && (wide.2 - width / 8.0).abs() < 0.01, "a wide image is scaled down to the frame: {wide:?}"); } +/// A QR field at a text insertion point is refused instead of merging its payload as text. +#[test] +fn a_qr_field_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "@Photo,#Code\n/x.png,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + assert_eq!(texts(&s), vec!["Hi ".to_string()]); + assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); +} + /// A typed `<>` marker for an image column places the image too, from an absolute path; /// an explicit text role still writes the path as text. #[test] diff --git a/docs/agents.md b/docs/agents.md index d2f416c83..13977d2af 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -90,9 +90,10 @@ external PDF/X certification. `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the -frame. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with -one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image -fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. +frame. A QR field (a `#` column) inserted at a text insertion point is refused; bind it to a frame instead. An image +path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator +(`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; +`data.preview {record}` / `data.preview.stop` show one record without saving it. `data.merge` now **creates a new document** and leaves the template unchanged (the old `spread` parameter, which appended pages to the template, is an error). It uses the linked source, or inline `csv` / `rows` / `path` / `bytes`: From c8136c538ba91a6b977bc83ee15de87fd2bd1623 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:20:51 -0800 Subject: [PATCH 105/328] Place: an unusable EXIF resolution falls back to the JFIF density A JPEG whose EXIF resolution is 0 ppi or outside 1 to 100,000 ppi now takes its size from its JFIF density instead of one point per pixel. Tests place an 11 x 17 in image (330 x 510 px at 30 ppi) with a click, check that it comes in at 792 x 1224 pt and keeps that size through a save and reopen, and that an image with no stored resolution comes in at 72 ppi. --- crates/engine/src/cmd/file/place.rs | 84 +++++++++++++++++++++++------ crates/images/src/lib.rs | 4 +- crates/images/src/resolution.rs | 10 ++-- crates/images/src/tests.rs | 13 +++++ crates/render/src/decode.rs | 2 +- 5 files changed, 88 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 29358d834..e0d285702 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -589,10 +589,8 @@ pub(super) mod image_place_tests { } } - #[test] - fn placed_photo_honors_its_embedded_resolution() { - // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place - // 4.8 pt wide), instead of a pixel always becoming a point. + /// A `width` x `height` PNG with a pHYs chunk of `ppm` pixels per meter on both axes, or none. + fn png_with_density(width: u32, height: u32, ppm: Option) -> std::io::Result { fn crc32(data: &[u8]) -> u32 { let mut crc = 0xFFFF_FFFFu32; for &b in data { @@ -603,22 +601,33 @@ pub(super) mod image_place_tests { } !crc } - let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [30, 90, 180, 255].repeat(800) }.to_png(); + let pixels = [30, 90, 180, 255].repeat((width * height) as usize); + let png = designcraft_render::Rendered { width, height, pixels }.to_png(); assert_eq!(&png[12..16], b"IHDR"); - let mut phys = Vec::new(); - phys.extend_from_slice(&23622u32.to_be_bytes()); - phys.extend_from_slice(&23622u32.to_be_bytes()); - phys.push(1); let mut bytes = png[..33].to_vec(); - bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); - bytes.extend_from_slice(b"pHYs"); - bytes.extend_from_slice(&phys); - let mut c = b"pHYs".to_vec(); - c.extend_from_slice(&phys); - bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + if let Some(ppm) = ppm { + let mut phys = Vec::new(); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.extend_from_slice(&ppm.to_be_bytes()); + phys.push(1); + bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes()); + bytes.extend_from_slice(b"pHYs"); + bytes.extend_from_slice(&phys); + let mut c = b"pHYs".to_vec(); + c.extend_from_slice(&phys); + bytes.extend_from_slice(&crc32(&c).to_be_bytes()); + } bytes.extend_from_slice(&png[33..]); - let file = tempfile::Builder::new().suffix(".png").tempfile().unwrap(); - std::fs::write(file.path(), bytes).unwrap(); + let file = tempfile::Builder::new().suffix(".png").tempfile()?; + std::fs::write(file.path(), bytes)?; + Ok(file) + } + + #[test] + fn placed_photo_honors_its_embedded_resolution() { + // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place + // 4.8 pt wide), instead of a pixel always becoming a point. + let file = png_with_density(40, 20, Some(23622)).unwrap(); let mut session = Session::new(); session.execute("file.new", &json!({})).unwrap(); let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap(); @@ -629,6 +638,47 @@ pub(super) mod image_place_tests { assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}"); } + /// File › Place, then a click: an 11 x 17 in image (330 x 510 px at 30 ppi) comes in at + /// 792 x 1224 pt, keeps that size through a save and reopen, and an image with no stored + /// resolution comes in at 72 ppi (330 x 510 pt). + #[test] + fn a_clicked_image_keeps_its_print_size_through_save_and_reopen() { + // 1181 pixels per meter is 29.9974 ppi. + let (w, h) = (330.0 * 72.0 / (1181.0 * 0.0254), 510.0 * 72.0 / (1181.0 * 0.0254)); + for (ppm, (ew, eh)) in [(Some(1181), (w, h)), (None, (330.0, 510.0))] { + let image = png_with_density(330, 510, ppm).unwrap(); + let mut session = Session::new(); + session.execute("file.new", &json!({})).unwrap(); + session.execute("file.place", &json!({"path": image.path(), "loadCursor": true})).unwrap(); + session.execute("place.drop", &json!({"x": 0, "y": 0})).unwrap(); + // The bounds and natural size of the document's one placed graphic. + let shown = |session: &Session| { + let doc = &session.doc().unwrap().doc; + let graphics: Vec<_> = doc + .all_items() + .into_iter() + .filter_map(|id| doc.item(id)) + .filter_map(|item| match &item.content { + Content::Graphic(g) => Some((item.bounds(), g.size)), + _ => None, + }) + .collect(); + assert_eq!(graphics.len(), 1, "{graphics:?}"); + graphics[0] + }; + let (b, size) = shown(&session); + assert!((b.width() - ew).abs() < 1e-6 && (b.height() - eh).abs() < 1e-6, "{ppm:?}: {b:?}"); + assert!((size.0 - ew).abs() < 1e-6 && (size.1 - eh).abs() < 1e-6, "{ppm:?}: {size:?}"); + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("placed.designcraft"); + session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap(); + assert_eq!(shown(&reopened), (b, size), "{ppm:?}"); + } + } + #[test] fn explicit_frame_wins_over_placement_and_selection() { let image = image_file().unwrap(); diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 7540eee90..b32be1063 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -374,8 +374,8 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { return Some((bb[2] - bb[0], bb[3] - bb[1])).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); } let (w, h) = pixel_size(bytes)?; - // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide, - // as in InDesign. Absurd metadata falls back to a pixel per point. + // Honor the file's density (#1991): a 600 px photo saved at 600 dpi places one inch wide. + // Absurd metadata falls back to a pixel per point. match raster_resolution(bytes) { Some(dpi) if resolution::sane_resolution(dpi) => Some((w as f64 * 72.0 / dpi.0, h as f64 * 72.0 / dpi.1)), _ => Some((w as f64, h as f64)), diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index c4a95e8e5..dabaf1c61 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -1,6 +1,6 @@ //! Embedded raster resolution: the density a placed graphic was saved with, so placing honors -//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide, -//! as in InDesign). Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution +//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide). +//! Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution //! tags from TIFF, and the header density from BMP. GIF, PSD and files without (usable) metadata //! report nothing and keep the pixel-is-a-point size. @@ -78,10 +78,10 @@ fn jpeg_resolution(bytes: &[u8]) -> Option<(f64, f64)> { if m == 0xE0 && jfif.is_none() { jfif = jfif_density(payload); } else if m == 0xE1 - && let Some(dpi) = exif_resolution(payload) + && let Some(dpi) = exif_resolution(payload).filter(|dpi| sane_resolution(*dpi)) { - // A non-EXIF APP1 (XMP, ICC, ...) parses to nothing: keep scanning, since a - // later APP1 can still carry the EXIF resolution. + // A non-EXIF APP1 (XMP, ICC, ...) or an unusable EXIF density parses to nothing: + // keep scanning, so a later APP1 or the JFIF density still sets the size. return Some(dpi); } pos += len; diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 917693f87..f2fcf2bf0 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -537,6 +537,19 @@ fn jpeg_exif_resolution_beats_jfif() { assert_eq!(raster_resolution(&zero), None); } +/// An EXIF density of 0 ppi (or any value outside the usable range) does not hide the JFIF +/// density: the 600x900 px photo at a JFIF 300 dpi still places 144 x 216 pt. +#[test] +fn unusable_exif_density_keeps_the_jfif_density() { + for exif in [(0, 1), (1, 4), (1_000_000, 1)] { + let mut app = jfif_app(1, 300, 300); + app.extend_from_slice(&exif_app(&tiff_bytes(exif, exif, Some(2)))); + let jpg = jpeg_with(&app); + assert_eq!(raster_resolution(&jpg), Some((300.0, 300.0)), "EXIF {exif:?}"); + assert_eq!(natural_size(&jpg), Some((144.0, 216.0)), "EXIF {exif:?}"); + } +} + /// Big-endian EXIF parses too. #[test] fn jpeg_exif_big_endian_parses() { diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..df8e1f047 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -87,7 +87,7 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { } /// Natural size of a placed graphic, unrounded: a PDF page (crop box) and an SVG in points, a raster -/// in pixels, an EPS its bounding box independently of preview pixels. Placed graphics are drawn at +/// at its stored resolution (72 ppi without one), an EPS its bounding box independently of preview pixels. Placed graphics are drawn at /// this size; `image_size` rounds it to whole pixels for display. pub fn natural_size(bytes: &[u8], page: usize) -> Option<(f64, f64)> { if is_pdf(bytes) { From 293fe55a4d9c1841b8dea9cae4b3162b5d1280e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:25:01 -0800 Subject: [PATCH 106/328] Text Frame Options: test the four sides for a mixed selection An oval selected first with a rectangle shows the four side fields, and a changed top inset leaves the rectangle's other sides as they were. --- crates/ui-egui/src/dialogs/tests.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index a11bd2f3f..8f1681611 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1486,6 +1486,34 @@ fn text_frame_options_set_one_inset_for_a_non_rectangular_frame() { assert_eq!(d.s("inset"), "0p6"); } +/// A selection that mixes a non-rectangular frame with a rectangle shows the four sides, even with +/// the oval first, and a changed side leaves the rectangle's other sides as they were. +#[test] +fn text_frame_options_show_four_sides_for_a_mixed_selection() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let oval = app.run("frame.create", json!({"rect": [36, 36, 336, 236], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 300, 336, 500], "content": "text", "text": "Hello"})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + app.run("selection.set", json!({"ids": [oval.0, rect.0]})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "a mixed selection shows the four sides"); + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, rect).inset, [12.0, 2.0, 3.0, 4.0]); + assert_eq!(opts(&app, oval).inset, [12.0, 2.0, 3.0, 4.0]); + // Two non-rectangular frames still show the one Inset. + app.run("object.cornerOptions", json!({"ids": [rect.0], "shape": "rounded", "size": 12})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(d.b("_shaped")); +} + /// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an /// Inset field; for a rectangle it shows no Inset field and the sides stay editable. #[test] From 0db4ba3dd426834935aa8a9c300aa346b61c58ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:39:10 -0800 Subject: [PATCH 107/328] Text Frame Options: the dialog is one row taller for a non-rectangular frame The Inset row made the General tab taller than the dialog's fixed height, so the buttons moved when switching tabs. The fixed height now includes that row. --- crates/ui-egui/src/dialogs.rs | 8 +++++--- crates/ui-egui/src/dialogs/tests.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6335f8fca..702c6bcc2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1106,9 +1106,11 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) } ui.set_min_width(560.0); ui.horizontal_top(|ui| { - // A fixed height: the separator would otherwise stretch the dialog to the window. - ui.set_min_height(330.0); - ui.set_max_height(330.0); + // A fixed height: the separator would otherwise stretch the dialog to the window. A + // non-rectangular frame's Inset row needs one more row. + let height = if d.b("_shaped") { 360.0 } else { 330.0 }; + ui.set_min_height(height); + ui.set_max_height(height); section_list( &lang, ui, diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 8f1681611..38ffc28cb 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1549,6 +1549,14 @@ fn text_frame_options_dims_the_sides_for_a_non_rectangular_frame() { } assert_eq!(h.query_by_label("Inset:").is_some(), shaped, "{shape}: the Inset caption"); assert_eq!(h.query_by_label("Increase tfo_inset").is_some(), shaped, "{shape}: the Inset field"); + // The General tab fits in the dialog's fixed height: the buttons stay put on another tab. + let (wrap, cancel) = (h.get_by_label("Ignore Text Wrap").rect().bottom(), h.get_by_label("Cancel").rect().top()); + assert!(wrap < cancel, "{shape}: Ignore Text Wrap ends at {wrap}, below the top of Cancel at {cancel}"); + h.get_by_label("Auto-Size").click(); + h.run_steps(3); + assert_eq!(h.get_by_label("Cancel").rect().top(), cancel, "{shape}: the buttons stay put on another tab"); + h.get_by_label("General").click(); + h.run_steps(3); // The link toggles only for a rectangle. let linked = |h: &Harness<'_, DesignApp>| h.state().ui.dialog.as_ref().unwrap().b("insetLinked"); let before = linked(&h); From 510269744ac3cc0b9bd9a3bab307ce30d5bf7b65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:21:39 -0800 Subject: [PATCH 108/328] Text: Text Frame Options open from the Type tool and change the frame holding the caret Object > Text Frame Options and Cmd+B are enabled with a text caret or a text selection. Without ids or selected objects, object.textFrameOptions changes the frame that shows the insertion point, or every frame that holds part of the selected text, instead of every frame of the story. The dialog shows that frame's options and keeps the frames it opened with while the preview reflows the text. An empty ids list and an id that is not in the document are refused. Options a frame already has leave the document unchanged and add no undo step. Fixes #2396 --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/object.rs | 267 +++++++++++++++++++++++++++++- crates/ui-egui/src/dialogs.rs | 73 ++++++-- crates/ui-egui/src/menus/tests.rs | 27 +++ docs/mcp.md | 9 + docs/target-app-parity.md | 1 + 7 files changed, 359 insertions(+), 20 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..42a160c94 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..4fdd375e0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -41,6 +41,7 @@ mod mathexpr; mod media; mod notes; mod object; +pub use object::text_frame_options_frames; mod overrides; mod package; pub mod params; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..67b1d21d4 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -610,8 +610,8 @@ pub fn specs() -> Vec { "Text Frame Options…", ["Object"], Some("Cmd+B"), - "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", - has_selection, + "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids? (without ids or selected objects: the frame showing the text caret, or every frame holding part of the selected text)}", + has_selection_or_text, text_frame_options ), cmd!( @@ -2569,14 +2569,38 @@ fn content_type(s: &mut Session, p: &Value) -> Result { }) } +/// The frames `object.textFrameOptions` changes when the call names none: the selected objects, +/// or with the Type tool the frame that shows the caret or every frame holding part of the +/// selected text. +pub fn text_frame_options_frames(s: &Session) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + if !st.selection.items.is_empty() { + return st.selection.items.clone(); + } + st.selection.text.map(|t| text_selection_frames(s, &t)).unwrap_or_default() +} + +/// Text Frame Options act on the selected objects, or with the Type tool on the frames that hold +/// the caret or the selected text. +fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> { + if s.active().is_some_and(|d| d.selection.text.is_some()) { + return Ok(()); + } + has_selection(s) +} + fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; - let mut ids = targets(s, p)?; - if ids.is_empty() - && let Some(t) = st.selection.text - { - ids = st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(); + // A call that names its objects acts on those; an empty `ids` names nothing. + let named = p.get("ids").is_some() || p.get("id").is_some(); + let ids = if named { targets(s, p)? } else { text_frame_options_frames(s) }; + // With a text caret the command runs before named objects are checked. + if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { + return Err(bad(ID, format!("no object with id {}", gone.0))); + } + if ids.is_empty() { + return Err(bad(ID, super::NOTHING_SELECTED)); } let ranged = |key: &str, lo: f64, hi: f64, what: &str| match p.get(key) { None | Some(Value::Null) => Ok(None), @@ -2644,8 +2668,10 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { Some(Value::String(c)) if st.doc.swatch(c).is_some() => Some(c.clone()), Some(v) => return Err(bad(ID, format!("no swatch {v}"))), }; + let (before, revision) = (Arc::clone(&st.doc), st.revision); + let find = s.find_context.take(); let p = p.clone(); - s.edit(|d, _| { + let edited = s.edit(|d, _| { for id in &ids { let Some(tf) = d.item_mut(*id).and_then(Item::text_frame_mut) else { continue }; let o = &mut tf.options; @@ -2738,6 +2764,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if fixed_width && ["columnsKind", "columnWidth", "columns", "gutter", "inset"].iter().any(|k| p.get(*k).is_some()) && let Some(r) = d.item(*id).map(Item::inner_bounds) + && ((r.width() - width).abs() >= 1e-9 || !width.is_finite()) { let r = super::finite_rect("object.textFrameOptions", Rect::new(r.x0, r.y0, r.x0 + width, r.y1))?; crate::autosize::resize(d, *id, r); @@ -2749,7 +2776,71 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { super::text::set_story_direction(d, &stories, v); } Ok(json!({"changed": ids.len()})) - }) + }); + let changed = match edited { + Ok(v) => v, + Err(e) => { + s.find_context = find; + return Err(e); + } + }; + // Options the frames already have: the document, its revision and the Find Next scope go back + // to what they were, which leaves no undo step. Only the frames and their stories are compared. + let st = s.doc_mut()?; + let same = ids.iter().all(|id| { + let (now, was) = (st.doc.item(*id), before.item(*id)); + now == was && now.and_then(Item::text_frame).is_none_or(|t| st.doc.story(t.story) == before.story(t.story)) + }); + if same { + st.doc = before; + st.revision = revision; + s.find_context = find; + return Ok(json!({"changed": 0})); + } + Ok(changed) +} + +/// The frames Text Frame Options acts on from the Type tool: the frame that shows the caret, or +/// every frame that holds part of the selected text. Text past the last frame counts as the last +/// frame's. +fn text_selection_frames(s: &Session, t: &TextSel) -> Vec { + let Ok(st) = s.doc() else { return Vec::new() }; + let Some(story) = st.doc.story(t.story) else { return Vec::new() }; + let last = story.frames.last().copied(); + // In a table cell, `anchor` and `focus` index the cell's text: the frame the caret is shown in. + if t.cell.is_some() { + return t.frame.filter(|f| story.frames.contains(f)).or(last).into_iter().collect(); + } + let cs = s.cache.get(&st.doc, t.story, None); + let r = t.range(); + // The frame the caret at the start is drawn in; the caret's stored frame only when no line + // holds it. + let caret_frame = || { + designcraft_compose::caret(&cs, r.start) + .and_then(|(fi, ..)| cs.frames.get(fi)) + .map(|f| f.frame) + .or_else(|| t.frame.filter(|f| story.frames.contains(f) && cs.overset_at.is_none_or(|o| r.start < o))) + }; + // A frame's range stops before the paragraph return that ends its last line; the return + // belongs to that frame. + let end_of = |f: &designcraft_compose::FrameText| f.range.end + usize::from(story.text.as_bytes().get(f.range.end) == Some(&b'\n')); + let mut frames: Vec = if t.is_caret() { + caret_frame().into_iter().collect() + } else { + cs.frames.iter().filter(|f| f.range.start < r.end && r.start < end_of(f)).map(|f| f.frame).collect() + }; + // Selected text no frame holds goes with the line before it. + if frames.is_empty() { + frames.extend(caret_frame()); + } + let overset = cs.overset_at.is_some_and(|o| r.end > o); + if let Some(l) = last + && (frames.is_empty() || overset) + && !frames.contains(&l) + { + frames.push(l); + } + frames } fn apply_custom_frame_grid( @@ -4820,6 +4911,7 @@ mod named_target_tests { s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); assert!(s.doc().unwrap().selection.items.is_empty(), "frame.create leaves a text caret"); + s.execute("edit.deselectAll", &json!({})).unwrap(); let e = s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap_err().to_string(); assert!(e.contains("nothing selected"), "{e}"); s.execute("object.textFrameOptions", &json!({"ids": [r["id"]], "columns": 2})).unwrap(); @@ -4839,6 +4931,163 @@ mod named_target_tests { } } +#[cfg(test)] +mod type_tool_frame_options_tests { + use super::*; + use designcraft_doc::VerticalJustification; + + /// One story threaded through two frames, with text in both: (first frame, second frame, story). + fn two_frame_thread(s: &mut Session) -> (ItemId, ItemId, StoryId) { + s.execute("file.new", &json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 200, 300, 700], "content": "text", "text": ""})).unwrap(); + let (a, b) = (ItemId(a["id"].as_u64().unwrap()), ItemId(b["id"].as_u64().unwrap())); + s.execute("text.thread", &json!({"from": a.0, "to": b.0})).unwrap(); + let sid = s.doc().unwrap().doc.item(a).and_then(Item::text_frame).unwrap().story; + (a, b, sid) + } + + /// The story bytes `frame` shows. + fn shown(s: &Session, sid: StoryId, frame: ItemId) -> std::ops::Range { + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + cs.frame(frame).unwrap().range.clone() + } + + fn options(s: &Session, id: ItemId) -> TextFrameOptions { + s.doc().unwrap().doc.item(id).and_then(Item::text_frame).unwrap().options.clone() + } + + fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + /// With the Type tool, Text Frame Options change the frame that shows the caret, not every + /// frame of the story. + #[test] + fn a_caret_changes_the_frame_it_is_in() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + assert!(!ra.is_empty() && !rb.is_empty(), "both frames hold text: {ra:?} {rb:?}"); + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 2})).unwrap(); + assert!(s.doc().unwrap().selection.items.is_empty()); + let steps = undo_steps(&s); + s.execute("object.textFrameOptions", &json!({"columns": 3, "verticalJustification": "center", "inset": 6})).unwrap(); + assert_eq!( + (options(&s, b).columns, options(&s, b).vertical_justification, options(&s, b).inset), + (3, VerticalJustification::Center, [6.0; 4]) + ); + assert_eq!((options(&s, a).columns, options(&s, a).vertical_justification), (1, VerticalJustification::Top), "the first frame is left alone"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(options(&s, b).columns, 1); + // A caret in the first frame changes the first frame. + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.start + 2})).unwrap(); + s.execute("object.textFrameOptions", &json!({"verticalJustification": "bottom"})).unwrap(); + assert_eq!( + (options(&s, a).vertical_justification, options(&s, b).vertical_justification), + (VerticalJustification::Bottom, VerticalJustification::Top) + ); + } + + /// A caret moved to the start of the second frame keeps the first frame as its stored frame; + /// the options go to the frame the caret is drawn in. + #[test] + fn a_caret_at_a_frame_boundary_changes_the_frame_it_is_drawn_in() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let rb = shown(&s, sid, b); + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + let drawn = designcraft_compose::caret(&cs, rb.start).and_then(|(fi, ..)| cs.frames.get(fi)).map(|f| f.frame); + assert_eq!(drawn, Some(b), "the caret at the boundary is drawn in the second frame"); + s.doc_mut().unwrap().selection = Selection::text(TextSel { story: sid, anchor: rb.start, focus: rb.start, frame: Some(a), cell: None }); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 2)); + } + + /// Selected text that runs from one frame into the next changes both frames. + #[test] + fn selected_text_changes_every_frame_it_runs_through() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end - 3, "focus": rb.start + 3})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 2)); + // Text inside one frame changes that frame only. + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 1, "focus": rb.start + 6})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 4})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 4)); + } + + /// A selected paragraph return at the end of the first frame changes the first frame. + #[test] + fn a_selected_return_at_the_end_of_a_frame_changes_that_frame() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = (0..40).map(|i| format!("Paragraph {i}")).collect::>().join("\n"); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 200, 300, 700], "content": "text", "text": ""})).unwrap(); + let (a, b) = (ItemId(a["id"].as_u64().unwrap()), ItemId(b["id"].as_u64().unwrap())); + s.execute("text.thread", &json!({"from": a.0, "to": b.0})).unwrap(); + let sid = s.doc().unwrap().doc.item(a).and_then(Item::text_frame).unwrap().story; + let (ra, rb) = (shown(&s, sid, a), shown(&s, sid, b)); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text.as_bytes()[ra.end], b'\n', "the first frame ends before a return"); + assert_eq!(rb.start, ra.end + 1, "the second frame starts after it"); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end, "focus": ra.end + 1})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (2, 1)); + // From that return into the second frame, with the first frame back as it was: both frames. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((shown(&s, sid, a), shown(&s, sid, b)), (ra.clone(), rb.clone())); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.end, "focus": rb.start + 3})).unwrap(); + s.execute("object.textFrameOptions", &json!({"columns": 3})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (3, 3)); + } + + /// An empty `ids` names no frame, so it does not fall back to the caret's frame. + #[test] + fn empty_ids_with_a_caret_is_an_error() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + s.execute("text.select", &json!({"story": sid.0, "anchor": 2})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("object.textFrameOptions", &json!({"ids": [], "columns": 3})).unwrap_err().to_string(); + assert!(e.contains("nothing selected"), "{e}"); + // An id that is not in the document is refused too. + let e = s.execute("object.textFrameOptions", &json!({"ids": [99999, b.0], "columns": 3})).unwrap_err().to_string(); + assert!(e.contains("no object with id 99999"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); + } + + /// Options the frame already has change nothing and add no undo step. + #[test] + fn unchanged_options_add_no_undo_step() { + let mut s = Session::new(); + let (_, b, sid) = two_frame_thread(&mut s); + let rb = shown(&s, sid, b); + s.execute("text.select", &json!({"story": sid.0, "anchor": rb.start + 2})).unwrap(); + let steps = undo_steps(&s); + let (before, revision) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().revision); + let r = s.execute("object.textFrameOptions", &json!({"columns": 1, "verticalJustification": "top", "inset": 0})).unwrap(); + assert_eq!(r["changed"], 0); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!(s.doc().unwrap().revision, revision, "the revision stays"); + assert_eq!(undo_steps(&s), steps); + // The same holds for selected frames, Fixed Width columns included. + s.execute("selection.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.textFrameOptions", &json!({"gutter": options(&s, b).gutter})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let fixed = json!({"columnsKind": "fixedWidth", "columnWidth": 100.3, "columns": 2, "gutter": 12.1}); + s.execute("object.textFrameOptions", &fixed).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + assert_eq!(s.execute("object.textFrameOptions", &fixed).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), steps + 1, "the same Fixed Width options again add no undo step"); + } +} + #[cfg(test)] mod column_rule_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..f2689c927 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -556,6 +556,39 @@ mod color_theme_tests { assert_eq!(opts(&app).columns, 1, "one undo step"); } + /// Opened with the caret on the last line of a frame, Text Frame Options keep acting on that + /// frame while a preview pushes the caret's line into the next frame of the thread. + #[test] + fn text_frame_options_keep_their_frame_while_the_preview_reflows_the_caret() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = + (designcraft_doc::ItemId(a["id"].as_u64().unwrap()), designcraft_doc::ItemId(b["id"].as_u64().unwrap()), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a.0, "to": b.0})).unwrap(); + let shown = |app: &DesignApp, f| { + let cs = designcraft_compose::compose_story(&app.session.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default()); + cs.frame(f).unwrap().range.clone() + }; + let caret = shown(&app, a).end - 1; + app.run("text.select", json!({"story": sid, "anchor": caret})).unwrap(); + let inset = |app: &DesignApp, f| app.session.doc().unwrap().doc.item(f).unwrap().text_frame().unwrap().options.inset[0]; + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("inset".into(), json!("2p0")); + d.fields.insert("preview".into(), json!(true)); + text_frame_preview(&mut app, &mut d); + assert!(shown(&app, b).contains(&caret), "the preview moved the caret's line into the next frame"); + d.fields.insert("columns".into(), json!("2")); + text_frame_preview(&mut app, &mut d); + assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0), "the preview stays on the first frame"); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); + } + #[test] fn toc_right_indent_separator_survives_the_dialog_and_update() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -991,18 +1024,22 @@ fn pdf_export(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } } +/// The first frame Text Frame Options changes: the first selected item, the frame that shows the +/// caret, or the first frame holding selected text. +fn options_frame(app: &DesignApp) -> Option { + designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied() +} + /// The selected text frame's width (its own, before rotation). fn selected_frame_width(app: &DesignApp) -> Option { let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; - Some(st.doc.item(fid)?.inner_bounds().width()) + Some(st.doc.item(options_frame(app)?)?.inner_bounds().width()) } -/// The options of the selected text frame (the first selected item, or the frame of the caret). +/// The options of the frame Text Frame Options shows. fn selected_frame_options(app: &DesignApp) -> Option { let st = app.session.active()?; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame))?; - st.doc.item(fid)?.text_frame().map(|t| t.options.clone()) + st.doc.item(options_frame(app)?)?.text_frame().map(|t| t.options.clone()) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, @@ -1061,9 +1098,25 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { if let Some(w) = selected_frame_width(app) { d.fields.insert("_frameWidth".into(), json!(w)); } + // Typing in a frame: the frames taken when the dialog opens, so a preview that reflows the + // text into another frame does not change which frames the options apply to. + if let Some(ids) = typing_frame_ids(app) { + d.fields.insert("_targets".into(), ids); + } d.fields.insert("_shown".into(), shown); } +/// With the Type tool and no frame selected: the frame that shows the caret, or every frame that +/// holds part of the selected text. +fn typing_frame_ids(app: &DesignApp) -> Option { + let st = app.session.active()?; + if !st.selection.items.is_empty() || st.selection.text.is_none() { + return None; + } + let ids: Vec = designcraft_engine::cmd::text_frame_options_frames(&app.session).iter().map(|f| f.0).collect(); + Some(json!(ids)) +} + /// A 0..1 tint as a percentage ("40", "12.5"). fn percent(t: f32) -> String { let s = format!("{:.2}", f64::from(t) * 100.0); @@ -1552,12 +1605,10 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, json!(d.m("paragraphSpacingLimit").filter(|v| *v >= 0.0).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?), ); } - // Typing in a frame: the options apply to that frame. - if let Some(st) = app.session.active() - && st.selection.items.is_empty() - && let Some(f) = st.selection.text.and_then(|t| t.frame) - { - p.insert("ids".into(), json!([f.0])); + // Typing in a frame: the options apply to the frame that showed the caret, or to every frame + // that held part of the selected text, when the dialog opened. + if let Some(ids) = d.fields.get("_targets").cloned().or_else(|| typing_frame_ids(app)) { + p.insert("ids".into(), ids); } Ok(p) } diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index e977c6733..c3b679b1b 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -335,6 +335,33 @@ fn pdf_export_menu_item_opens_the_dialog_or_exports() { assert!(app.ui.dialog.is_none()); } +/// With the Type tool in the second frame of a thread, Cmd+B opens Text Frame Options, and OK +/// changes the frame that shows the caret. +#[test] +fn text_frame_options_open_from_the_type_tool() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + // The end of the story is in the second frame. + app.run("text.select", json!({"story": sid, "anchor": text.len()})).unwrap(); + assert!(super::state::enabled(&app, "object.textFrameOptions"), "the menu item is enabled while typing"); + let ctx = egui::Context::default(); + press_keys(&mut app, &ctx, &[(egui::Key::B, egui::Modifiers::COMMAND)]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("textFrameOptions"), "Cmd+B opens the dialog while typing"); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("columns".into(), json!(3)); + } + crate::dialogs::confirm(&mut app).unwrap(); + let columns = |app: &crate::DesignApp, id: u64| { + app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).and_then(|i| i.text_frame().map(|t| t.options.columns)) + }; + assert_eq!((columns(&app, a), columns(&app, b)), (Some(1), Some(3))); +} + #[test] fn snap_preferences_are_a_command() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); diff --git a/docs/mcp.md b/docs/mcp.md index f7e0b8187..17c7e330b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -225,6 +225,15 @@ execute {"command": "type.para", "params": {"attrs": {"hyphenate": fals With a text selection, this formats the selected paragraphs; with selected text frames, it formats their whole stories. +`object.textFrameOptions` (columns, inset spacing, vertical justification and the rest of Text Frame Options) acts on +the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that +shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the +thread. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. + +```text +execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} +``` + Use `execute` with `object.fit` to fit a selected graphic frame (or pass `ids`): | `mode` | What it does | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 193d3ae9a..1f6e0ff14 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -351,6 +351,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Column rules (Text Frame Options › Column Rules, `object.textFrameOptions {columnRule, columnRuleWeight, columnRuleColor, columnRuleTint, columnRuleOffset, columnRuleTopInset, columnRuleBottomInset}`, reported by `document.inspect`): a bar centred in each gutter of a multi-column frame from the top line's ascent to the bottom line's descent, between the columns of right-to-left and vertical frames too, broken around paragraphs that span columns, with weight, colour, tint, horizontal offset and top/bottom insets; on screen, in PDF (tagged as an artifact) and in IDML (`ColumnRule…` attributes of `TextFramePreference`, also in object styles). The dialog shows the frame's options and changes only the fields edited. Rule stroke types and overprint aren't there yet. - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. +- Text Frame Options from the Type tool (Object › Text Frame Options…, Cmd+B, `object.textFrameOptions` without `ids`): with the insertion point in a frame, the options change the frame it is drawn in; with text selected, every frame that holds part of it. Options a frame already has add no undo step. - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports. From 7809f5e9da01c84672333a4f0840233567b6ba83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:34:25 -0800 Subject: [PATCH 109/328] Text: frame columns, gutter, switches and indents are checked too object.textFrameOptions refuses a gutter outside 0 to 15552 pt, a column count outside 1 to 40 (it was clamped) and an on/off option that is not true or false (it was skipped). The Control bar's Columns field stops at 40, as the other column fields do. The params text gives the ranges and lists flexibleWidth. type.para and paragraph style create and edit refuse left and right indents outside 0 to 15552 pt and first and last line indents outside -15552 to 15552 pt. A style made from the selection is checked with the values it takes from the selection. style.paragraph.apply and style.paragraph.redefine check that Minimum, Desired and Maximum stay in order in each justification row they change, over the overrides paragraphs keep, and refuse the change otherwise. --- crates/engine/src/cmd/object.rs | 90 ++++++++++++---- crates/engine/src/cmd/style/paragraph.rs | 34 ++++-- crates/engine/src/cmd/text.rs | 6 +- crates/engine/src/cmd/text/format.rs | 127 ++++++++++++++++++++--- crates/ui-egui/src/object_control.rs | 2 +- docs/target-app-parity.md | 2 +- 6 files changed, 213 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 69e2d2b04..d8f6eddb5 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -610,7 +610,7 @@ pub fn specs() -> Vec { "Text Frame Options…", ["Object"], Some("Cmd+B"), - "{columns?, gutter?, inset?: number|[t,l,b,r] (null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", + "{columns? (1..40), gutter? (pt, 0..15552), inset?: number|[t,l,b,r] (pt, each 0..15552; a list has four sides, null keeps that side), verticalJustification?: top|center|bottom|justify, paragraphSpacingLimit? (pt: Justify adds at most this between paragraphs, the rest between lines), columnsKind?: fixedNumber|fixedWidth|flexibleWidth, columnWidth? (pt, Fixed Width), firstBaseline?: ascent|capHeight|leading|xHeight|emboxHeight|fixed, firstBaselineMin? (pt), autoSize?: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference?: topLeft|topCenter|topRight|leftCenter|center|rightCenter|bottomLeft|bottomCenter|bottomRight (the point that stays put), useMinimumHeight?: bool, minimumHeight? (pt), useMinimumWidth?: bool, minimumWidth? (pt), noLineBreaks?: bool, ignoreWrap?, balanceColumns?, columnRule?: bool, columnRuleWeight? (pt), columnRuleColor? (swatch name), columnRuleTint? (0..1), columnRuleOffset? (pt, horizontal), columnRuleTopInset? (pt), columnRuleBottomInset? (pt), baselineGrid?: {start? (pt), increment? (pt), relativeTo?: page|margin|frame|inset} (the frame's custom baseline grid; fields not given keep the frame's, or come from the document grid; null turns it off), vertical?: bool (sets the story direction of the frames' stories, as Type ▸ Story Direction), ids?}", has_selection, text_frame_options ), @@ -2569,6 +2569,9 @@ fn content_type(s: &mut Session, p: &Value) -> Result { }) } +/// The most columns a text frame takes. +const MAX_FRAME_COLUMNS: u64 = 40; + fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; @@ -2595,6 +2598,27 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { let column_width = ranged("columnWidth", 0.0, 15552.0, "a number of points")?; let first_baseline_min = ranged("firstBaselineMin", 0.0, 15552.0, "a number of points")?; let spacing_limit = ranged("paragraphSpacingLimit", 0.0, 15552.0, "a number of points")?; + let gutter = ranged("gutter", 0.0, 15552.0, "a number of points")?; + let columns = match p.get("columns") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_u64() + .filter(|n| (1..=MAX_FRAME_COLUMNS).contains(n)) + .ok_or_else(|| bad(ID, format!("columns must be a whole number from 1 to {MAX_FRAME_COLUMNS}, not {v}")))? as u32, + ), + }; + let flag = |key: &str| match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) => Ok(Some(*b)), + Some(v) => Err(bad(ID, format!("{key} must be true or false, not {v}"))), + }; + let use_min_height = flag("useMinimumHeight")?; + let use_min_width = flag("useMinimumWidth")?; + let no_line_breaks = flag("noLineBreaks")?; + let ignore_wrap = flag("ignoreWrap")?; + let balance_columns = flag("balanceColumns")?; + let column_rule = flag("columnRule")?; + let vertical = flag("vertical")?; let inset = frame_inset_param(p)?; let vertical_justification: Option = frame_choice_param(p, "verticalJustification", "top|center|bottom|justify")?; @@ -2657,11 +2681,11 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { for id in &ids { let Some(tf) = d.item_mut(*id).and_then(Item::text_frame_mut) else { continue }; let o = &mut tf.options; - if let Some(v) = p.get("columns").and_then(Value::as_u64) { - o.columns = v.clamp(1, 40) as u32; + if let Some(v) = columns { + o.columns = v; } - if let Some(v) = p.get("gutter").and_then(Value::as_f64) { - o.gutter = v.max(0.0); + if let Some(v) = gutter { + o.gutter = v; } for (side, v) in o.inset.iter_mut().zip(inset.unwrap_or_default()) { if let Some(v) = v { @@ -2684,22 +2708,22 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { o.auto_size_ref = v; } o.vj_paragraph_spacing_limit = spacing_limit.unwrap_or(o.vj_paragraph_spacing_limit); - if let Some(v) = p.get("useMinimumHeight").and_then(Value::as_bool) { + if let Some(v) = use_min_height { o.auto_size_use_min_height = v; } if let Some(v) = min_height { o.auto_size_min_height = v; } - if let Some(v) = p.get("useMinimumWidth").and_then(Value::as_bool) { + if let Some(v) = use_min_width { o.auto_size_use_min_width = v; } if let Some(v) = min_width { o.auto_size_min_width = v; } - if let Some(v) = p.get("noLineBreaks").and_then(Value::as_bool) { + if let Some(v) = no_line_breaks { o.auto_size_no_line_breaks = v; } - if let Some(v) = p.get("ignoreWrap").and_then(Value::as_bool) { + if let Some(v) = ignore_wrap { o.ignore_wrap = v; } if let Some(v) = column_width { @@ -2708,10 +2732,10 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { if let Some(v) = first_baseline_min { o.first_baseline_min = v; } - if let Some(v) = p.get("balanceColumns").and_then(Value::as_bool) { + if let Some(v) = balance_columns { o.balance_columns = v; } - if let Some(v) = p.get("columnRule").and_then(Value::as_bool) { + if let Some(v) = column_rule { o.column_rule = v; } if let Some(w) = rule_weight { @@ -2746,7 +2770,7 @@ fn text_frame_options(s: &mut Session, p: &Value) -> Result { } } // Story direction belongs to the story: every frame of the thread turns. - if let Some(v) = p.get("vertical").and_then(Value::as_bool) { + if let Some(v) = vertical { let stories: Vec = ids.iter().filter_map(|id| d.item(*id).and_then(Item::text_frame).map(|t| t.story)).collect(); super::text::set_story_direction(d, &stories, v); } @@ -4925,18 +4949,23 @@ mod column_rule_tests { assert_eq!(opts(&s), before); } - /// A column count past `u32::MAX` was cast to `u32` before the clamp, so - /// 2^32 + 1 wrapped to 1 column instead of clamping to the maximum, 40. + /// A column count outside 1 to 40 is refused, past `u32::MAX` too (2^32 + 1 must not + /// wrap to 1 column), and the frame keeps its columns. #[test] - fn huge_column_count_clamps_to_the_maximum() { + fn column_count_outside_one_to_forty_is_refused() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text"})).unwrap(); let id = ItemId(r["id"].as_u64().unwrap()); let columns = |s: &Session| s.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.columns; - for (given, want) in [(4_294_967_297_u64, 40), (u64::MAX, 40), (0, 1)] { + for given in [4_294_967_297_u64, u64::MAX, 41, 0] { + let e = s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": given})).expect_err("refused").to_string(); + assert!(e.contains("columns must be a whole number from 1 to 40"), "columns {given}: {e}"); + assert_eq!(columns(&s), 1, "columns {given}"); + } + for given in [40, 1] { s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": given})).unwrap(); - assert_eq!(columns(&s), want, "columns {given}"); + assert_eq!(columns(&s), given as u32, "columns {given}"); } } } @@ -6042,9 +6071,10 @@ mod frame_baseline_grid_tests { assert_eq!(grid(&s), None); } - /// A negative or huge inset, an inset list that isn't four sides, and a vertical - /// justification or first baseline that isn't one of the names were applied or skipped - /// without a word. They are refused and the frame keeps its options. + /// A negative or huge inset or gutter, an inset list that isn't four sides, a column count + /// outside 1 to 40, a switch that isn't true or false, and a vertical justification or first + /// baseline that isn't one of the names were applied, clamped or skipped without a word. They + /// are refused and the frame keeps its options. #[test] fn text_frame_options_refuse_insets_and_names_outside_their_ranges() { let mut s = Session::new(); @@ -6066,6 +6096,19 @@ mod frame_baseline_grid_tests { (json!({"columnsKind": "flexible"}), "columnsKind must be one of"), (json!({"paragraphSpacingLimit": -1}), "paragraphSpacingLimit must be a number of points from 0 to 15552"), (json!({"firstBaselineMin": 20000}), "firstBaselineMin must be a number of points from 0 to 15552"), + (json!({"gutter": -5}), "gutter must be a number of points from 0 to 15552"), + (json!({"gutter": 1e300}), "gutter must be a number of points from 0 to 15552"), + (json!({"gutter": "12pt"}), "gutter must be a number of points from 0 to 15552"), + (json!({"columns": 99}), "columns must be a whole number from 1 to 40"), + (json!({"columns": "two"}), "columns must be a whole number from 1 to 40"), + (json!({"columns": 2.5}), "columns must be a whole number from 1 to 40"), + (json!({"balanceColumns": "yes"}), "balanceColumns must be true or false"), + (json!({"ignoreWrap": 1}), "ignoreWrap must be true or false"), + (json!({"columnRule": "on"}), "columnRule must be true or false"), + (json!({"noLineBreaks": 0}), "noLineBreaks must be true or false"), + (json!({"useMinimumHeight": "true"}), "useMinimumHeight must be true or false"), + (json!({"useMinimumWidth": []}), "useMinimumWidth must be true or false"), + (json!({"vertical": "yes"}), "vertical must be true or false"), ] { let mut p = params.clone(); p["ids"] = json!([id.0]); @@ -6082,6 +6125,13 @@ mod frame_baseline_grid_tests { let o = options(&s); assert_eq!(o.inset, [6.0; 4]); assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::CapHeight); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "columns": 3, "gutter": 15552, "balanceColumns": true, "ignoreWrap": true})) + .unwrap(); + let o = options(&s); + assert_eq!((o.columns, o.gutter, o.balance_columns, o.ignore_wrap), (3, 15552.0, true, true)); + s.execute("object.textFrameOptions", &json!({"ids": [id.0], "gutter": 0, "balanceColumns": false})).unwrap(); + let o = options(&s); + assert_eq!((o.gutter, o.balance_columns), (0.0, false)); } } diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 04a3f6a8d..e336b0f4f 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -241,9 +241,14 @@ pub(super) fn redefine(s: &mut Session, p: &Value, paragraph: bool) -> Result Result { s.edit(|d, _| { let styles = d.styles.clone(); let (style_para, style_chars) = styles.resolve_para_style(&name); + // Minimum ≤ Desired ≤ Maximum holds in each justification row the style changes in a + // paragraph, over the overrides the paragraph keeps. + let mut refused = None; for t in &targets { if let Some(st) = d.text_story_mut(t.story, t.cell) { + let last = if t.range.is_empty() { t.range.start } else { t.range.end.saturating_sub(1) }; + let touched = st.para_at(t.range.start)..=st.para_at(last); + let before: Vec<_> = st.paras.get(touched.clone()).unwrap_or_default().iter().map(|pf| styles.resolve_para(pf).0).collect(); apply_para_in_story(st, &t.range, &name, clear, (&style_para, &style_chars), &styles); + if refused.is_none() { + refused = st.paras.get(touched).unwrap_or_default().iter().zip(&before).find_map(|(pf, old)| { + let new = styles.resolve_para(pf).0; + crate::cmd::text::justification_order_error(&new, crate::cmd::text::justification_rows_changed(old, &new)) + }); + } } } - ok() + refused.map_or_else(ok, |m| Err(bad("style.paragraph.apply", m))) }) } @@ -418,8 +435,7 @@ fn continue_numbering(p: Option<&Value>, para: &mut ParaAttrs) { /// After an edit of paragraph style `name`: Minimum ≤ Desired ≤ Maximum in `rows` for the style, /// the styles based on it and the story paragraphs that use any of them. -fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3]) -> Result<()> { - const ID: &str = "style.paragraph.edit"; +fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, rows: [bool; 3], command_id: &str) -> Result<()> { if !rows.contains(&true) { return Ok(()); } @@ -427,7 +443,7 @@ fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, row let affected: Vec<&str> = styles.paragraph.iter().map(|st| st.name.as_str()).filter(|n| styles.para_based_on_cycles(name, n)).collect(); for n in &affected { if let Some(m) = crate::cmd::text::justification_order_error(&styles.resolve_para_style(n).0, rows) { - return Err(bad(ID, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); + return Err(bad(command_id, if *n == name { m } else { format!("paragraph style {n:?}: {m}") })); } } for st in d.stories.values() { @@ -435,7 +451,7 @@ fn check_justification_after_edit(d: &designcraft_doc::Document, name: &str, row if affected.contains(&pf.style.as_str()) { crate::cmd::text::justification_order_error(&styles.resolve_para(pf).0, rows) } else { None } }; if let Some(m) = first_in_nested_paras(st, &mut check) { - return Err(bad(ID, format!("a paragraph of story {}: {m}", st.id.0))); + return Err(bad(command_id, format!("a paragraph of story {}: {m}", st.id.0))); } } Ok(()) @@ -479,8 +495,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { continue_numbering(p.get("para"), &mut para); explicit_default_kinsoku(&mut para, p.get("para")); check_grep_styles("style.paragraph.create", ¶)?; - crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; - let rows = justification_rows_given(p); + let mut rows = justification_rows_given(p); let mut chars: CharAttrs = attrs("style.paragraph.create", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?; // Validate caller-supplied fills, not selection fills retained after a swatch is deleted. crate::cmd::text::validate_char_fill(&s.doc()?.doc, &chars, "style.paragraph.create")?; @@ -492,6 +507,7 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { let mut full = ParaProps_to_attrs(&pp); full.merge(¶); para = full; + rows = [true; 3]; } if let Ok(cp) = serde_json::from_value::(cur["chars"].clone()) { let mut full = CharProps_to_attrs(&cp); @@ -499,6 +515,8 @@ pub(super) fn create_para(s: &mut Session, p: &Value) -> Result { chars = full; } } + // The values taken from the selection are checked with the given ones. + crate::cmd::text::validate_para_values(¶, "style.paragraph.create")?; s.edit(|d, _| { let name = Styles::unique_name(|n| d.styles.para(n).is_some(), &base); if let Some(b) = &based_on @@ -635,7 +653,7 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { // Minimum ≤ Desired ≤ Maximum holds over what the style resolves to: in the rows the edit // names, or in every row when it changes Based On or resets the style. let rows = if reset || based.is_some() { [true; 3] } else { justification_rows_given(p) }; - check_justification_after_edit(d, &name, rows)?; + check_justification_after_edit(d, &name, rows, "style.paragraph.edit")?; let st = d.styles_mut().para_mut(&name).ok_or_else(|| bad("style.paragraph.edit", format!("no style `{name}`")))?; match next { Some(Value::String(n)) => st.next_style = Some(n), diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index 421df09bc..ae016d4f9 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -25,8 +25,8 @@ pub use edit::{PLACEHOLDER, quote_marks}; use edit::{change_case, delete, delete_surrounding, fill_placeholder, insert}; pub(crate) use format::{ Target, TypingFormat, apply_char_attrs, effective_char_format, format_chars, format_paras, format_targets, format_targets_pub, - justification_order_error, justification_rows_named, rename_typing_swatch, validate_char_fill, validate_justification_order, - validate_para_values, + justification_order_error, justification_rows_changed, justification_rows_named, rename_typing_swatch, validate_char_fill, + validate_justification_order, validate_para_values, }; use format::{break_link, kern_pair, kern_step, link_style, para_toggle, pick_up_format, step_size, swap_fill_stroke}; use opentype::{open_type, open_type_features, set_features}; @@ -235,7 +235,7 @@ pub fn specs() -> Vec { "Paragraph Formatting", [], None, - "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", + "{attrs: {align?, leftIndent?, rightIndent?, spaceBefore?, spaceAfter?, sameParaStyleSpacing? (pt, each 0..15552), firstLineIndent?, lastLineIndent? (pt, each -15552..15552), wordSpaceMin?/wordSpaceDesired?/wordSpaceMax? (0..10, 1 = 100%), letterSpaceMin?/…Desired?/…Max? (-1..5), glyphScaleMin?/…Desired?/…Max? (0.5..2) (each row Minimum ≤ Desired ≤ Maximum), autoLeading? (0..5 of the type size), singleWordJustify?: left|center|right|fullyJustified, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?: bool (default true), composer?, opticalMargin?: bool (hang at each character's own size; a story with story.options opticalMargin overrides it), ignoreOpticalMargin?: bool (no hang in the paragraph), tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}", has_text_or_frames, |s, p| format_paras(s, p.get("attrs").unwrap_or(p)) ), diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index 23d84bed6..25a0c87ba 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -146,8 +146,9 @@ pub(crate) const MIN_TYPE_SIZE: f64 = 0.1; pub(crate) const MAX_TYPE_SIZE: f64 = 1296.0; -/// Space Before, Space After and Space Between Paragraphs Using Same Style: 0 to 15552 pt, the -/// limit `object.textFrameOptions` applies to its Paragraph Spacing Limit. +/// Left and right indents, Space Before, Space After and Space Between Paragraphs Using Same +/// Style: 0 to 15552 pt, the limit `object.textFrameOptions` applies to its Paragraph Spacing +/// Limit. First and last line indents may be negative, down to -15552 pt. pub(crate) const MAX_PARA_SPACE: f64 = 15552.0; /// The justification rows as fractions (1.0 = 100%): key stem, label, range. @@ -163,20 +164,28 @@ fn percent(v: f64) -> String { format!("{p}") } -/// Checks the paragraph spacing and justification values `attrs` sets: Space Before, Space After -/// and same-style spacing 0 to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing +/// Checks the paragraph spacing and justification values `attrs` sets: left and right indents, +/// Space Before, Space After and same-style spacing 0 to [`MAX_PARA_SPACE`] pt, first and last +/// line indents -[`MAX_PARA_SPACE`] to [`MAX_PARA_SPACE`] pt; word spacing 0% to 1000%, letter spacing /// -100% to 500% and glyph scaling 50% to 200%; Auto Leading 0% to 500%; Single Word /// Justification left, center, right or fullyJustified. [`validate_justification_order`] checks /// the order of each row once the values are applied. pub(crate) fn validate_para_values(attrs: &ParaAttrs, command_id: &str) -> Result<()> { use designcraft_doc::Align; - let spaces = - [("spaceBefore", attrs.space_before), ("spaceAfter", attrs.space_after), ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten())]; - for (key, v) in spaces { + let spaces = [ + ("leftIndent", attrs.left_indent, 0.0), + ("rightIndent", attrs.right_indent, 0.0), + ("firstLineIndent", attrs.first_line_indent, -MAX_PARA_SPACE), + ("lastLineIndent", attrs.last_line_indent, -MAX_PARA_SPACE), + ("spaceBefore", attrs.space_before, 0.0), + ("spaceAfter", attrs.space_after, 0.0), + ("sameParaStyleSpacing", attrs.same_para_style_spacing.flatten(), 0.0), + ]; + for (key, v, lo) in spaces { if let Some(v) = v - && !(0.0..=MAX_PARA_SPACE).contains(&v) + && !(lo..=MAX_PARA_SPACE).contains(&v) { - return Err(bad(command_id, format!("{key} {v}: 0 to {MAX_PARA_SPACE} pt"))); + return Err(bad(command_id, format!("{key} {v}: {lo} to {MAX_PARA_SPACE} pt"))); } } let rows = [ @@ -225,13 +234,24 @@ pub(crate) fn validate_justification_order(resolved: &designcraft_doc::ParaProps justification_order_error(resolved, rows).map_or(Ok(()), |m| Err(bad(command_id, m))) } -/// What [`validate_justification_order`] refuses, as a message. -pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { - let values = [ +/// The justification rows of resolved paragraph attributes: Minimum, Desired, Maximum. +fn justification_values(resolved: &designcraft_doc::ParaProps) -> [[f64; 3]; 3] { + [ [resolved.word_space_min, resolved.word_space_desired, resolved.word_space_max], [resolved.letter_space_min, resolved.letter_space_desired, resolved.letter_space_max], [resolved.glyph_scale_min, resolved.glyph_scale_desired, resolved.glyph_scale_max], - ]; + ] +} + +/// The justification rows whose values differ between `before` and `after`. +pub(crate) fn justification_rows_changed(before: &designcraft_doc::ParaProps, after: &designcraft_doc::ParaProps) -> [bool; 3] { + let (b, a) = (justification_values(before), justification_values(after)); + [b[0] != a[0], b[1] != a[1], b[2] != a[2]] +} + +/// What [`validate_justification_order`] refuses, as a message. +pub(crate) fn justification_order_error(resolved: &designcraft_doc::ParaProps, rows: [bool; 3]) -> Option { + let values = justification_values(resolved); JUSTIFICATION_ROWS.into_iter().zip(values).zip(rows).find_map(|(((_, label, ..), [min, desired, max]), checked)| { (checked && (min > desired || desired > max)) .then(|| format!("{label} needs Minimum ≤ Desired ≤ Maximum, not {}%, {}%, {}%", percent(min), percent(desired), percent(max))) @@ -1213,8 +1233,8 @@ mod size_bounds_tests { } } - /// `type.para` set any number for paragraph spacing and justification: a negative Space - /// Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, + /// `type.para` set any number for paragraph indents, spacing and justification: a negative + /// left indent or Space Before, word spacing of 5000% and a Minimum above Maximum all went into the paragraph, /// and Single Word Justification took any alignment. Values outside the ranges are refused, /// nothing changes, and the ends of each range still apply. #[test] @@ -1232,6 +1252,11 @@ mod size_bounds_tests { (json!({"spaceBefore": -1}), "spaceBefore -1: 0 to 15552 pt"), (json!({"spaceAfter": 15553}), "spaceAfter 15553: 0 to 15552 pt"), (json!({"sameParaStyleSpacing": -2}), "sameParaStyleSpacing -2: 0 to 15552 pt"), + (json!({"leftIndent": -50}), "leftIndent -50: 0 to 15552 pt"), + (json!({"rightIndent": -20}), "rightIndent -20: 0 to 15552 pt"), + (json!({"rightIndent": 1e300}), "rightIndent 1"), + (json!({"firstLineIndent": -15553}), "firstLineIndent -15553: -15552 to 15552 pt"), + (json!({"lastLineIndent": 15553}), "lastLineIndent 15553: -15552 to 15552 pt"), (json!({"wordSpaceMax": 10.5}), "wordSpaceMax 1050%: word spacing is 0% to 1000%"), (json!({"wordSpaceMin": -0.1}), "wordSpaceMin -10%: word spacing is 0% to 1000%"), (json!({"letterSpaceMin": -1.5}), "letterSpaceMin -150%: letter spacing is -100% to 500%"), @@ -1256,6 +1281,8 @@ mod size_bounds_tests { // The ends of each range apply and read back. for attrs in [ json!({"spaceBefore": 0, "spaceAfter": 15552, "sameParaStyleSpacing": 15552}), + json!({"leftIndent": 0, "rightIndent": 15552, "firstLineIndent": -15552, "lastLineIndent": 15552}), + json!({"leftIndent": 18, "rightIndent": 0, "firstLineIndent": -18, "lastLineIndent": 0}), json!({"wordSpaceMin": 0, "wordSpaceDesired": 0, "wordSpaceMax": 10}), json!({"letterSpaceMin": -1, "letterSpaceDesired": 0, "letterSpaceMax": 5}), json!({"glyphScaleMin": 0.5, "glyphScaleDesired": 1, "glyphScaleMax": 2}), @@ -1341,6 +1368,76 @@ mod size_bounds_tests { ); assert_eq!(s.doc().unwrap().doc.styles.para("Parent").unwrap().para.letter_space_desired, None); } + + /// Applying or redefining a paragraph style could leave a paragraph's own override and the + /// style's values out of order: a Maximum of 10% kept over a style's Desired of 20%. Both are + /// refused and nothing changes; Clear Overrides still applies the style. + #[test] + fn applying_or_redefining_a_style_keeps_justification_in_order() { + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [20, 20, 400, 300], "content": "text", "text": "Hello world\nSecond"})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + let select = |s: &mut Session, anchor: u64, focus: u64| { + s.execute("text.select", &json!({"story": f["story"].clone(), "anchor": anchor, "focus": focus})).unwrap(); + }; + let styles = |s: &Session| s.doc().unwrap().doc.story(sid).unwrap().paras.iter().map(|p| p.style.clone()).collect::>(); + let letter = |s: &mut Session| { + let p = s.execute("type.selectionAttrs", &json!({})).unwrap()["para"].clone(); + [p["letterSpaceMin"].as_f64(), p["letterSpaceDesired"].as_f64(), p["letterSpaceMax"].as_f64()] + }; + s.execute("style.paragraph.create", &json!({"name": "Wide", "para": {"letterSpaceDesired": 0.2, "letterSpaceMax": 0.5}})).unwrap(); + select(&mut s, 0, 18); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.1}})).unwrap(); + let before = styles(&s); + select(&mut s, 0, 18); + let e = s.execute("style.paragraph.apply", &json!({"name": "Wide"})).expect_err("refused").to_string(); + assert!(e.contains("style.paragraph.apply") && e.contains("letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 20%, 10%"), "{e}"); + assert_eq!(styles(&s), before); + select(&mut s, 0, 18); + assert_eq!(letter(&mut s), [Some(0.0), Some(0.0), Some(0.1)]); + // A style that changes no justification row applies over the same override. + s.execute("style.paragraph.create", &json!({"name": "Airy", "para": {"spaceAfter": 6}})).unwrap(); + select(&mut s, 0, 18); + s.execute("style.paragraph.apply", &json!({"name": "Airy"})).unwrap(); + select(&mut s, 0, 18); + s.execute("style.paragraph.apply", &json!({"name": "Wide", "clearOverrides": true})).unwrap(); + assert_eq!(styles(&s), ["Wide", "Wide"]); + select(&mut s, 0, 18); + assert_eq!(letter(&mut s), [Some(0.0), Some(0.2), Some(0.5)]); + + // Redefine Style from a paragraph whose Desired is 30% while the second paragraph keeps a + // Maximum of 25%. + select(&mut s, 12, 18); + s.execute("type.para", &json!({"attrs": {"letterSpaceMax": 0.25}})).unwrap(); + select(&mut s, 0, 5); + s.execute("type.para", &json!({"attrs": {"letterSpaceDesired": 0.3}})).unwrap(); + select(&mut s, 0, 5); + let e = s.execute("style.paragraph.redefine", &json!({})).expect_err("refused").to_string(); + assert!( + e.contains("style.paragraph.redefine") + && e.contains(&format!("a paragraph of story {}: letter spacing needs Minimum ≤ Desired ≤ Maximum, not 0%, 30%, 25%", sid.0)), + "{e}" + ); + assert_eq!(s.doc().unwrap().doc.styles.para("Wide").unwrap().para.letter_space_desired, Some(0.2)); + + // A new style from a selection whose paragraph holds a value no command sets (as an + // import could leave) is refused the same way as a given value. + s.edit(|d, _| { + for pf in &mut d.story_mut(sid).unwrap().paras { + pf.para.left_indent = Some(-30.0); + } + Ok(()) + }) + .unwrap(); + select(&mut s, 0, 5); + let e = s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true})).expect_err("refused").to_string(); + assert!(e.contains("leftIndent -30: 0 to 15552 pt"), "{e}"); + assert!(s.doc().unwrap().doc.styles.para("Captured").is_none()); + select(&mut s, 0, 5); + s.execute("style.paragraph.create", &json!({"name": "Captured", "fromSelection": true, "para": {"leftIndent": 0}})).unwrap(); + assert_eq!(s.doc().unwrap().doc.styles.para("Captured").unwrap().para.left_indent, Some(0.0)); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/object_control.rs b/crates/ui-egui/src/object_control.rs index 55ebd5e31..056ea68cf 100644 --- a/crates/ui-egui/src/object_control.rs +++ b/crates/ui-egui/src/object_control.rs @@ -304,7 +304,7 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut Ui) { group(ui, "columns", (caption_w + 2.0).ceil().max(48.0), |ui, rect| { cell(ui, rect, 0.0, 0, rect.width(), true, |ui| widgets::caption(ui, &caption)); if let Some(v) = cell(ui, rect, 0.0, 1, 48.0, true, |ui| { - NumField::number("ccols", Some(columns as f64), "", 0).width(48.0).spinner().range(1.0, 100.0).show(ui) + NumField::number("ccols", Some(columns as f64), "", 0).width(48.0).spinner().range(1.0, 40.0).show(ui) }) { let _ = app.run("object.textFrameOptions", json!({"columns": v as u64})); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 63da03254..a71731243 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -285,7 +285,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options. - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room, or across all the columns of the frame with Span Footnotes Across Columns; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands. - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named. -- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse Space Before, Space After and same-style spacing outside 0 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit is also checked over the styles based on it and the paragraphs that use them. `object.textFrameOptions` refuses an inset outside 0 to 15552 pt or a list that isn't four sides, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. +- Paragraph spacing and justification values are checked: `type.para`, `style.paragraph.create` and `style.paragraph.edit` refuse left and right indents, Space Before, Space After and same-style spacing outside 0 to 15552 pt, first and last line indents outside -15552 to 15552 pt, word spacing outside 0% to 1000%, letter spacing outside -100% to 500%, glyph scaling outside 50% to 200%, a Minimum above Desired or a Desired above Maximum, Auto Leading outside 0% to 500%, and a Single Word Justification other than left, center, right or fullyJustified. A style edit or redefinition is also checked over the styles based on it and the paragraphs that use them, and `style.paragraph.apply` refuses a style whose values would put a row out of order with a paragraph's own overrides. `object.textFrameOptions` refuses an inset or gutter outside 0 to 15552 pt, an inset list that isn't four sides, a column count outside 1 to 40, an on/off option that isn't true or false, and a vertical justification, first baseline, auto-size or columns kind that isn't one of its names. IDML import reads these values as before. - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands. - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands. - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus. From 9994665436cb10eecfa39928753aecd8daf31875 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:43:13 -0800 Subject: [PATCH 110/328] Pages: an edit no longer renders every page thumbnail again While the Pages panel was shown, every edit made all page thumbnails out of date, and the next frame rendered one for every page of the document on the interface thread, including pages out of view. Each move step, drag step and typed character paid for it. - Only thumbnails of rows in view are rendered. - After an edit, the previous thumbnail stays on screen until the document has been unchanged for 0.4 s. Then one out-of-date thumbnail is rendered again per frame. - Thumbnails of deleted pages and parents are dropped. Part of #1411 --- crates/ui-egui/src/panels/pages.rs | 84 ++++++++++++++++++++---- crates/ui-egui/src/panels/pages/tests.rs | 56 ++++++++++++++-- 2 files changed, 123 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index f46868a35..ff8e2f3c7 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -17,22 +17,85 @@ enum ThumbOf { Parent(SpreadId), } -/// (document uid, revision, page or parent, thumbnail height). -type ThumbKey = (u64, u64, ThumbOf, u32); +/// (document uid, page or parent, thumbnail height). +type ThumbKey = (u64, ThumbOf, u32); -static THUMBS: Mutex>> = Mutex::new(None); +/// The newest thumbnail of each page and parent, with the document revision it shows. +static THUMBS: Mutex>> = Mutex::new(None); /// Widest parent thumbnail, in pixels (a spread of many pages stays a small texture). const MAX_THUMB_W: f64 = 1024.0; +/// Seconds the document stays unchanged before thumbnails of an older revision are drawn again. +const THUMB_QUIET_SECS: f64 = 0.4; + +/// Thumbnails of an older revision drawn again in one frame. +const THUMB_REFRESHES_PER_FRAME: usize = 1; + +/// When the active document's revision last changed, and how many thumbnails were drawn again in +/// the current frame. +#[derive(Clone, Copy, Debug, Default)] +struct ThumbClock { + doc: (u64, u64), + changed_at: f64, + frame: u64, + refreshed: usize, +} + +#[cfg(test)] +thread_local! { + /// Thumbnails rendered on this thread. + static THUMB_RENDERS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The thumbnail of `of`, `h` points high. A thumbnail of an older revision stays on screen until +/// the document has been unchanged for [`THUMB_QUIET_SECS`]; after that, at most +/// [`THUMB_REFRESHES_PER_FRAME`] of them are drawn again per frame. fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Option { let st = app.session.active()?; - let key = (st.uid, st.revision, of, h.round() as u32); + let key = (st.uid, of, h.round() as u32); + let clock_id = egui::Id::unique("pages_thumb_clock"); + let (now, frame) = (ctx.input(|i| i.time), ctx.cumulative_frame_nr()); + let mut clock = ctx.data(|d| d.get_temp::(clock_id)).unwrap_or_default(); + let changed = clock.doc != (st.uid, st.revision); + if changed { + clock = ThumbClock { doc: (st.uid, st.revision), changed_at: now, frame, refreshed: 0 }; + } + if clock.frame != frame { + clock.frame = frame; + clock.refreshed = 0; + } + if now < clock.changed_at { + clock.changed_at = now; + } let mut g = THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let map = g.get_or_insert_with(HashMap::new); - if let Some(t) = map.get(&key) { - return Some(t.clone()); + if changed { + // Drop the thumbnails of pages and parents the document no longer has. + let pages = st.doc.page_count(); + map.retain(|k, _| { + k.0 != st.uid + || match k.1 { + ThumbOf::Page(abs) => abs < pages, + ThumbOf::Parent(id) => st.doc.parent_index(id).is_some(), + } + }); } + if let Some((rev, t)) = map.get(&key) { + if *rev == st.revision { + return Some(t.clone()); + } + let wait = THUMB_QUIET_SECS - (now - clock.changed_at); + if wait > 0.0 || clock.refreshed >= THUMB_REFRESHES_PER_FRAME { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait.max(0.0))); + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); + return Some(t.clone()); + } + clock.refreshed += 1; + } + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); + #[cfg(test)] + THUMB_RENDERS.with(|n| n.set(n.get() + 1)); let px = h as f64 * ctx.pixels_per_point() as f64; let mut r = designcraft_render::Renderer::new(); r.threads = 0; @@ -59,10 +122,7 @@ fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Optio }; let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); let tex = crate::widgets::load_texture(ctx, format!("{name}_{}", h.round()), ci, egui::TextureOptions::LINEAR); - // Drop thumbnails of older revisions. - let (uid, rev) = (st.uid, st.revision); - map.retain(|k, _| !(k.0 == uid && k.1 != rev)); - map.insert(key, tex.clone()); + map.insert(key, (st.revision, tex.clone())); Some(tex) } @@ -268,7 +328,7 @@ impl ParentRow { /// `thumbnails`), or blank pages for [None] and when the spread can't be rendered. fn parent_icon(app: &mut DesignApp, ui: &egui::Ui, right: egui::Pos2, row: &ParentRow, h: f32, thumbnails: bool, t: &Tokens) { let area = egui::Rect::from_min_size(egui::pos2(right.x - row.unit_w * h, right.y - h / 2.0), vec2(row.unit_w * h, h)); - let tex = if thumbnails { row.parent.and_then(|(_, id)| thumb(app, ui.ctx(), ThumbOf::Parent(id), h)) } else { None }; + let tex = if thumbnails && ui.is_rect_visible(area) { row.parent.and_then(|(_, id)| thumb(app, ui.ctx(), ThumbOf::Parent(id), h)) } else { None }; let p = ui.painter(); match tex { Some(tex) => { @@ -488,7 +548,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { egui::WidgetInfo::selected(egui::Role::Button, true, selected, format!("Page {}", app.session.page_label(abs))) }); let tint = if selected { SELECTED_TINT } else { Color32::WHITE }; - match thumbnails.then(|| thumb(app, ui.ctx(), ThumbOf::Page(abs), th)).flatten() { + match (thumbnails && ui.is_rect_visible(pr)).then(|| thumb(app, ui.ctx(), ThumbOf::Page(abs), th)).flatten() { Some(tex) => { ui.painter().image(tex.id(), pr, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint); } diff --git a/crates/ui-egui/src/panels/pages/tests.rs b/crates/ui-egui/src/panels/pages/tests.rs index 7e97a262d..62644227f 100644 --- a/crates/ui-egui/src/panels/pages/tests.rs +++ b/crates/ui-egui/src/panels/pages/tests.rs @@ -61,11 +61,11 @@ fn double_clicking_a_parent_shows_that_parent() { for name in names { assert_eq!(h.get_by_label(name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True), name == "C-Parent", "{name}"); } - // Parent rows show a rendered thumbnail. + // Parent rows show a rendered thumbnail (of the revision before the double click until the + // document has been unchanged for THUMB_QUIET_SECS). let id = st.doc.parents[2].id; - let rev = (st.uid, st.revision); - let thumbs = super::THUMBS.lock().unwrap(); - assert!(thumbs.as_ref().unwrap().keys().any(|k| (k.0, k.1) == rev && k.2 == super::ThumbOf::Parent(id))); + let thumbs = super::THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(thumbs.as_ref().unwrap().keys().any(|k| k.0 == st.uid && k.1 == super::ThumbOf::Parent(id))); } fn harness(app: DesignApp) -> Harness<'static, DesignApp> { @@ -321,12 +321,58 @@ fn parent_thumbnails_follow_panel_options() { let id = st.doc.parents[0].id; let thumbs = super::THUMBS.lock().unwrap(); let keys = thumbs.as_ref().map(|m| m.keys().copied().collect::>()).unwrap_or_default(); - keys.into_iter().filter(|k| k.0 == st.uid && k.2 == super::ThumbOf::Parent(id)).map(|k| k.3).collect::>() + keys.into_iter().filter(|k| k.0 == st.uid && k.1 == super::ThumbOf::Parent(id)).map(|k| k.2).collect::>() }; assert_eq!(parent_thumb_heights(true), vec![IconSize::Large.row_h() as u32 - 5]); assert_eq!(parent_thumb_heights(false), Vec::::new()); } +/// Page thumbnails are rendered only for rows in view. After an edit the previous thumbnails stay +/// until the document has been unchanged for `THUMB_QUIET_SECS`, and then one is drawn again per +/// frame. Thumbnails of deleted pages are dropped. +#[test] +fn an_edit_redraws_only_thumbnails_in_view_one_per_frame() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 60, "facingPages": false})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp, time: f64| { + let before = THUMB_RENDERS.with(std::cell::Cell::get); + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 520.0))), + time: Some(time), + ..Default::default() + }; + ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear(); + THUMB_RENDERS.with(std::cell::Cell::get) - before + }; + let shown: usize = (0..3).map(|_| frame(&mut app, 0.0)).sum(); + assert!(shown > 0 && shown < 60, "only the rows in view are rendered: {shown}"); + assert_eq!(frame(&mut app, 0.0), 0, "an unchanged document renders nothing"); + + app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap(); + assert_eq!(frame(&mut app, 1.0), 0, "the edit's frame keeps the previous thumbnails"); + assert_eq!(frame(&mut app, 1.0 + THUMB_QUIET_SECS / 2.0), 0, "still editing"); + let quiet = 1.0 + THUMB_QUIET_SECS + 0.01; + let mut redrawn = 0; + for _ in 0..shown { + let n = frame(&mut app, quiet); + assert_eq!(n, THUMB_REFRESHES_PER_FRAME, "one thumbnail per frame"); + redrawn += n; + } + assert_eq!(redrawn, shown); + assert_eq!(frame(&mut app, quiet), 0, "every thumbnail in view is current"); + + // Deleted pages lose their thumbnails. + let uid = app.session.active().unwrap().uid; + let cached = |abs: usize| { + THUMBS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref().unwrap().keys().any(|k| k.0 == uid && k.1 == ThumbOf::Page(abs)) + }; + assert!(cached(2)); + app.run("layout.pages.delete", json!({"pages": (2..60).collect::>()})).unwrap(); + frame(&mut app, quiet + 1.0); + assert!((2..60).all(|abs| !cached(abs)), "no thumbnail of a deleted page is kept"); +} + #[test] fn parents_are_added_duplicated_and_renamed_from_the_panel() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 81f0d766cfb54df1a61b11d07e7494cf19133949 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 02:47:57 +0000 Subject: [PATCH 111/328] Apply review fixes - crates/images/src/resolution.rs - crates/render/src/decode.rs --- crates/images/src/resolution.rs | 8 +++----- crates/render/src/decode.rs | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index dabaf1c61..ea0a55eaa 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -178,7 +178,7 @@ pub fn tiff_resolution(tiff: &[u8]) -> Option<(f64, f64)> { /// The pHYs chunk: pixels-per-unit in x and y plus the unit (1 = meter → dpi). fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let mut pos = 8; - for _ in 0..64 { + loop { let len = u32::from_be_bytes(bytes.get(pos..pos + 4)?.try_into().ok()?) as usize; let kind = bytes.get(pos + 4..pos + 8)?; if kind == b"pHYs" { @@ -189,7 +189,7 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { } return None; } - if kind == b"IEND" { + if kind == b"IEND" || kind == b"IDAT" { return None; } pos = pos.checked_add(8)?.checked_add(len)?.checked_add(4)?; @@ -197,7 +197,6 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { return None; } } - None } // ---------- WebP ---------- @@ -207,7 +206,7 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; let end = 12usize.checked_add(riff)?.min(bytes.len()); let mut pos = 12; - for _ in 0..64 { + loop { let kind = bytes.get(pos..pos + 4)?; let size = u32::from_le_bytes(bytes.get(pos + 4..pos + 8)?.try_into().ok()?) as usize; let data = pos.checked_add(8)?; @@ -223,7 +222,6 @@ fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { } pos = data.checked_add(size.checked_add(size & 1)?)?; } - None } // ---------- BMP ---------- diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index df8e1f047..5047ca169 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -88,7 +88,7 @@ pub fn image_size(bytes: &[u8]) -> Option<(u32, u32)> { /// Natural size of a placed graphic, unrounded: a PDF page (crop box) and an SVG in points, a raster /// at its stored resolution (72 ppi without one), an EPS its bounding box independently of preview pixels. Placed graphics are drawn at -/// this size; `image_size` rounds it to whole pixels for display. +/// this size; `image_size` gives a raster's pixel size and rounds a PDF page or SVG to whole points. pub fn natural_size(bytes: &[u8], page: usize) -> Option<(f64, f64)> { if is_pdf(bytes) { return pdf_page_size(bytes, page).map(|(w, h)| (w.max(1e-3), h.max(1e-3))); From 099b89f53d40841bf79c4a6e2f24454e5e902ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:27:07 -0800 Subject: [PATCH 112/328] Preflight: check the document on a background worker, not on every edit The status bar's error count ran the whole-document preflight check on the interface thread for every new state of the document, so every drag step and every typed character waited for it. The Preflight panel ran the same check on every frame. The check composes every story and asks the file system about every linked graphic, so its cost grows with the document: on a 300-page document with 900 placed images it took 137 ms on a fast machine, and moving or resizing a frame and typing became unusable on large documents. The check now runs on a worker thread that takes the newest state of the document; the issues last found stay shown until it answers. An unchanged document is checked again every few seconds for linked files changed outside the app, a save under a new path or a font reload is checked again, and a check blocked on another document's linked file is handed off to a fresh worker after 200 ms. Tests and the web build check on the interface thread, once per state of the document. preflight::check_document takes the document, the composition cache and the save path, so the worker needs no session. --- ROADMAP.md | 1 + crates/engine/src/cmd/preflight.rs | 25 +- .../src/cmd/preflight/white_overprint.rs | 10 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/chrome/status_bar.rs | 2 +- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/panels.rs | 18 +- crates/ui-egui/src/panels/properties/links.rs | 4 +- crates/ui-egui/src/preflight_worker.rs | 389 ++++++++++++++++++ crates/ui-egui/src/preflight_worker/tests.rs | 259 ++++++++++++ 10 files changed, 678 insertions(+), 34 deletions(-) create mode 100644 crates/ui-egui/src/preflight_worker.rs create mode 100644 crates/ui-egui/src/preflight_worker/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..4722bb5ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index 6fada503d..ff6512ad6 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -2,7 +2,7 @@ //! fonts and glyphs, missing or low-resolution graphics, RGB content in print documents, empty //! text frames, white or [Paper] set to overprint. -use designcraft_compose::ComposedStory; +use designcraft_compose::{Cache, ComposedStory}; use designcraft_doc::{Content, Document, Intent, Item, SpreadRef}; use designcraft_fonts::FaceRef; use designcraft_geom::Affine; @@ -99,8 +99,7 @@ fn missing_glyphs( /// its centre is on, and every page it reaches (see [`pages_of`]). type Located = (designcraft_doc::ItemId, Option, Vec); -fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option { - let d = &s.active()?.doc; +fn overset_location(d: &Document, cache: &Cache, target: designcraft_doc::ItemId) -> Option { let at = |id: designcraft_doc::ItemId, loc: &designcraft_doc::ItemLoc| { let it = d.item(id); let xf = d.parent_xf(loc); @@ -131,7 +130,7 @@ fn overset_location(s: &Session, target: designcraft_doc::ItemId) -> Option) -> Vec { out.push(format!("a story with no text frame: {n} character(s) of it are not in the export")); continue; } - let location = last.and_then(|f| overset_location(s, f)); + let location = last.and_then(|f| overset_location(d, &s.cache, f)); let centre = location.as_ref().and_then(|(_, page, _)| *page); let touched: &[usize] = location.as_ref().map(|(_, _, ps)| ps.as_slice()).unwrap_or_default(); // A sheet draws its spread's items without asking which page they are on, so a frame @@ -263,8 +262,12 @@ pub fn overset_warnings(s: &Session, pages: Option<&[usize]>) -> Vec { pub fn check(s: &Session, min_ppi: f64) -> Vec { let Some(st) = s.active() else { return vec![] }; - let d = &st.doc; - let document = st.path.as_deref().map(std::path::Path::new); + check_document(&st.doc, &s.cache, st.path.as_deref().map(std::path::Path::new), min_ppi) +} + +/// [`check`] of document `d` saved at `document` (relative links resolve against it), with the +/// compositions in `cache`. It needs no session, so it can run on another thread. +pub fn check_document(d: &Document, cache: &Cache, document: Option<&std::path::Path>, min_ppi: f64) -> Vec { let mut out = Vec::new(); // Stories: overset and fonts. let mut missing_fonts: Vec = Vec::new(); @@ -274,11 +277,11 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { // a cell's or an unplaced story, which has no frame of its own). let mut white_text: std::collections::BTreeMap, Vec<&'static str>> = std::collections::BTreeMap::new(); for story in d.stories.values() { - let cs = s.cache.get(d, story.id, None); + let cs = cache.get(d, story.id, None); missing_glyphs(&cs, None, 0, &mut missing); if cs.is_overset() { let last = story.frames.last().copied(); - let location = last.and_then(|f| overset_location(s, f)); + let location = last.and_then(|f| overset_location(d, cache, f)); let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count(); let unplaced = story.frames.is_empty(); out.push(Issue { @@ -336,7 +339,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { let props = d.styles.resolve_char(&base, f); let white = white_overprint::adornments(d, &props); if !white.is_empty() { - let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(s, d, story)); + let shown = shown.get_or_insert_with(|| white_overprint::frame_ranges(cache, d, story)); for frame in white_overprint::frames_showing(story, shown, run.start.max(range.start)..run.end.min(range.end)) { let parts = white_text.entry(frame).or_default(); for part in &white { @@ -386,7 +389,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec { for message in unsupported_typography { out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None }); } - let (white_items, printed_frames) = white_overprint::printed(s, d); + let (white_items, printed_frames) = white_overprint::printed(cache, d); for (item, parts) in white_text { // A frame PDF export leaves out (hidden, nonprinting, on a hidden or nonprintable layer, // on a parent page no page shows) prints none of its text. diff --git a/crates/engine/src/cmd/preflight/white_overprint.rs b/crates/engine/src/cmd/preflight/white_overprint.rs index 5df0d1fa2..7d9e8098a 100644 --- a/crates/engine/src/cmd/preflight/white_overprint.rs +++ b/crates/engine/src/cmd/preflight/white_overprint.rs @@ -12,13 +12,13 @@ use std::ops::Range; use std::sync::Arc; use designcraft_color::{Color, ColorType, SwatchValue, swatch}; +use designcraft_compose::Cache; use designcraft_doc::cjk_settings::AdornmentOverprint; use designcraft_doc::{AnchoredObject, CharProps, Content, Document, Item, ItemId, SpreadRef, Story, StrokeType}; use designcraft_geom::Affine; use designcraft_pdf::{drawn_children, item_exported, layer_exported, shown_parent_items}; use super::{Issue, page_of}; -use crate::Session; /// The issue's `kind`. pub(super) const KIND: &str = "whiteOverprint"; @@ -100,7 +100,7 @@ enum On { /// that show them, and anchored objects in the frames that place them. Returns the white /// overprint issues of those items, and the page each text frame among them is first drawn on /// (the frames whose ruby and kenten print). -pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap>) { +pub(super) fn printed(cache: &Cache, d: &Document) -> (Vec, BTreeMap>) { let mut issues = Vec::new(); let mut frames = BTreeMap::new(); // A parent page's item shows on every page based on it: it is reported once, on the first. @@ -129,7 +129,7 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap = drawn_children(it).map(|c| (Node::Item(c.clone()), inside, composed)).collect(); if let Content::Text(tf) = &it.content { frames.entry(it.id).or_insert(page); - let cs = s.cache.get(d, tf.story, composed); + let cs = cache.get(d, tf.story, composed); // The frame's anchored objects, and those in its footnotes and table cells. let mut pending: Vec<_> = cs.frame(it.id).into_iter().collect(); while let Some(frame) = pending.pop() { @@ -146,11 +146,11 @@ pub(super) fn printed(s: &Session, d: &Document) -> (Vec, BTreeMap Vec<(ItemId, Range)> { +pub(super) fn frame_ranges(cache: &Cache, d: &Document, story: &Story) -> Vec<(ItemId, Range)> { if story.frames.is_empty() { return Vec::new(); } - s.cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect() + cache.get(d, story.id, None).frames.iter().map(|f| (f.frame, f.range.clone())).collect() } /// The frames of `story` that show the bytes `run` (`shown`: [`frame_ranges`]). `None` stands diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 88bd48c58..d848aa4ae 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -55,6 +55,7 @@ impl DesignApp { canvas: CanvasCache::new(), #[cfg(not(target_arch = "wasm32"))] links_worker: crate::links_worker::State::default(), + preflight: crate::preflight_worker::State::default(), canvas_rect: None, split: false, second_window: false, diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 5fde929be..c602b1721 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -164,7 +164,7 @@ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "[Basic] (working) ▾")).font(small.clone())); ui.add_space(8.0); // Preflight: overset text is an error. - let errors = panels::preflight_errors(app); + let errors = panels::preflight_errors(app, ui.ctx()); let (r, dot) = ui.allocate_exact_size(vec2(9.0, 9.0), Sense::click()); ui.painter().circle_filled( r.center(), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 40bdfbcb3..77aa507f7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -38,6 +38,7 @@ pub mod package_dialog; mod page_history; mod panel_docking; pub mod panels; +mod preflight_worker; mod prefs; pub mod render_worker; mod rtl; @@ -158,6 +159,8 @@ pub struct DesignApp { /// operating-system timeout. #[cfg(not(target_arch = "wasm32"))] pub(crate) links_worker: links_worker::State, + /// Live preflight: the issues last found for the active document. + pub(crate) preflight: preflight_worker::State, pub canvas_rect: Option, /// Window › Arrange › Split Window: two views of the document side by side. pub split: bool, diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2efdd9ec7..45606f4cd 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -299,21 +299,9 @@ pub fn text_attrs(app: &mut DesignApp) -> Option { if v.is_null() { None } else { Some(serde_json::to_value(v).ok()?) } } -/// Count preflight errors: overset stories (more checks land with the Preflight panel). -pub fn preflight_errors(app: &DesignApp) -> usize { - // Memoized per document snapshot (the status bar asks every frame). - static MEMO: std::sync::Mutex> = std::sync::Mutex::new(None); - let Some(st) = app.session.active() else { return 0 }; - let key = std::sync::Arc::as_ptr(&st.doc) as usize; - let mut g = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some((k, n)) = *g - && k == key - { - return n; - } - let n = designcraft_engine::cmd::preflight::check(&app.session, 150.0).iter().filter(|i| i.severity == "error").count(); - *g = Some((key, n)); - n +/// Count the preflight errors last found for the active document (0 until its first check ends). +pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> usize { + crate::preflight_worker::issues(app, ctx).map_or(0, |issues| issues.iter().filter(|i| i.severity == "error").count()) } /// Height of one swatch-menu row. diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 5ee02ea79..7a1a6f0d0 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -300,7 +300,7 @@ pub fn info_panel(app: &mut DesignApp, ui: &mut egui::Ui) { pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let issues = designcraft_engine::cmd::preflight::check(&app.session, 150.0); + let issues = crate::preflight_worker::issues(app, ui.ctx()).unwrap_or_default(); let errors = issues.iter().filter(|i| i.severity == "error").count(); ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); @@ -323,7 +323,7 @@ pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { ); }); divider(ui); - for i in issues { + for i in issues.iter() { let page = i.page.filter(|_| app.session.active().is_some()).map(|p| app.session.page_label(p)); let text = format!("{} {}", if i.severity == "error" { "⛔" } else { "⚠" }, i.message); let resp = ui.add(egui::Button::new(egui::RichText::new(text).size(11.0)).frame(false)); diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs new file mode 100644 index 000000000..6abb67e0c --- /dev/null +++ b/crates/ui-egui/src/preflight_worker.rs @@ -0,0 +1,389 @@ +//! Live preflight for the status bar and the Preflight panel. +//! +//! A check reads every story's composition and every placed graphic's linked file, so on a long +//! document it takes much longer than a frame. On native builds it runs on a worker thread, which +//! checks the newest state of the document it was given; the issues last found for the document +//! stay shown until the check of its current state ends. The worker checks an unchanged document +//! again from time to time, for linked files changed outside the app. The web build and tests +//! check on the interface thread, once per state of the document. + +use std::sync::{Arc, Weak}; +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +use designcraft_compose::Cache; +use designcraft_doc::Document; +use designcraft_engine::cmd::preflight::{Issue, check_document}; + +use crate::DesignApp; + +/// Lowest effective resolution, in pixels per inch, before a placed image is reported. +pub(crate) const MIN_PPI: f64 = 150.0; + +/// Documents whose issues are kept: going back to one shows its issues at once. +const MAX_DOCUMENTS: usize = 8; + +// An unchanged document is checked again after as long as its last check took, at least this +// long and at most `REFRESH_MAX`, so the worker is idle at least half the time. +#[cfg(not(target_arch = "wasm32"))] +const REFRESH_MIN: Duration = Duration::from_secs(2); +#[cfg(not(target_arch = "wasm32"))] +const REFRESH_MAX: Duration = Duration::from_secs(5 * 60); +// A check of another document still running this long after it was queued is blocked (a linked +// file on a share that doesn't answer): the active document gets a fresh worker. +#[cfg(not(target_arch = "wasm32"))] +const SUPERSEDE_AFTER: Duration = Duration::from_millis(200); +// Workers alive at once, counting replaced ones still blocked. +#[cfg(not(target_arch = "wasm32"))] +const MAX_WORKERS: usize = 4; +// A worker that couldn't be started, or that ended (a panic in a check), is tried again after +// this long. +#[cfg(not(target_arch = "wasm32"))] +const RETRY_AFTER: Duration = Duration::from_secs(30); + +/// A state of a document as a check sees it: which document, which state of it with which +/// compositions (a font reload replaces the cache and bumps the revision), and where it is saved +/// (relative links resolve against that). The state isn't kept alive: once it is dropped, no +/// later state can pass for it. +#[derive(Clone, Default)] +struct Checked { + uid: u64, + revision: u64, + doc: Weak, + cache: Weak, + path: Option, +} + +impl Checked { + fn new(app: &DesignApp) -> Option<(Self, Arc)> { + let st = app.session.active()?; + let of = Checked { + uid: st.uid, + revision: st.revision, + doc: Arc::downgrade(&st.doc), + cache: Arc::downgrade(&app.session.cache), + path: st.path.clone(), + }; + Some((of, Arc::clone(&st.doc))) + } + + fn same(&self, other: &Checked) -> bool { + self.uid == other.uid + && self.revision == other.revision + && self.path == other.path + && Weak::ptr_eq(&self.cache, &other.cache) + && self.doc.upgrade().zip(other.doc.upgrade()).is_some_and(|(a, b)| Arc::ptr_eq(&a, &b)) + } +} + +/// The issues found for one state of a document. +struct Found { + of: Checked, + issues: Arc>, + /// How long the check took. + #[cfg(not(target_arch = "wasm32"))] + took: Duration, + /// When the interface last asked for this state (`egui` input time, seconds). + #[cfg(not(target_arch = "wasm32"))] + asked_at: f64, +} + +#[derive(Default)] +pub(crate) struct State { + /// The issues last found for each of the documents checked last, oldest first. + found: Vec, + #[cfg(not(target_arch = "wasm32"))] + worker: Worker, + /// Checks run on the interface thread. + #[cfg(test)] + pub(crate) inline_checks: usize, +} + +impl State { + /// Keeps `found` in place of the issues found before for its document. + fn keep(&mut self, found: Found) { + self.found.retain(|f| f.of.uid != found.of.uid); + if self.found.len() >= MAX_DOCUMENTS { + self.found.remove(0); + } + self.found.push(found); + } +} + +/// The issues of the active document: those last found, which may be of an earlier state of it +/// while the worker checks the current one. `None` until the first check of the document ends. +pub(crate) fn issues(app: &mut DesignApp, ctx: &egui::Context) -> Option>> { + let now = ctx.input(|i| i.time); + issues_at(app, ctx, now) +} + +fn issues_at(app: &mut DesignApp, ctx: &egui::Context, now: f64) -> Option>> { + let (of, doc) = Checked::new(app)?; + let cache = Arc::clone(&app.session.cache); + let state = &mut app.preflight; + #[cfg(not(target_arch = "wasm32"))] + for mut done in state.worker.poll() { + done.asked_at = now; + state.keep(done); + } + if let Some(i) = state.found.iter().position(|f| f.of.same(&of)) { + // The active document's issues are the last to be dropped. + let shown = state.found.remove(i); + state.found.push(shown); + } + if let Some(found) = state.found.last_mut().filter(|f| f.of.same(&of)) { + let issues = Arc::clone(&found.issues); + #[cfg(not(target_arch = "wasm32"))] + if let Some(wait) = state.worker.retry_wait() { + if wait.is_zero() { + found.asked_at = now; + state.worker.ask(ctx, of, doc, &cache, true); + } else { + // Come back when a new worker may be tried. + ctx.request_repaint_after(wait); + } + } else if state.worker.enabled() { + let wait = refresh_after(found.took).as_secs_f64() - (now - found.asked_at); + if wait > 0.0 { + // Come back when the issues are due to be checked again, in case nothing else + // wakes the interface. + ctx.request_repaint_after(Duration::from_secs_f64(wait)); + } else { + found.asked_at = now; + state.worker.ask(ctx, of, doc, &cache, true); + } + } + return Some(issues); + } + #[cfg(not(target_arch = "wasm32"))] + if state.worker.ask(ctx, of.clone(), Arc::clone(&doc), &cache, false) { + return state.found.iter().find(|f| f.of.uid == of.uid).map(|f| Arc::clone(&f.issues)); + } + let _ = (ctx, now); + let issues = Arc::new(check_document(&doc, &cache, of.path.as_deref().map(std::path::Path::new), MIN_PPI)); + #[cfg(test)] + { + state.inline_checks += 1; + } + state.keep(Found { + of, + issues: Arc::clone(&issues), + #[cfg(not(target_arch = "wasm32"))] + took: Duration::ZERO, + #[cfg(not(target_arch = "wasm32"))] + asked_at: now, + }); + Some(issues) +} + +/// How long a check that took `took` stays current. +#[cfg(not(target_arch = "wasm32"))] +fn refresh_after(took: Duration) -> Duration { + took.clamp(REFRESH_MIN, REFRESH_MAX) +} + +#[cfg(not(target_arch = "wasm32"))] +struct Job { + of: Checked, + doc: Arc, + cache: Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +type Channels = (std::sync::mpsc::SyncSender, std::sync::mpsc::Receiver); + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Worker { + channels: Option, + /// The state last asked for. + asked: Checked, + /// The job for that state while the worker's queue is full. A newer state replaces it, so at + /// most one job waits here, one in the queue and one is being checked. + waiting: Option, + /// The jobs queued whose results haven't arrived, oldest (the one being checked) first, each + /// with when it was queued. The worker answers each job in order, so there are at most two. + in_flight: std::collections::VecDeque<(Checked, Instant)>, + /// Worker threads alive, counting replaced ones still blocked. + live: Arc, + /// When the worker could not be started, or ended (a panic in a check). Checks run on the + /// interface thread until a new worker is tried, [`RETRY_AFTER`] later. + failed: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Worker { + /// Whether a worker runs or may be started. + fn enabled(&self) -> bool { + self.channels.is_some() || (background() && self.retry_due()) + } + + fn retry_due(&self) -> bool { + self.failed.is_none_or(|at| at.elapsed() >= RETRY_AFTER) + } + + /// How long until a new worker may be tried after one failed; `None` while one runs or when + /// none failed. + fn retry_wait(&self) -> Option { + if self.channels.is_some() { + return None; + } + self.failed.map(|at| RETRY_AFTER.saturating_sub(at.elapsed())) + } + + fn fail(&mut self) { + self.channels = None; + self.asked = Checked::default(); + self.waiting = None; + self.in_flight.clear(); + self.failed = Some(Instant::now()); + } + + /// Asks the worker for state `of` unless it was the last state asked for (`again` asks for it + /// anyway). False when there is no worker, so the caller checks on its own thread. + fn ask(&mut self, ctx: &egui::Context, of: Checked, doc: Arc, cache: &Arc, again: bool) -> bool { + if self.channels.is_none() { + if !background() || !self.retry_due() { + return false; + } + self.failed = None; + self.channels = spawn(ctx.clone(), &self.live); + if self.channels.is_none() { + self.fail(); + return false; + } + } + self.supersede_blocked(ctx, &of); + // A state already queued or being checked isn't asked for again. + let pending = self.in_flight.iter().any(|(job, _)| job.same(&of)) || self.waiting.as_ref().is_some_and(|job| job.of.same(&of)); + if (again && !pending) || !self.asked.same(&of) { + self.asked = of.clone(); + self.waiting = Some(Job { of, doc, cache: Arc::clone(cache) }); + } + self.send_waiting(); + self.channels.is_some() + } + + /// Replaces the worker when it is still on a job for another document queued more than + /// [`SUPERSEDE_AFTER`] ago, unless [`MAX_WORKERS`] are alive. The replaced thread ends when + /// its check returns; a job queued behind it is asked of the new worker. + fn supersede_blocked(&mut self, ctx: &egui::Context, of: &Checked) { + let Some(running) = self.in_flight.front().filter(|(job, _)| job.uid != of.uid).map(|(_, at)| at.elapsed()) else { return }; + if running < SUPERSEDE_AFTER { + // Come back when it has run that long, in case nothing else wakes the interface. + ctx.request_repaint_after(SUPERSEDE_AFTER - running); + return; + } + if self.live.load(std::sync::atomic::Ordering::Relaxed) >= MAX_WORKERS { + return; + } + if let Some(channels) = spawn(ctx.clone(), &self.live) { + self.channels = Some(channels); + self.in_flight.clear(); + self.asked = Checked::default(); + } + } + + /// Queues the waiting job if the worker's queue has room. + fn send_waiting(&mut self) { + let (Some(job), Some((tx, _))) = (self.waiting.take(), self.channels.as_ref()) else { return }; + let of = job.of.clone(); + match tx.try_send(job) { + Ok(()) => self.in_flight.push_back((of, Instant::now())), + Err(std::sync::mpsc::TrySendError::Full(job)) => self.waiting = Some(job), + Err(std::sync::mpsc::TrySendError::Disconnected(_)) => self.fail(), + } + } + + /// The results the worker sent since the last poll, oldest first. + fn poll(&mut self) -> Vec { + let Some((_, rx)) = self.channels.as_ref() else { return Vec::new() }; + let mut latest = Vec::new(); + loop { + match rx.try_recv() { + Ok(found) => { + self.in_flight.pop_front(); + latest.push(found); + } + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.fail(); + break; + } + } + } + // The worker took a job and has room for the next. + self.send_waiting(); + latest + } + + /// Waits for the worker's next result. + #[cfg(test)] + fn wait(&mut self) -> Option { + let found = self.channels.as_ref()?.1.recv().ok()?; + self.in_flight.pop_front(); + self.send_waiting(); + Some(found) + } +} + +/// Whether checks run on the worker: not in tests (they can start one with [`start_worker`]) and +/// not with `DESIGNCRAFT_SYNC_RENDER` set. +#[cfg(not(target_arch = "wasm32"))] +fn background() -> bool { + !cfg!(test) && std::env::var_os("DESIGNCRAFT_SYNC_RENDER").is_none() +} + +/// Counts a worker thread as alive until it ends, however it ends. +#[cfg(not(target_arch = "wasm32"))] +struct Alive(Arc); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Alive { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn(ctx: egui::Context, live: &Arc) -> Option { + let (tx, jobs) = std::sync::mpsc::sync_channel::(1); + let (done_tx, rx) = std::sync::mpsc::channel::(); + live.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let alive = Alive(Arc::clone(live)); + std::thread::Builder::new() + .name("designcraft-preflight".into()) + .spawn(move || { + let _alive = alive; + while let Ok(job) = jobs.recv() { + let started = Instant::now(); + let issues = check_document(&job.doc, &job.cache, job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); + let found = Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 }; + // The checked state isn't kept alive by its check once the result is sent. + drop(job.doc); + if done_tx.send(found).is_err() { + break; + } + ctx.request_repaint(); + } + }) + .ok()?; + Some((tx, rx)) +} + +/// Starts the worker in a test, where checks otherwise run on the interface thread. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { + app.preflight.worker.channels = spawn(ctx.clone(), &app.preflight.worker.live); +} + +/// Waits in a test for the worker's next result and keeps it, as a frame that polls would. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_worker(app: &mut DesignApp) { + if let Some(found) = app.preflight.worker.wait() { + app.preflight.keep(found); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs new file mode 100644 index 000000000..f437a4174 --- /dev/null +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -0,0 +1,259 @@ +use std::sync::Arc; + +use egui::vec2; +use serde_json::json; + +use super::Checked; +use crate::test_window; + +/// A document whose one text frame is too small for its text (one preflight error), with the +/// frame's id. +fn overset_app() -> (crate::DesignApp, u64) { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + let text = "Words that do not fit the frame. ".repeat(40); + let r = app.run("frame.create", json!({"rect": [72, 72, 200, 100], "content": "text", "text": text})).unwrap(); + app.run("edit.deselectAll", json!({})).unwrap(); + (app, r["id"].as_u64().unwrap()) +} + +/// The active document's current state. +fn current(app: &crate::DesignApp) -> Checked { + Checked::new(app).unwrap().0 +} + +/// The errors in the issues last found for the active document, and whether they are of its +/// current state. +fn found(app: &crate::DesignApp) -> Option<(usize, bool)> { + let now = current(app); + let f = app.preflight.found.iter().find(|f| f.of.uid == now.uid)?; + Some((f.issues.iter().filter(|i| i.severity == "error").count(), f.of.same(&now))) +} + +/// A worker whose thread never takes a job: the test reads the queue. +fn stalled_worker(app: &mut crate::DesignApp) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { + let (tx, jobs) = std::sync::mpsc::sync_channel(1); + let (done, rx) = std::sync::mpsc::channel(); + app.preflight.worker.channels = Some((tx, rx)); + (jobs, done) +} + +/// Frames with the status bar and the Preflight panel showing check each state of the document +/// once, however many frames draw it. +#[test] +fn each_document_state_is_checked_once() { + let (mut app, id) = overset_app(); + app.ui.dock_tab = "properties".into(); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + h.state_mut().app.run("window.panel", json!({"panel": "preflight"})).unwrap(); + h.run_steps(20); + assert_eq!(h.state().app.preflight.inline_checks, 1); + assert_eq!(found(&h.state().app), Some((1, true))); + for k in 0..5 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + h.state_mut().app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + h.run_steps(10); + } + assert_eq!(h.state().app.preflight.inline_checks, 6, "one check per edit"); + assert_eq!(found(&h.state().app), Some((1, true))); +} + +/// Saving under a new path changes where relative links resolve, and a font reload replaces the +/// compositions and bumps the revision: either way the document is checked again. +#[test] +fn a_new_save_path_or_font_reload_is_checked_again() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + assert!(super::issues(&mut app, &ctx).is_some()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 1); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("a.designcraft").to_string_lossy()})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 2, "saved under a path"); + app.session.cache = Arc::new(designcraft_compose::Cache::new()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 3, "new compositions"); + if let Some(st) = app.session.active_mut() { + st.bump_revision(); + } + assert!(super::issues(&mut app, &ctx).is_some()); + assert_eq!(app.preflight.inline_checks, 4, "a new revision"); + assert_eq!(found(&app), Some((1, true))); +} + +/// States asked for while the worker is busy don't queue up: one job waits in the worker's queue +/// and one beside it, the newest state, which replaces the one before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_busy_worker_keeps_one_waiting_job() { + let (mut app, id) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, _done) = stalled_worker(&mut app); + for k in 0..20 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_none(), "nothing found yet"); + } + assert_eq!(app.preflight.inline_checks, 0); + let now = current(&app); + let waiting = app.preflight.worker.waiting.as_ref().expect("the newest state waits"); + assert!(waiting.of.same(&now)); + let queued = jobs.try_recv().expect("the first state is queued"); + assert!(!queued.of.same(&now)); + assert!(jobs.try_recv().is_err(), "nothing else is queued"); +} + +/// An unchanged document is checked again once its result is older than the refresh interval +/// (linked files can change outside the app), and not before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_unchanged_document_is_checked_again_after_the_refresh_interval() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, done) = stalled_worker(&mut app); + assert!(super::issues_at(&mut app, &ctx, 10.0).is_none()); + let job = jobs.try_recv().expect("the state is queued"); + done.send(super::Found { of: job.of, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + assert!(super::issues_at(&mut app, &ctx, 11.0).is_some(), "the worker's result"); + let refresh = super::REFRESH_MIN.as_secs_f64(); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh - 0.5).is_some()); + assert!(jobs.try_recv().is_err(), "not checked again yet"); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh).is_some(), "the last issues stay shown"); + assert!(jobs.try_recv().expect("checked again").of.same(¤t(&app))); + assert!(super::issues_at(&mut app, &ctx, 11.0 + refresh + 0.5).is_some()); + assert!(jobs.try_recv().is_err(), "asked once"); + // A check that outlasts the refresh interval isn't asked for again while it runs. + assert!(super::issues_at(&mut app, &ctx, 11.0 + 3.0 * refresh).is_some()); + assert!(jobs.try_recv().is_err(), "the check of this state is still running"); + assert_eq!(app.preflight.inline_checks, 0); +} + +/// Issues shown before they are due to be checked again ask for a frame at that time, so the check +/// runs even when nothing else wakes the interface. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn shown_issues_ask_for_a_frame_when_they_are_due_again() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, done) = stalled_worker(&mut app); + assert!(super::issues_at(&mut app, &ctx, 10.0).is_none()); + let job = jobs.try_recv().expect("the state is queued"); + done.send(super::Found { of: job.of, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues_at(&mut app, &ctx, 11.0).is_some()); + assert!(ctx.has_requested_repaint()); +} + +/// A worker that ends leaves checks to the interface thread, and a new one is tried after +/// `RETRY_AFTER`. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_worker_that_ends_is_tried_again_later() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (_jobs, done) = stalled_worker(&mut app); + drop(done); + assert_eq!(super::issues(&mut app, &ctx).map(|i| i.iter().filter(|i| i.severity == "error").count()), Some(1)); + assert_eq!(app.preflight.inline_checks, 1, "checked on the interface thread"); + assert!(app.preflight.worker.channels.is_none() && !app.preflight.worker.retry_due()); + // The shown issues ask for a frame when a new worker may be tried. + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues(&mut app, &ctx).is_some()); + assert!(ctx.has_requested_repaint()); + assert_eq!(app.preflight.inline_checks, 1); + let worker = &mut app.preflight.worker; + worker.failed = std::time::Instant::now().checked_sub(super::RETRY_AFTER); + assert!(worker.retry_due()); + assert_eq!(worker.retry_wait(), Some(std::time::Duration::ZERO)); +} + +/// A check of another document that has been running longer than `SUPERSEDE_AFTER` (a file +/// on a share that doesn't answer) doesn't hold up the active document: a fresh worker takes it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_blocked_check_of_another_document_is_superseded() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let (jobs, _done) = stalled_worker(&mut app); + let mut other = current(&app); + other.uid += 1; + let long_ago = std::time::Instant::now().checked_sub(super::SUPERSEDE_AFTER * 2).unwrap(); + let in_flight = |app: &crate::DesignApp| app.preflight.worker.in_flight.iter().map(|(of, _)| of.same(¤t(app))).collect::>(); + // Asked while the other document's check had only just started: the active document's job is + // queued behind it. + app.preflight.worker.in_flight.push_back((other.clone(), std::time::Instant::now())); + for _ in 0..3 { + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint()); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(ctx.has_requested_repaint(), "a frame comes back to see whether it is blocked"); + assert!(jobs.try_recv().is_ok_and(|job| job.of.same(¤t(&app))), "queued behind the other document's check"); + assert_eq!(in_flight(&app), vec![false, true]); + // A later frame, once that check has been running too long, moves the job to a fresh worker. + app.preflight.worker.in_flight.front_mut().unwrap().1 = long_ago; + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(jobs.try_recv().is_err(), "the blocked worker gets nothing more"); + assert_eq!(in_flight(&app), vec![true], "the fresh worker has the active document"); + // The same document's own earlier state waits for its worker instead. + let (jobs, _done) = stalled_worker(&mut app); + let mut earlier = current(&app); + earlier.revision += 1; + app.preflight.worker.in_flight = [(earlier, long_ago)].into(); + app.preflight.worker.asked = Checked::default(); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(jobs.try_recv().is_ok(), "queued on the same worker"); +} + +/// A result for another document keeps the active document's issues, and the issues of at most +/// `MAX_DOCUMENTS` documents are kept. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn another_documents_result_keeps_the_active_documents_issues() { + let (mut app, _) = overset_app(); + let ctx = egui::Context::default(); + let errors = |app: &mut crate::DesignApp| super::issues(app, &ctx).map(|i| i.iter().filter(|i| i.severity == "error").count()); + assert_eq!(errors(&mut app), Some(1)); + let (_jobs, done) = stalled_worker(&mut app); + for k in 1..=super::MAX_DOCUMENTS as u64 + 2 { + let mut other = current(&app); + other.uid += k; + done.send(super::Found { of: other, issues: Arc::new(vec![]), took: std::time::Duration::ZERO, asked_at: 0.0 }).unwrap(); + assert_eq!(errors(&mut app), Some(1), "the active document's issues"); + } + assert_eq!(app.preflight.found.len(), super::MAX_DOCUMENTS); + assert_eq!(app.preflight.inline_checks, 1); +} + +/// With the worker running, edits and the frames that draw them run no check on the interface +/// thread. The count last found stays shown until the worker has checked the current state. +#[test] +fn the_worker_checks_and_the_interface_thread_does_not() { + let (app, id) = overset_app(); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + let ctx = h.ctx.clone(); + assert_eq!(found(&h.state().app), Some((1, true)), "checked on the interface thread before the worker starts"); + super::start_worker(&mut h.state_mut().app, &ctx); + h.state_mut().app.preflight.inline_checks = 0; + for k in 0..20 { + let dx = if k % 2 == 0 { 1.0 } else { -1.0 }; + h.state_mut().app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + h.run_steps(1); + assert_eq!(found(&h.state().app).map(|f| f.0), Some(1), "the count last found stays shown"); + } + assert_eq!(h.state().app.preflight.inline_checks, 0, "no check ran on the interface thread"); + // The last frame handed the current state to the worker, whose last answer is for it. + while found(&h.state().app) != Some((1, true)) { + super::wait_for_worker(&mut h.state_mut().app); + } + let issues = super::issues(&mut h.state_mut().app, &ctx).unwrap(); + assert_eq!(issues.iter().filter(|i| i.severity == "error").count(), 1); + assert_eq!(h.state().app.preflight.inline_checks, 0, "the worker's answer is kept, not checked again"); +} From 0a8e9a5697e48394a07d19cc79c3e63a6127510b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 18:56:30 -0800 Subject: [PATCH 113/328] Canvas: moving an object with a drop shadow repaints only its area Damage treated any object with an effect as unbounded, so every drag step of a frame with a drop shadow, outer glow, feather or inner effect rendered the whole canvas again. An object's own effects are now bounded: the drop shadow and outer glow by the reach the renderer draws them with, the inner effects and feathers by the shape. Effects on items nested in a group still repaint everything. Strokes are drawn through the item's transform, so the stroke allowance now scales with it, and the strokes of a group's children count toward the group's area. --- crates/render/src/damage.rs | 135 +++++++++++++++++++++++++++-- crates/ui-egui/src/canvas/tests.rs | 28 ++++++ 2 files changed, 155 insertions(+), 8 deletions(-) diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index ff76e0ecb..bacd3864c 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -158,36 +158,52 @@ fn shows_other_text(d: &Document, s: &Story) -> bool { fn item_area(it: &Item) -> Option { let mut ok = true; it.walk(&mut |i| { - // Effects spill outside; text wrap reflows other frames. - if i.effects.any() || i.has_wrap() { + // Text wrap reflows other frames. A nested item's effects are drawn through its parents' + // transforms, which can scale how far they reach. + if i.has_wrap() || !std::ptr::eq(i, it) && i.effects.any() { ok = false; } }); if !ok { return None; } - let pad = it.stroke.extent().max(0.0) + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 }; - Some(painted_bounds(it).inflate(pad, pad)) + // The stroke is drawn through the item's transform. The item's own drop shadow and outer glow + // reach `fx::outset` past what it paints; its inner effects and feathers stay inside the shape. + let stroke = it.stroke.extent().max(0.0) * max_scale(it.xf)?; + let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset(it); + Some(painted_bounds(it)?.inflate(pad, pad)) +} + +/// The largest factor `m` stretches a length by (its linear part's largest singular value), or +/// None when that is not finite. +fn max_scale(m: designcraft_geom::Affine) -> Option { + let [a, b, c, d, _, _] = m.as_coeffs(); + let s = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + v.is_finite().then_some(v) } /// An item's bounds, grown to its text: text is composed in the box around the frame's path in /// the frame's own coordinates, which a sheared then rotated frame turns past its path's bounds. -fn painted_bounds(it: &Item) -> Rect { +/// Its children's bounds include their strokes. None when a child's transform is not finite. +fn painted_bounds(it: &Item) -> Option { let mut b = it.bounds(); if it.is_text_frame() { b = b.union(it.xf.transform_rect_bbox(it.inner_bounds())); } for c in it.children() { - b = b.union(it.xf.transform_rect_bbox(painted_bounds(c))); + let stroke = c.stroke.extent().max(0.0) * max_scale(c.xf)?; + b = b.union(it.xf.transform_rect_bbox(painted_bounds(c)?.inflate(stroke, stroke))); } - b + Some(b) } /// A text frame's area: its spread and bounds with room for glyph overhang. fn frame_area(d: &Document, f: ItemId) -> Option<(SpreadRef, Rect)> { let loc = d.find(f)?; let it = d.item_at(&loc)?; - let b = d.parent_xf(&loc).transform_rect_bbox(painted_bounds(it)); + let b = d.parent_xf(&loc).transform_rect_bbox(painted_bounds(it)?); // Overhang of italics, swashes and big initials, and anchored objects pinned to lines. Some((loc.spread, b.inflate(24.0 + 0.1 * b.width().max(b.height()), 24.0))) } @@ -384,4 +400,107 @@ mod tests { let spreads: Vec = dmg.iter().map(|(r, _)| *r).collect(); assert!(spreads.contains(&SpreadRef::Doc(1)), "{dmg:?}"); } + + /// Moving an object with a drop shadow or an outer glow damages where its effect was and is, + /// and every pixel the move changes lies in that damage: the canvas repaints those regions, + /// not the whole view. + #[test] + fn moving_an_object_with_a_shadow_or_glow_damages_its_effect_area() { + for glow in [false, true] { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = + Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 250.0, 200.0))); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + if glow { + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 30.0, 20.0); + } else { + let s = &mut it.effects.drop_shadow; + (s.on, s.color, s.opacity, s.size, s.distance, s.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 25.0, 30.0); + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.path.transform(designcraft_geom::Affine::translate((60.0, 40.0))); + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| !Rect::new(98.0, 98.0, 312.0, 242.0).contains(*p)), "glow {glow}: the effect paints outside the object"); + } + // An effect on an object inside a group is drawn through the group's transform: unbounded. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let mut child = + Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 9.0, 9.0))); + child.effects.drop_shadow.on = true; + let gid = ItemId(d.alloc()); + let mut group = Item::new(gid, lid, designcraft_doc::Shape::Group, Default::default()); + group.content = designcraft_doc::Content::Group { items: vec![Arc::new(child)] }; + d.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + let old = d.clone(); + d.item_mut(gid).unwrap().xf = designcraft_geom::Affine::scale(4.0); + assert!(damage(&old, &d).is_none()); + } + + /// A stroke is drawn through its item's transform: a frame scaled up paints its stroke that + /// much wider, and moving it damages all of it. + #[test] + fn moving_a_scaled_frame_damages_its_whole_stroke() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 125.0, 100.0))); + it.xf = designcraft_geom::Affine::scale(2.0); + it.stroke.swatch = designcraft_color::swatch::BLACK.into(); + it.stroke.weight = 20.0; + it.stroke.align = designcraft_doc::StrokeAlign::Outside; + it.effects.outer_glow.on = true; + it.effects.outer_glow.size = 0.0; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.xf = designcraft_geom::Affine::translate((60.0, 40.0)) * it.xf; + // The stroke reaches 40 pt past the frame's 100..250 × 100..200 outline on the spread. + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 70.0), "the stroke paints its scaled width"); + // The same frame inside a group with a gradient feather: the child's stroke counts too. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let mut child = old.spreads[0].items[0].as_ref().clone(); + child.effects = Default::default(); + child.id = ItemId(d.alloc()); + let gid = ItemId(d.alloc()); + let outline = designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 250.0, 200.0)); + let mut group = Item::new(gid, d.default_layer(), designcraft_doc::Shape::Group, outline); + group.content = designcraft_doc::Content::Group { items: vec![Arc::new(child)] }; + let gf = &mut group.effects.gradient_feather; + (gf.on, gf.start, gf.end) = (true, 1.0, 0.5); + d.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + let old = d.clone(); + d.item_mut(gid).unwrap().xf = designcraft_geom::Affine::translate((60.0, 40.0)); + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 70.0), "the child's stroke paints its scaled width"); + } + + /// The pixels a page render changes from `old` to `new`, each checked to lie in the damage. + fn changed_pixels_in_damage(old: &Document, new: &Document) -> Vec { + let dmg = damage(old, new).expect("bounded damage"); + let cache = designcraft_compose::Cache::new(); + let mut r = crate::Renderer::new(); + r.threads = 0; + let opts = crate::RenderOptions::default(); + let before = r.render_page(old, &cache, 0, 1.0, false, &opts).unwrap(); + let after = r.render_page(new, &cache, 0, 1.0, false, &opts).unwrap(); + let mut changed = Vec::new(); + for y in 0..before.height { + for x in 0..before.width { + if before.pixel(x, y) == after.pixel(x, y) { + continue; + } + let p = designcraft_geom::Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5); + assert!(dmg.iter().any(|(_, r)| r.inflate(1.0, 1.0).contains(p)), "changed pixel {p:?} outside {dmg:?}"); + changed.push(p); + } + } + changed + } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..685c1b205 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2176,6 +2176,34 @@ fn edits_patch_the_canvas_only_at_full_resolution() { } } +/// Moving a frame with a drop shadow repaints the regions the frame and its shadow cover, as +/// moving one without a shadow does, instead of rendering the whole canvas again on every step. +#[test] +fn moving_a_frame_with_a_drop_shadow_patches_the_canvas() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 200, 180], "content": "unassigned"})).unwrap(); + app.run("object.fill", json!({"swatch": "[Black]"})).unwrap(); + app.run("object.dropShadow", json!({"on": true})).unwrap(); + for _ in 0..3 { + frame(&mut app); + } + for step in 1..=3 { + app.run("transform.move", json!({"dx": 4, "dy": 2})).unwrap(); + frame(&mut app); + assert_eq!(app.canvas.patches, step, "drag step {step} repaints only what changed"); + } +} + /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames /// drawn; returns the story id. fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value { From 18be5b76f5972905fdc4d4638ef1ab5f126fd143 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:06:29 -0800 Subject: [PATCH 114/328] Text: Text Frame Options in a footnote or table cell change the frame that shows it With the insertion point in footnote text or a table cell and no stored frame on the caret, Text Frame Options changed the last frame of the thread. They now change the frame the caret is drawn in: the frame that holds the placed footnote, or the cell's own occurrence (not a repeated header or footer), else the frame that shows the footnote reference or the table's anchor. --- crates/engine/src/cmd/object.rs | 96 +++++++++++++++++++++++++++++++-- docs/mcp.md | 3 +- 2 files changed, 94 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 67b1d21d4..50628d2bc 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2807,11 +2807,24 @@ fn text_selection_frames(s: &Session, t: &TextSel) -> Vec { let Ok(st) = s.doc() else { return Vec::new() }; let Some(story) = st.doc.story(t.story) else { return Vec::new() }; let last = story.frames.last().copied(); - // In a table cell, `anchor` and `focus` index the cell's text: the frame the caret is shown in. - if t.cell.is_some() { - return t.frame.filter(|f| story.frames.contains(f)).or(last).into_iter().collect(); - } let cs = s.cache.get(&st.doc, t.story, None); + // In footnote text or a table cell, `anchor` and `focus` index that text: the frame the caret + // is drawn in (the placed footnote, or the cell's first non-repeated occurrence), else the + // frame that shows the footnote reference or the table's anchor character. + if let Some(c) = t.cell { + let (drawn, anchor) = match c.footnote_id() { + Some(id) => (designcraft_compose::find_note(&cs, id).map(|(fi, _)| fi), story.note_anchor(id)), + None => (designcraft_compose::find_cell(&cs, c.table, c.row, c.col).map(|(fi, ..)| fi), story.table_anchor(c.table)), + }; + return drawn + .or_else(|| anchor.and_then(|a| designcraft_compose::caret(&cs, a)).map(|(fi, ..)| fi)) + .and_then(|fi| cs.frames.get(fi)) + .map(|f| f.frame) + .or_else(|| t.frame.filter(|f| story.frames.contains(f))) + .or(last) + .into_iter() + .collect(); + } let r = t.range(); // The frame the caret at the start is drawn in; the caret's stored frame only when no line // holds it. @@ -5086,6 +5099,81 @@ mod type_tool_frame_options_tests { assert_eq!(s.execute("object.textFrameOptions", &fixed).unwrap()["changed"], 0); assert_eq!(undo_steps(&s), steps + 1, "the same Fixed Width options again add no undo step"); } + + /// A caret in footnote text changes the frame that shows the footnote, with or without a + /// stored frame on the caret. + #[test] + fn a_caret_in_a_footnote_changes_the_frame_that_shows_it() { + for (in_second, stored) in [(false, None), (true, None), (false, Some(true))] { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let r = shown(&s, sid, if in_second { b } else { a }); + s.execute("text.select", &json!({"story": sid.0, "anchor": r.start + 2})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note."})).unwrap(); + let mut t = s.doc().unwrap().selection.text.unwrap(); + assert!(t.cell.and_then(|c| c.footnote_id()).is_some(), "the caret is in the footnote: {t:?}"); + if let Some(second) = stored { + t.frame = Some(if second { b } else { a }); + s.doc_mut().unwrap().selection = Selection::text(t); + } + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + let want = if in_second { (1, 2) } else { (2, 1) }; + assert_eq!((options(&s, a).columns, options(&s, b).columns), want, "footnote in the second frame: {in_second}, stored frame: {stored:?}"); + } + } + + /// A caret in a table cell changes the frame that shows the cell, with or without a stored + /// frame on the caret. + #[test] + fn a_caret_in_a_table_cell_changes_the_frame_that_shows_it() { + for (in_second, stored) in [(false, None), (true, None), (false, Some(true))] { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let r = shown(&s, sid, if in_second { b } else { a }); + s.execute("text.select", &json!({"story": sid.0, "anchor": r.start + 2})).unwrap(); + s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap(); + let mut t = s.doc().unwrap().selection.text.unwrap(); + assert!(t.cell.is_some_and(|c| c.footnote_id().is_none()), "the caret is in the cell: {t:?}"); + if let Some(second) = stored { + t.frame = Some(if second { b } else { a }); + s.doc_mut().unwrap().selection = Selection::text(t); + } + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + let want = if in_second { (1, 2) } else { (2, 1) }; + assert_eq!((options(&s, a).columns, options(&s, b).columns), want, "table in the second frame: {in_second}, stored frame: {stored:?}"); + } + } + + /// A caret in a repeated footer row is drawn in the footer's own occurrence at the end of the + /// table: that frame changes, not the earlier frame that shows a repeat of the footer. + #[test] + fn a_caret_in_a_repeated_footer_changes_the_frame_with_the_footer_itself() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + let ra = shown(&s, sid, a); + s.execute("text.select", &json!({"story": sid.0, "anchor": ra.start + 2})).unwrap(); + s.execute("table.insert", &json!({"rows": 15, "cols": 1, "footerRows": 1})).unwrap(); + s.execute("table.options", &json!({"repeatFooter": true})).unwrap(); + let t = s.doc().unwrap().selection.text.unwrap(); + let table = t.cell.unwrap().table; + let footer = s.doc().unwrap().doc.story(sid).unwrap().tables.get(&table).unwrap().nrows() - 1; + let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default()); + let placed = |f: ItemId| { + cs.frame(f) + .unwrap() + .tables + .iter() + .filter(|tf| tf.table == table) + .filter_map(|tf| tf.cell(footer, 0)) + .map(|c| c.repeated) + .collect::>() + }; + assert_eq!((placed(a), placed(b)), (vec![true], vec![false]), "the footer repeats in the first frame and ends the table in the second"); + s.doc_mut().unwrap().selection = + Selection::text(TextSel { cell: Some(designcraft_doc::CellAddr { table, row: footer, col: 0 }), anchor: 0, focus: 0, frame: None, ..t }); + s.execute("object.textFrameOptions", &json!({"columns": 2})).unwrap(); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 2)); + } } #[cfg(test)] diff --git a/docs/mcp.md b/docs/mcp.md index 17c7e330b..d9a15256a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -228,7 +228,8 @@ With a text selection, this formats the selected paragraphs; with selected text `object.textFrameOptions` (columns, inset spacing, vertical justification and the rest of Text Frame Options) acts on the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the -thread. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. +thread. With the insertion point in a footnote or a table cell, it acts on the frame that shows the footnote or the +cell. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. ```text execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} From e5010f363c8659b26da277fb14f2a2e8bcc78ee6 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:07:11 +0000 Subject: [PATCH 115/328] Apply review fixes - crates/ui-egui/src/panels/pages.rs --- crates/ui-egui/src/panels/pages.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs index ff8e2f3c7..8825a5bf2 100644 --- a/crates/ui-egui/src/panels/pages.rs +++ b/crates/ui-egui/src/panels/pages.rs @@ -83,6 +83,7 @@ fn thumb(app: &mut DesignApp, ctx: &egui::Context, of: ThumbOf, h: f32) -> Optio } if let Some((rev, t)) = map.get(&key) { if *rev == st.revision { + ctx.data_mut(|d| d.insert_temp(clock_id, clock)); return Some(t.clone()); } let wait = THUMB_QUIET_SECS - (now - clock.changed_at); From 7ba1f8b96f6f84874045294dc7d023b4af48f27d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:07:29 -0800 Subject: [PATCH 116/328] Place: test PNG and WebP resolution past 64 chunks Tests read a pHYs chunk behind 100 text chunks in a PNG, ignore a pHYs after the image data, and read an EXIF chunk stored after 100 frames of an animated WebP. --- crates/images/src/tests.rs | 50 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index f2fcf2bf0..1803b310a 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -626,6 +626,56 @@ fn png_phys_sets_natural_size() { assert_eq!(natural_size(&plain), Some((4.0, 4.0))); } +/// A pHYs chunk behind 100 text chunks is still read, and the scan stops at the first IDAT. +#[test] +fn png_phys_after_many_chunks_is_read() { + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(data); + out.extend_from_slice(&[0, 0, 0, 0]); + } + let mut phys = 11811u32.to_be_bytes().repeat(2); + phys.push(1); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &[0; 13]); + for _ in 0..100 { + chunk(&mut png, b"tEXt", b"Comment\x00x"); + } + let mut late = png.clone(); + chunk(&mut png, b"pHYs", &phys); + let (dx, dy) = raster_resolution(&png).unwrap(); + assert!((dx - 300.0).abs() < 0.05 && (dy - 300.0).abs() < 0.05, "{dx} x {dy}"); + // A pHYs after the image data is not read. + chunk(&mut late, b"IDAT", &[0; 4]); + chunk(&mut late, b"pHYs", &phys); + assert_eq!(raster_resolution(&late), None); +} + +/// An EXIF chunk stored after 100 animation frames of a WebP is still read. +#[test] +fn webp_exif_after_many_frames_is_read() { + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(kind); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out.extend_from_slice(data); + if data.len() % 2 == 1 { + out.push(0); + } + } + let mut body = b"WEBP".to_vec(); + chunk(&mut body, b"VP8X", &[0; 10]); + chunk(&mut body, b"ANIM", &[0; 6]); + for _ in 0..100 { + chunk(&mut body, b"ANMF", &[0; 17]); + } + chunk(&mut body, b"EXIF", &tiff_bytes((300, 1), (300, 1), Some(2))); + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&(body.len() as u32).to_le_bytes()); + webp.extend_from_slice(&body); + assert_eq!(raster_resolution(&webp), Some((300.0, 300.0))); +} + /// A real encoder-written BMP with the header pixels-per-meter patched (compression and image /// size stay zero, as the encoder writes them). fn bmp_with_ppm(ppm: i32) -> Vec { From 4b06bb219c04bd75ffd8931473e9553de622a1e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:14:37 -0800 Subject: [PATCH 117/328] Render: keep drop shadow and outer glow images while an object moves The canvas drew and blurred every drop shadow and outer glow on every render, also when the object or the view had only moved. Each image is now kept per object, effect, page and ink pass, with the whole effect drawn once. While the object (apart from its position), the effect, the view's scale and rotation, the render options and the document's colours, styles, layers and images stay the same, a move by whole device pixels places the kept image again. Any other change draws it afresh. Only multithreaded renders (the canvas) keep images, and only for objects without text or nested items. Kept images are limited to 4 Mpx each and 128 MiB in all; the images used longest ago go first, and an image no render placed in 256 renders is dropped. --- crates/render/src/driver.rs | 5 +- crates/render/src/fx.rs | 417 ++++++++++++++++++++++++++++++++++-- crates/render/src/lib.rs | 2 + 3 files changed, 403 insertions(+), 21 deletions(-) diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index a5dd2b86b..b9568a595 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -15,6 +15,7 @@ impl Renderer { drawing_items: Vec::new(), cmyk_view: None, cmyk_ran: false, + kept: Default::default(), #[cfg(test)] cmyk_passes: 0, #[cfg(test)] @@ -26,11 +27,12 @@ impl Renderer { } } - /// Drop cached glyph paths and the CMYK viewport (rebuilt on demand). + /// Drop cached glyph paths, effect images and the CMYK viewport (rebuilt on demand). pub fn clear_caches(&mut self) { self.cmyk_view = None; self.glyphs.clear(); self.stories.clear(); + self.kept.clear(); } /// Number of text frames whose glyph paths are cached. @@ -88,6 +90,7 @@ impl Renderer { self.stats = FrameStats::default(); self.stories.clear(); self.glyphs.tick(); + self.kept.begin(doc); if let Some(bg) = opts.background { ctx.set_transform(Affine::IDENTITY); ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..44513c3ac 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -17,13 +17,16 @@ //! - Feather: the object is masked by its shape inset by half the width and blurred, so the //! edge fades from ~0 at the path to full strength `width` inside. -use designcraft_doc::Item; +use std::collections::HashMap; +use std::sync::Arc; + +use designcraft_doc::{Asset, AssetId, DocSettings, Document, InkManager, Item, ItemId, Layer, StrokeStyleDef}; use designcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use vello_common::filter_effects::{EdgeMode, Filter, FilterPrimitive}; use vello_cpu::peniko::{self, BlendMode, Compose, Mix}; -use vello_cpu::{RenderContext, kurbo}; +use vello_cpu::{Pixmap, RenderContext, kurbo}; -use crate::{Frame, Renderer, color_of}; +use crate::{Frame, RenderOptions, Renderer, color_of}; use designcraft_compose::ShownOn; /// Shadow offset (spread units) for an InDesign angle (degrees, light direction) and distance. @@ -113,16 +116,25 @@ impl Renderer { let mut below = vec![]; if e.outer_glow.on { let g = &e.outer_glow; - below.push((Vec2::ZERO, g.size, g.spread, g.color.clone(), g.opacity, g.mode)); + below.push((Slot::OuterGlow, Vec2::ZERO, g.size, g.spread, g.color.clone(), g.opacity, g.mode)); } if e.drop_shadow.on { let d = &e.drop_shadow; - below.push((offset(doc.light_angle(d.angle, d.global_light), d.distance), d.size, d.spread, d.color.clone(), d.opacity, d.mode)); + below.push(( + Slot::DropShadow, + offset(doc.light_angle(d.angle, d.global_light), d.distance), + d.size, + d.spread, + d.color.clone(), + d.opacity, + d.mode, + )); } - for (off, size, pct, color, opacity, mode) in below { + for (slot, off, size, pct, color, opacity, mode) in below { let Some(c) = doc.resolve_color(&color, 1.0) else { continue }; let (sigma, grow) = split(size, pct); - let filter = shadow(sigma, color_of(&c, opacity.clamp(0.0, 1.0))); + let paint = color_of(&c, opacity.clamp(0.0, 1.0)); + let filter = shadow(sigma, paint); // The offset moves the geometry, not the filter: vello drops layer content that lies // entirely outside the viewport before filtering. let r = (reach + off).inflate(grow, grow); @@ -132,7 +144,8 @@ impl Renderer { ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); } - self.with_filters(ctx, f, r, sigma, None, |me, c, fr| { + let look = Look { slot, off, sigma, grow, paint: paint.components }; + self.with_kept_filters(ctx, f, it, xf, page, look, r, |me, c, fr| { let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; c.set_transform(moved.view); c.push_layer(None, None, None, None, Some(filter)); @@ -448,23 +461,251 @@ impl Renderer { return; } let Some(o) = offscreen(f.view.transform_rect_bbox(reach), spread, ctx.width(), ctx.height()) else { return }; + // Clip where the result is at full resolution: offscreen unless that is reduced. + let (inner, outer) = if o.scale > 1.0 { (None, clip) } else { (clip, None) }; + let pm = self.draw_offscreen(f, &o, inner, draw); + push_clip(ctx, f, outer); + place(ctx, o.x0, o.y0, o.scale, Arc::new(pm)); + pop_clip(ctx, outer); + } + + /// `draw` into the single-threaded offscreen image `o`. + fn draw_offscreen( + &mut self, + f: &Frame, + o: &Offscreen, + clip: Option<(&BezPath, Affine)>, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) -> Pixmap { let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * f.view; let shifted = Frame { mt: false, view, px: f.px * o.scale, ..*f }; - // Clip where the result is at full resolution: offscreen unless that is reduced. - let (inner, outer) = if o.scale > 1.0 { (None, clip) } else { (clip, None) }; - push_clip(&mut off, &shifted, inner); + push_clip(&mut off, &shifted, clip); draw(self, &mut off, &shifted); - pop_clip(&mut off, inner); + pop_clip(&mut off, clip); off.flush(); - let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + let mut pm = Pixmap::new(o.width, o.height); off.render(&mut pm, &mut self.resources); - push_clip(ctx, f, outer); - ctx.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); - ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(pm)), sampler: peniko::ImageSampler::default() }); - ctx.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); - pop_clip(ctx, outer); - ctx.set_transform(Affine::IDENTITY); + pm + } + + /// [`Renderer::with_filters`] for a drop shadow or an outer glow of `it`, keeping its image + /// between renders. While the object, its effect, the view's scale and rotation, the render + /// options and the document's colours, styles and images stay the same, a move of the object + /// or of the view by whole device pixels places the kept image again instead of drawing and + /// blurring it. Only multithreaded contexts (the canvas) keep images, and only of objects + /// without text or nested items. + #[allow(clippy::too_many_arguments)] + fn with_kept_filters( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + it: &Item, + xf: Affine, + page: ShownOn, + look: Look, + reach: Rect, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) { + let keepable = f.mt && it.text_frame().is_none() && it.children().is_empty() && it.media.is_none(); + if !keepable { + self.with_filters(ctx, f, reach, look.sigma, None, draw); + return; + } + let [a, b, c, d, e, g] = (f.view * xf).as_coeffs(); + let (linear, anchor) = ([a, b, c, d], Vec2::new(e, g)); + let plate = crate::PLATE.with(std::cell::Cell::get); + let rich_black = crate::color::RICH_BLACK.with(std::cell::Cell::get); + let key = (it.id, page, look.slot, plate); + let tick = self.kept.tick; + if let Some(k) = self.kept.entries.get_mut(&key) + && k.look == look + && k.linear == linear + && k.px == f.px + && k.rich_black == rich_black + && k.opts == *f.opts + && (Item { xf: k.item.xf, ..it.clone() }) == k.item + { + let shift = anchor - k.anchor; + let (dx, dy) = (shift.x.round(), shift.y.round()); + if (shift.x - dx).abs() < 1e-3 && (shift.y - dy).abs() < 1e-3 { + k.used = tick; + let (x0, y0, scale, image) = (k.x0 + dx, k.y0 + dy, k.scale, k.image.clone()); + place(ctx, x0, y0, scale, image); + return; + } + } + // The whole effect, not only the part in view, so that it can be placed anywhere later. + let spread = bound(look.sigma).max(0.0) * 3.0 / f.px + 2.0; + let whole = f.view.transform_rect_bbox(reach).inflate(spread, spread); + let covers = |o: &Offscreen| f64::from(o.width) * o.scale >= whole.x1 - o.x0 && f64::from(o.height) * o.scale >= whole.y1 - o.y0; + let Some(o) = fit(whole, spread).filter(|o| usize::from(o.width) * usize::from(o.height) <= KEEP_MAX_PIXELS && covers(o)) else { + self.with_filters(ctx, f, reach, look.sigma, None, draw); + return; + }; + let image = Arc::new(self.draw_offscreen(f, &o, None, draw)); + #[cfg(test)] + { + self.kept.drawn += 1; + } + place(ctx, o.x0, o.y0, o.scale, image.clone()); + let kept = Kept { + item: it.clone(), + linear, + anchor, + look, + opts: f.opts.clone(), + px: f.px, + rich_black, + x0: o.x0, + y0: o.y0, + scale: o.scale, + image, + used: tick, + }; + self.kept.insert(f.doc, key, kept); + } +} + +/// Paint `image` with its top-left corner at device pixel (`x0`, `y0`), each of its pixels +/// covering `scale` device pixels. +fn place(ctx: &mut RenderContext, x0: f64, y0: f64, scale: f64, image: Arc) { + let (w, h) = (f64::from(image.width()), f64::from(image.height())); + ctx.set_transform(Affine::translate((x0, y0)) * Affine::scale(scale)); + ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(image), sampler: peniko::ImageSampler::default() }); + ctx.fill_rect(&Rect::new(0.0, 0.0, w, h)); + ctx.set_transform(Affine::IDENTITY); +} + +/// Pixels one kept effect image may have; a larger one is drawn each time. +const KEEP_MAX_PIXELS: usize = 4 << 20; +/// Pixels all kept effect images may have together (128 MiB). +const KEEP_BUDGET: usize = 32 << 20; +/// Renders an image no render has placed is kept for. +const KEEP_RENDERS: u64 = 256; + +/// The effect below an object a kept image is of. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Slot { + OuterGlow, + DropShadow, +} + +/// What an effect image looks like apart from the object: its offset (spread space), blur, +/// growth and colour. +#[derive(Clone, Copy, PartialEq)] +struct Look { + slot: Slot, + off: Vec2, + sigma: f64, + grow: f64, + paint: [f32; 4], +} + +/// One kept effect image and what it was drawn from. +struct Kept { + /// The object, with the transform it had. + item: Item, + /// The linear part of the object's spread → device transform. + linear: [f64; 4], + /// The device position of the object's origin. + anchor: Vec2, + look: Look, + opts: RenderOptions, + px: f64, + rich_black: bool, + x0: f64, + y0: f64, + scale: f64, + image: Arc, + used: u64, +} + +/// What every kept image depends on besides its object. +struct Deps { + colors: designcraft_color::cms::ColorSettings, + swatches: Vec, + settings: DocSettings, + inks: InkManager, + stroke_styles: Vec, + layers: Vec, + /// Held, so that an asset changed in place or a new one at the same address is a new `Arc`. + assets: Vec<(AssetId, Arc)>, +} + +impl Deps { + fn of(doc: &Document) -> Self { + Deps { + colors: designcraft_color::cms::active_settings(), + swatches: doc.swatches.clone(), + settings: doc.settings.clone(), + inks: doc.inks.clone(), + stroke_styles: doc.stroke_styles.clone(), + layers: doc.layers.clone(), + assets: doc.assets.iter().map(|(id, a)| (*id, a.clone())).collect(), + } + } + fn same(&self, doc: &Document) -> bool { + self.colors == designcraft_color::cms::active_settings() + && self.swatches == doc.swatches + && self.settings == doc.settings + && self.inks == doc.inks + && self.stroke_styles == doc.stroke_styles + && self.layers == doc.layers + && self.assets.len() == doc.assets.len() + && self.assets.iter().zip(&doc.assets).all(|((a, p), (b, x))| a == b && Arc::ptr_eq(p, x)) + } +} + +/// Drop shadows and outer glows kept between renders ([`Renderer::with_kept_filters`]), at most +/// [`KEEP_BUDGET`] pixels; the images used longest ago go first, and an image no render placed +/// in [`KEEP_RENDERS`] renders goes too. +#[derive(Default)] +pub(crate) struct KeptEffects { + deps: Option, + entries: HashMap<(ItemId, ShownOn, Slot, Option), Kept>, + pixels: usize, + tick: u64, + /// Effect images drawn for keeping (tests). + #[cfg(test)] + pub(crate) drawn: usize, +} + +impl KeptEffects { + /// Start a render of `doc`: drop every image when what they depend on changed. + pub(crate) fn begin(&mut self, doc: &Document) { + self.tick += 1; + if !self.deps.as_ref().is_some_and(|d| d.same(doc)) { + self.clear(); + return; + } + let tick = self.tick; + let before = self.entries.len(); + self.entries.retain(|_, k| k.used + KEEP_RENDERS >= tick); + if self.entries.len() != before { + self.pixels = self.entries.values().map(|k| k.image.width() as usize * k.image.height() as usize).sum(); + } + } + pub(crate) fn clear(&mut self) { + self.entries.clear(); + self.pixels = 0; + self.deps = None; + } + fn insert(&mut self, doc: &Document, key: (ItemId, ShownOn, Slot, Option), kept: Kept) { + if self.deps.is_none() { + self.deps = Some(Deps::of(doc)); + } + let size = |k: &Kept| k.image.width() as usize * k.image.height() as usize; + self.pixels += size(&kept); + if let Some(old) = self.entries.insert(key, kept) { + self.pixels -= size(&old); + } + while self.pixels > KEEP_BUDGET { + let Some(oldest) = self.entries.iter().min_by_key(|(_, k)| k.used).map(|(key, _)| *key) else { break }; + if let Some(old) = self.entries.remove(&oldest) { + self.pixels -= size(&old); + } + } } } @@ -502,7 +743,15 @@ struct Offscreen { /// [`MAX_BLUR_SPREAD`], at most `MAX_SIDE` a side. `None` when none of it shows. fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option { let screen = Rect::new(0.0, 0.0, f64::from(width), f64::from(height)).inflate(spread, spread); - let r = reach.inflate(spread, spread).intersect(screen); + fit(reach.inflate(spread, spread).intersect(screen), spread) +} + +/// The offscreen image covering `r` (device pixels) for a blur of `spread`, or `None` when it is +/// empty, not finite or more than `MAX_SIDE` a side. +fn fit(r: Rect, spread: f64) -> Option { + if !(r.x0.is_finite() && r.y0.is_finite() && r.x1.is_finite() && r.y1.is_finite()) { + return None; + } let (x0, y0) = (r.x0.floor(), r.y0.floor()); let scale = (spread / MAX_BLUR_SPREAD).max(1.0); let side = |len: f64| (len / scale).ceil().min(crate::MAX_SIDE as f64); @@ -607,4 +856,132 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A document with one image frame casting a drop shadow, and the frame's id. + fn shadowed_image() -> (designcraft_doc::Document, designcraft_doc::ItemId) { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let img = image::RgbaImage::from_fn(64, 48, |x, y| image::Rgba([(x * 4) as u8, (y * 5) as u8, 128, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let aid = designcraft_doc::AssetId(d.alloc()); + d.assets.insert( + aid, + Arc::new(designcraft_doc::Asset { + id: aid, + name: "photo.png".into(), + mime: "image/png".into(), + data: Arc::new(png), + pixels: Some((64, 48)), + ..Default::default() + }), + ); + let id = designcraft_doc::ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 160.0, 120.0))); + it.xf = Affine::translate((100.0, 100.0)); + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (160.0, 120.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + let s = &mut it.effects.drop_shadow; + (s.on, s.color, s.opacity, s.size, s.distance) = (true, "[Black]".into(), 0.75, 12.0, 9.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + (d, id) + } + + /// Moving a shadowed frame, or the view, by whole pixels places the kept shadow again: the + /// shadow is drawn and blurred once, and every frame matches a render that draws it afresh. + /// A new effect setting, zoom, colour or a move by part of a pixel draws it again. + #[test] + fn a_moved_shadow_is_drawn_once_and_placed_again() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut kept = Renderer::new(); + kept.threads = 2; + let render = + |r: &mut Renderer, d: &designcraft_doc::Document, size: (u32, u32), view: Affine| r.render(d, &cache, &placed, size, view, &opts); + let fresh = |d: &designcraft_doc::Document, size: (u32, u32), view: Affine| { + let mut r = Renderer::new(); + r.threads = 2; + r.render(d, &crate::Cache::new(), &placed, size, view, &opts) + }; + let close = |a: &crate::Rendered, b: &crate::Rendered, what: &str| { + let worst = a.pixels.iter().zip(&b.pixels).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + assert!(a.pixels.len() == b.pixels.len() && worst <= 1, "{what}: off by {worst}"); + }; + let view = Affine::scale(1.5); + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "first render"); + assert_eq!(kept.kept.drawn, 1); + for step in 1..=4 { + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((2.0, 4.0 / 3.0)) * it.xf; + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "after a move"); + // A patch of the view, as the canvas repaints after an edit. + let patch = Affine::translate((-150.0, -140.0)) * view; + close(&render(&mut kept, &d, (120, 90), patch), &fresh(&d, (120, 90), patch), "a patch"); + assert_eq!(kept.kept.drawn, 1, "step {step}: placed again, not drawn"); + } + // Panning by whole pixels. + let panned = Affine::translate((-37.0, 11.0)) * view; + close(&render(&mut kept, &d, (500, 450), panned), &fresh(&d, (500, 450), panned), "panned"); + assert_eq!(kept.kept.drawn, 1); + // Part of a pixel, another zoom, another size, another colour: drawn again. + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((0.25, 0.0)) * it.xf; + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 2); + render(&mut kept, &d, (500, 450), Affine::scale(2.0)); + assert_eq!(kept.kept.drawn, 3); + d.item_mut(id).unwrap().effects.drop_shadow.size = 20.0; + close(&render(&mut kept, &d, (500, 450), view), &fresh(&d, (500, 450), view), "a new size"); + assert_eq!(kept.kept.drawn, 4); + d.swatches.push(designcraft_color::Swatch::color("Extra", designcraft_color::Color::rgb8(1, 2, 3))); + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 5, "a swatch change drops kept images"); + // An image changed in place (its only document owner editing it). + let asset = d.assets.values_mut().next().unwrap(); + Arc::make_mut(asset).name = "edited.png".into(); + render(&mut kept, &d, (500, 450), view); + assert_eq!(kept.kept.drawn, 6, "an edited image drops kept images"); + // Single-threaded renders (exports) draw as before and keep nothing. + let mut single = Renderer::new(); + single.threads = 0; + render(&mut single, &d, (500, 450), view); + assert_eq!(single.kept.drawn, 0); + } + + /// In the CMYK blend space view the ink passes keep an image per plate, placed again on a move. + #[test] + fn the_ink_passes_keep_their_shadows() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + d.settings.blend_space = designcraft_doc::BlendSpace::Cmyk; + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { blend_space_view: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + // One for each ink pass, and one for the ordinary drawing around their area. + assert_eq!(r.kept.drawn, 3); + for _ in 0..3 { + let it = d.item_mut(id).unwrap(); + it.xf = Affine::translate((3.0, 1.0)) * it.xf; + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + } + assert_eq!(r.kept.drawn, 3); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 25207b248..973f1eb21 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -155,6 +155,8 @@ pub struct Renderer { cmyk_view: Option, /// Whether the last render ran the CMYK ink passes (only then is its view worth keeping). cmyk_ran: bool, + /// Drop shadow and outer glow images kept between renders. + kept: fx::KeptEffects, #[cfg(test)] cmyk_passes: usize, /// Pixels the last ink pass covered (tests). From 670ada58c22ffae76c16f53af212e89cdce0cade Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:20:11 -0800 Subject: [PATCH 118/328] Pages: test that a cached document is stored in the thumbnail clock The test switches to a document whose thumbnails are all current and checks that the clock names that document afterwards. --- crates/ui-egui/src/panels/pages/tests.rs | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/panels/pages/tests.rs b/crates/ui-egui/src/panels/pages/tests.rs index 62644227f..66d05fbb7 100644 --- a/crates/ui-egui/src/panels/pages/tests.rs +++ b/crates/ui-egui/src/panels/pages/tests.rs @@ -373,6 +373,34 @@ fn an_edit_redraws_only_thumbnails_in_view_one_per_frame() { assert!((2..60).all(|abs| !cached(abs)), "no thumbnail of a deleted page is kept"); } +/// Switching to a document whose thumbnails are all current stores that document in the clock, +/// so the next frames do not scan the whole cache again. +#[test] +fn switching_to_a_cached_document_stores_it_in_the_clock() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut DesignApp| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(280.0, 520.0))), + time: Some(0.0), + ..Default::default() + }; + ctx.run_ui(raw, |ui| show(app, ui)).textures_delta.clear(); + }; + for _ in 0..2 { + app.run("file.new", json!({"pages": 2, "facingPages": false})).unwrap(); + frame(&mut app); + } + app.session.set_active(0); + let st = app.session.active().unwrap(); + let first = (st.uid, st.revision); + let before = THUMB_RENDERS.with(std::cell::Cell::get); + frame(&mut app); + assert_eq!(THUMB_RENDERS.with(std::cell::Cell::get), before, "the first document's thumbnails are current"); + let clock = ctx.data(|d| d.get_temp::(egui::Id::unique("pages_thumb_clock"))).unwrap(); + assert_eq!(clock.doc, first); +} + #[test] fn parents_are_added_duplicated_and_renamed_from_the_panel() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5c6d45908d447f6e96599505c9225d31b612862f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:25:22 -0800 Subject: [PATCH 119/328] Compose: vertical justification keeps grid-aligned lines on the baseline grid With Align to Baseline Grid, Center and Bottom moved the lines by any amount, so they left the grid. They now move by whole grid steps: Bottom puts the last baseline on the lowest grid line above the bottom inset, and Center on the grid line nearest the centered position. With Justify the first line stays in place and the last baseline goes to the lowest grid line above the bottom inset; the lines between are spread evenly. --- crates/compose/src/lib.rs | 61 +++++++++++++++++++++++++++++++------ crates/compose/src/tests.rs | 53 +++++++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 72c0f69cb..f43caad84 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2737,6 +2737,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Each paragraph's Align to Baseline Grid (vertical justification moves grid-aligned lines by + // whole grid steps). + let mut grid_paras = vec![GridAlign::None; np]; 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2896,6 +2899,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // it, a paragraph moves on to the next sub-column. let split_cfg = SplitCfg::of(&pp); split_paras[pi] = split_cfg.is_some(); + grid_paras[pi] = pp.grid_align; if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) { cur.split = None; } @@ -3124,6 +3128,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C boxes: &boxes, span_paras: &span_paras, split_paras: &split_paras, + grid_paras: &grid_paras, styles_tab, }) } @@ -3138,11 +3143,12 @@ struct FinishInput<'a> { boxes: &'a [Option], span_paras: &'a [bool], split_paras: &'a [bool], + grid_paras: &'a [GridAlign], styles_tab: Vec, } fn finish_composition(input: FinishInput<'_>) -> ComposedStory { - let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, styles_tab } = input; + let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { @@ -3159,7 +3165,7 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned, &doc.footnote_options); + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -5484,8 +5490,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `grid_aligns`: +/// each paragraph's Align to Baseline Grid setting. +fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions, grid_aligns: &[GridAlign]) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5563,10 +5570,13 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de let fits = |shift: &[f64]| { idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) }; - // Every row moves no less as `space` grows, so the most room that fits is found by halving. - let mut shift = shifts(space); - if !fits(&shift) { - let (mut lo, mut hi) = (0.0, space); + // Every row moves no less as the room grows, so the most room that fits, up to `top`, is + // found by halving. + let most_room = |top: f64| -> f64 { + if fits(&shifts(top)) { + return top; + } + let (mut lo, mut hi) = (0.0, top); for _ in 0..60 { let mid = (lo + hi) / 2.0; if fits(&shifts(mid)) { @@ -5575,8 +5585,39 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de hi = mid; } } - shift = shifts(lo); - } + lo + }; + // Lines aligned to the baseline grid move by whole grid steps, so they stay on the grid. + // With Justify only the last row has to land on the grid (the first row doesn't move). + let on_grid = |i: usize| { + let line = &ft.lines[i]; + match grid_aligns.get(line.para) { + Some(GridAlign::AllLines) => true, + Some(GridAlign::FirstLineOnly) => line.first_in_para, + _ => false, + } + }; + let center = f.opts.vertical_justification == VerticalJustification::Center; + let step = f.grid.map(|(_, inc)| inc).filter(|inc| *inc > 0.0 && inc.is_finite()).filter(|_| match f.opts.vertical_justification { + VerticalJustification::Justify => idx.iter().zip(&rows).any(|(&i, &k)| k == n && on_grid(i)), + _ => idx.iter().any(|&i| on_grid(i)), + }); + let shift = match step { + None => shifts(most_room(space)), + Some(inc) => { + // The room one grid step takes: Center moves the lines by half the room. + let unit = if center { 2.0 * inc } else { inc }; + let room = most_room(if center { 2.0 * space } else { space }); + // The last baseline stays above the bottom of the text, and the rows above it fit. + let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); + // Bottom and Justify take the lowest grid line, Center the one nearest the middle. + let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; + if steps > 0.0 && !fits(&shifts(steps * unit)) { + steps -= 1.0; + } + shifts(steps * unit) + } + }; let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); for (&i, &k) in idx.iter().zip(&rows) { ft.lines[i].baseline += shift[k]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b94d94000..0f7b54da2 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2291,7 +2291,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; @@ -2384,6 +2384,57 @@ fn vertical_justification_keeps_earlier_descenders_inside() { assert!((last - area.y1).abs() < 1e-6, "Justify: last baseline at {last}, text area at {}", area.y1); } +/// With Align to Baseline Grid, Center and Bottom move the lines by whole grid steps, so every +/// line stays on the grid: Bottom puts the last baseline on the lowest grid line above the bottom +/// inset, and Center on the grid line nearest the centered place. Justify keeps the first and last +/// lines on the grid and spreads the lines between them. +#[test] +fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + let compose_with = |mode: VerticalJustification, align: GridAlign| { + let mut area = Rect::ZERO; + let (lines, grid) = grid_doc("One\nTwo\nThree", ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = mode; + }); + (area, lines.iter().map(|l| l.baseline).collect::>(), grid) + }; + let (area, top, grid) = compose_with(Top, GridAlign::AllLines); + let inc = grid.1; + assert_eq!(top.len(), 3); + assert!(top.iter().all(|&b| on_grid(b, grid)), "Top: {top:?}"); + assert!(!on_grid(area.y1, grid), "the bottom inset is between grid lines: {area:?}"); + + let (_, bottom, _) = compose_with(Bottom, GridAlign::AllLines); + assert!(bottom.iter().all(|&b| on_grid(b, grid)), "Bottom keeps every line on the grid: {bottom:?}"); + let last = bottom[2]; + assert!(last <= area.y1 + 1e-6 && last > area.y1 - inc, "Bottom: last baseline {last} on the lowest grid line above {}", area.y1); + assert!((bottom[1] - bottom[0] - (top[1] - top[0])).abs() < 1e-6, "Bottom keeps the leading"); + + let (_, center, _) = compose_with(Center, GridAlign::AllLines); + assert!(center.iter().all(|&b| on_grid(b, grid)), "Center keeps every line on the grid: {center:?}"); + let shift = center[0] - top[0]; + let ideal = (area.y1 - top[2]) / 2.0; + assert!(shift > 1.0 && (shift - ideal).abs() <= inc / 2.0 + 1e-6, "Center: moved {shift}, centered at {ideal}"); + assert!(center[2] <= area.y1 + 1e-6); + + let (_, justify, _) = compose_with(Justify, GridAlign::AllLines); + assert!((justify[0] - top[0]).abs() < 1e-6, "Justify keeps the first baseline: {justify:?}"); + assert!(on_grid(justify[2], grid), "Justify keeps the last line on the grid: {justify:?}"); + assert!(justify[2] <= area.y1 + 1e-6 && justify[2] > area.y1 - inc, "Justify: last baseline {} near {}", justify[2], area.y1); + assert!((justify[1] - justify[0] - (justify[2] - justify[1])).abs() < 1e-6, "Justify spreads the lines evenly: {justify:?}"); + + // First lines only: each paragraph here is one line, so Bottom keeps every line on the grid. + let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); + assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + + // Without grid alignment the last baseline goes down to the bottom inset. + let (_, free, _) = compose_with(Bottom, GridAlign::None); + assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). /// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in From 9f99420e32bbde7baab20d040344c3d99ac82785 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:40:54 -0800 Subject: [PATCH 120/328] Recovery: tests hold the background writer instead of sleeping The timer test now holds the recovery writer at the start of its write through a handshake (`recovery::testing`, behind the engine's `testing` feature), checks that frames and edits go on while the write is held, and fails when the write runs on the interface thread. The engine tests wait for the writer to go idle instead of polling with sleeps. `file.recovery.save` rejects a `background` that is not true or false. --- crates/engine/Cargo.toml | 4 + crates/engine/src/cmd/file/registry.rs | 6 +- crates/engine/src/recovery.rs | 118 ++++++++++++++++++++++++- crates/engine/src/recovery/tests.rs | 70 ++++++++++----- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/tests.rs | 28 ++++-- 6 files changed, 193 insertions(+), 34 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c1c0f1d33..6b6a43a87 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -8,6 +8,10 @@ description = "DesignCraft engine: session, documents, history, selection, comma [lints] workspace = true +[features] +# Recovery-writer handshakes for other crates' tests (`designcraft_engine::recovery::testing`). +testing = [] + [dependencies] craft-print = { workspace = true } craft-docpath = { workspace = true } diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index a9d14892c..df8709f10 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -70,8 +70,12 @@ pub fn specs() -> Vec { cmd!(noundo "file.recovery.save", "Save Recovery Data", [], None, "{dir?, background?} — write every unsaved document to the recovery folder (the app does this on a timer; `background` queues the writes and returns at once) → {saved} or {queued}", always, |s, p| { + let background = match p.get("background") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad("file.recovery.save", "`background` must be true or false"))?, + }; let dir = recovery_dir(s, p, FolderAccess::Write)?; - if p.get("background").and_then(Value::as_bool).unwrap_or(false) { + if background { return Ok(json!({"queued": crate::recovery::start_tracked(s, &dir)?})); } Ok(json!({"saved": crate::recovery::save_tracked(s, &dir)?})) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index a84034fb7..420d1795f 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -679,6 +679,8 @@ struct Written { /// document was saved, reverted or closed since the write started: its snapshot is then dropped /// instead of published, so a crash cannot offer back a copy older than the saved file. fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { + #[cfg(any(test, feature = "testing"))] + testing::gate(&entry.dir); let (doc, meta) = files(&entry.dir, entry.uid); let published = publish_recovery_written( &doc, @@ -812,7 +814,7 @@ pub(crate) fn finished(_s: &mut Session) -> Finished { mod worker { use std::collections::BTreeSet; use std::sync::mpsc::{Receiver, Sender}; - use std::sync::{Mutex, OnceLock}; + use std::sync::{Condvar, Mutex, OnceLock}; use super::{Path, PathBuf, Result, Snapshot, write_snapshot}; @@ -834,6 +836,8 @@ mod worker { /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, + /// Notified each time a write finishes and leaves `running`. + idle: Condvar, } static WRITER: OnceLock> = OnceLock::new(); @@ -851,6 +855,16 @@ mod worker { if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.remove(&key); } + self.idle.notify_all(); + } + + /// Block until no write is queued or running. + #[cfg(any(test, feature = "testing"))] + pub(super) fn wait_until_idle(&self) { + let mut running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while !running.is_empty() { + running = self.idle.wait(running).unwrap_or_else(std::sync::PoisonError::into_inner); + } } /// Do not publish the snapshot being written for `dir`/`uid`: the document was saved, @@ -898,6 +912,7 @@ mod worker { done: Mutex::new(done_rx), running: Mutex::new(BTreeSet::new()), cancelled: Mutex::new(BTreeSet::new()), + idle: Condvar::new(), }) }) .as_ref() @@ -959,6 +974,107 @@ mod worker { } } +/// Handshakes for tests of the recovery writer, in this crate and, with the `testing` feature, in +/// the app's: hold a write at its start, and wait for the writer to finish. +#[cfg(any(test, feature = "testing"))] +pub mod testing { + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc::{Receiver, Sender}; + use std::sync::{Arc, Mutex, PoisonError}; + use std::thread::ThreadId; + + struct Gate { + dir: PathBuf, + holder: ThreadId, + entered: Sender<()>, + go: Receiver<()>, + ran_on_holder: Arc, + } + + static GATE: Mutex> = Mutex::new(None); + + /// The next recovery write into one folder, held at its start until this is released or + /// dropped. + pub struct HeldWrite { + entered: Receiver<()>, + go: Option>, + ran_on_holder: Arc, + } + + /// Hold the next recovery write into `dir`. A write on another thread waits before it writes + /// anything; a write on the calling thread does not wait, and [`HeldWrite::ran_here`] reports it. + pub fn hold_next_write(dir: &Path) -> HeldWrite { + let (entered_tx, entered) = std::sync::mpsc::channel(); + let (go, go_rx) = std::sync::mpsc::channel(); + let ran_on_holder = Arc::new(AtomicBool::new(false)); + let gate = Gate { + dir: dir.to_path_buf(), + holder: std::thread::current().id(), + entered: entered_tx, + go: go_rx, + ran_on_holder: ran_on_holder.clone(), + }; + *GATE.lock().unwrap_or_else(PoisonError::into_inner) = Some(gate); + HeldWrite { entered, go: Some(go), ran_on_holder } + } + + impl HeldWrite { + /// The held write ran on the thread that called [`hold_next_write`]. + pub fn ran_here(&self) -> bool { + self.ran_on_holder.load(Ordering::SeqCst) + } + + /// Block until the write has reached the gate. + pub fn wait_until_held(&self) { + let _ = self.entered.recv(); + } + + /// Let the held write go on. + pub fn release(mut self) { + if let Some(go) = self.go.take() { + let _ = go.send(()); + } + } + } + + impl Drop for HeldWrite { + fn drop(&mut self) { + // A gate no write reached is removed, so it cannot hold a later test's write. + let mut slot = GATE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.ran_on_holder, &self.ran_on_holder)) { + *slot = None; + } + } + } + + /// Called at the start of every recovery write. + pub(super) fn gate(dir: &Path) { + let gate = { + let mut slot = GATE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|gate| gate.dir == dir) { slot.take() } else { None } + }; + let Some(gate) = gate else { return }; + if std::thread::current().id() == gate.holder { + gate.ran_on_holder.store(true, Ordering::SeqCst); + let _ = gate.entered.send(()); + return; + } + let _ = gate.entered.send(()); + // A dropped `HeldWrite` closes the channel, which also lets the write go on. + let _ = gate.go.recv(); + } + + /// Block until the background writer has no write queued or running. + pub fn wait_until_idle() { + // Nothing is written in the background on the web. + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = super::worker::started() { + w.wait_until_idle(); + } + } +} + #[cfg(not(target_arch = "wasm32"))] fn secure_recovery_dir(dir: &Path) -> Result { match std::fs::symlink_metadata(dir) { diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index c1a742a31..3b7c2303d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -135,20 +135,49 @@ fn background() -> std::sync::MutexGuard<'static, ()> { BACKGROUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } -/// Poll `file.recovery.progress` until the background writer has nothing left, as the app does at -/// the end of a frame. +/// Wait for the background writer to have nothing left, then read `file.recovery.progress` as the +/// app does at the end of a frame. fn finished_writes(s: &mut Session) -> usize { - let mut written = 0; - for _ in 0..1200 { - let v = s.execute("file.recovery.progress", &json!({})).unwrap(); - assert_eq!(v["errors"], json!([]), "{v}"); - written += v["written"].as_u64().unwrap_or(0) as usize; - if !v["busy"].as_bool().unwrap_or(false) { - return written; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - panic!("the background writer did not finish"); + testing::wait_until_idle(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["errors"], json!([]), "{v}"); + assert_eq!(v["busy"], false, "{v}"); + v["written"].as_u64().unwrap_or(0) as usize +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_save_returns_while_its_write_is_held() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let (file, _) = files(dir.path(), uid); + let held = testing::hold_next_write(dir.path()); + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert!(!held.ran_here(), "the write ran on the calling thread"); + assert_eq!(queued["queued"], 1, "{queued}"); + // The writer thread is stopped at the start of the write, and the session goes on. + held.wait_until_held(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["busy"], true, "{v}"); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + assert!(!file.exists(), "nothing is published while the write is held"); + held.release(); + assert_eq!(finished_writes(&mut s), 1); + assert!(file.exists()); + discard(dir.path(), uid); +} + +#[test] +fn a_background_save_rejects_a_background_that_is_not_true_or_false() { + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let err = s.execute("file.recovery.save", &json!({"background": "yes"})).unwrap_err(); + assert!(err.to_string().contains("`background` must be true or false"), "{err}"); + assert!(list(dir.path()).is_empty(), "nothing was written"); } #[test] @@ -242,17 +271,10 @@ fn a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove( std::fs::create_dir(&metadata).unwrap(); let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); assert_eq!(queued["queued"], 1, "{queued}"); - let mut reported = None; - for _ in 0..1200 { - let v = s.execute("file.recovery.progress", &json!({})).unwrap(); - if let Some(first) = v["errors"].as_array().and_then(|errors| errors.first()) { - reported = first.as_str().map(str::to_string); - } - if !v["busy"].as_bool().unwrap_or(false) { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } + testing::wait_until_idle(); + let v = s.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["busy"], false, "{v}"); + let reported = v["errors"].as_array().and_then(|errors| errors.first()).and_then(Value::as_str).map(str::to_string); let reported = reported.expect("the metadata failure is reported"); assert!(reported.contains(&metadata.display().to_string()), "{reported}"); assert!(document.exists(), "the primary landed"); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 6b08420a9..f7fe65d8e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -44,6 +44,7 @@ zip = { workspace = true } # Headless (offscreen wgpu) rendering of the whole window for UI screenshots: `examples/ui_shot.rs`. egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } designcraft-fonts = { workspace = true, features = ["testing"] } +designcraft-engine = { workspace = true, features = ["testing"] } [build-dependencies] serde_json = { workspace = true } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 17cc20d28..8f2eef43d 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -151,18 +151,30 @@ fn the_recovery_timer_writes_off_the_interface_thread() { app.last_recovery = -1.0e9; let uid = app.session.documents()[0].uid; let entry = dir.path().join(format!("{uid}.designcraft")); - let mut written = false; - for _ in 0..600 { + // The writer stops at the start of the write until the test lets it go on, so a frame that + // waited for the write would never return. + let held = designcraft_engine::recovery::testing::hold_next_write(dir.path()); + // egui discards a pass that needs another layout; the timer runs in the first pass it keeps. + for _ in 0..10 { shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); - // The timer fired and the write finished: the file is there and nothing is still queued. - if entry.exists() && !app.recovery_writing { - written = true; + if app.last_recovery > 0.0 { break; } - std::thread::sleep(std::time::Duration::from_millis(5)); } - assert!(written, "the timer's background write published the document"); - assert!(app.last_recovery > 0.0, "the timer restarted its interval"); + assert!(app.last_recovery > 0.0, "the timer fired and restarted its interval"); + assert!(!held.ran_here(), "the timer wrote the recovery data on the interface thread"); + assert!(app.recovery_writing, "the timer queued the write"); + held.wait_until_held(); + // While the write is held, the interface keeps drawing frames and taking edits. + app.run("frame.create", json!({"rect": [20, 20, 80, 80]})).unwrap(); + shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); + assert!(app.recovery_writing, "the write is still held"); + assert!(!entry.exists(), "nothing is published while the write is held"); + held.release(); + designcraft_engine::recovery::testing::wait_until_idle(); + shot_frame(&mut app, &ctx, egui::vec2(1400.0, 900.0)); + assert!(!app.recovery_writing, "the frame after the write took its result"); + assert!(entry.exists(), "the timer's background write published the document"); // The checkpoint is the document's: saving it removes the recovery entry. let saved = dir.path().join("saved.designcraft"); app.run("file.saveAs", json!({"path": saved.to_string_lossy()})).unwrap(); From ee69d5ac390f024afdd68995ba660ed514fbc9d5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:42:03 -0800 Subject: [PATCH 121/328] Preflight: the worker keeps its compositions out of the interface thread's cache The worker checks the document state it was given, which is often one edit behind the interface. It composed that older state into the shared composition cache, replacing the interface thread's composition of the current state, so the next frame composed the edited story again (about 14 ms per edit for a 10-page story). Cache::over makes a cache that uses another cache's compositions of the same state and keeps whatever it composes to itself. The worker checks with one over the interface thread's cache, keeps it for the next check of the same document, and drops it after a minute without jobs. With no active document, the job waiting for a busy worker is dropped, so it no longer keeps a closed document in memory until another document opens. --- crates/compose/src/cache.rs | 35 ++++++++++++ crates/compose/src/tests.rs | 19 +++++++ crates/ui-egui/src/preflight_worker.rs | 56 +++++++++++++++++--- crates/ui-egui/src/preflight_worker/tests.rs | 47 ++++++++++++++++ 4 files changed, 149 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..9cf96e497 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -62,6 +62,9 @@ pub struct Cache { /// The composition each story (page-independent key) had before its latest recomposition, /// with the story revision it was composed from (repaint only the frames an edit changed). previous: Mutex, Arc)>>, + /// A cache this one reads without writing to: a composition or index found there for the same + /// inputs is used, and anything composed is kept here only. + base: Option>, } /// A signature's hash, standing in for it in another story's signature. @@ -104,6 +107,18 @@ impl Cache { Self::default() } + /// An empty cache that also uses what `base` holds for the same inputs, and never changes + /// `base`. A reader of an older state of the document composes that state here instead of + /// replacing the compositions of the current state in `base`. + pub fn over(base: Arc) -> Self { + Cache { base: Some(base), ..Self::default() } + } + + /// The cache given to [`Cache::over`]. + pub fn base(&self) -> Option<&Arc> { + self.base.as_ref() + } + /// The composed story, from cache or freshly composed. `page` is the absolute page a /// parent-page item is shown on (its page number markers and variables are that page's), or /// `None` for a story's own frames. Pages are identified by index, not name: names repeat when @@ -255,6 +270,14 @@ impl Cache { return e.out.clone(); } } + if let Some(base) = &self.base { + let g = base.map.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(e) = g.0.get(&key) + && e.sig == sig + { + return e.out.clone(); + } + } // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); @@ -368,6 +391,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.xrefs.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(crate::xref::XrefIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.xrefs.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r @@ -381,6 +410,12 @@ impl Cache { { return r.clone(); } + if let Some(base) = &self.base + && let Some((s, r)) = &*base.running.lock().unwrap_or_else(PoisonError::into_inner) + && *s == sig + { + return r.clone(); + } let r = Arc::new(RunningIndex::build(doc, &|sid| self.get(doc, sid, None))); *self.running.lock().unwrap_or_else(PoisonError::into_inner) = Some((sig, r.clone())); r diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..900bced97 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8156,6 +8156,25 @@ fn cache_recomposes_when_the_baseline_grid_changes() { assert!((la.baseline - lb.baseline).abs() > 1.0, "{} {}", la.baseline, lb.baseline); } +/// A cache over another uses its compositions of the same state, and composes an older state +/// without replacing the other cache's composition of the current one. +#[test] +fn a_cache_over_another_reads_it_without_writing_to_it() { + let (old, sid, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), ParaAttrs::default()); + let mut new = old.clone(); + new.story_mut(sid).unwrap().rev += 1; + let base = Arc::new(Cache::new()); + let current = base.get(&new, sid, None); + let reader = Cache::over(Arc::clone(&base)); + assert!(reader.base().is_some_and(|b| Arc::ptr_eq(b, &base))); + assert!(Arc::ptr_eq(&reader.get(&new, sid, None), ¤t), "the base's composition is used"); + let earlier = reader.get(&old, sid, None); + assert!(!Arc::ptr_eq(&earlier, ¤t)); + assert!(Arc::ptr_eq(&reader.get(&old, sid, None), &earlier), "kept in the reader"); + assert!(Arc::ptr_eq(&base.get(&new, sid, None), ¤t), "the base keeps the current state's composition"); + assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index 6abb67e0c..ddcdffe68 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -40,6 +40,10 @@ const MAX_WORKERS: usize = 4; // this long. #[cfg(not(target_arch = "wasm32"))] const RETRY_AFTER: Duration = Duration::from_secs(30); +// A worker given no job for this long drops its own compositions, which keep the document they +// were made from alive after it closes. +#[cfg(not(target_arch = "wasm32"))] +const FORGET_AFTER: Duration = Duration::from_secs(60); /// A state of a document as a check sees it: which document, which state of it with which /// compositions (a font reload replaces the cache and bumps the revision), and where it is saved @@ -118,7 +122,17 @@ pub(crate) fn issues(app: &mut DesignApp, ctx: &egui::Context) -> Option Option>> { - let (of, doc) = Checked::new(app)?; + let Some((of, doc)) = Checked::new(app) else { + // A job waiting for the worker would keep a closed document alive. + #[cfg(not(target_arch = "wasm32"))] + { + app.preflight.worker.waiting = None; + for done in app.preflight.worker.poll() { + app.preflight.keep(done); + } + } + return None; + }; let cache = Arc::clone(&app.session.cache); let state = &mut app.preflight; #[cfg(not(target_arch = "wasm32"))] @@ -355,13 +369,17 @@ fn spawn(ctx: egui::Context, live: &Arc) -> Opti .name("designcraft-preflight".into()) .spawn(move || { let _alive = alive; - while let Ok(job) = jobs.recv() { - let started = Instant::now(); - let issues = check_document(&job.doc, &job.cache, job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); - let found = Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 }; - // The checked state isn't kept alive by its check once the result is sent. - drop(job.doc); - if done_tx.send(found).is_err() { + let mut own = None; + loop { + let job = match jobs.recv_timeout(FORGET_AFTER) { + Ok(job) => job, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + own = None; + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + }; + if done_tx.send(check(&mut own, job)).is_err() { break; } ctx.request_repaint(); @@ -371,6 +389,28 @@ fn spawn(ctx: egui::Context, live: &Arc) -> Opti Some((tx, rx)) } +/// Checks `job` with the worker's own compositions, `own`. +#[cfg(not(target_arch = "wasm32"))] +fn check(own: &mut Option<(u64, Cache)>, job: Job) -> Found { + let started = Instant::now(); + let issues = check_document(&job.doc, reader(own, &job), job.of.path.as_deref().map(std::path::Path::new), MIN_PPI); + // The checked state isn't kept alive by its check once the result is sent. + drop(job.doc); + Found { of: job.of, issues: Arc::new(issues), took: started.elapsed(), asked_at: 0.0 } +} + +/// The cache a worker checks `job` with: a cache over the interface thread's cache, which the +/// worker reads and never writes. The worker keeps it for the next job of the same document over +/// the same cache. +#[cfg(not(target_arch = "wasm32"))] +fn reader<'a>(own: &'a mut Option<(u64, Cache)>, job: &Job) -> &'a Cache { + let reuse = own.as_ref().is_some_and(|(uid, c)| *uid == job.of.uid && c.base().is_some_and(|b| Arc::ptr_eq(b, &job.cache))); + if !reuse { + *own = None; + } + &own.get_or_insert_with(|| (job.of.uid, Cache::over(Arc::clone(&job.cache)))).1 +} + /// Starts the worker in a test, where checks otherwise run on the interface thread. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs index f437a4174..9cc9a394b 100644 --- a/crates/ui-egui/src/preflight_worker/tests.rs +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -212,6 +212,53 @@ fn a_blocked_check_of_another_document_is_superseded() { assert!(jobs.try_recv().is_ok(), "queued on the same worker"); } +/// A worker checking an older state of the document leaves the interface thread's composition of +/// the current state in its cache. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_check_of_an_older_state_keeps_the_current_compositions() { + let (mut app, id) = overset_app(); + let (older, _) = Checked::new(&app).unwrap(); + let older_doc = Arc::clone(&app.session.active().unwrap().doc); + app.run("transform.move", json!({"ids": [id], "dx": 1.0, "dy": 0.0})).unwrap(); + let doc = Arc::clone(&app.session.active().unwrap().doc); + let sid = *doc.stories.keys().next().unwrap(); + let cache = Arc::clone(&app.session.cache); + let current = cache.get(&doc, sid, None); + let mut own = None; + let found = super::check(&mut own, super::Job { of: older, doc: Arc::clone(&older_doc), cache: Arc::clone(&cache) }); + assert_eq!(found.issues.iter().filter(|i| i.severity == "error").count(), 1); + assert!(Arc::ptr_eq(&cache.get(&doc, sid, None), ¤t), "the current state's composition is kept"); + // The worker keeps its compositions for the next check of the document over the same cache. + let earlier = own.as_ref().unwrap().1.get(&older_doc, sid, None); + let (of, doc) = Checked::new(&app).unwrap(); + super::check(&mut own, super::Job { of, doc, cache: Arc::clone(&cache) }); + assert!(Arc::ptr_eq(&own.as_ref().unwrap().1.get(&older_doc, sid, None), &earlier), "kept for the next check"); + let reloaded = Arc::new(designcraft_compose::Cache::new()); + let (of, doc) = Checked::new(&app).unwrap(); + super::check(&mut own, super::Job { of, doc, cache: Arc::clone(&reloaded) }); + assert!(own.as_ref().unwrap().1.base().is_some_and(|b| Arc::ptr_eq(b, &reloaded)), "a new cache after a font reload"); +} + +/// Closing the last document drops the job waiting for a busy worker, which holds that document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn closing_the_last_document_drops_the_waiting_job() { + let (mut app, id) = overset_app(); + let ctx = egui::Context::default(); + let (_jobs, _done) = stalled_worker(&mut app); + for dx in [1.0, -1.0] { + app.run("transform.move", json!({"ids": [id], "dx": dx, "dy": 0.0})).unwrap(); + assert!(super::issues(&mut app, &ctx).is_none()); + } + assert!(app.preflight.worker.waiting.is_some()); + app.run("file.close", json!({})).unwrap(); + assert!(app.session.active().is_none()); + assert!(super::issues(&mut app, &ctx).is_none()); + assert!(app.preflight.worker.waiting.is_none(), "the waiting job is dropped"); + assert!(app.preflight.found.is_empty()); +} + /// A result for another document keeps the active document's issues, and the issues of at most /// `MAX_DOCUMENTS` documents are kept. #[cfg(not(target_arch = "wasm32"))] From 9c4c3730ab5425eed3177e900cb4cb871d65a776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:42:30 -0800 Subject: [PATCH 122/328] CMYK view: convert the blended inks to screen colours on the render threads In the CMYK blend space view (Proof Colors off) every render converted each pixel of the ink passes' area from the blended inks to a screen colour on the calling thread, through a 16-entry lookup per pixel. With render threads it now converts bands of rows on that many threads at once, at least 32 rows a band. The colours are the same; the Wasm build and single-threaded renders convert on one thread as before. --- crates/render/src/blendspace.rs | 93 +++++++++++++++++++++++++++++---- crates/render/src/driver.rs | 2 + crates/render/src/lib.rs | 3 ++ 3 files changed, 88 insertions(+), 10 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 449410c59..1d992c6fd 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -12,6 +12,7 @@ use crate::{Frame, Placed, RenderOptions, Rendered, Renderer}; use designcraft_color::BlendMode as DcBlend; use designcraft_doc::{Document, Item, SpreadRef}; use designcraft_geom::{Affine, Rect, Shape}; +use vello_cpu::color::PremulRgba8; use vello_cpu::{RenderContext, peniko}; /// At most one viewport, capped at 64 MiB. The snapshot shares the document's large Arcs; @@ -284,6 +285,58 @@ fn srgb_in(table: &[[f32; 3]], cmyk: [f32; 4]) -> [f32; 3] { out } +/// Rows of the ink passes' area one conversion thread takes at least. +const MIN_BAND_ROWS: usize = 32; + +/// The blended inks, the C/M/Y complements in `cmy` and the K complement in `black` (`width` +/// pixels a row), converted to screen colours in `cmy`. With render threads, bands of rows are +/// converted on that many threads at once. Returns the number of bands. +fn inks_to_screen(cmy: &mut [PremulRgba8], black: &[PremulRgba8], width: usize, rich_black: bool, threads: u16) -> usize { + let table = srgb_table(); + let convert = |cmy: &mut [PremulRgba8], black: &[PremulRgba8]| { + for (c, k) in cmy.iter_mut().zip(black) { + if c.a == 0 { + continue; + } + let a = c.a as f32; + let inks = [1.0 - c.r as f32 / a, 1.0 - c.g as f32 / a, 1.0 - c.b as f32 / a, 1.0 - k.r as f32 / a]; + let rgb = if rich_black && inks[0..3].iter().all(|v| *v <= 1e-3) && inks[3] >= 0.999 { [0.0; 3] } else { srgb_in(&table, inks) }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a).round() as u8); + (c.r, c.g, c.b) = (r, g, b); + } + }; + let rows = cmy.len().checked_div(width).unwrap_or(0); + let bands = usize::from(threads).min(rows / MIN_BAND_ROWS).max(1); + if cfg!(target_arch = "wasm32") || bands == 1 { + convert(cmy, black); + return 1; + } + let chunk = rows.div_ceil(bands) * width; + let mut parts: Vec<(&mut [PremulRgba8], &[PremulRgba8])> = cmy.chunks_mut(chunk).zip(black.chunks(chunk)).collect(); + let convert = &convert; + let mut failed = Vec::new(); + std::thread::scope(|s| { + let mut each = parts.iter_mut().enumerate(); + let first = each.next(); + for (i, (c, k)) in each { + if let Err(e) = std::thread::Builder::new().spawn_scoped(s, move || convert(c, k)) { + log::warn!("CMYK view: a conversion thread did not start ({e})"); + failed.push(i); + } + } + if let Some((_, (c, k))) = first { + convert(c, k); + } + }); + // A band whose thread did not start is converted here. + for i in failed { + if let Some((c, k)) = parts.get_mut(i) { + convert(c, k); + } + } + bands +} + impl Renderer { /// The view pixels the spread's transparency can change: the union of its transparent /// objects (opacity, blend, effects, knockout, also nested or anchored) with their effects' @@ -413,16 +466,10 @@ impl Renderer { crate::PLATE.with(|p| p.set(f.opts.plate)); self.stats.items = (self.stats.items - stats.items) / 2 + stats.items; self.stats.glyphs = (self.stats.glyphs - stats.glyphs) / 2 + stats.glyphs; - let table = srgb_table(); - for (c, k) in cmy.data_mut().iter_mut().zip(black.data()) { - if c.a == 0 { - continue; - } - let a = c.a as f32; - let inks = [1.0 - c.r as f32 / a, 1.0 - c.g as f32 / a, 1.0 - c.b as f32 / a, 1.0 - k.r as f32 / a]; - let rgb = if f.opts.rich_black && inks[0..3].iter().all(|v| *v <= 1e-3) && inks[3] >= 0.999 { [0.0; 3] } else { srgb_in(&table, inks) }; - let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * a).round() as u8); - (c.r, c.g, c.b) = (r, g, b); + let _bands = inks_to_screen(cmy.data_mut(), black.data(), usize::from(aw), f.opts.rich_black, threads); + #[cfg(test)] + { + self.cmyk_convert_bands = _bands; } ctx.set_transform(Affine::translate((area.x0, area.y0))); ctx.set_paint(vello_cpu::Image { image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(cmy)), sampler: peniko::ImageSampler::default() }); @@ -669,6 +716,32 @@ mod tests { } } + /// With render threads, the ink passes' colours are converted in that many bands of rows at + /// once, each band by its own thread, and the result is the same as converting on one thread. + #[test] + fn ink_colours_convert_in_a_band_per_render_thread() { + let mut doc = document(); + rectangle(&mut doc, SpreadRef::Doc(0), Rect::new(-20.0, -5.0, 180.0, 125.0), "C=100 M=0 Y=0 K=0", DcBlend::Multiply); + let render = |threads: u16| { + let mut renderer = Renderer::new(); + renderer.threads = threads; + let image = renderer.render( + &doc, + &Cache::new(), + &[Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }], + (400, 300), + Affine::scale(2.0) * Affine::translate((30.0, 10.0)), + &RenderOptions { blend_space_view: true, background: Some([180, 180, 180, 255]), ..Default::default() }, + ); + (image, renderer.cmyk_convert_bands) + }; + let (one, bands) = render(0); + assert_eq!(bands, 1); + let (four, bands) = render(4); + assert_eq!(bands, 4, "a band per render thread"); + assert_eq!(four.pixels, one.pixels); + } + #[test] fn cmyk_nonseparable_modes_use_the_existing_rgb_approximation() { let mut doc = document(); diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index a5dd2b86b..7230644a6 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -21,6 +21,8 @@ impl Renderer { cmyk_pass_pixels: 0, #[cfg(test)] cmyk_pass_items: 0, + #[cfg(test)] + cmyk_convert_bands: 0, threads: default_threads(), stats: FrameStats::default(), } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 25207b248..9f790c9f4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -163,6 +163,9 @@ pub struct Renderer { /// Items the last ink pass drew (tests). #[cfg(test)] cmyk_pass_items: usize, + /// Bands of rows the last ink passes' colours were converted in (tests). + #[cfg(test)] + cmyk_convert_bands: usize, pub threads: u16, pub stats: FrameStats, } From 229abafbe60e07574b37b9bf826b98670c765ccf Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:43:53 +0000 Subject: [PATCH 123/328] Apply review fixes - crates/render/src/driver.rs - crates/render/src/fx.rs --- crates/render/src/driver.rs | 2 +- crates/render/src/fx.rs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index b9568a595..cee99590c 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -46,6 +46,7 @@ impl Renderer { let (width, height) = size; RICH_BLACK.with(|r| r.set(opts.rich_black)); PLATE.with(|p| p.set(opts.plate)); + self.kept.begin(doc); if let Some(hit) = self.cmyk_view.as_ref().filter(|entry| entry.matches(doc, spreads, width, height, view, opts, self.threads)) { let image = hit.image(); self.stats = hit.stats(); @@ -90,7 +91,6 @@ impl Renderer { self.stats = FrameStats::default(); self.stories.clear(); self.glyphs.tick(); - self.kept.begin(doc); if let Some(bg) = opts.background { ctx.set_transform(Affine::IDENTITY); ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 44513c3ac..5248bf9ba 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -513,7 +513,8 @@ impl Renderer { return; } let [a, b, c, d, e, g] = (f.view * xf).as_coeffs(); - let (linear, anchor) = ([a, b, c, d], Vec2::new(e, g)); + let [va, vb, vc, vd, _, _] = f.view.as_coeffs(); + let (linear, anchor) = ([a, b, c, d, va, vb, vc, vd], Vec2::new(e, g)); let plate = crate::PLATE.with(std::cell::Cell::get); let rich_black = crate::color::RICH_BLACK.with(std::cell::Cell::get); let key = (it.id, page, look.slot, plate); @@ -606,8 +607,8 @@ struct Look { struct Kept { /// The object, with the transform it had. item: Item, - /// The linear part of the object's spread → device transform. - linear: [f64; 4], + /// The linear parts of the object's spread → device transform and of the view (the effect offset turns with the view). + linear: [f64; 8], /// The device position of the object's origin. anchor: Vec2, look: Look, From 27963d6d055133820ba7d6326d171822cd811dc0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:45:30 -0800 Subject: [PATCH 124/328] Justification: the dialog sets Auto Leading and Single Word Justification Type > Justification and Paragraph Style Options > Justification now show Auto Leading (0% to 500% of the type size) and Single Word Justification (Align Left, Align Center, Align Right, Full Justify). Both fields show the selected paragraphs' values, or blank where they differ, and OK writes autoLeading and singleWordJustify only when they were edited. An Auto Leading outside 0% to 500% keeps the dialog open with the reason. --- crates/ui-egui/src/dialogs.rs | 49 ++++++++++++- crates/ui-egui/src/dialogs/tests.rs | 107 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/cs.rs | 3 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/hu.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/pl.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/ru.rs | 3 + crates/ui-egui/src/i18n/sv.rs | 2 + crates/ui-egui/src/i18n/table.rs | 5 ++ crates/ui-egui/src/i18n/uk.rs | 3 + docs/typography-parity.md | 2 +- 16 files changed, 191 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..6664fc349 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7689,7 +7689,7 @@ fn shown_rule(d: &Dialog, prefix: &str, which: &str, current: &Value) -> Value { } /// The paragraph attributes of the Justification controls. -pub const JUSTIFY_ATTRS: [&str; 12] = [ +pub const JUSTIFY_ATTRS: [&str; 14] = [ "wordSpaceMin", "wordSpaceDesired", "wordSpaceMax", @@ -7699,6 +7699,8 @@ pub const JUSTIFY_ATTRS: [&str; 12] = [ "glyphScaleMin", "glyphScaleDesired", "glyphScaleMax", + "autoLeading", + "singleWordJustify", "composer", "kashidas", "koreanCharBreaks", @@ -7711,9 +7713,29 @@ const JUSTIFY_ROWS: [(&str, &str, (f64, f64)); 3] = [ ("Glyph Scaling", "glyphScale", (50.0, 200.0)), ]; +/// The allowed Auto Leading, in percent of the type size. +const AUTO_LEADING_RANGE: (f64, f64) = (0.0, 500.0); + +/// The Single Word Justification choices: (attribute value, label). +const SINGLE_WORD_CHOICES: [(&str, &str); 4] = + [("left", "Align Left"), ("center", "Align Center"), ("right", "Align Right"), ("fullyJustified", "Full Justify")]; + /// Checks the edited spacing values: each within its range, and minimum ≤ desired ≤ maximum -/// (values left mixed are not compared). +/// (values left mixed are not compared); an edited Auto Leading within its range, and an edited +/// Single Word Justification one of its choices. fn check_justification(d: &Dialog, prefix: &str, current: &Value) -> Result<(), String> { + if let Some(v) = d.fields.get(&format!("{prefix}autoLeading")) { + let (lo, hi) = AUTO_LEADING_RANGE; + let pct = v.as_f64().map(|x| x * 100.0).filter(|x| x.is_finite()).ok_or("Justification: Auto Leading is not a number")?; + if !(lo..=hi).contains(&pct) { + return Err(format!("Justification: Auto Leading must be between {lo}% and {hi}%")); + } + } + if let Some(v) = d.fields.get(&format!("{prefix}singleWordJustify")) + && !SINGLE_WORD_CHOICES.iter().any(|(k, _)| v.as_str() == Some(k)) + { + return Err(format!("Justification: Single Word Justification cannot be {v}")); + } for (label, stem, (lo, hi)) in JUSTIFY_ROWS { let mut edited = false; let mut known = Vec::new(); @@ -7916,6 +7938,29 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu } ui.end_row(); } + crate::rtl::label(ui, crate::i18n::tr(lang, "Auto Leading:")); + let auto = cur(d, "autoLeading").as_f64().map(|x| x * 100.0); + if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{prefix}autoLeading"), auto, "%", 60.0, 0)).inner { + d.fields.insert(format!("{prefix}autoLeading"), json!(n / 100.0)); + } + ui.end_row(); + let single_label = crate::rtl::label(ui, crate::i18n::tr(lang, "Single Word Justification:")); + let single = cur(d, "singleWordJustify"); + // Mixed (null) shows blank until a choice is made. + let shown = SINGLE_WORD_CHOICES.iter().find(|(k, _)| single.as_str() == Some(k)).map_or("", |(_, label)| label); + craft_ui::ComboBox::from_id_salt(("singleWordJustify", prefix)) + .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, shown))) + .width(130.0) + .show_ui(ui, |ui| { + for (v, label) in SINGLE_WORD_CHOICES { + if ui.selectable_label(single.as_str() == Some(v), crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() { + d.fields.insert(format!("{prefix}singleWordJustify"), json!(v)); + } + } + }) + .response + .labelled_by(single_label.id); + ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Composer:")); let composer = cur(d, "composer"); // Mixed (null) selects neither; a Japanese composer keeps its kind. diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..1343b30d7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1130,6 +1130,113 @@ fn justification_dialog_leaves_mixed_fields_alone_and_refuses_bad_values() { } } +/// The Justification dialog shows Auto Leading and Single Word Justification, OK sets them on the +/// selected paragraph as one undo step, bad values keep the dialog open, and both values survive +/// saving and opening the native file and an IDML export. +#[test] +fn justification_dialog_sets_auto_leading_and_single_word_justification() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, story) = two_paragraphs(); + app.run("app.justificationDialog", json!({})).unwrap(); + let d = app.ui.dialog.clone().unwrap(); + let current = d.fields["current"].clone(); + assert_eq!((current["autoLeading"].clone(), current["singleWordJustify"].clone()), (json!(1.2), json!("fullyJustified"))); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("justification_single_word_fonts"); + if ui.data(|d| d.get_temp::(key)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(key, true)); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + assert!(h.query_by_label("Auto Leading:").is_some()); + assert!(h.query_by_label("Single Word Justification:").is_some()); + // The dropdown shows the paragraph's Full Justify; pick Align Center. + h.get_by(|n| n.role() == egui::accesskit::Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + h.get_by_label("Align Center").click(); + h.run_steps(3); + let mut app = std::mem::replace(h.state_mut(), DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())); + drop(h); + let ctx = egui::Context::default(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["singleWordJustify"], "center", "the choice is the edit"); + + // Out of range or not a choice: an error, the dialog stays open, nothing changes. + let d = app.ui.dialog.clone().unwrap(); + let before = undo_steps(&app); + let bad = [ + ("autoLeading", json!(5.004)), + ("autoLeading", json!(-0.004)), + ("autoLeading", json!(f64::NAN)), + ("singleWordJustify", json!("leftJustified")), + ]; + for (key, v) in bad { + app.ui.dialog = Some(d.clone()); + app.ui.dialog.as_mut().unwrap().fields.insert(key.into(), v.clone()); + assert!(confirm(&mut app).is_err(), "{key} = {v}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.fields.contains_key("justifyError")), "{key}: the dialog shows why"); + } + assert_eq!(undo_steps(&app), before); + + app.ui.dialog = Some(d); + app.ui.dialog.as_mut().unwrap().fields.insert("autoLeading".into(), json!(1.5)); + draw(&mut app, &ctx); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before + 1, "one undo step"); + let both = |app: &mut DesignApp, story: &Value, at| (para_attr(app, story, at, "autoLeading"), para_attr(app, story, at, "singleWordJustify")); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + assert_eq!(both(&mut app, &story, 4), (json!(1.2), json!("fullyJustified")), "only the selected paragraph"); + + // Both paragraphs selected: the fields that differ show blank, and OK with no edit adds no undo step. + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 7})).unwrap(); + app.run("app.justificationDialog", json!({})).unwrap(); + draw(&mut app, &ctx); + let current = app.ui.dialog.as_ref().unwrap().fields["current"].clone(); + assert_eq!((current["autoLeading"].clone(), current["singleWordJustify"].clone()), (Value::Null, Value::Null)); + let before = undo_steps(&app); + confirm(&mut app).unwrap(); + assert_eq!(undo_steps(&app), before); + + // Saved and opened again, natively and through IDML. + let native = app.run("file.serialize", json!({})).unwrap(); + app.run("file.openBytes", json!({"name": "justify.designcraft", "base64": native["base64"]})).unwrap(); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + let idml = app.run("file.exportIdml", json!({})).unwrap(); + app.run("file.openBytes", json!({"name": "justify.idml", "base64": idml["base64"]})).unwrap(); + let doc = &app.session.doc().unwrap().doc; + let sid = doc.stories.iter().find(|(_, s)| s.text == "One\nTwo").map(|(id, _)| *id).expect("the story comes back"); + let story = serde_json::to_value(sid).unwrap(); + assert_eq!(both(&mut app, &story, 0), (json!(1.5), json!("center"))); + assert_eq!(both(&mut app, &story, 4), (json!(1.2), json!("fullyJustified"))); +} + +/// Paragraph Style Options › Justification sets Auto Leading and Single Word Justification on the +/// style, and refuses an Auto Leading out of range. +#[test] +fn paragraph_style_options_justification_sets_auto_leading_and_single_word_justification() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("style.paragraph.create", json!({"name": "Headline"})).unwrap(); + let ctx = egui::Context::default(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Headline", "section": "justify"}))); + draw(&mut app, &ctx); + app.ui.dialog.as_mut().unwrap().fields.insert("p.autoLeading".into(), json!(6.0)); + assert!(confirm(&mut app).unwrap_err().contains("Auto Leading")); + let style = |app: &DesignApp| app.session.doc().unwrap().doc.styles.para("Headline").unwrap().para.clone(); + assert_eq!(style(&app).auto_leading, None, "nothing saved"); + app.ui.dialog.as_mut().unwrap().fields.insert("p.autoLeading".into(), json!(1.0)); + app.ui.dialog.as_mut().unwrap().fields.insert("p.singleWordJustify".into(), json!("right")); + draw(&mut app, &ctx); + confirm(&mut app).unwrap(); + let para = style(&app); + assert_eq!((para.auto_leading, para.single_word_justify), (Some(1.0), Some(designcraft_doc::Align::Right))); +} + fn command_app(id: &str, fields: Value) -> DesignApp { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields)); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index adf22f4fb..1a75534a5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -611,6 +611,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "في النص العربي المضبوط"), ("Korean Line Breaks:", "فواصل الأسطر الكورية:"), ("Between syllables (not only at spaces)", "بين المقاطع (وليس عند المسافات فقط)"), + ("Auto Leading:", "التباعد التلقائي بين الأسطر:"), + ("Single Word Justification:", "ضبط الكلمة المفردة:"), + ("Full Justify", "ضبط كامل"), ("Minimum Space Before First Footnote:", "أقل مسافة قبل الحاشية الأولى:"), ("Space Between Footnotes:", "المسافة بين الحواشي:"), ("Offset:", "الإزاحة:"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 5310e8d12..31fb1876c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -1185,6 +1185,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "V arabském textu zarovnaném do bloku"), ("Korean Line Breaks:", "Zalomení řádků v korejštině:"), ("Between syllables (not only at spaces)", "Mezi slabikami (nejen u mezer)"), + ("Auto Leading:", "Automatický proklad:"), + ("Single Word Justification:", "Zarovnání jednoho slova:"), + ("Full Justify", "Plné zarovnání"), ("Binding:", "Vazba:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Umístí se nad vybraný text; prázdné pole ho odstraní."), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2e9920126..ce333f489 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1155,6 +1155,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "Im arabischen Blocksatz"), ("Korean Line Breaks:", "Koreanische Zeilenumbrüche:"), ("Between syllables (not only at spaces)", "Zwischen Silben (nicht nur an Leerzeichen)"), + ("Auto Leading:", "Automatischer Zeilenabstand:"), + ("Single Word Justification:", "Ausrichtung einzelner Wörter:"), ("Binding:", "Bindung:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Wird über den ausgewählten Text gesetzt; leer entfernt es."), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..1a63f3fad 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -156,6 +156,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Before", "Előtte"), ("Before Last:", "Az utolsó előtt:"), ("Between syllables (not only at spaces)", "Szótagok között (nem csak szóközöknél)"), + ("Auto Leading:", "Automatikus sorköz:"), + ("Single Word Justification:", "Egyetlen szó igazítása:"), + ("Full Justify", "Teljes sorkizárás"), ("Bevel", "Levágott sarok"), ("Bevel and Emboss", "Domborítás"), ("Beveled Rectangle", "Levágott sarkú téglalap"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 131875d46..de768d8e9 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1329,6 +1329,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "Nel testo arabo giustificato"), ("Korean Line Breaks:", "Interruzioni di riga coreane:"), ("Between syllables (not only at spaces)", "Tra le sillabe (non solo agli spazi)"), + ("Auto Leading:", "Interlinea automatica:"), + ("Single Word Justification:", "Giustificazione parola singola:"), + ("Full Justify", "Giustifica tutto"), ("Binding:", "Rilegatura:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Applicato sopra il testo selezionato; se vuoto viene rimosso."), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ae2dd653f..e4f436171 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1351,6 +1351,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "両端揃えのアラビア語テキストで使用"), ("Korean Line Breaks:", "韓国語の改行:"), ("Between syllables (not only at spaces)", "音節間で改行 (スペース以外も可)"), + ("Auto Leading:", "自動行送り:"), + ("Single Word Justification:", "単語のみの行の揃え:"), ("Binding:", "綴じ方向:"), ("Ruby:", "ルビ:"), ("Set over the selected text; empty removes it.", "選択したテキストの上にルビを付けます。空欄にすると削除します。"), diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 1ba9a61a9..c9db1eab0 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -1254,6 +1254,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "ორმხრივად სწორებულ არაბულ ტექსტში"), ("Korean Line Breaks:", "კორეული სტრიქონების წყვეტა:"), ("Between syllables (not only at spaces)", "მარცვლებს შორის (არა მხოლოდ ჰარებთან)"), + ("Auto Leading:", "ავტომატური სტრიქონთაშორისი:"), + ("Single Word Justification:", "ერთი სიტყვის სწორება:"), ("Binding:", "აკინძვა:"), ("Ruby:", "რუბი:"), ("Set over the selected text; empty removes it.", "დაისმება მონიშნული ტექსტის თავზე; ცარიელი წაშლის მას."), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index 7aac5d74b..e0b10e9cd 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1198,6 +1198,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "W justowanym tekście arabskim"), ("Korean Line Breaks:", "Podział wierszy w koreańskim:"), ("Between syllables (not only at spaces)", "Między sylabami (nie tylko na spacjach)"), + ("Auto Leading:", "Interlinia automatyczna:"), + ("Single Word Justification:", "Justowanie pojedynczego słowa:"), + ("Full Justify", "Pełne justowanie"), ("Binding:", "Oprawa:"), ("Ruby:", "Ruby:"), ("Set over the selected text; empty removes it.", "Nad zaznaczonym tekstem; puste usuwa."), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 147947dbd..2bc5fc935 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1962,6 +1962,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Utilities", "Utilitários"), ("Korean Line Breaks:", "Quebras de linha em coreano:"), ("Between syllables (not only at spaces)", "Entre sílabas (não apenas nos espaços)"), + ("Auto Leading:", "Entrelinha automática:"), + ("Single Word Justification:", "Justificação de palavra única:"), ("Show Font Names in English", "Mostrar nomes de fontes em inglês"), ("Missing Glyphs", "Glifos ausentes"), ("Draw Missing Glyphs from Fallback Fonts", "Desenhar glifos ausentes com fontes substitutas"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 178cc9bc3..e6c223d9d 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -1175,6 +1175,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "В арабском тексте, выровненном по ширине"), ("Korean Line Breaks:", "Переносы корейского текста:"), ("Between syllables (not only at spaces)", "Между слогами (а не только на пробелах)"), + ("Auto Leading:", "Автоинтерлиньяж:"), + ("Single Word Justification:", "Выключка одного слова:"), + ("Full Justify", "Полная выключка"), ("Binding:", "Переплет:"), ("Ruby:", "Руби:"), ("Set over the selected text; empty removes it.", "Размещается над выделенным текстом; пустое значение удаляет подпись."), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..485dffa5f 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -409,6 +409,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "I marginaljusterad arabisk text"), ("Korean Line Breaks:", "Koreanska radbrytningar:"), ("Between syllables (not only at spaces)", "Mellan stavelser (inte bara vid blanksteg)"), + ("Auto Leading:", "Automatiskt radavstånd:"), + ("Single Word Justification:", "Justering av enstaka ord:"), ("Minimum Space Before First Footnote:", "Minsta avstånd före första fotnoten:"), ("Space Between Footnotes:", "Avstånd mellan fotnoter:"), ("Offset:", "Förskjutning:"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index ebde2b629..c216d6b97 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -3480,6 +3480,11 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ "在音节之间(不仅在空格处)", ], ), + ("Auto Leading:", ["Automatischer Zeilenabstand:", "Interlignage automatique :", "Interlineado automático:", "自動行送り:", "自动行距:"]), + ( + "Single Word Justification:", + ["Ausrichtung einzelner Wörter:", "Justification des mots isolés :", "Justificación de palabra única:", "単語のみの行の揃え:", "单字齐行:"], + ), ("Binding:", ["Binding:", "Reliure :", "Binding:", "Binding:", "装订方向:"]), ("Ruby:", ["Ruby:", "Ruby :", "Ruby:", "Ruby:", "旁注:"]), ( diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 4b2853eae..65dace8a5 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1326,6 +1326,9 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("In justified Arabic text", "В арабському тексті, вирівняному за шириною"), ("Korean Line Breaks:", "Переноси корейського тексту:"), ("Between syllables (not only at spaces)", "Між складами (а не лише на пробілах)"), + ("Auto Leading:", "Автоінтерліньяж:"), + ("Single Word Justification:", "Вирівнювання одного слова:"), + ("Full Justify", "Повне вирівнювання"), ("Binding:", "Напрямок палітурки:"), ("Ruby:", "Фонетичні підписи:"), ("Set over the selected text; empty removes it.", "Розміщується над виділеним текстом; порожнє значення вилучає підпис."), diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..1064ef823 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -35,7 +35,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph Composer | Adobe's multi-line composer | Knuth–Plass total fit, fitness classes, hyphen penalties | ~ | same family of algorithm, Adobe's weights unknown; breaks will differ on some paragraphs | | Single-line Composer | greedy | greedy with the same ranges | ✓ | | | World-Ready composers | Paragraph / Single-line World-Ready | RTL, Arabic and bidi in the main composer | ~ | Indic scripts (Devanagari etc.) shape through harfrust but are untested | -| Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531) | +| Justification | word/letter spacing, glyph scaling min/desired/max, single-word, last line | all of these | ✓ | a justified line with a tab justifies after the tab (#284); set per paragraph in Type › Justification… and the Paragraph panel menu (#531); Auto Leading (0% to 500%) and Single Word Justification are set there and in Paragraph Style Options › Justification | | Hyphenation | per-language dictionaries (~40), zone, limits, capitalized, last word, across columns | Liang patterns: English (trained from the public-domain Moby list), Spanish (Bezos), Portuguese (hyph-pt), Norwegian (hyph-no), Danish (hyph-da), Greek (hyph-el-monoton), German 2006 (hyph-de-1996), French (hyph-fr), Italian (hyph-it) and Dutch (Tutelaers); zone, limits, exceptions in the user dictionary; Hyphenate Across Column off keeps automatic hyphens off the last line of a column or frame; discretionary U+00AD breaks with both composers regardless of automatic hyphenation and replaces pattern points within its word (#1955) | ~ | other languages don't hyphenate (#87 reported "doesn't work") | | Spelling | per-language dictionaries | English (Moby) + document/user dictionary | ~ | | | Kerning | Metrics, Optical, manual, none | Metrics, Optical (outline-based: pairs pulled towards the font's stem gap, `crates/compose/src/optical.rs`), manual, none | ~ | Optical is an approximation of Adobe's algorithm (#181), not a match: imported display text can still break differently | From 3473b8d96ef9d9c0c01398919f3e0b9a0404bab2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:46:20 -0800 Subject: [PATCH 125/328] Text: Text Frame Options refuse an ids that is not a list of object ids A call with an `ids` or `id` that is not an object id used to fall back to the selected frame or the caret's frame. It now fails and leaves the document unchanged. The Properties panel's Text Frame section shows the frame Text Frame Options change: with the Type tool, the frame the caret is drawn in. --- crates/engine/src/cmd/object.rs | 32 +++++++++++++++++-- crates/ui-egui/src/panels/properties/tests.rs | 20 ++++++++++++ crates/ui-egui/src/panels/properties/text.rs | 16 +++++++--- docs/mcp.md | 2 +- 4 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 50628d2bc..e8b3267bc 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2592,9 +2592,16 @@ fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> { fn text_frame_options(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.textFrameOptions"; let st = s.doc()?; - // A call that names its objects acts on those; an empty `ids` names nothing. - let named = p.get("ids").is_some() || p.get("id").is_some(); - let ids = if named { targets(s, p)? } else { text_frame_options_frames(s) }; + // A call that names its objects acts on those; an empty `ids` names nothing. `ids`, when + // given, wins over `id`, and a value that is not an object id is an error. + let ids = match (p.get("ids"), p.get("id")) { + (Some(v), _) => v + .as_array() + .and_then(|a| a.iter().map(|x| x.as_u64().map(ItemId)).collect::>>()) + .ok_or_else(|| bad(ID, format!("ids must be a list of object ids, not {v}")))?, + (None, Some(v)) => vec![v.as_u64().map(ItemId).ok_or_else(|| bad(ID, format!("id must be an object id, not {v}")))?], + (None, None) => text_frame_options_frames(s), + }; // With a text caret the command runs before named objects are checked. if let Some(gone) = ids.iter().find(|i| st.doc.item(**i).is_none()) { return Err(bad(ID, format!("no object with id {}", gone.0))); @@ -5075,6 +5082,25 @@ mod type_tool_frame_options_tests { assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); } + /// An `ids` that is not a list of object ids is refused, not read as the selected frame or the + /// caret's frame. + #[test] + fn malformed_ids_are_an_error() { + let mut s = Session::new(); + let (a, b, sid) = two_frame_thread(&mut s); + s.execute("selection.set", &json!({"ids": [b.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + for p in [json!({"ids": "bad", "columns": 2}), json!({"ids": [b.0, "x"], "columns": 2}), json!({"ids": null, "columns": 2})] { + let e = s.execute("object.textFrameOptions", &p).unwrap_err().to_string(); + assert!(e.contains("ids must be a list of object ids"), "{p}: {e}"); + } + s.execute("text.select", &json!({"story": sid.0, "anchor": 2})).unwrap(); + let e = s.execute("object.textFrameOptions", &json!({"ids": "bad", "columns": 2})).unwrap_err().to_string(); + assert!(e.contains("ids must be a list of object ids"), "with a caret: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "nothing changed"); + assert_eq!((options(&s, a).columns, options(&s, b).columns), (1, 1)); + } + /// Options the frame already has change nothing and add no undo step. #[test] fn unchanged_options_add_no_undo_step() { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 1e7c40c8a..59e0cbd1e 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1277,3 +1277,23 @@ fn transform_flips_and_rotates_from_properties() { // The angle and scale fields are there. assert!(h.query_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("90°")).is_some()); } + +/// With the Type tool, the Text Frame section shows the frame Text Frame Options change: the frame +/// the caret is drawn in, not the caret's stored frame. +#[test] +fn text_frame_section_shows_the_frame_that_shows_the_caret() { + use designcraft_doc::{ItemId, Selection, StoryId, TextSel}; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [b], "columns": 3})).unwrap(); + // The end of the story is drawn in the second frame; the caret's stored frame is the first. + app.session.doc_mut().unwrap().selection = + Selection::text(TextSel { story: StoryId(sid), anchor: text.len(), focus: text.len(), frame: Some(ItemId(a)), cell: None }); + let shown = super::text::text_frame_target(&app).map(|(id, o)| (id, o.columns)); + assert_eq!(shown, Some((ItemId(b), 3))); +} diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index 36c23c195..f444d6ba2 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -516,13 +516,21 @@ pub(super) fn quick_actions_text(app: &mut DesignApp, ui: &mut Ui) { } } -/// Text Frame section: columns, gutter, [Options]. +/// The text frame the Text Frame section shows, as Text Frame Options shows it: the first selected +/// frame, the frame that shows the caret, or the first frame holding selected text. Its id and its +/// options. +pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions)> { + let st = app.session.active()?; + let fid = designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied()?; + Some((fid, st.doc.item(fid)?.text_frame()?.options.clone())) +} + +/// Text Frame section: columns, gutter, [Options]. With the Type tool it changes the frame that +/// shows the caret, or every frame that holds part of the selected text. pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let u = units(app); - let Some(st) = app.session.active() else { return }; - let fid = st.selection.items.first().copied().or_else(|| st.selection.text.and_then(|t| t.frame)); - let Some(opts) = fid.and_then(|f| st.doc.item(f)).and_then(|i| i.text_frame()).map(|t| t.options.clone()) else { return }; + let Some((_, opts)) = text_frame_target(app) else { return }; let b = block(ui, FIELD_H); icons::paint(ui.painter(), sub(b, 0.0, 1.0, 19.0, 19.0), "text-columns", t.icon); if let Some(v) = place(ui, sub(b, 22.0, 0.0, 54.0, FIELD_H), |ui| { diff --git a/docs/mcp.md b/docs/mcp.md index d9a15256a..255f282a4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -229,7 +229,7 @@ With a text selection, this formats the selected paragraphs; with selected text the selected frames or on the `ids` the call passes. With the Type tool and no frame selected, it acts on the frame that shows the insertion point, or on every frame that holds part of the selected text, not on the other frames of the thread. With the insertion point in a footnote or a table cell, it acts on the frame that shows the footnote or the -cell. An empty `ids` is an error. Options a frame already has leave the document unchanged and add no undo step. +cell. An empty `ids`, or an `ids` that is not a list of object ids, is an error. Options a frame already has leave the document unchanged and add no undo step. ```text execute {"command": "object.textFrameOptions", "params": {"verticalJustification": "center", "inset": 6}} From 43088a87c0214ecb475c8b31fe1c30c2502563cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:51:54 -0800 Subject: [PATCH 126/328] Recovery: a cancel cannot race the rename, and results go to their session A save, revert or close that cancels a background write now waits for a rename already under way, and a later rename sees the cancel, so a stale snapshot or its metadata cannot be published after the cleanup. The writer's results go back to the session that queued them: another session's poll no longer removes their snapshots, and results for a session that has been dropped are not kept. --- crates/engine/src/lib.rs | 4 ++ crates/engine/src/recovery.rs | 97 ++++++++++++++++++++++++----- crates/engine/src/recovery/tests.rs | 59 ++++++++++++++++++ 3 files changed, 145 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3d43a80e0..bb67875b4 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -412,6 +412,9 @@ pub struct Session { pub clipboard_origin: f64, /// Crash-recovery folder (the app sets it; saving or closing a document removes its entry). pub recovery_dir: Option, + /// This session's number for the background recovery writer, which returns each result to + /// the session that queued it. + pub(crate) recovery_owner: recovery::Owner, /// Copied text with its formatting (a frameless story slice), its plain text, and what pasting /// it needs from its document: a copy holding only the stories its anchored text frames show /// (and theirs) and the graphics the text and those stories place. @@ -477,6 +480,7 @@ impl Session { clipboard: None, clipboard_origin: 0.0, recovery_dir: None, + recovery_owner: recovery::Owner::new(), text_clipboard: None, link_checks: Default::default(), ui_requests: vec![], diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 420d1795f..dc7d63ed7 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -649,6 +649,32 @@ struct Snapshot { own: bool, /// The folder's canonical key, for recording that a shared entry is this run's now. key: PathBuf, + /// The session that queued a background write ([`Session::recovery_owner`]), which takes its + /// result. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + owner: u64, +} + +/// A number for each session, so background results go back to the session that queued them. +/// Dropping it retires the number: results still queued for it are then dropped. +pub(crate) struct Owner(pub(crate) u64); + +/// The numbers of the sessions that exist. +static LIVE_OWNERS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); + +impl Owner { + pub(crate) fn new() -> Self { + static NEXT_OWNER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let id = NEXT_OWNER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(id); + Owner(id) + } +} + +impl Drop for Owner { + fn drop(&mut self) { + LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.0); + } } impl Snapshot { @@ -662,6 +688,7 @@ impl Snapshot { // An entry this run did not write is never replaced, even one made since it checked. own: access.owns(d.uid), key: access.key.clone(), + owner: 0, } } } @@ -700,7 +727,16 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); - Written { published: true, error: publish_recovery_file(&meta, metadata.to_string().as_bytes(), entry.own).err() } + // A cancel after the primary landed removes it; the metadata must not be left without it. + let bytes = metadata.to_string(); + let error = publish_recovery_written( + &meta, + entry.own, + |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), + &cancelled, + ) + .err(); + Written { published: true, error } } /// Write recovery entries for dirty documents on a background thread and drop clean checkpoints @@ -729,7 +765,8 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { continue; } let Some(document) = s.docs.get(index) else { continue }; - let entry = Snapshot::of(&access, dir, document); + let mut entry = Snapshot::of(&access, dir, document); + entry.owner = s.recovery_owner.0; // A write still running for this document already holds a snapshot of it; the next // timer tick catches up with the edits made since. match worker::submit(entry) { @@ -787,8 +824,20 @@ pub(crate) fn finished(s: &mut Session) -> Finished { let Some(w) = worker::started() else { return out }; // Before draining: the worker sends a result before it clears the document as running, so a writer idle now has every result in the channel already. let busy = w.busy(); - let done = w.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - while let Ok(d) = done.try_recv() { + // Results go to the session that queued them: another session has none of those documents, + // and would remove their snapshots as if they had been closed. + let mine: Vec = { + let done = w.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut others = w.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut all = std::mem::take(&mut *others); + all.extend(done.try_iter()); + let (mine, rest): (Vec<_>, Vec<_>) = all.into_iter().partition(|d| d.owner == s.recovery_owner.0); + // A session that is gone takes nothing: its results are dropped rather than kept for ever. + let live = LIVE_OWNERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + *others = rest.into_iter().filter(|d| live.contains(&d.owner)).collect(); + mine + }; + for d in mine { // A primary that landed belongs to this run even if its optional metadata failed: record // it, so Save and Close remove the snapshot instead of leaving it in the folder for ever. if d.published && record_checkpoint(s, d.dir, d.uid) { @@ -826,11 +875,15 @@ mod worker { /// The primary document reached the folder (its optional metadata may have failed): the /// checkpoint must still be recorded, or Save and Close could not remove it. pub(super) published: bool, + /// The session that queued the write. + pub(super) owner: u64, } pub(super) struct Writer { jobs: Sender, pub(super) done: Mutex>, + /// Results taken from `done` by a session that did not queue them, kept for their own. + pub(super) undelivered: Mutex>, /// Documents queued or being written: a second write of one still holds nothing newer. running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the @@ -872,6 +925,9 @@ mod worker { /// as small as the work in flight. fn cancel(&self, dir: &Path, uid: u64) { let key = (dir.to_path_buf(), uid); + // A rename under way finishes first, so the caller's cleanup comes after it; a later + // one sees the mark. + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); if !self.running.lock().is_ok_and(|running| running.contains(&key)) { return; } @@ -894,11 +950,11 @@ mod worker { let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { while let Ok(job) = job_rx.recv() { let (published, error) = guarded_write(&job); - let (dir, uid) = (job.dir, job.uid); + let (dir, uid, owner) = (job.dir, job.uid, job.owner); // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an // answer still on its way. - let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published }).is_ok(); + let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok(); if let Some(w) = WRITER.get().and_then(Option::as_ref) { w.finish(&dir, uid); } @@ -910,6 +966,7 @@ mod worker { spawned.ok().map(|_| Writer { jobs, done: Mutex::new(done_rx), + undelivered: Mutex::new(Vec::new()), running: Mutex::new(BTreeSet::new()), cancelled: Mutex::new(BTreeSet::new()), idle: Condvar::new(), @@ -1124,6 +1181,11 @@ fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> .map(|_| ()) } +/// Serializes the last check for a cancelled write with the rename that publishes it, and with +/// [`worker::cancel`]. +#[cfg(not(target_arch = "wasm32"))] +static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); + /// [`publish_recovery_file`], with `write` filling the temporary file: a large document is written /// straight to disk instead of being built in memory first. Returns whether it was published; /// `cancelled` is asked after the bytes are written and before the rename, so a document saved or @@ -1155,16 +1217,21 @@ fn publish_recovery_written( out.flush().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; } tmp.as_file_mut().sync_all().map_err(|e| EngineError::Other(format!("{}: {e}", path.display())))?; - // Last moment: the document was saved, reverted or closed while the bytes were written. The - // temporary file is dropped, so nothing of the stale snapshot stays. - if cancelled() { - return Ok(false); + { + // Held from the check to the rename: a cancel waits for a rename already under way (the + // cleanup after it then removes the file), and a rename after a cancel sees it. + let _publishing = PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Last moment: the document was saved, reverted or closed while the bytes were written. + // The temporary file is dropped, so nothing of the stale snapshot stays. + if cancelled() { + return Ok(false); + } + // Validate the non-followed leaf again immediately before renaming the randomized + // temporary file to its fixed sibling destination. + validate_recovery_dir(dir)?; + let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; + published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; } - // Validate the non-followed leaf again immediately before renaming the randomized temporary - // file to its fixed sibling destination. - validate_recovery_dir(dir)?; - let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; - published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; sync_recovery_dir(dir)?; Ok(true) } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 3b7c2303d..79644ca3d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -170,6 +170,65 @@ fn a_background_save_returns_while_its_write_is_held() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_saved_while_its_write_is_held_leaves_no_snapshot() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let saved = dir.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut s), 0); + assert!(!files(dir.path(), uid).0.exists(), "the stale snapshot was not published"); + assert!(!files(dir.path(), uid).1.exists(), "nor its metadata"); + assert!(list(dir.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_result_goes_to_the_session_that_queued_it() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + let mut other = dirty_session(); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + // Another session has none of these documents: it must neither take the result nor remove + // the snapshot as if its document had been closed. + let v = other.execute("file.recovery.progress", &json!({})).unwrap(); + assert_eq!(v["written"], 0, "{v}"); + assert!(files(dir.path(), uid).0.exists(), "the snapshot is still there"); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(queued_by.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, dir.path())), "the checkpoint is recorded"); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn results_for_a_session_that_is_gone_are_not_kept() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut gone = dirty_session(); + gone.recovery_dir = Some(dir.path().to_path_buf()); + let owner = gone.recovery_owner.0; + gone.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + drop(gone); + let mut other = dirty_session(); + other.execute("file.recovery.progress", &json!({})).unwrap(); + let writer = worker::started().unwrap(); + let kept = writer.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + assert!(!kept.iter().any(|d| d.owner == owner), "a result nobody can take was kept"); +} + #[test] fn a_background_save_rejects_a_background_that_is_not_true_or_false() { let dir = tempfile::tempdir().unwrap(); From 29f259bf077d42798cc5072fba5cc65bc59a742b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 19:54:23 -0800 Subject: [PATCH 127/328] Render: test that a turned view and snapshot renders handle kept shadows A view turned 90 degrees with the frame turned back draws the shadow again and matches a fresh render. Renders served from the CMYK viewport snapshot drop kept images unused for 256 renders. --- crates/render/src/fx.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 5248bf9ba..c6cbd532e 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -984,5 +984,41 @@ mod tests { r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); } assert_eq!(r.kept.drawn, 3); + // Renders served from the CMYK viewport snapshot count towards the expiry too. + assert!(!r.kept.entries.is_empty()); + for _ in 0..=KEEP_RENDERS { + r.render(&d, &cache, &placed, (500, 450), Affine::IDENTITY, &opts); + } + assert_eq!(r.kept.drawn, 3, "the snapshot served every render"); + assert!(r.kept.entries.is_empty(), "images unused for {KEEP_RENDERS} renders are dropped"); + } + + /// A view turned 90° with the frame turned back by 90° leaves the frame where it was on the + /// device, but turns the shadow's offset: the shadow is drawn again. + #[test] + fn a_turned_view_draws_the_shadow_again() { + use designcraft_doc::SpreadRef; + let (mut d, id) = shadowed_image(); + let cache = crate::Cache::new(); + let placed = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut kept = Renderer::new(); + kept.threads = 2; + let view = Affine::scale(1.5); + kept.render(&d, &cache, &placed, (500, 450), view, &opts); + assert_eq!(kept.kept.drawn, 1); + // Exact quarter turns, so that the frame's spread → device transform stays the same. + let (turn, back) = (Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0]), Affine::new([0.0, -1.0, 1.0, 0.0, 0.0, 0.0])); + let it = d.item_mut(id).unwrap(); + it.xf = back * it.xf; + assert_eq!((view * turn * it.xf).as_coeffs(), (view * Affine::translate((100.0, 100.0))).as_coeffs()); + let turned = view * turn; + let image = kept.render(&d, &cache, &placed, (500, 450), turned, &opts); + let mut r = Renderer::new(); + r.threads = 2; + let fresh = r.render(&d, &crate::Cache::new(), &placed, (500, 450), turned, &opts); + let worst = image.pixels.iter().zip(&fresh.pixels).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + assert!(worst <= 1, "off by {worst}"); + assert_eq!(kept.kept.drawn, 2); } } From 5d9fbb4d4eb892a51f3563574c11c20530badcfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:02:54 -0800 Subject: [PATCH 128/328] Docs: vertical justification moves grid-aligned lines by whole grid steps --- docs/typography-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..7987b9632 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -47,7 +47,7 @@ Fidelity: **unmeasured** unless stated. | First baseline | ascent, cap height, x-height, leading, fixed, min | ✓ | ✓ | | | Frame fit / overset | baseline of the last line must fit | descenders must fit | ~ | **differs** (#180): frames go overset where InDesign fits | | Baseline grid | document grid relative to the top of the page or each page's top margin; frame grids relative to the top of the page, top margin, top of frame or top inset | ✓ | ✓ | | -| Vertical justification | top, centre, bottom, justify, paragraph spacing limit | ✓ | ✓ | | +| Vertical justification | top, centre, bottom, justify, paragraph spacing limit | ✓ | ✓ | with Center and Bottom, lines aligned to the baseline grid move by whole grid steps; with Justify only the first and last lines stay on the grid | | Text in shaped frames | lines follow oval, polygon and freeform frame outlines, one inset from the outline | ✓ | ~ | concave shapes set one slot per line (the widest); vertical justification and paragraph shading use the frame's rectangle (#646) | | Columns, span / split columns | ✓ | ✓ | ✓ | split columns within a column (#295); text after a span flows below it (#276) | | Column rules | ✓ | ✓ (screen, PDF, IDML) | ~ | no stroke types or overprint (#274) | From 5b89a13c2e979bb8f66211a62d503779910ebb61 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:04:50 -0800 Subject: [PATCH 129/328] Text wrap: anchored images keep their Alpha Channel outline Outlines are traced for images anchored in text as well as for those on the spreads, so an anchored image's Alpha Channel contour follows its visible pixels instead of falling back to the frame. Tracing reads the pixels once: a coarser grid, used when the outline has too many edges, is made from the finer grid's mask when each side halves, and the cell of each pixel is counted along the row instead of divided. --- crates/engine/src/cmd/alpha_wrap.rs | 145 +++++++++++++++++++++++----- 1 file changed, 123 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 8a94ae818..cd6a1d00b 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -5,7 +5,7 @@ //! current transform, so it follows the image when it is moved, scaled or refitted. use std::sync::Arc; -use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, WrapMode}; +use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, Item, WrapMode}; use designcraft_geom::{BezPath, PathData, Point}; /// Images larger than this many pixels aren't traced (their contour follows the frame). @@ -19,18 +19,26 @@ const MAX_EDGES: usize = 1 << 16; /// nothing changed: tracing happens only for an image and threshold not seen before. pub(crate) fn sync(doc: &mut Document) { let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on + // its placed graphic (Direct Selection sets the graphic's). + let mut want = |it: &Item| { + let Some(g) = it.graphic() else { return }; + for w in [&it.wrap, &g.wrap] { + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { + wanted.push((g.asset, w.alpha_threshold)); + } + } + }; for sp in doc.spreads.iter().chain(doc.parents.iter()) { - // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or - // on its placed graphic (Direct Selection sets the graphic's). for top in &sp.items { - top.walk(&mut |it| { - let Some(g) = it.graphic() else { return }; - for w in [&it.wrap, &g.wrap] { - if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { - wanted.push((g.asset, w.alpha_threshold)); - } - } - }); + top.walk(&mut want); + } + } + // Objects anchored in text wrap the lines after their anchor; anchored_items lists their + // children too. + if doc.has_anchored_items() { + for (_, it) in doc.anchored_items() { + want(it); } } if wanted.is_empty() && doc.alpha_outlines.is_empty() { @@ -69,12 +77,20 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio return None; } let mut grid = MAX_GRID; + // The previous grid's mask: a grid half as fine is made from it without reading the pixels again. + let mut finer: Option<(Vec, u32, u32)> = None; while grid >= 16 { let (cols, rows) = (w.min(grid), h.min(grid)); - let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); - if !transparent { - return None; - } + let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { + Some(m) => m, + None => { + let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); + if !transparent { + return None; + } + mask + } + }; if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); let path = |rings: &[Vec<(i32, i32)>]| { @@ -93,24 +109,55 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio let source = Arc::downgrade(data); return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); } + finer = Some((mask, cols, rows)); grid /= 2; } None } +/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of +/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None +/// otherwise: the pixels are read again. +fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option> { + let step = |fine: u32, coarse: u32| match fine { + f if f == coarse => Some(1), + f if u64::from(f) == 2 * u64::from(coarse) => Some(2), + _ => None, + }; + let (sx, sy) = (step(fc, cols)?, step(fr, rows)?); + let (fc, cols) = (fc as usize, cols as usize); + let mut out = vec![false; cols * rows as usize]; + for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) { + let (x, y) = (i % fc, i / fc); + if let Some(c) = out.get_mut(y / sy * cols + x / sx) { + *c = true; + } + } + Some(out) +} + /// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more /// opaque than `threshold` (a cell is visible when any of its pixels is), and whether the image /// has any transparency. fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> (Vec, bool) { let mut mask = vec![false; (cols as usize) * (rows as usize)]; let mut transparent = false; - for (i, px) in rgba.as_chunks::<4>().0.iter().enumerate() { - let alpha = px[3]; - transparent |= alpha < 255; - if alpha > threshold { - let (x, y) = ((i as u64) % u64::from(w), (i as u64) / u64::from(w)); - let (gx, gy) = (x * u64::from(cols) / u64::from(w), y * u64::from(rows) / u64::from(h)); - if let Some(c) = mask.get_mut((gy * u64::from(cols) + gx) as usize) { + // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x + // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. + for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { + let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize; + let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w)); + for px in row.as_chunks::<4>().0 { + if acc >= edge { + gx += 1; + edge += u64::from(w); + } + acc += u64::from(cols); + let alpha = px[3]; + transparent |= alpha < 255; + if alpha > threshold + && let Some(c) = mask.get_mut(base + gx) + { *c = true; } } @@ -218,6 +265,39 @@ mod tests { assert!(trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).is_none()); } + /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a + /// mask half as fine made from the finer one matches the mask read from the pixels. + #[test] + fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() { + let (w, h) = (600u32, 300u32); + // An irregular pattern: visible where a small hash says so. + let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7); + let mut rgba = vec![0u8; (w * h * 4) as usize]; + for y in 0..h { + for x in 0..w { + rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 }; + } + } + for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] { + let mut expect = vec![false; (cols * rows) as usize]; + for y in 0..h { + for x in 0..w { + if on(x, y) { + expect[((y * rows / h) * cols + x * cols / w) as usize] = true; + } + } + } + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), (expect, true), "{cols} x {rows}"); + } + let (fine, _) = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + // Same count on one side, twice on the other. + let (fine, _) = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + // Any other ratio is read from the pixels. + assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); + } + #[test] fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() { let mut s = Session::new(); @@ -314,6 +394,27 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their + /// anchor, and they are kept in the story, not on the spread. + #[test] + fn an_anchored_image_keeps_its_outline() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1); + let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text"); + assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline"); + } + /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no /// offset, and a caption frame at `caption` with 8 pt "Hi". fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) { From c69db898623c0efebf920a30c33c9f4e98707cb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:06:28 -0800 Subject: [PATCH 130/328] Justification: Auto Leading stores the shown percent, and the current choice is no edit The Auto Leading field shows whole percents, and it now stores the whole percent it shows, so a typed 500.4% (shown as 500%) is accepted as 500% instead of being refused. Picking the Single Word Justification the paragraphs already have is no longer an edit, so OK adds no undo step for it. --- crates/ui-egui/src/dialogs.rs | 16 ++++++++++++++-- crates/ui-egui/src/dialogs/tests.rs | 24 ++++++++++++++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6664fc349..1ad599bbd 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -7716,6 +7716,12 @@ const JUSTIFY_ROWS: [(&str, &str, (f64, f64)); 3] = [ /// The allowed Auto Leading, in percent of the type size. const AUTO_LEADING_RANGE: (f64, f64) = (0.0, 500.0); +/// The Auto Leading stored for a percent typed into its field: the whole percent the field shows. +fn auto_leading_typed(pct: f64) -> f64 { + // Adding 0.0 turns a rounded -0 into 0. + (pct.round() + 0.0) / 100.0 +} + /// The Single Word Justification choices: (attribute value, label). const SINGLE_WORD_CHOICES: [(&str, &str); 4] = [("left", "Align Left"), ("center", "Align Center"), ("right", "Align Right"), ("fullyJustified", "Full Justify")]; @@ -7941,7 +7947,7 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu crate::rtl::label(ui, crate::i18n::tr(lang, "Auto Leading:")); let auto = cur(d, "autoLeading").as_f64().map(|x| x * 100.0); if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{prefix}autoLeading"), auto, "%", 60.0, 0)).inner { - d.fields.insert(format!("{prefix}autoLeading"), json!(n / 100.0)); + d.fields.insert(format!("{prefix}autoLeading"), json!(auto_leading_typed(n))); } ui.end_row(); let single_label = crate::rtl::label(ui, crate::i18n::tr(lang, "Single Word Justification:")); @@ -7954,7 +7960,13 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu .show_ui(ui, |ui| { for (v, label) in SINGLE_WORD_CHOICES { if ui.selectable_label(single.as_str() == Some(v), crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() { - d.fields.insert(format!("{prefix}singleWordJustify"), json!(v)); + // The paragraphs' own choice is no edit, so OK adds no undo step for it. + let key = format!("{prefix}singleWordJustify"); + if current["singleWordJustify"].as_str() == Some(v) { + d.fields.remove(&key); + } else { + d.fields.insert(key, json!(v)); + } } } }) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1343b30d7..2e3cd162a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1156,8 +1156,15 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { h.run_steps(3); assert!(h.query_by_label("Auto Leading:").is_some()); assert!(h.query_by_label("Single Word Justification:").is_some()); - // The dropdown shows the paragraph's Full Justify; pick Align Center. - h.get_by(|n| n.role() == egui::accesskit::Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + use egui::accesskit::Role; + // The dropdown shows the paragraph's Full Justify. Picking Full Justify again is no edit. + h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + h.get_by(|n| n.role() != Role::ComboBox && n.label().as_deref() == Some("Full Justify")).click(); + h.run_steps(3); + assert!(!h.state().ui.dialog.as_ref().unwrap().fields.contains_key("singleWordJustify"), "the paragraph's own choice is no edit"); + // Pick Align Center. + h.get_by(|n| n.role() == Role::ComboBox && n.value().as_deref() == Some("Full Justify")).click(); h.run_steps(3); h.get_by_label("Align Center").click(); h.run_steps(3); @@ -1170,8 +1177,8 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { let d = app.ui.dialog.clone().unwrap(); let before = undo_steps(&app); let bad = [ - ("autoLeading", json!(5.004)), - ("autoLeading", json!(-0.004)), + ("autoLeading", json!(5.01)), + ("autoLeading", json!(-0.01)), ("autoLeading", json!(f64::NAN)), ("singleWordJustify", json!("leftJustified")), ]; @@ -1183,6 +1190,15 @@ fn justification_dialog_sets_auto_leading_and_single_word_justification() { } assert_eq!(undo_steps(&app), before); + // A typed percent is stored as the whole percent the field shows, so 500.4% (shown as 500%) + // and -0.4% (shown as 0%) are accepted. + for (typed, stored) in [(500.4, 5.0), (-0.4, 0.0), (149.6, 1.5)] { + assert_eq!(auto_leading_typed(typed), stored, "{typed}%"); + let mut probe = d.clone(); + probe.fields.insert("autoLeading".into(), json!(auto_leading_typed(typed))); + assert_eq!(check_justification(&probe, "", ¤t), Ok(()), "{typed}%"); + } + app.ui.dialog = Some(d); app.ui.dialog.as_mut().unwrap().fields.insert("autoLeading".into(), json!(1.5)); draw(&mut app, &ctx); From 9fcab8e66baca0cce1406b783c05f418d74ce216 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:13:21 -0800 Subject: [PATCH 131/328] Text wrap: Alpha Channel outlines fit composition, and an empty one wraps nothing An outline with more path elements than composition follows is traced on a coarser grid, so a fragmented image keeps an Alpha Channel contour instead of falling back to the frame. An image with no pixel more opaque than the threshold leaves the text alone. --- crates/compose/src/lib.rs | 38 +++++++++++++++++++----- crates/engine/src/cmd/alpha_wrap.rs | 46 +++++++++++++++++++++++++---- 2 files changed, 71 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 47798d7a3..f0451f938 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -386,7 +386,7 @@ pub struct Contour { } /// Points a contour outline may have; a larger outline wraps around its bounding box. -const MAX_CONTOUR_POINTS: usize = 8192; +pub const MAX_CONTOUR_POINTS: usize = 8192; impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. @@ -587,7 +587,8 @@ pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_pag let group = other.shape == designcraft_doc::Shape::Group; let b = if group { (xf * other.xf.inverse()).transform_rect_bbox(other.bounds()) } else { other.path.transformed(xf).bounds().unwrap_or(Rect::ZERO) }; - wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page) + let e = wrap_exclusion(&other.wrap, b, || (!group).then(|| contour_path(doc, other, &other.wrap)), xf, inv, left_page); + nothing_visible_wraps_nothing(doc, other, &other.wrap, e) } /// The wrap exclusion of the graphic placed in frame `it` (arguments as for [`exclusion`]): around @@ -595,7 +596,26 @@ pub fn exclusion(doc: &Document, other: &Item, xf: Affine, inv: Affine, left_pag pub fn graphic_exclusion(doc: &Document, it: &Item, xf: Affine, inv: Affine, left_page: bool) -> Option { let g = it.graphic()?; let shown = g.shown_bounds(it.inner_bounds())?; - Some(wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page)) + let e = wrap_exclusion(&g.wrap, xf.transform_rect_bbox(shown), || Some(contour_path(doc, it, &g.wrap)), xf, inv, left_page); + Some(nothing_visible_wraps_nothing(doc, it, &g.wrap, e)) +} + +/// An Alpha Channel contour around an image with no pixel more opaque than the threshold leaves +/// the text alone (the exclusion's mode becomes None). +fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap, mut e: Exclusion) -> Exclusion { + if wrap.mode == WrapMode::Contour + && wrap.contour == designcraft_doc::ContourType::AlphaChannel + && wrap.path.is_none() + && let Some(g) = it.graphic() + && let Some(o) = doc.alpha_outline(g.asset, wrap.alpha_threshold) + && o.width > 0 + && o.height > 0 + && o.outer.subpaths.is_empty() + { + e.mode = WrapMode::None; + e.contour = None; + } + e } /// The exclusion of `wrap` around an object with spread-space bounds `b`; `outline` gives its @@ -637,8 +657,9 @@ fn wrap_exclusion( /// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and /// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box /// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; detected edges, alpha channels and image paths need the image, -/// so they follow the frame's path (as other frames do). +/// clipping path when it has one; Alpha Channel follows the image's traced outline when the +/// engine has traced one; detected edges and image paths follow the frame's path (as other +/// frames do). fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> (designcraft_geom::BezPath, Option) { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); let kind = wrap.contour; @@ -765,11 +786,14 @@ fn wrap_obstacles( } let xf = parent * it.xf; let left = || left_page(parent.transform_rect_bbox(it.bounds()).center().x); + // An exclusion whose mode came back None (nothing visible to wrap) is left out. if it.wrap.mode != WrapMode::None { - out.push(exclusion(doc, it, xf, inv, left())); + out.extend(Some(exclusion(doc, it, xf, inv, left())).filter(|e| e.mode != WrapMode::None)); } match &it.content { - Content::Graphic(g) if g.wrap.mode != WrapMode::None => out.extend(graphic_exclusion(doc, it, xf, inv, left())), + Content::Graphic(g) if g.wrap.mode != WrapMode::None => { + out.extend(graphic_exclusion(doc, it, xf, inv, left()).filter(|e| e.mode != WrapMode::None)) + } Content::Group { .. } => { for c in it.shown_children() { wrap_obstacles(doc, c, xf, inv, skip, left_page, depth + 1, out); diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index cd6a1d00b..b4009de1d 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -91,7 +91,12 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio mask } }; - if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize) { + // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes + // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. + let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| { + outer.iter().chain(holes).map(|r| r.len() + 1).sum::() <= designcraft_compose::MAX_CONTOUR_POINTS + }; + if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) { let (sx, sy) = (f64::from(w) / f64::from(cols), f64::from(h) / f64::from(rows)); let path = |rings: &[Vec<(i32, i32)>]| { let mut p = BezPath::new(); @@ -240,15 +245,44 @@ mod tests { /// A 64 × 64 PNG: visible where `on(x, y)`. fn png(on: impl Fn(usize, usize) -> bool) -> Vec { - let mut pixels = vec![0; 64 * 64 * 4]; - for y in 0..64 { - for x in 0..64 { - let i = (y * 64 + x) * 4; + png_sized(64, on) + } + + /// A `size` × `size` PNG: visible where `on(x, y)`. + fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec { + let mut pixels = vec![0; size * size * 4]; + for y in 0..size { + for x in 0..size { + let i = (y * size + x) * 4; pixels[i] = 120; pixels[i + 3] = if on(x, y) { 255 } else { 0 }; } } - designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png() + designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png() + } + + /// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements + /// on the finest grid) is traced on a coarser grid until composition can follow it. + #[test] + fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() { + let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0); + let o = trace(&Arc::new(dots), AssetId(1), 25).unwrap(); + let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len(); + assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements"); + } + + /// An image with no pixel more opaque than the threshold leaves the text alone: with the + /// frame's contour the caption over it is overset, with Alpha Channel it is set. + #[test] + fn an_image_with_nothing_visible_wraps_no_text() { + let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]); + assert!(overset(&s, story), "the frame's contour covers the caption"); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "nothing visible: nothing wraps"); + // The same for the wrap set on the placed graphic. + s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story)); } #[test] From 97ed25093f03ff03b9fc7c73466e8df64ad8581d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:23:59 -0800 Subject: [PATCH 132/328] Text wrap: a vertical open path keeps its offset, and previewed images are traced A contour's zero-width spans (a vertical open path) are kept until the wrap offset widens them, so text no longer crosses such a path. A record previewed into an image placeholder gets the image's Alpha Channel outline, as an edit would. --- crates/compose/src/lib.rs | 10 ++++++--- crates/compose/src/tests.rs | 15 +++++++++++++ crates/engine/src/cmd/datamerge.rs | 2 ++ crates/engine/src/cmd/datamerge/tests.rs | 27 ++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f0451f938..62e319f36 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -451,8 +451,10 @@ impl Contour { let mut cut = Vec::new(); let (mut i, mut j) = (0, 0); while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { - if a.max(c) < b.min(d) { - cut.push((a.max(c), b.min(d))); + let (lo, hi) = (a.max(c), b.min(d)); + // A zero-width span (a vertical open path) is kept where the clip covers it. + if lo < hi || (a == b && lo == hi) { + cut.push((lo, hi)); } if b < d { i += 1; @@ -466,8 +468,10 @@ impl Contour { } } +/// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: +/// the wrap offset widens them, and without one they still split the line there. fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { - spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b - a > 1e-9); + spans.retain(|(a, b)| a.is_finite() && b.is_finite() && b >= a); spans.sort_by(|a, b| a.0.total_cmp(&b.0)); let mut out: Vec<(f64, f64)> = Vec::new(); for (a, b) in spans { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e96e33cf4..3df861733 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8464,6 +8464,21 @@ fn contour_intervals_cover_the_whole_slanted_line_band() { assert_eq!(c.band_spans(0.0, 10.0), vec![(0.0, 12.0)]); } +/// A vertical open path blocks the offset on both sides of it, and splits the line with no +/// offset; clipped to a frame that holds it, it still does. +#[test] +fn a_vertical_open_path_keeps_its_offset() { + let mut path = designcraft_geom::BezPath::new(); + path.move_to((10.0, 0.0)); + path.line_to((10.0, 100.0)); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 3.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let frame = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 100.0)).to_bezpath(); + assert_eq!(c.within(&frame, designcraft_geom::Affine::IDENTITY).band_spans(40.0, 50.0), vec![(7.0, 13.0)]); + let c = Contour::of(&path, designcraft_geom::Affine::IDENTITY, 0.0).unwrap(); + assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 7cb332fd3..aad5b72f3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -210,6 +210,8 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result { let images = ImageCache::default(); let sources = Sources { options: &options, data_dir: data_dir.as_deref(), doc_dir: doc_dir.as_deref(), images: &images }; fill_row(&mut doc, &source.fields, &row, record as u32, &maps, &sources); + // An image the record placed gets its Alpha Channel outline, as an edit's would. + crate::cmd::alpha_wrap::sync(&mut doc); st.doc = Arc::new(doc); st.preview_record = Some(record as u32); st.bump_revision(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..dad43af66 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1310,3 +1310,30 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +/// A record previewed into an image placeholder whose frame wraps with an Alpha Channel contour +/// gets the image's outline, as an edit would. +#[test] +fn a_previewed_image_gets_its_alpha_channel_outline() { + let dir = scratch("alpha-preview"); + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 16..48 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [0.0, 0.0, 200.0, 100.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel"})); + assert!(s.doc().unwrap().doc.alpha_outlines.is_empty(), "no image placed yet"); + exec(&mut s, "data.preview", json!({"record": 1})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 1, "the previewed image is traced"); + assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} From 7b91cad608f2c47f626a2d4818710a98ab9f5f6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:24:55 -0800 Subject: [PATCH 133/328] Recovery: Save cancels a document's writes to any folder Save, Revert and Close now cancel the document's background writes to every folder, including one named with `file.recovery.save {dir}` that is not in its entries yet, and remove a snapshot such a write already published even when its result has not been taken. A cancel that comes after the write published retires its result, so the removed snapshot is not recorded as a checkpoint after a later edit. Cancels apply only to writes the same session queued. The test that closes a run's lock and expects it free no longer runs while a test starts its child process, which held a copy of the lock until the child ran its program. --- crates/engine/src/recovery.rs | 64 ++++++++++++++++--- crates/engine/src/recovery/tests.rs | 96 ++++++++++++++++++++++++++--- 2 files changed, 146 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index dc7d63ed7..6d2eac44d 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -514,6 +514,15 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio { entries.push((dir.to_path_buf(), uid)); } + // Background writes still queued or running for it, in any folder (one named by + // `file.recovery.save {dir}` is not in its entries until the write's result is taken): none + // may publish after this point, and what one already published is removed below. + #[cfg(not(target_arch = "wasm32"))] + for dir in worker::cancel_document(uid, s.recovery_owner.0) { + if !entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) { + entries.push((dir, uid)); + } + } for (dir, uid) in entries { // Session ownership governs deletion as well as writes: never consume another live // document's only source merely because its old uid matches this unrelated document. @@ -861,7 +870,7 @@ pub(crate) fn finished(_s: &mut Session) -> Finished { /// gigabytes of placed files is written without stopping the interface. #[cfg(not(target_arch = "wasm32"))] mod worker { - use std::collections::BTreeSet; + use std::collections::{BTreeMap, BTreeSet}; use std::sync::mpsc::{Receiver, Sender}; use std::sync::{Condvar, Mutex, OnceLock}; @@ -884,8 +893,9 @@ mod worker { pub(super) done: Mutex>, /// Results taken from `done` by a session that did not queue them, kept for their own. pub(super) undelivered: Mutex>, - /// Documents queued or being written: a second write of one still holds nothing newer. - running: Mutex>, + /// Documents queued or being written, with the session that queued each: a second write + /// of one still holds nothing newer. + running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, @@ -928,7 +938,7 @@ mod worker { // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !self.running.lock().is_ok_and(|running| running.contains(&key)) { + if !self.running.lock().is_ok_and(|running| running.contains_key(&key)) { return; } if let Ok(mut cancelled) = self.cancelled.lock() { @@ -936,6 +946,35 @@ mod worker { } } + /// [`Writer::cancel`] for every folder a write of `uid` queued by session `owner` is queued + /// or running for. Returns those folders, and the folders of its finished writes whose + /// results nobody has taken. + fn cancel_document(&self, uid: u64, owner: u64) -> Vec { + // Held while results are read: the writer checks for a cancel and sends its result + // under it, so a result sent after this sees the cancel. + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|((_, u), o)| *u == uid && **o == owner).map(|(key, _)| key.clone()).collect()) + .unwrap_or_default(); + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys.iter().cloned()); + } + let mut dirs: Vec = keys.into_iter().map(|(dir, _)| dir).collect(); + // Results stay queued for their session; only their folders are read here. + let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + undelivered.extend(done.try_iter()); + for d in undelivered.iter_mut().filter(|d| d.uid == uid && d.owner == owner && d.published) { + dirs.push(d.dir.clone()); + // The caller removes that snapshot: its result must not record it as a checkpoint + // once the document has changed again. + d.published = false; + } + dirs + } + fn cancelled(&self, dir: &Path, uid: u64) -> bool { self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&(dir.to_path_buf(), uid))) } @@ -954,7 +993,12 @@ mod worker { // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an // answer still on its way. - let sent = done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok(); + let sent = { + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Cancelled after it was published: the canceller removes the snapshot. + let published = published && !cancelled(&dir, uid); + done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok() + }; if let Some(w) = WRITER.get().and_then(Option::as_ref) { w.finish(&dir, uid); } @@ -967,7 +1011,7 @@ mod worker { jobs, done: Mutex::new(done_rx), undelivered: Mutex::new(Vec::new()), - running: Mutex::new(BTreeSet::new()), + running: Mutex::new(BTreeMap::new()), cancelled: Mutex::new(BTreeSet::new()), idle: Condvar::new(), }) @@ -987,6 +1031,11 @@ mod worker { } } + /// Do not publish any write of `uid` in flight (see [`Writer::cancel_document`]). + pub(super) fn cancel_document(uid: u64, owner: u64) -> Vec { + started().map(|w| w.cancel_document(uid, owner)).unwrap_or_default() + } + /// Whether that write is already marked as cancelled (see [`Writer::cancelled`]). pub(super) fn cancelled(dir: &Path, uid: u64) -> bool { started().is_some_and(|w| w.cancelled(dir, uid)) @@ -1016,9 +1065,10 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.dir.clone(), entry.uid); - if !running.insert(key.clone()) { + if running.contains_key(&key) { return Some(false); } + running.insert(key.clone(), entry.owner); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 79644ca3d..2d6cc8861 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -184,12 +184,57 @@ fn a_document_saved_while_its_write_is_held_leaves_no_snapshot() { let saved = dir.path().join("saved.designcraft"); s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); held.release(); - assert_eq!(finished_writes(&mut s), 0); + // Before the session takes the result: a crash now must not find the stale snapshot. + testing::wait_until_idle(); assert!(!files(dir.path(), uid).0.exists(), "the stale snapshot was not published"); assert!(!files(dir.path(), uid).1.exists(), "nor its metadata"); + assert_eq!(finished_writes(&mut s), 0); assert!(list(dir.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_saved_while_its_write_to_a_named_folder_is_held_leaves_no_snapshot() { + // A folder given to `file.recovery.save` is not the session's, and is not in the document's + // entries until the write's result is taken. + let _turn = background(); + let named = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(named.path()); + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": named.path().to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.wait_until_held(); + let saved = named.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + held.release(); + // Before the session takes the result: a crash now must not find the stale snapshot. + testing::wait_until_idle(); + assert!(!files(named.path(), uid).0.exists(), "the stale snapshot was not published"); + assert_eq!(finished_writes(&mut s), 0); + assert!(list(named.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken() { + let _turn = background(); + let named = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true, "dir": named.path().to_string_lossy()})).unwrap(); + testing::wait_until_idle(); + assert!(files(named.path(), uid).0.exists(), "the write finished"); + let saved = named.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!files(named.path(), uid).0.exists(), "Save removed the snapshot before its result was taken"); + // Edited again before the result is taken: the removed snapshot is not its checkpoint. + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + assert_eq!(finished_writes(&mut s), 0); + assert!(!s.docs[0].recovery_entries.iter().any(|(d, _)| same_directory(d, named.path())), "no checkpoint for a removed snapshot"); + assert!(list(named.path()).is_empty()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_result_goes_to_the_session_that_queued_it() { @@ -211,6 +256,28 @@ fn a_background_result_goes_to_the_session_that_queued_it() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_in_one_session_leaves_another_sessions_write_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid in another session (recovered documents keep the uids of their entries). + let mut other = dirty_session(); + other.docs[0].uid = uid; + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let elsewhere = tempfile::tempdir().unwrap(); + other.execute("file.saveAs", &json!({"path": elsewhere.path().join("other.designcraft").to_string_lossy()})).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "the other session's save did not cancel this write"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn results_for_a_session_that_is_gone_are_not_kept() { @@ -709,6 +776,11 @@ fn restart_recovery_child() { } } +/// A child process starts with a copy of every open file of this one until it runs its program, so +/// a lock file closed meanwhile stays locked: a test that closes a lock and expects it free does +/// not run while a child is started. +static SPAWN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + fn run_restart_case(mode: &str) { let source = restart_fixture(); if mode == "max_uid" { @@ -717,12 +789,20 @@ fn run_restart_case(mode: &str) { std::fs::rename(doc, max_doc).unwrap(); std::fs::rename(meta, max_meta).unwrap(); } - let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "recovery::tests::restart_recovery_child", "--ignored", "--nocapture"]) - .env("DESIGNCRAFT_TEST_RECOVERY_SOURCE", source.path()) - .env("DESIGNCRAFT_TEST_RECOVERY_MODE", mode) - .output() - .unwrap(); + // `spawn` returns once the child runs its program, and its copies of this process's files + // are closed by then. + let child = { + let _spawning = SPAWN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "recovery::tests::restart_recovery_child", "--ignored", "--nocapture"]) + .env("DESIGNCRAFT_TEST_RECOVERY_SOURCE", source.path()) + .env("DESIGNCRAFT_TEST_RECOVERY_MODE", mode) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }; + let output = child.wait_with_output().unwrap(); assert!(output.status.success(), "fresh child failed: {}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); let child_stdout = String::from_utf8_lossy(&output.stdout); assert!(child_stdout.contains("test result: ok. 1 passed; 0 failed;"), "the fresh-process helper did not run exactly once: {child_stdout}"); @@ -953,6 +1033,8 @@ fn documents_of_two_apps_that_ended_are_both_recovered() { fn a_running_apps_recovery_data_is_left_alone() { let root = tempfile::tempdir().unwrap(); let running = run_left(root.path(), "run-7-0", "still open", 1); + // No child starts while the lock is open, so closing it frees it (see `SPAWN`). + let _no_spawn = SPAWN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let lock = std::fs::File::open(running.join(LOCK)).unwrap(); lock.try_lock().unwrap(); let own = run_dir(root.path()).unwrap(); From f27e2c380bac9221e1234fc17423b2c35573f3bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:30:25 -0800 Subject: [PATCH 134/328] Data merge: overset count composes with the merged images' Alpha Channel outlines --- crates/engine/src/cmd/datamerge.rs | 2 ++ crates/engine/src/cmd/datamerge/tests.rs | 27 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index aad5b72f3..84e8b65e3 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -263,6 +263,8 @@ fn merge_cmd(s: &mut Session, p: &Value) -> Result { merged.data_merge.placeholders.clear(); merged.title = format!("{} merged", src.title); let pages = merged.page_count(); + // The merged images' Alpha Channel outlines first: the overset count composes with them. + crate::cmd::alpha_wrap::sync(&mut merged); let overset = overset_count(&merged); let records = selected.len(); let missing_json: Vec = missing.iter().map(|m| json!({"record": m.record, "field": m.field, "path": m.path})).collect(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index dad43af66..062ff9483 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1337,3 +1337,30 @@ fn a_previewed_image_gets_its_alpha_channel_outline() { assert!(d.alpha_outlines[0].width > 0 && !d.alpha_outlines[0].outer.subpaths.is_empty()); let _ = std::fs::remove_dir_all(&dir); } + +/// The overset count data merge reports is composed with the merged images' Alpha Channel +/// outlines: a caption over the image's transparent part is set, not counted as overset. +#[test] +fn a_merge_counts_overset_text_with_the_merged_images_outlines() { + let dir = scratch("alpha-merge"); + // Visible only in the left quarter. + let mut pixels = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..16 { + pixels[(y * 64 + x) * 4 + 3] = 255; + } + } + std::fs::write(dir.join("cut.png"), designcraft_render::Rendered { width: 64, height: 64, pixels }.to_png()).unwrap(); + write(&dir.join("pics.csv"), "Photo\ncut.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": dir.join("pics.csv")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); + exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel", "offset": 0})); + text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + let _ = std::fs::remove_dir_all(&dir); +} From b73c21db37acf667461d99007be84ee7c2a8099b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:36:39 -0800 Subject: [PATCH 135/328] Data merge: a file that is not an image does not hide a later image candidate The image search stopped at the first file that could be read and checked whether it decodes afterwards. A non-image file at an earlier candidate (the drive root, or beside the data file) then hid a valid image beside the data file or the document, and the field was reported missing. The decode check now runs inside the search, so only an image ends it. --- crates/engine/src/cmd/datamerge/fill.rs | 11 ++++++----- crates/engine/src/cmd/datamerge/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index caea4d67e..ebe950fb6 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -464,7 +464,7 @@ struct LoadedImage { fn load_image(cell: &str, sources: &Sources) -> Option { let Sources { data_dir, doc_dir, images, .. } = *sources; let cands = image_candidates(cell, data_dir, doc_dir); - let (path, bytes) = cands.iter().find_map(|p| { + cands.iter().find_map(|p| { // Read once per merge: many records naming one file is the normal case, and reading it // per record is the amplification (#1595). let bytes = images.get_or_read(p, || { @@ -475,10 +475,11 @@ fn load_image(cell: &str, sources: &Sources) -> Option { } crate::io::read_file(p).ok().filter(|b| !b.is_empty()) })?; - Some((p.clone(), bytes)) - })?; - let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; - Some(LoadedImage { path, bytes, pixels, natural }) + // A file that does not decode leaves the search going, so a valid image at a later + // candidate is still found. + let (pixels, natural) = designcraft_render::image_size(&bytes).zip(designcraft_render::natural_size(&bytes, 0))?; + Some(LoadedImage { path: p.clone(), bytes, pixels, natural }) + }) } fn report_missing(report: &mut FillReport, record: u32, field: &str, cell: &str) { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 39b1988e2..5480a5686 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -914,6 +914,28 @@ fn an_image_path_with_a_leading_separator_is_found_beside_the_data_file() { assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); } +/// A file at an earlier candidate that is not an image does not hide a valid image at a later +/// one: the search goes on past it. +#[test] +fn a_non_image_file_beside_the_data_does_not_hide_the_image_beside_the_document() { + let dir = scratch("undecodable-image"); + let (data, docs) = (dir.join("data"), dir.join("docs")); + write(&data.join("pics").join("a.png"), "not an image"); + write_png_sized(&docs.join("pics").join("a.png"), 12, 12); + write(&data.join("cards.csv"), "@Photo\npics/a.png\n"); + let mut s = Session::new(); + new_doc(&mut s, 1); + exec(&mut s, "data.source.select", json!({"path": data.join("cards.csv")})); + exec(&mut s, "file.save", json!({"path": docs.join("layout.designcraft")})); + let frame = exec(&mut s, "frame.create", json!({"rect": [36.0, 36.0, 80.0, 80.0], "content": "graphic"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "item": frame["id"]})); + exec(&mut s, "data.options", json!({"linkImages": true})); + let r = exec(&mut s, "data.merge", json!({})); + assert_eq!(r["missingImages"].as_array().map(Vec::len), Some(0), "{r}"); + let link = graphic_link(&s).unwrap_or_default(); + assert!(link.contains("docs"), "{link}"); +} + #[test] fn single_record_merge_copies_pages_and_leaves_the_template() { let mut s = Session::new(); From 1455093812ee039a3e67acd495821b098f368791 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:37:03 -0800 Subject: [PATCH 136/328] Text wrap: the alpha threshold default is described as DesignCraft's own --- crates/doc/src/item/text_frame.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index c87b74e0a..62f12eb24 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -306,7 +306,7 @@ pub struct TextWrap { pub alpha_threshold: u8, } -/// InDesign's default alpha threshold for contour wraps. +/// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; impl Default for TextWrap { From 04fac58d9b9b229805e0fb165763b2fe0463afcc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:43:12 -0800 Subject: [PATCH 137/328] Recovery: writes are keyed by the folder's canonical path A synchronous recovery write now cancels a background write to the same folder named another way, and a cancel also matches the folder as the session named it. Background writes whose results have not been taken count toward the per-document checkpoint limit, cancelled ones excluded. Save, Revert and Close clean up a cancelled write's folder under the name the session used for it. --- crates/engine/src/recovery.rs | 103 ++++++++++++++++++++++------ crates/engine/src/recovery/tests.rs | 57 +++++++++++++++ 2 files changed, 138 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 6d2eac44d..f5bafd316 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -636,7 +636,21 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { /// Reject a complete batch before writing rather than silently losing old ownership records. fn reject_overfull_checkpoints(s: &Session, dir: &Path) -> Result<()> { for document in &s.docs { - if document.is_dirty() && !has_checkpoint(document, dir) && document.recovery_entries.len() >= MAX_RECOVERY_ENTRIES { + if !document.is_dirty() || has_checkpoint(document, dir) { + continue; + } + // Background writes whose results are not taken yet hold checkpoints the entries do not. + #[cfg(not(target_arch = "wasm32"))] + let pending = worker::pending_folders(document.uid, s.recovery_owner.0) + .into_iter() + .map(|pending| directory_key(&pending).unwrap_or(pending)) + .collect::>() + .iter() + .filter(|pending| !same_directory(pending, dir) && !has_checkpoint(document, pending)) + .count(); + #[cfg(target_arch = "wasm32")] + let pending = 0; + if document.recovery_entries.len() + pending >= MAX_RECOVERY_ENTRIES { return Err(EngineError::Other( "too many recovery checkpoints; save or close the document before choosing another recovery folder".into(), )); @@ -895,7 +909,7 @@ mod worker { pub(super) undelivered: Mutex>, /// Documents queued or being written, with the session that queued each: a second write /// of one still holds nothing newer. - running: Mutex>, + running: Mutex>, /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, @@ -903,15 +917,27 @@ mod worker { idle: Condvar, } + /// A write in flight: the session that queued it, and its folder as that session named it. + struct Queued { + owner: u64, + dir: PathBuf, + } + static WRITER: OnceLock> = OnceLock::new(); + /// A write's key: the folder's canonical path, so two spellings of one folder are one write. + fn key(dir: &Path, uid: u64) -> (PathBuf, u64) { + (super::directory_key(dir).unwrap_or_else(|_| dir.to_path_buf()), uid) + } + impl Writer { pub(super) fn busy(&self) -> bool { self.running.lock().is_ok_and(|running| !running.is_empty()) } - fn finish(&self, dir: &Path, uid: u64) { - let key = (dir.to_path_buf(), uid); + /// `key` is the job's ([`Snapshot::key`], uid). + fn finish(&self, key: &(PathBuf, u64)) { + let key = key.clone(); if let Ok(mut running) = self.running.lock() { running.remove(&key); } @@ -934,15 +960,19 @@ mod worker { /// reverted or closed. Only a write that is queued or running is marked, so the set stays /// as small as the work in flight. fn cancel(&self, dir: &Path, uid: u64) { - let key = (dir.to_path_buf(), uid); + let canonical = key(dir, uid); // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if !self.running.lock().is_ok_and(|running| running.contains_key(&key)) { - return; - } + // The folder's canonical path, or its name as given: a link in the path may lead + // elsewhere now than when the write was queued. + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect()) + .unwrap_or_default(); if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.insert(key); + cancelled.extend(keys); } } @@ -953,15 +983,18 @@ mod worker { // Held while results are read: the writer checks for a cancel and sends its result // under it, so a result sent after this sees the cancel. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - let keys: Vec<(PathBuf, u64)> = self + // The canonical keys to mark, and the folders as the session named them, which is how + // the cleanup finds this run's folder. + let (keys, mut dirs): (Vec<(PathBuf, u64)>, Vec) = self .running .lock() - .map(|running| running.iter().filter(|((_, u), o)| *u == uid && **o == owner).map(|(key, _)| key.clone()).collect()) + .map(|running| { + running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, q)| (key.clone(), q.dir.clone())).unzip() + }) .unwrap_or_default(); if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.extend(keys.iter().cloned()); + cancelled.extend(keys); } - let mut dirs: Vec = keys.into_iter().map(|(dir, _)| dir).collect(); // Results stay queued for their session; only their folders are read here. let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -975,8 +1008,26 @@ mod worker { dirs } - fn cancelled(&self, dir: &Path, uid: u64) -> bool { - self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&(dir.to_path_buf(), uid))) + /// The folders of writes of `uid` queued by session `owner` that are in flight, or finished + /// and published with their results not taken yet: checkpoints its entries do not hold yet. + fn pending_folders(&self, uid: u64, owner: u64) -> Vec { + let keys: Vec<(PathBuf, u64)> = self + .running + .lock() + .map(|running| running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, _)| key.clone()).collect()) + .unwrap_or_default(); + // A cancelled write publishes nothing. + let mut dirs: Vec = keys.into_iter().filter(|key| !self.cancelled(key)).map(|(dir, _)| dir).collect(); + let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + undelivered.extend(done.try_iter()); + dirs.extend(undelivered.iter().filter(|d| d.uid == uid && d.owner == owner && d.published).map(|d| d.dir.clone())); + dirs + } + + /// `key` as in [`Writer::finish`]. + fn cancelled(&self, key: &(PathBuf, u64)) -> bool { + self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(key)) } } @@ -989,6 +1040,7 @@ mod worker { let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { while let Ok(job) = job_rx.recv() { let (published, error) = guarded_write(&job); + let key = (job.key.clone(), job.uid); let (dir, uid, owner) = (job.dir, job.uid, job.owner); // The result before the document reads as idle: a writer that is not busy // has already delivered it, so the interface never stops polling with an @@ -996,11 +1048,11 @@ mod worker { let sent = { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // Cancelled after it was published: the canceller removes the snapshot. - let published = published && !cancelled(&dir, uid); - done_tx.send(Done { dir: dir.clone(), uid, error, published, owner }).is_ok() + let published = published && !started().is_some_and(|w| w.cancelled(&key)); + done_tx.send(Done { dir, uid, error, published, owner }).is_ok() }; if let Some(w) = WRITER.get().and_then(Option::as_ref) { - w.finish(&dir, uid); + w.finish(&key); } if !sent { break; @@ -1031,21 +1083,28 @@ mod worker { } } + /// See [`Writer::pending_folders`]. + pub(super) fn pending_folders(uid: u64, owner: u64) -> Vec { + started().map(|w| w.pending_folders(uid, owner)).unwrap_or_default() + } + /// Do not publish any write of `uid` in flight (see [`Writer::cancel_document`]). pub(super) fn cancel_document(uid: u64, owner: u64) -> Vec { started().map(|w| w.cancel_document(uid, owner)).unwrap_or_default() } /// Whether that write is already marked as cancelled (see [`Writer::cancelled`]). + #[cfg(test)] pub(super) fn cancelled(dir: &Path, uid: u64) -> bool { - started().is_some_and(|w| w.cancelled(dir, uid)) + started().is_some_and(|w| w.cancelled(&key(dir, uid))) } /// Write one snapshot, turning a panic into its error: a panic that ended this thread would /// leave the document marked as running for ever (so it is never written again) and the /// interface asking for frames for ever. A safety net: a writer still must not panic. fn guarded_write(job: &Snapshot) -> (bool, Option) { - match guarded(|| Ok(write_snapshot(job, || cancelled(&job.dir, job.uid)))) { + let key = (job.key.clone(), job.uid); + match guarded(|| Ok(write_snapshot(job, || started().is_some_and(|w| w.cancelled(&key))))) { // A primary that landed is this run's to remove, even if its metadata failed. Ok(written) => (written.published, written.error.map(|e| e.to_string())), Err(e) => (false, Some(e.to_string())), @@ -1064,11 +1123,11 @@ mod worker { pub(super) fn submit(entry: Snapshot) -> Option { let w = writer()?; let mut running = w.running.lock().ok()?; - let key = (entry.dir.clone(), entry.uid); + let key = (entry.key.clone(), entry.uid); if running.contains_key(&key) { return Some(false); } - running.insert(key.clone(), entry.owner); + running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone() }); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 2d6cc8861..2353e476d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -278,6 +278,63 @@ fn saving_in_one_session_leaves_another_sessions_write_alone() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("sub")).unwrap(); + let spelled = dir.path().join("sub").join(".."); + let mut s = dirty_session(); + s.recovery_dir = Some(spelled.clone()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(&spelled); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + // The newer state, written now under the folder's plain name. + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + s.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); + assert!(worker::cancelled(&spelled, uid), "the older write is cancelled"); + held.release(); + testing::wait_until_idle(); + let _ = s.execute("file.recovery.progress", &json!({})).unwrap(); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "the newer snapshot was kept"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn queued_background_writes_count_toward_the_checkpoint_limit() { + let _turn = background(); + let mut s = dirty_session(); + let folders: Vec = (0..=MAX_RECOVERY_ENTRIES).map(|_| tempfile::tempdir().unwrap()).collect(); + // The first write is held, so every later one is still queued when the next is asked for. + let held = testing::hold_next_write(folders[0].path()); + for folder in &folders[..MAX_RECOVERY_ENTRIES] { + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": folder.path().to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + } + let over = folders[MAX_RECOVERY_ENTRIES].path(); + let err = s.execute("file.recovery.save", &json!({"background": true, "dir": over.to_string_lossy()})).unwrap_err(); + assert!(err.to_string().contains("too many recovery checkpoints"), "{err}"); + // Saving cancels the queued writes: they no longer count once the document changes again. + let saved = folders[0].path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let queued = s.execute("file.recovery.save", &json!({"background": true, "dir": over.to_string_lossy()})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.release(); + assert_eq!(finished_writes(&mut s), 1, "only the write queued after the save is a checkpoint"); + assert_eq!(list(over).len(), 1); + let uid = s.docs[0].uid; + for folder in &folders { + discard(folder.path(), uid); + } +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn results_for_a_session_that_is_gone_are_not_kept() { From 9cea62b2380e447342fbddc0a5ecd29b87f6be55 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:48:43 -0800 Subject: [PATCH 138/328] Type: a repeated alignment records no undo step; menu-bar inserts stop with the window's shortcuts - Align Left, Center, Right, Justify Left, Justify All Lines and type.align leave the document and the undo list alone when every target paragraph already has that alignment as its own value. - On the Mac, Em Space, En Space and Current Page Number from the menu bar also do nothing while Quick Apply or a dialog is open, an input method is composing or a canvas context menu is open, the cases that stop the window's own shortcuts. - Tests for both, and for Justify All Lines across threaded frames, over a paragraph style, through IDML export and import, and with parameters it does not take. --- ROADMAP.md | 3 +- crates/engine/src/cmd/text.rs | 174 ++++++++++++++++++++++++++--- crates/ui-egui/src/menus/invoke.rs | 8 +- crates/ui-egui/src/menus/keys.rs | 2 +- crates/ui-egui/src/menus/tests.rs | 27 ++++- 5 files changed, 187 insertions(+), 27 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b5967dd01..8dc79c909 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. @@ -860,5 +861,3 @@ The shared craft-installer UI preserves this revision's install options and prov - **2026-10-15** · Windows recovery folders validate the identity of the live locked file without reading it through a second handle. Missing or replaced locks disable writes and cleanup; regression tests cover retained exclusive locking and replacement-file protection. No readiness percentage change. - PDF reader infrastructure: pinned shared parsing/rasterization, transformed page-box geometry and explicit failures for known incomplete layered-PDF exports. Application ownership and parity targets are unchanged. - -- **2026-10-16** · InDesign's type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus. No readiness percentage change. diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index eb6e3e0b5..7f8def96c 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -2,7 +2,7 @@ use designcraft_compose as compose; use designcraft_doc::story::floor_char_boundary; -use designcraft_doc::{CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel}; +use designcraft_doc::{Align, CellAddr, CharAttrs, Content, ItemId, ParaAttrs, Selection, StoryId, TextSel}; use designcraft_geom::Point; use serde_json::{Value, json}; @@ -240,21 +240,19 @@ pub fn specs() -> Vec { ), cmd!("type.align", "Align", [], None, "{align: left|center|right|leftJustified|…|null} (required)", has_text_or_frames, |s, p| { let align = p.get("align").cloned().ok_or_else(|| bad("type.align", "`align` required"))?; - format_paras(s, &json!({ "align": align })) + // A value that isn't an alignment goes to `format_paras`, which names the error. + match serde_json::from_value::>(align.clone()) { + Ok(a) => align_paras(s, a), + Err(_) => format_paras(s, &json!({ "align": align })), + } }), - cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "left"}))), - cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| format_paras( + cmd!("type.alignLeft", "Align Left", [], Some("Cmd+Shift+L"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Left))), + cmd!("type.alignCenter", "Align Center", [], Some("Cmd+Shift+C"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Center))), + cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::Right))), + cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| align_paras(s, Some(Align::LeftJustified))), + cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| align_paras( s, - &json!({"align": "center"}) - )), - cmd!("type.alignRight", "Align Right", [], Some("Cmd+Shift+R"), "{}", has_text_or_frames, |s, _| format_paras(s, &json!({"align": "right"}))), - cmd!("type.justify", "Justify Left", [], Some("Cmd+Shift+J"), "{}", has_text_or_frames, |s, _| format_paras( - s, - &json!({"align": "leftJustified"}) - )), - cmd!("type.justifyAll", "Justify all lines", [], Some("Cmd+Shift+F"), "{}", has_text_or_frames, |s, _| format_paras( - s, - &json!({"align": "fullyJustified"}) + Some(Align::FullyJustified) )), cmd!( "type.bold", @@ -448,24 +446,164 @@ pub fn specs() -> Vec { ] } +/// Sets the alignment of the paragraphs a formatting command targets (`None` removes the +/// override, back to the style's value). When each of them already carries that value as its +/// own, or there is no paragraph to change, the document is left as it is and no undo step is +/// recorded. +fn align_paras(s: &mut Session, align: Option) -> Result { + let targets = format_targets(s); + let doc = &s.doc()?.doc; + let unchanged = targets.iter().all(|t| { + doc.text_story(t.story, t.cell).is_none_or(|st| { + let (a, b) = (st.para_at(t.range.start), st.para_at(t.range.end.max(t.range.start))); + st.paras.get(a..=b).is_none_or(|paras| paras.iter().all(|p| p.para.align == align)) + }) + }); + if unchanged { + return ok(); + } + format_paras(s, &json!({ "align": align })) +} + #[cfg(test)] mod alignment_shortcut_tests { - use serde_json::json; + use designcraft_doc::{Align, Document}; + use serde_json::{Value, json}; use crate::Session; - /// InDesign's Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. + fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() + } + + fn selection_align(s: &mut Session) -> Value { + s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone() + } + + /// The resolved alignment of every paragraph of the story whose text starts with `start`. + fn story_aligns(d: &Document, start: &str) -> Vec { + let st = d.stories.values().find(|st| st.text.starts_with(start)).unwrap(); + st.paras.iter().map(|p| d.styles.resolve_para(p).0.align).collect() + } + + /// Justify All Lines is ⇧⌘F (Shift+Ctrl+F), next to Justify Left ⇧⌘J. #[test] - fn justify_all_lines_has_indesigns_shortcut_and_justifies_the_last_line_too() { + fn justify_all_lines_has_its_shortcut_and_justifies_the_last_line_too() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); s.execute("text.select", &json!({"story": r["story"], "anchor": 3, "focus": 3})).unwrap(); - // From Justify Left, so the result is not a default or a neighbouring justification. + // From Justify Left, so the result is not a default or a neighboring justification. s.execute("type.justify", &json!({})).unwrap(); assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "leftJustified"); s.execute("type.justifyAll", &json!({})).unwrap(); assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"], "fullyJustified"); assert_eq!(crate::find_command("type.justifyAll").and_then(|c| c.shortcut), Some("Cmd+Shift+F")); } + + /// A second press of an alignment shortcut, or `type.align` with the value the paragraphs + /// already have, leaves the document and the undo list alone. + #[test] + fn an_alignment_the_paragraphs_already_have_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "One\nTwo"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap(); + for (id, params, align) in [ + ("type.justifyAll", json!({}), "fullyJustified"), + ("type.align", json!({"align": "center"}), "center"), + ("type.alignLeft", json!({}), "left"), + ("type.alignCenter", json!({}), "center"), + ("type.alignRight", json!({}), "right"), + ("type.justify", json!({}), "leftJustified"), + ] { + let before = undo_steps(&s); + s.execute(id, ¶ms).unwrap(); + assert_eq!(selection_align(&mut s), align, "{id}"); + assert_eq!(undo_steps(&s), before + 1, "{id}: one step"); + let rev = s.doc().unwrap().doc.clone(); + s.execute(id, ¶ms).unwrap(); + assert_eq!(undo_steps(&s), before + 1, "{id} again: no step"); + assert!(std::sync::Arc::ptr_eq(&rev, &s.doc().unwrap().doc), "{id} again: the document is unchanged"); + } + // Removing the override: once it is gone, a second removal does nothing. + s.execute("type.align", &json!({"align": null})).unwrap(); + let before = undo_steps(&s); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(undo_steps(&s), before); + // One paragraph that differs is enough to apply it, to both. + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 5})).unwrap(); + let before = undo_steps(&s); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "One"), [Align::FullyJustified; 2]); + } + + /// The shortcut commands take no parameters: a misspelled call is refused and changes nothing. + #[test] + fn justify_all_lines_refuses_parameters() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 1, "focus": 1})).unwrap(); + let before = undo_steps(&s); + assert!(s.execute("type.justifyAll", &json!({"align": "left"})).is_err()); + assert_eq!(selection_align(&mut s), "left"); + assert_eq!(undo_steps(&s), before); + } + + /// With text frames selected, every paragraph of their stories, across threaded frames; + /// other selected frames are skipped, and a selection with no text frame is refused. + #[test] + fn justify_all_lines_on_frames_reaches_threaded_text_and_skips_other_frames() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [36, 36, 300, 60], "content": "text", "text": "Alpha\nBeta\nGamma\nDelta"})).unwrap(); + let b = s.execute("frame.create", &json!({"rect": [36, 300, 300, 500], "content": "text"})).unwrap(); + s.execute("text.thread", &json!({"from": a["id"], "to": b["id"]})).unwrap(); + let rect = s.execute("frame.create", &json!({"rect": [400, 36, 500, 136]})).unwrap(); + s.execute("selection.set", &json!({"ids": [rect["id"]]})).unwrap(); + let before = undo_steps(&s); + assert!(s.execute("type.justifyAll", &json!({})).is_err(), "no text frame selected"); + assert_eq!(undo_steps(&s), before); + // The second frame of the thread and the rectangle. + s.execute("selection.set", &json!({"ids": [b["id"], rect["id"]]})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "Alpha"), [Align::FullyJustified; 4]); + } + + /// Over a paragraph style's alignment, Justify All Lines is a local override: the style keeps + /// its value, and removing the override goes back to it. + #[test] + fn justify_all_lines_overrides_the_paragraph_style() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring issue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 2, "focus": 2})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Caption", "para": {"align": "right"}})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Caption"})).unwrap(); + assert_eq!(selection_align(&mut s), "right"); + s.execute("type.justifyAll", &json!({})).unwrap(); + assert_eq!(selection_align(&mut s), "fullyJustified"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.styles.resolve_para_style("Caption").0.align, Align::Right); + s.execute("type.align", &json!({"align": null})).unwrap(); + assert_eq!(selection_align(&mut s), "right"); + } + + /// IDML writes the paragraph's Justification as FullyJustified and reads it back. + #[test] + fn justify_all_lines_survives_idml_export_and_import() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Spring\nissue"})).unwrap(); + s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap(); + s.execute("type.justifyAll", &json!({})).unwrap(); + let bytes = designcraft_idml::export_idml(&s.doc().unwrap().doc); + s.execute("file.openIdml", &json!({"base64": crate::cmd::base64_encode(&bytes), "name": "in.idml"})).unwrap(); + assert_eq!(story_aligns(&s.doc().unwrap().doc, "Spring"), [Align::FullyJustified, Align::Left]); + } } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 33096849d..492cdc7e2 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -146,9 +146,11 @@ pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, param if params.is_null() && ctx.text_edit_focused() && forward_to_text_edit(app, ctx, id) { return; } - // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change) - // or a dialog open, the character would land at the canvas caret behind it. - if params.is_null() && (ctx.text_edit_focused() || app.ui.dialog.is_some()) && TEXT_INSERTS.contains(&id) { + // The menu bar takes ⇧⌘M before the window: with a field focused (Story Editor, Find/Change), + // a dialog or Quick Apply open, an input method composing or a context menu open, the + // character would land at the canvas caret behind it. The window's shortcuts stop for the + // same cases. + if params.is_null() && (ctx.text_edit_focused() || super::keys::keys_taken(app, ctx)) && TEXT_INSERTS.contains(&id) { return; } // The canvas text editor is not an egui TextEdit, so its clipboard events must pass through diff --git a/crates/ui-egui/src/menus/keys.rs b/crates/ui-egui/src/menus/keys.rs index 8b2179469..a4cf59eed 100644 --- a/crates/ui-egui/src/menus/keys.rs +++ b/crates/ui-egui/src/menus/keys.rs @@ -66,7 +66,7 @@ pub fn forwarded_shortcuts(app: &mut DesignApp, ctx: &egui::Context, events: Vec /// Whether something other than the shortcuts has the keyboard: a dialog or Quick Apply, an input /// method composing at the text caret, an open canvas context menu (Escape closes it, as a /// native menu would) or the menu search. -fn keys_taken(app: &DesignApp, ctx: &egui::Context) -> bool { +pub(super) fn keys_taken(app: &DesignApp, ctx: &egui::Context) -> bool { app.ui.dialog.is_some() || app.ui.palette.is_some() || app.session.tool_composing() diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 5958bcd4d..24ccb02a0 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2499,14 +2499,14 @@ fn story_text(app: &crate::DesignApp, story: &Value) -> String { } #[test] -fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { +fn type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { use egui::{Key, Modifiers}; let ctx = egui::Context::default(); let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({})).unwrap(); let frame = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap(); let story = frame["story"].clone(); - // A selected frame and no insertion point: the spaces have nowhere to go, as in InDesign. + // A selected frame and no insertion point: the spaces have nowhere to go. app.run("selection.set", json!({"ids": [frame["id"]]})).unwrap(); assert!(app.session.doc().unwrap().selection.text.is_none()); assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); @@ -2521,7 +2521,7 @@ fn indesigns_type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_r app.run("type.justify", json!({})).unwrap(); press(&mut app, &ctx, Key::F, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(app.run("type.selectionAttrs", json!({})).unwrap()["para"]["align"], "fullyJustified", "⇧⌘F justifies all lines"); - // Guard: ⌥⇧⌘J is another chord (InDesign's Justification…); the rules want Shift up. + // Guard: ⌥⇧⌘J is another chord (Justification…); the rules want Shift up. press(&mut app, &ctx, Key::J, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT); assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("justification"), "⌥⇧⌘J opens Justification"); app.ui.dialog = None; @@ -2581,6 +2581,27 @@ fn native_insert_shortcuts_leave_the_document_alone_while_a_field_has_focus() { assert_eq!(app.ui.palette.as_deref(), Some("x")); } +#[test] +fn native_insert_shortcuts_leave_the_document_alone_while_a_dialog_or_quick_apply_is_open() { + // The same cases stop the window's shortcuts. In the first frame nothing has keyboard focus + // yet, so only the open dialog or Quick Apply keeps the character out of the story. + for open in ["", "dialog", "palette"] { + let ctx = egui::Context::default(); + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let story = app.run("frame.create", json!({"rect": [36, 36, 300, 200], "content": "text", "text": "ab"})).unwrap()["story"].clone(); + app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); + match open { + "dialog" => app.ui.dialog = Some(crate::dialogs::Dialog::new("paragraphRules", json!({}))), + "palette" => app.ui.palette = Some(String::new()), + _ => {} + } + native_frame(&mut app, &ctx, vec![], Some("app.insertEmSpace")); + let want = if open.is_empty() { "a\u{2003}b" } else { "ab" }; + assert_eq!(story_text(&app, &story), want, "{open:?}"); + } +} + #[test] fn custom_workspaces_save_apply_and_delete() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 630b5dfc43d32b15181afaee13a2bf6b95dd7cd0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:50:24 -0800 Subject: [PATCH 139/328] Paste: images on the system clipboard paste as embedded images (#2204) Paste ignored a bitmap on the system clipboard: a screenshot or an image copied in a browser had to be saved and placed. Paste now places it. - edit.pasteImage {base64, name?, spread?, at?} embeds the image in the selected empty frame, or in a new frame centered on `at` at its stored resolution (72 ppi when none) and at most 60% of the page width, as File > Place sizes it. Save and reopen and IDML export keep the pixels. Images over 64 million pixels and names without an image extension are refused. - Ctrl/Cmd+V pastes the image egui delivers with no text, and Edit > Paste reads the clipboard's bitmap, or the first image file of a copied file list, when there is no text or the text is only an address. - The menu read waits at most 1.5 s on its own thread, with one read in flight at a time. - With a native menu, objects copied here still paste as objects until the pasteboard's change count shows a newer copy. - ui.paste takes {image} for the control channel. --- apps/designcraft/Cargo.toml | 8 +- apps/designcraft/src/clipboard_image.rs | 135 +++++++++++++ apps/designcraft/src/main.rs | 4 + crates/engine/src/cmd.rs | 3 + crates/engine/src/cmd/paste_image.rs | 251 ++++++++++++++++++++++++ crates/images/src/lib.rs | 9 + crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/clipboard.rs | 89 ++++++++- crates/ui-egui/src/app/commands.rs | 12 +- crates/ui-egui/src/canvas/input.rs | 16 +- crates/ui-egui/src/canvas/tests.rs | 121 ++++++++++++ crates/ui-egui/src/control.rs | 21 +- crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/services.rs | 33 ++++ docs/control-protocol.md | 2 +- 15 files changed, 694 insertions(+), 19 deletions(-) create mode 100644 apps/designcraft/src/clipboard_image.rs create mode 100644 crates/engine/src/cmd/paste_image.rs diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index b17258acd..b66041a04 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -27,7 +27,8 @@ winresource = "0.1" # Not called here: craft-dialogs shows the dialogs. rfd's default features keep its Wayland # support on, so portal dialogs get the window as their parent. rfd = { workspace = true } -arboard = { workspace = true } +# `image-data`: Edit › Paste reads bitmaps from the clipboard (src/clipboard_image.rs). +arboard = { workspace = true, features = ["image-data"] } [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] # The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs. @@ -46,9 +47,10 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user"] } winit = { version = "0.30", default-features = false } muda = { version = "0.21", default-features = false } # The input context, to drop the IME's marked text when the Type tool ends a composition. The -# versions muda uses, through safe methods. +# versions muda uses, through safe methods. `NSPasteboard`: the pasteboard's change count, which +# tells Paste whether anything was copied since an object Copy (src/clipboard_image.rs). objc2 = "0.6" -objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSResponder", "NSScreen", "NSTextInputContext"] } +objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSEvent", "NSPasteboard", "NSResponder", "NSScreen", "NSTextInputContext"] } # Files dragged in from the Finder: the pointer's place on the screen (src/pointer.rs). objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSGeometry"] } # The window's `movable` flag follows the application bar's controls. diff --git a/apps/designcraft/src/clipboard_image.rs b/apps/designcraft/src/clipboard_image.rs new file mode 100644 index 000000000..0e8339ff4 --- /dev/null +++ b/apps/designcraft/src/clipboard_image.rs @@ -0,0 +1,135 @@ +//! The system clipboard's image for Edit › Paste (`Services::clipboard_image`): a bitmap +//! (Windows `CF_DIBV5` or `PNG`, the macOS pasteboard's TIFF or PNG, `image/png` on X11), else the +//! first image file of files copied in a file manager. The read runs on its own thread, and Paste +//! waits for it at most [`WAIT`], so an application that is slow to hand over the clipboard does +//! not freeze the window. While a read that timed out is still waiting, Paste starts no other. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use designcraft_ui_egui::ClipboardImage; + +/// How long Paste waits for the clipboard's image. +const WAIT: Duration = Duration::from_millis(1500); + +/// The largest image file Paste reads from a copied file list, in bytes. +const MAX_FILE_BYTES: u64 = 256 << 20; + +/// A clipboard read is running. +static READING: AtomicBool = AtomicBool::new(false); + +/// The clipboard's image, or `None` when it holds none or does not answer within [`WAIT`]. +pub fn read() -> Option { + within(&READING, WAIT, read_now) +} + +/// Clears the in-flight flag when the read's thread ends. +struct Reading(&'static AtomicBool); + +impl Drop for Reading { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +/// `read`'s result when it arrives within `wait`. A read that takes longer finishes on its own +/// thread and is dropped; until it does, `busy` stays set and no other read starts. +fn within(busy: &'static AtomicBool, wait: Duration, read: impl FnOnce() -> Option + Send + 'static) -> Option { + if busy.swap(true, Ordering::AcqRel) { + log::warn!("clipboard image: the previous read has not finished"); + return None; + } + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new().name("clipboard image".into()).spawn(move || { + let _reading = Reading(busy); + let _ = tx.send(read()); + }); + if let Err(e) = spawned { + busy.store(false, Ordering::Release); + log::warn!("clipboard image: no thread to read it: {e}"); + return None; + } + match rx.recv_timeout(wait) { + Ok(image) => image, + Err(mpsc::RecvTimeoutError::Timeout) => { + log::warn!("clipboard image: the clipboard did not answer within {} ms", wait.as_millis()); + None + } + Err(mpsc::RecvTimeoutError::Disconnected) => None, + } +} + +/// The general pasteboard's change count, which AppKit raises with every copy. +#[cfg(target_os = "macos")] +pub fn change_count() -> Option { + i64::try_from(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount()).ok() +} + +fn read_now() -> Option { + let mut clipboard = arboard::Clipboard::new().ok()?; + if let Ok(image) = clipboard.get_image() { + let width = u32::try_from(image.width).ok()?; + let height = u32::try_from(image.height).ok()?; + return Some(ClipboardImage::Pixels { width, height, rgba: image.bytes.into_owned() }); + } + first_image_file(&clipboard.get().file_list().ok()?) +} + +/// The first of `paths` that is an image file no larger than [`MAX_FILE_BYTES`], with its name. +fn first_image_file(paths: &[PathBuf]) -> Option { + paths.iter().find_map(|path| { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + if !designcraft_engine::cmd::IMAGE_EXTENSIONS.contains(&ext.as_str()) || std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES { + return None; + } + // At most one byte past the limit is read, should the file grow after the size check. + let bytes = designcraft_engine::io::read_capped(path, MAX_FILE_BYTES).ok().filter(|b| b.len() as u64 <= MAX_FILE_BYTES)?; + Some(ClipboardImage::File { name: file_name(path), bytes }) + }) +} + +fn file_name(path: &Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_read_that_does_not_answer_is_given_up_and_no_second_one_starts_meanwhile() { + static BUSY: AtomicBool = AtomicBool::new(false); + let (release, blocked) = mpsc::channel::<()>(); + // The read waits for a message that is only sent after Paste has given up on it. + assert_eq!(within(&BUSY, Duration::ZERO, move || blocked.recv().ok().map(|()| 1)), None); + let (started, ran) = mpsc::channel::<()>(); + let second = within(&BUSY, Duration::from_secs(60), move || started.send(()).ok().map(|()| 2)); + assert_eq!(second, None, "refused while the first read waits"); + assert!(ran.try_recv().is_err(), "the second read never ran"); + let _ = release.send(()); + while BUSY.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(within(&BUSY, Duration::from_secs(60), || Some(3)), Some(3), "an answer is taken as soon as it comes"); + } + + #[test] + fn a_copied_file_list_pastes_its_first_image_file() { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let dir = std::env::temp_dir().join(format!("designcraft-clipboard-files-{}-{stamp}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let (text, missing, png) = (dir.join("notes.txt"), dir.join("gone.png"), dir.join("Photo.PNG")); + std::fs::write(&text, b"text").unwrap(); + std::fs::write(&png, b"png bytes").unwrap(); + let picked = first_image_file(&[text, missing, png.clone()]); + let none = first_image_file(&[dir.join("a.txt")]); + let _ = std::fs::remove_dir_all(&dir); + match picked { + Some(ClipboardImage::File { name, bytes }) => assert_eq!((name.as_str(), bytes.as_slice()), ("Photo.PNG", b"png bytes".as_slice())), + _ => panic!("the image file is picked"), + } + assert!(none.is_none()); + } +} diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index ab6970332..5f465e46d 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -15,6 +15,7 @@ #[cfg(target_os = "macos")] mod apple_events; +mod clipboard_image; mod control_server; mod gpu; mod gpu_limits; @@ -227,6 +228,9 @@ fn services() -> Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), write: Some(Box::new(|p: &str, b: &[u8]| designcraft_engine::atomic::write_atomic(std::path::Path::new(p), b).map_err(|e| e.to_string()))), clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())), + clipboard_image: Some(Box::new(clipboard_image::read)), + #[cfg(target_os = "macos")] + clipboard_change: Some(Box::new(clipboard_image::change_count)), #[cfg(target_os = "macos")] pointer: Some(Box::new(pointer::screen_position)), ..Default::default() diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index dc1acaf15..20260a5ad 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -44,6 +44,7 @@ mod object; mod overrides; mod package; pub mod params; +mod paste_image; mod paste_svg; mod path_type; mod paths; @@ -179,6 +180,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(export::specs()); v.extend(export_batch::specs()); v.extend(edit::specs()); + v.extend(paste_image::specs()); v.extend(paste_svg::specs()); v.extend(endnotes::specs()); v.extend(editorial::specs()); @@ -376,5 +378,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; pub use layout::chapter_numbering; +pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs new file mode 100644 index 000000000..d5197a90c --- /dev/null +++ b/crates/engine/src/cmd/paste_image.rs @@ -0,0 +1,251 @@ +//! Paste a bitmap from the system clipboard (a screenshot, an image copied in a web browser or an +//! image editor, an image file copied in a file manager) as a placed image. The pixels are +//! embedded in the document, so a save and reopen or an IDML export keeps them. + +use designcraft_doc::Content; +use designcraft_geom::Point; +use serde_json::{Value, json}; + +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, spread_param}; + +const ID: &str = "edit.pasteImage"; + +/// The most pixels a pasted image may have (8,000 × 8,000). +pub const MAX_PASTED_PIXELS: u64 = 64_000_000; + +/// The largest pasted image file, in bytes. +const MAX_PASTED_BYTES: usize = 256 << 20; + +/// The extensions a pasted image's name may end in. +pub const IMAGE_EXTENSIONS: [&str; 8] = ["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp"]; + +/// The name a pasted bitmap gets in the Links panel when it comes with none. +pub const PASTED_IMAGE_NAME: &str = "Pasted image.png"; + +pub fn specs() -> Vec { + vec![cmd!( + "edit.pasteImage", + "Paste Image", + [], + None, + "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at its stored resolution (72 ppi when none) and at most 60% of the page width", + has_doc, + paste_image + )] +} + +/// Whether a `width × height` bitmap is small enough to paste; the error says why not. +pub fn check_pasted_size(width: u32, height: u32) -> std::result::Result<(), String> { + if width == 0 || height == 0 { + return Err("the image on the clipboard has no pixels".into()); + } + if u64::from(width) * u64::from(height) > MAX_PASTED_PIXELS { + return Err(format!( + "the image on the clipboard is {width} × {height} pixels; images of up to 64 million pixels can be pasted (save it and use File › Place)" + )); + } + Ok(()) +} + +/// Unpremultiplied RGBA pixels from the clipboard, rows top to bottom, as a PNG file for +/// [`edit.pasteImage`](specs). +pub fn pasted_png(width: u32, height: u32, rgba: Vec) -> std::result::Result, String> { + check_pasted_size(width, height)?; + if (rgba.len() as u64) != u64::from(width) * u64::from(height) * 4 { + return Err("the image on the clipboard has the wrong number of pixels".into()); + } + designcraft_images::png_from_rgba(width, height, rgba).ok_or_else(|| "the image on the clipboard can't be stored".to_string()) +} + +/// An image file's pixels: (width, height, unpremultiplied RGBA). `None` when it is not a raster +/// DesignCraft reads or has more pixels than [`MAX_PASTED_PIXELS`]. +pub fn pasted_pixels(bytes: &[u8]) -> Option<(u32, u32, Vec)> { + let (w, h) = raster_size(bytes)?; + check_pasted_size(w, h).ok()?; + let img = designcraft_images::decode_rgba(bytes)?; + Some((img.width(), img.height(), img.into_raw())) +} + +/// A raster's pixel size; `None` for vector formats (PDF, SVG, EPS) and unreadable data. +fn raster_size(bytes: &[u8]) -> Option<(u32, u32)> { + if designcraft_images::is_pdf(bytes) || designcraft_images::is_svg(bytes) || designcraft_images::is_eps(bytes) { + return None; + } + designcraft_images::pixel_size(bytes) +} + +fn paste_image(s: &mut Session, p: &Value) -> Result { + let b64 = match p.get("base64") { + Some(Value::String(b)) if !b.is_empty() => b, + Some(_) => return Err(bad(ID, "`base64` must be a non-empty string")), + None => return Err(bad(ID, "missing base64")), + }; + if b64.len() / 4 * 3 > MAX_PASTED_BYTES { + return Err(bad(ID, format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20))); + } + let name = match p.get("name") { + None | Some(Value::Null) => PASTED_IMAGE_NAME, + Some(Value::String(n)) if !n.trim().is_empty() => n.as_str(), + Some(_) => return Err(bad(ID, "`name` must be a non-empty string")), + }; + // File › Place picks text and layout import by the name's extension: keep it an image's. + let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default(); + if !IMAGE_EXTENSIONS.contains(&ext.as_str()) { + return Err(bad(ID, format!("`name` must end in an image extension ({})", IMAGE_EXTENSIONS.join(", ")))); + } + let bytes = super::base64_decode(b64); + let (pw, ph) = raster_size(&bytes).ok_or_else(|| bad(ID, "the clipboard doesn't hold an image DesignCraft can read"))?; + check_pasted_size(pw, ph).map_err(|e| bad(ID, e))?; + let sr = spread_param(p, ID)?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(_) => { + let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "`at` must be [x, y]"))?; + if !(at.x.is_finite() && at.y.is_finite()) { + return Err(bad(ID, "`at` must be finite")); + } + Some(at) + } + }; + // A selected empty frame takes the image, as File › Place fills it. + let st = s.doc()?; + let empty_frame = match st.selection.items.as_slice() { + [only] if st.doc.item(*only).is_some_and(|it| !it.locked && it.path.encloses_area() && matches!(it.content, Content::Unassigned)) => { + Some(only.0) + } + _ => None, + }; + if let Some(frame) = empty_frame { + return s.execute("file.place", &json!({"base64": b64, "name": name, "frame": frame})); + } + let d = &s.doc()?.doc; + let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?; + let center = match at { + Some(at) => at, + None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()), + }; + // The size File › Place gives it: the stored resolution (72 ppi when none), at most 60% of + // the page width. + let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph))); + let w = nw.min(d.settings.page_width * 0.6); + let h = nh * w / nw; + let spread = p.get("spread").cloned().unwrap_or(Value::Null); + s.execute("file.place", &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cmd::{base64_decode, base64_encode}; + use designcraft_doc::{ItemId, SpreadRef}; + + /// A `w × h` PNG whose pixels count up, so a changed pixel shows. + fn png(w: u32, h: u32) -> Vec { + let rgba: Vec = (0..w * h * 4).map(|i| (i % 251) as u8).collect(); + pasted_png(w, h, rgba).unwrap() + } + + fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s + } + + fn placed_png(s: &Session, id: ItemId) -> Vec { + let d = &s.doc().unwrap().doc; + let Content::Graphic(g) = &d.item(id).unwrap().content else { panic!("not a graphic") }; + let a = &d.assets[&g.asset]; + assert_eq!(a.link, None, "embedded, not linked"); + a.data.to_vec() + } + + #[test] + fn a_pasted_bitmap_is_embedded_at_the_center_and_kept_by_save_and_idml() { + let mut s = doc(); + let png = png(40, 30); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png), "at": [300, 400]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let id = ItemId(r["id"].as_u64().unwrap()); + let st = s.doc().unwrap(); + assert_eq!(st.selection.items, [id], "the pasted image is selected"); + let b = st.doc.item(id).unwrap().bounds(); + assert!( + (b.x0 - 280.0).abs() < 1e-9 && (b.y0 - 385.0).abs() < 1e-9 && (b.width() - 40.0).abs() < 1e-9 && (b.height() - 30.0).abs() < 1e-9, + "{b:?}" + ); + assert_eq!(placed_png(&s, id), png); + assert_eq!(s.doc().unwrap().doc.assets[&designcraft_doc::AssetId(r["asset"].as_u64().unwrap())].name, PASTED_IMAGE_NAME); + + let saved = s.execute("file.serialize", &json!({})).unwrap(); + let mut t = Session::new(); + t.execute("file.openBytes", &json!({"name": "a.designcraft", "base64": saved["base64"]})).unwrap(); + assert_eq!(placed_png(&t, id), png, "saved with the document"); + + let idml = s.execute("file.exportIdml", &json!({})).unwrap(); + let imported = designcraft_idml::import_idml(&base64_decode(idml["base64"].as_str().unwrap())).unwrap(); + assert!(imported.assets.values().any(|a| *a.data == png), "the IDML package carries the pixels"); + } + + #[test] + fn without_a_point_the_image_lands_in_the_middle_of_the_first_page_and_shrinks_to_the_page() { + let mut s = doc(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png(1000, 10))})).unwrap(); + let d = &s.doc().unwrap().doc; + let b = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds(); + let page = d.spread(SpreadRef::Doc(0)).unwrap().pages[0].bounds(); + let w = d.settings.page_width * 0.6; + assert!((b.width() - w).abs() < 1e-9 && (b.height() - w / 100.0).abs() < 1e-9, "{b:?}"); + assert!((b.center().x - page.center().x).abs() < 1e-9 && (b.center().y - page.center().y).abs() < 1e-9, "{b:?}"); + } + + #[test] + fn a_selected_empty_frame_takes_the_image() { + let mut s = doc(); + let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + let items = s.doc().unwrap().doc.spreads[0].items.len(); + let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap(); + assert_eq!(r["id"].as_u64(), Some(frame)); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items, "no new frame"); + // A frame that already holds a graphic gets a new frame beside it instead. + let r = s.execute(ID, &json!({"base64": base64_encode(&png(10, 10)), "at": [500, 500]})).unwrap(); + assert_ne!(r["id"].as_u64(), Some(frame)); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), items + 1); + } + + #[test] + fn bad_input_is_refused_and_leaves_no_undo_step() { + let mut s = doc(); + let ok = base64_encode(&png(2, 2)); + let undo = s.doc().unwrap().history.undo.len(); + for (p, want) in [ + (json!({}), "missing base64"), + (json!({"base64": 5}), "`base64` must be a non-empty string"), + (json!({"base64": ""}), "`base64` must be a non-empty string"), + (json!({"base64": base64_encode(b"just text")}), "doesn't hold an image"), + (json!({"base64": base64_encode(b"")}), "doesn't hold an image"), + (json!({"base64": ok, "name": ""}), "`name` must be a non-empty string"), + (json!({"base64": ok, "name": 3}), "`name` must be a non-empty string"), + (json!({"base64": ok, "name": "notes.txt"}), "`name` must end in an image extension"), + (json!({"base64": ok, "name": "page.idml"}), "`name` must end in an image extension"), + (json!({"base64": ok, "name": "png"}), "`name` must end in an image extension"), + (json!({"base64": ok, "at": [1]}), "`at` must be [x, y]"), + (json!({"base64": ok, "spread": 9}), "no such spread"), + ] { + let e = s.execute(ID, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + } + + #[test] + fn images_beyond_the_pixel_limit_are_refused_before_they_are_encoded() { + let e = pasted_png(9000, 8000, Vec::new()).unwrap_err(); + assert!(e.contains("9000 × 8000 pixels") && e.contains("64 million"), "{e}"); + assert!(pasted_png(0, 5, Vec::new()).is_err()); + assert!(pasted_png(2, 2, vec![0; 15]).unwrap_err().contains("wrong number of pixels")); + assert_eq!(pasted_pixels(&png(3, 2)).map(|(w, h, px)| (w, h, px.len())), Some((3, 2, 24))); + assert_eq!(pasted_pixels(b"%PDF-1.4"), None, "vector files are not pasted as pixels"); + } +} diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..02f978b6a 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -373,6 +373,15 @@ pub fn natural_size(bytes: &[u8]) -> Option<(f64, f64)> { Some((w as f64, h as f64)) } +/// Unpremultiplied RGBA pixels, rows top to bottom, as a PNG file with no resolution stored. +/// `None` when `rgba` doesn't hold exactly `width × height` pixels. +pub fn png_from_rgba(width: u32, height: u32, rgba: Vec) -> Option> { + let img = image::RgbaImage::from_raw(width, height, rgba)?; + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; + Some(png) +} + /// Pixel dimensions of a raster. pub fn pixel_size(bytes: &[u8]) -> Option<(u32, u32)> { if let Some(p) = palette_tiff(bytes) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 88bd48c58..8355e236f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -113,6 +113,7 @@ impl DesignApp { egui_ctx: None, in_control: false, object_clip_text: None, + object_clip_change: None, ime_marked: None, ime_discard: false, canvas_ime: false, diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 4b813dd5c..bff5156f7 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -1,13 +1,35 @@ use super::{DesignApp, Value, canvas, json}; +use crate::services::ClipboardImage; + +/// What Paste takes from the system clipboard. +pub(super) enum Pasted { + /// The command's params, with the clipboard's text when it has some. + Params(Value), + /// An image, pasted as a placed image instead. + Image(ClipboardImage), +} + +/// Text that is only the address of a file or a web page: what a browser puts beside a copied +/// image. Paste prefers the image to such text. +fn is_bare_address(text: &str) -> bool { + let t = text.trim(); + !t.is_empty() + && !t.contains(char::is_whitespace) + && ["http://", "https://", "file://", "data:image/"] + .iter() + .any(|scheme| t.get(..scheme.len()).is_some_and(|s| s.eq_ignore_ascii_case(scheme))) +} impl DesignApp { /// Paste without the clipboard's text (a menu, not the paste keys): read it here. With no /// insertion point, text that doesn't stand for copied objects becomes a new text frame - /// centred in the view. - pub(super) fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Value { + /// centered in the view, and an image on the clipboard (when there is no text, or the text is + /// only an address) becomes a placed image, unless nothing was copied to the clipboard since + /// objects were last copied here. + pub(super) fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Pasted { let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); if !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") || !(typing || id == "edit.paste") { - return params; + return Pasted::Params(params); } if params.get("text").is_none() && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()) @@ -15,14 +37,33 @@ impl DesignApp { { o.insert("text".into(), Value::String(text)); } + // Nothing was copied to the clipboard since objects were copied here (native menu, where + // the system raises a change count with every copy). + let unchanged = match self.object_clip_change { + Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), + None => true, + }; // Still what an object copy put there: paste those objects, not the placeholder text. let norm = |t: &str| t.replace("\r\n", "\n"); - if let Some(copied) = &self.object_clip_text - && params.get("text").and_then(Value::as_str).is_some_and(|t| norm(t) == norm(copied)) - && let Some(o) = params.as_object_mut() - { + let ours = unchanged + && self + .object_clip_text + .as_ref() + .is_some_and(|copied| params.get("text").and_then(Value::as_str).is_some_and(|t| norm(t) == norm(copied))); + if ours && let Some(o) = params.as_object_mut() { o.remove("text"); } + let text = params.get("text").and_then(Value::as_str); + let copied_here = + text.is_none() && self.session.clipboard.is_some() && self.object_clip_text.is_none() && self.object_clip_change.is_some() && unchanged; + if !typing + && !ours + && !copied_here + && text.is_none_or(is_bare_address) + && let Some(image) = self.services.clipboard_image.as_mut().and_then(|f| f()) + { + return Pasted::Image(image); + } if !typing && params.get("text").and_then(Value::as_str).is_some_and(|t| !t.is_empty()) && let Some((spread, at)) = canvas::view_centre(self) @@ -32,7 +73,39 @@ impl DesignApp { o.entry("spread").or_insert(spread); o.entry("at").or_insert(json!([at.x, at.y])); } - params + Pasted::Params(params) + } + + /// Paste an image from the system clipboard as a placed image (`edit.pasteImage`), centered + /// in the view or in the selected empty frame. Text being edited takes no image. + pub(crate) fn paste_clipboard_image(&mut self, image: ClipboardImage) -> Result { + let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); + let file = if typing { + Err("To paste the image, stop editing the text first (Esc).".to_string()) + } else { + match image { + ClipboardImage::Pixels { width, height, rgba } => { + designcraft_engine::cmd::pasted_png(width, height, rgba).map(|png| (png, designcraft_engine::cmd::PASTED_IMAGE_NAME.to_string())) + } + ClipboardImage::File { name, bytes } => Ok((bytes, name)), + } + }; + let (bytes, name) = match file { + Ok(file) => file, + Err(e) => { + self.status(e.clone()); + return Err(e); + } + }; + let mut params = json!({"base64": designcraft_engine::cmd::base64_encode(&bytes), "name": name}); + if let Some((spread, at)) = canvas::view_centre(self) + && let Ok(spread) = serde_json::to_value(spread) + && let Some(o) = params.as_object_mut() + { + o.insert("spread".into(), spread); + o.insert("at".into(), json!([at.x, at.y])); + } + self.run("edit.pasteImage", params) } /// Keep widget clipboard output private while a queued control event is running. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index bb75c102e..dc0326172 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -8,7 +8,14 @@ impl DesignApp { } // Only user-initiated runs touch the system clipboard, never the control channel's. let system_clipboard = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed); - let mut params = if system_clipboard { self.with_system_clipboard(id, params) } else { params }; + let mut params = if system_clipboard { + match self.with_system_clipboard(id, params) { + super::clipboard::Pasted::Params(params) => params, + super::clipboard::Pasted::Image(image) => return self.paste_clipboard_image(image), + } + } else { + params + }; // Vector art copied in another app (Illustrator, VectorCraft, Figma) is SVG markup on the // system clipboard: with no insertion point it pastes as editable paths where text would go. let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); @@ -37,14 +44,17 @@ impl DesignApp { let text = match v.get("text").and_then(Value::as_str) { Some(t) => { self.object_clip_text = None; + self.object_clip_change = None; Some(t.to_string()) } None if !self.native_menu => { self.object_clip_text = Some(designcraft_engine::cmd::copied_objects_text(&self.session)); + self.object_clip_change = None; self.object_clip_text.clone() } None => { self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()); + self.object_clip_change = self.services.clipboard_change.as_mut().and_then(|f| f()); None } }; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 590b0f8c6..d9102e266 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -435,7 +435,13 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui:: let _ = app.run("text.insert", json!({"text": t})); } // The IME owns the keyboard until it commits: no typing, clipboard or editing keys. - egui::Event::Text(_) | egui::Event::Paste(_) | egui::Event::Copy | egui::Event::Cut | egui::Event::Key { .. } if composing => {} + egui::Event::Text(_) + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Key { .. } + if composing => {} egui::Event::Paste(t) if wants_text => { // Formatted when the system clipboard still holds what was copied here; // Shift (⇧⌘V) pastes without formatting. @@ -443,6 +449,10 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui:: let id = if plain { "edit.pasteWithoutFormatting" } else { "edit.paste" }; let _ = app.run(id, json!({"text": t})); } + // A clipboard image with no text (a screenshot, an image copied in a browser). + egui::Event::PasteImage(image) => { + let _ = app.paste_clipboard_image(crate::ClipboardImage::from_color_image(&image)); + } egui::Event::Copy | egui::Event::Cut if wants_text => { // `run` puts the copied text on the system clipboard. let id = if matches!(e, egui::Event::Cut) { "edit.cut" } else { "edit.copy" }; @@ -525,6 +535,10 @@ pub(crate) fn forwarded_keys(app: &mut DesignApp, events: Vec, modi (egui::Event::Copy, _) if !app.native_menu => ("edit.copy", serde_json::Value::Null), (egui::Event::Cut, _) if !app.native_menu => ("edit.cut", serde_json::Value::Null), (egui::Event::Paste(t), _) if !app.native_menu => ("edit.paste", json!({"text": t})), + (egui::Event::PasteImage(image), _) => { + let _ = app.paste_clipboard_image(crate::ClipboardImage::from_color_image(&image)); + continue; + } (egui::Event::Key { key, pressed: true, modifiers, .. }, _) => { tool_key(app, key, modifiers, vi); continue; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..0937904d9 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1051,6 +1051,127 @@ fn edit_paste_from_the_menu_pastes_svg_on_the_system_clipboard_as_paths() { assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items, "no paths added"); } +/// A fake system clipboard: its text, a bitmap of a given size and the change count that every +/// copy raises. +#[derive(Default)] +struct FakeClip { + text: Option, + image: Option<(u32, u32)>, + change: i64, +} + +type FakeClipboard = std::rc::Rc>; + +/// Another application copies `text` and an image of `image` pixels. +fn copy_elsewhere(clip: &FakeClipboard, text: Option<&str>, image: Option<(u32, u32)>) { + let mut c = clip.borrow_mut(); + (c.text, c.image, c.change) = (text.map(str::to_string), image, c.change + 1); +} + +fn fake_clipboard(text: Option<&str>, image: Option<(u32, u32)>) -> (FakeClipboard, crate::Services) { + let clip = FakeClipboard::default(); + copy_elsewhere(&clip, text, image); + let (t, i, c) = (clip.clone(), clip.clone(), clip.clone()); + let services = crate::Services { + clipboard_text: Some(Box::new(move || t.borrow().text.clone())), + clipboard_image: Some(Box::new(move || { + let (width, height) = i.borrow().image?; + // Sizes past the paste limit are refused before their pixels are read. + let len = if u64::from(width) * u64::from(height) > designcraft_engine::cmd::MAX_PASTED_PIXELS { 0 } else { width * height * 4 }; + Some(crate::ClipboardImage::Pixels { width, height, rgba: vec![90; len as usize] }) + })), + clipboard_change: Some(Box::new(move || Some(c.borrow().change))), + ..Default::default() + }; + (clip, services) +} + +/// The embedded image the selected frame shows: its pixel size and the asset's name. +fn pasted_image(app: &DesignApp) -> Option<((u32, u32), String)> { + let st = app.session.doc().unwrap(); + let id = *st.selection.items.first()?; + let designcraft_doc::Content::Graphic(g) = &st.doc.item(id)?.content else { return None }; + let asset = &st.doc.assets[&g.asset]; + assert_eq!(asset.link, None, "embedded"); + Some((asset.pixels?, asset.name.clone())) +} + +#[test] +fn edit_paste_from_the_menu_places_the_clipboard_image() { + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), Some(((40, 30), designcraft_engine::cmd::PASTED_IMAGE_NAME.to_string()))); + // A browser puts the image's address beside it: the image wins. + copy_elsewhere(&clip, Some("https://example.com/cat.png"), Some((8, 6))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((8, 6))); + // Other text wins over a picture of it. + copy_elsewhere(&clip, Some("Some words"), Some((8, 6))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None); + assert!(app.session.doc().unwrap().selection.text.is_none(), "a text frame, selected as an object"); + // Too many pixels: refused with a message, and nothing is added. + copy_elsewhere(&clip, None, Some((9000, 8000))); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(app.ui.status.contains("64 million"), "{}", app.ui.status); +} + +#[test] +fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { + // A native menu: Copy leaves the system clipboard (here an older image) alone. + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200], "content": "text"})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None, "the copied text frame"); + assert_ne!(app.session.doc().unwrap().selection.items.first().map(|i| i.0), id.as_u64()); + // The same image copied again in another application is a new copy. + copy_elsewhere(&clip, None, Some((40, 30))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((40, 30)), "an image copied since then"); + // The same goes for an image whose address was on the clipboard at the copy. + let url = "https://example.com/cat.png"; + copy_elsewhere(&clip, Some(url), Some((5, 5))); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app), None, "the copied text frame again"); + copy_elsewhere(&clip, Some(url), Some((5, 5))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); +} + +#[test] +fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = app.run("frame.create", json!({"rect": [100, 100, 300, 250]})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + let mut h = harness(app); + let image = || egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::filled([20, 10], egui::Color32::RED))); + h.input_mut().events.push(image()); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().selection.items.first().map(|i| i.0), Some(frame), "the frame took it"); + assert_eq!(pasted_image(h.state()).map(|(px, _)| px), Some((20, 10))); + // While text is edited, the image is not pasted and the status bar says why. + let story = h.state_mut().run("frame.create", json!({"rect": [10, 400, 300, 600], "content": "text"})).unwrap()["story"].clone(); + h.state_mut().run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + let items = h.state().session.doc().unwrap().doc.spreads[0].items.len(); + h.input_mut().events.push(image()); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(h.state().ui.status.contains("stop editing the text"), "{}", h.state().ui.status); +} + #[test] fn selected_merged_owners_paint_the_same_row_and_column_targets() { for column in [true, false] { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d70a79695..9a8e23900 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -272,11 +272,24 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); ok(Value::Null) } - // What Ctrl/Cmd+V delivers from the system clipboard: text, or SVG markup copied in an - // illustration app (pasted as editable paths when no text is being edited). + // What Ctrl/Cmd+V delivers from the system clipboard: text, SVG markup copied in an + // illustration app (pasted as editable paths when no text is being edited), or an image + // (`image`: an image file as base64, pasted as a placed image). "ui.paste" => { - let Some(text) = s("text") else { return err("missing `text`") }; - app.control_synthetic.push(egui::Event::Paste(text.to_string())); + let event = match (s("text"), s("image")) { + (Some(text), None) => egui::Event::Paste(text.to_string()), + (None, Some(image)) => { + let bytes = designcraft_engine::cmd::base64_decode(image); + let Some((w, h, rgba)) = designcraft_engine::cmd::pasted_pixels(&bytes) else { + return err("`image` is not an image file that can be pasted"); + }; + let size = [w, h].map(|n| usize::try_from(n).unwrap_or(0)); + egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied(size, &rgba))) + } + (Some(_), Some(_)) => return err("give `text` or `image`, not both"), + (None, None) => return err("missing `text` or `image`"), + }; + app.control_synthetic.push(event); ctx.request_repaint(); ok(Value::Null) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 40bdfbcb3..f441e2f1d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -74,7 +74,10 @@ use app::browser_import_tests; pub use app::opens_as_document; pub use clock::now_ms; pub use key_names::{drop_key_name_text, is_key_name}; -pub use services::{ClipboardFn, DownloadFn, Inbox, OpenAsyncFn, PointerFn, ReadFn, Services, WindowFrameFn, WriteFn}; +pub use services::{ + ClipboardChangeFn, ClipboardFn, ClipboardImage, ClipboardImageFn, DownloadFn, Inbox, OpenAsyncFn, PointerFn, ReadFn, Services, WindowFrameFn, + WriteFn, +}; pub(crate) use state::second_window_viewport; pub use state::{CanvasCache, HiddenPanels, ImportRequest, ImportedFile, PdfExportSettings, Perf, SavedWorkspace, ScreenMode, Shown, UiState, View}; @@ -257,6 +260,9 @@ pub struct DesignApp { /// (no native menu: without it the paste keys produce no paste event), or what it held then /// (native menu). It is never pasted as text: Paste with it pastes the copied objects. object_clip_text: Option, + /// The clipboard's change count at the last object copy (native menu). While it is unchanged, + /// Paste pastes the copied objects rather than an image the clipboard held before the copy. + object_clip_change: Option, /// The marked text the system IME last sent (`None` once it commits or clears). When the /// composition ends some other way (a click, a tool switch), the IME is told to drop it. pub(crate) ime_marked: Option, diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 384a75b4b..fd529ac42 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -11,6 +11,32 @@ pub type DownloadFn = Box Result<(), String>>; pub type ClipboardFn = Box Option>; +/// An image on the system clipboard. +pub enum ClipboardImage { + /// A bitmap (a screenshot, an image copied in a browser): unpremultiplied RGBA, rows top to + /// bottom. + Pixels { width: u32, height: u32, rgba: Vec }, + /// An image file copied in a file manager: its name and contents. + File { name: String, bytes: Vec }, +} + +impl ClipboardImage { + /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). + pub fn from_color_image(image: &egui::ColorImage) -> Self { + let rgba = image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); + let [w, h] = image.size.map(|n| u32::try_from(n).unwrap_or(u32::MAX)); + ClipboardImage::Pixels { width: w, height: h, rgba } + } +} + +/// The system clipboard's image, for Paste chosen from a menu. It returns within a short bound +/// even when the application that owns the clipboard is slow to answer (`None` then). +pub type ClipboardImageFn = Box Option>; + +/// A number the system raises with every copy to the clipboard (the macOS pasteboard's change +/// count), read without waiting for the clipboard's owner. +pub type ClipboardChangeFn = Box Option>; + /// Keeps the window's frame as the app needs it; called once per frame, before it is laid out. pub type WindowFrameFn = Box; @@ -40,6 +66,13 @@ pub struct Services { /// The system clipboard's text, for Paste chosen from a menu (egui only delivers it with the /// paste keys, which a native menu bar takes first). pub clipboard_text: Option, + /// The system clipboard's image (a bitmap, else the first image file of a copied file list), + /// for Paste chosen from a menu when the clipboard holds no text or only an image's address. + pub clipboard_image: Option, + /// The clipboard's change count, so Paste can tell an image copied after an object Copy from + /// one that was there before it. Needed where Copy leaves the system clipboard alone (a + /// native menu bar); `None` elsewhere. + pub clipboard_change: Option, /// Keeps the undecorated window borderless, so the content and the pointer stay aligned /// (Windows custom title bar, #1295). `None` when the window is decorated or the platform /// needs no fixing. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e886c07ab..706c1fc43 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -42,7 +42,7 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser | `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) | | `ui.ime` | `{preedit?, active?: [start, end], commit?}` | Input method events as the system IME sends them: marked text (shown in place, `active` is the clause being converted, in characters) and the committed text (typed as one `text.insert`) | -| `ui.paste` | `{text}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, or SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view | +| `ui.paste` | `{text}` or `{image}` | What Ctrl/Cmd+V delivers from the system clipboard: text into the text being edited, SVG markup (vector art copied in Illustrator, VectorCraft or Figma) as editable paths in the middle of the view, or an image (`image`: an image file as base64) as an embedded image in the selected empty frame or in the middle of the view (`edit.pasteImage`) | | `ui.move` / `ui.click` / `ui.drag` | screen points, `button?: left\|right\|middle`, `count?: 1–255` (click/drag, default 1), `steps?: positive integer` (drag, default 8) | Real egui pointer input — reaches every widget, menu and panel | | `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, documentGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state | | `ui.dialog.open` | `{id, fields?}` | Open a dialog by id (e.g. `paragraphStyleOptions` or `characterStyleOptions` with `{name, section}`, or `{new: true}` for a new style) | From eff8865f86c42218f8aba795c722b5607b16e802 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:50:31 -0800 Subject: [PATCH 140/328] Recovery: an edit after a save is written once the cancelled write stops A recovery write queued while a cancelled write of the same document and folder is still running now follows it instead of being refused until the next timer tick. A write in a folder that is not the run's own is recorded as the run's in the same step as its rename, so a save right after it can remove it. --- crates/engine/src/recovery.rs | 161 ++++++++++++++++++---------- crates/engine/src/recovery/tests.rs | 27 +++++ 2 files changed, 133 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index f5bafd316..e2e09a42b 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -737,6 +737,14 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { entry.own, |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), &cancelled, + // Written: in a folder that is not this run's own, the entry is now this run's to replace + // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the + // rename, so a cleanup after it can remove the entry. + || { + if !entry.own { + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); + } + }, ); match published { Ok(true) => {} @@ -744,11 +752,6 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { Ok(false) => return Written { published: false, error: None }, Err(e) => return Written { published: false, error: Some(e) }, } - // Written: in a folder that is not this run's own, the entry is now this run's to replace and - // remove (Save and Close must clean up the snapshot they wrote). - if !entry.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); - } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); // A cancel after the primary landed removes it; the metadata must not be left without it. let bytes = metadata.to_string(); @@ -757,6 +760,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { entry.own, |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), &cancelled, + || {}, ) .err(); Written { published: true, error } @@ -921,6 +925,9 @@ mod worker { struct Queued { owner: u64, dir: PathBuf, + /// A newer write of the same document and folder, queued after this one was cancelled: + /// it is written as soon as this one stops. + next: Option, } static WRITER: OnceLock> = OnceLock::new(); @@ -935,16 +942,30 @@ mod worker { self.running.lock().is_ok_and(|running| !running.is_empty()) } - /// `key` is the job's ([`Snapshot::key`], uid). - fn finish(&self, key: &(PathBuf, u64)) { - let key = key.clone(); - if let Ok(mut running) = self.running.lock() { - running.remove(&key); - } - if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.remove(&key); - } + /// `key` is the job's ([`Snapshot::key`], uid). Returns the write queued to follow it. + fn finish(&self, key: &(PathBuf, u64)) -> Option { + let next = match self.running.lock() { + Ok(mut running) => { + let next = running.get_mut(key).and_then(|q| q.next.take()); + match (&next, running.get_mut(key)) { + (Some(n), Some(q)) => { + q.owner = n.owner; + q.dir = n.dir.clone(); + } + _ => { + running.remove(key); + } + } + // The mark was for the write that stopped, not the one that follows it. + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.remove(key); + } + next + } + Err(_) => None, + }; self.idle.notify_all(); + next } /// Block until no write is queued or running. @@ -966,11 +987,15 @@ mod worker { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The folder's canonical path, or its name as given: a link in the path may lead // elsewhere now than when the write was queued. - let keys: Vec<(PathBuf, u64)> = self - .running - .lock() - .map(|running| running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect()) - .unwrap_or_default(); + let Ok(mut running) = self.running.lock() else { return }; + let keys: Vec<(PathBuf, u64)> = + running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect(); + // A write queued to follow it is older than what the caller has now, too. + for k in &keys { + if let Some(q) = running.get_mut(k) { + q.next = None; + } + } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); } @@ -985,15 +1010,17 @@ mod worker { let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The canonical keys to mark, and the folders as the session named them, which is how // the cleanup finds this run's folder. - let (keys, mut dirs): (Vec<(PathBuf, u64)>, Vec) = self - .running - .lock() - .map(|running| { - running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, q)| (key.clone(), q.dir.clone())).unzip() - }) - .unwrap_or_default(); - if let Ok(mut cancelled) = self.cancelled.lock() { - cancelled.extend(keys); + let mut dirs = Vec::new(); + if let Ok(mut running) = self.running.lock() { + let mut keys = Vec::new(); + for (key, q) in running.iter_mut().filter(|((_, u), q)| *u == uid && q.owner == owner) { + keys.push(key.clone()); + dirs.push(q.dir.clone()); + q.next = None; + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys); + } } // Results stay queued for their session; only their folders are read here. let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1011,13 +1038,20 @@ mod worker { /// The folders of writes of `uid` queued by session `owner` that are in flight, or finished /// and published with their results not taken yet: checkpoints its entries do not hold yet. fn pending_folders(&self, uid: u64, owner: u64) -> Vec { - let keys: Vec<(PathBuf, u64)> = self + // A cancelled write publishes nothing; a write queued to follow it does. + let mut dirs: Vec = self .running .lock() - .map(|running| running.iter().filter(|((_, u), q)| *u == uid && q.owner == owner).map(|(key, _)| key.clone()).collect()) + .map(|running| { + running + .iter() + .filter(|(key, q)| { + key.1 == uid && ((q.owner == owner && !self.cancelled(key)) || q.next.as_ref().is_some_and(|n| n.owner == owner)) + }) + .map(|((dir, _), _)| dir.clone()) + .collect() + }) .unwrap_or_default(); - // A cancelled write publishes nothing. - let mut dirs: Vec = keys.into_iter().filter(|key| !self.cancelled(key)).map(|(dir, _)| dir).collect(); let done = self.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut undelivered = self.undelivered.lock().unwrap_or_else(std::sync::PoisonError::into_inner); undelivered.extend(done.try_iter()); @@ -1038,24 +1072,25 @@ mod worker { let (jobs, job_rx) = std::sync::mpsc::channel::(); let (done_tx, done_rx) = std::sync::mpsc::channel::(); let spawned = std::thread::Builder::new().name("designcraft-recovery".into()).spawn(move || { - while let Ok(job) = job_rx.recv() { - let (published, error) = guarded_write(&job); - let key = (job.key.clone(), job.uid); - let (dir, uid, owner) = (job.dir, job.uid, job.owner); - // The result before the document reads as idle: a writer that is not busy - // has already delivered it, so the interface never stops polling with an - // answer still on its way. - let sent = { - let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - // Cancelled after it was published: the canceller removes the snapshot. - let published = published && !started().is_some_and(|w| w.cancelled(&key)); - done_tx.send(Done { dir, uid, error, published, owner }).is_ok() - }; - if let Some(w) = WRITER.get().and_then(Option::as_ref) { - w.finish(&key); - } - if !sent { - break; + while let Ok(first) = job_rx.recv() { + let mut queued = Some(first); + while let Some(job) = queued.take() { + let (published, error) = guarded_write(&job); + let key = (job.key.clone(), job.uid); + let (dir, uid, owner) = (job.dir, job.uid, job.owner); + // The result before the document reads as idle: a writer that is not + // busy has already delivered it, so the interface never stops polling + // with an answer still on its way. + let sent = { + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // Cancelled after it was published: the canceller removes the snapshot. + let published = published && !started().is_some_and(|w| w.cancelled(&key)); + done_tx.send(Done { dir, uid, error, published, owner }).is_ok() + }; + queued = WRITER.get().and_then(Option::as_ref).and_then(|w| w.finish(&key)); + if !sent { + return; + } } } }); @@ -1124,10 +1159,16 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); - if running.contains_key(&key) { + if let Some(q) = running.get_mut(&key) { + // The write in flight was cancelled (the document was saved since), so it holds + // nothing to recover: this one follows it, in place of any that was waiting. + if w.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&key)) { + q.next = Some(entry); + return Some(true); + } return Some(false); } - running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone() }); + running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone(), next: None }); // A write is wanted again: whatever cancelled the last one does not apply to this one. if let Ok(mut cancelled) = w.cancelled.lock() { cancelled.remove(&key); @@ -1286,8 +1327,14 @@ fn secure_recovery_dir(_dir: &Path) -> Result { #[cfg(not(target_arch = "wasm32"))] fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> { - publish_recovery_written(path, replace, |out| out.write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display()))), || false) - .map(|_| ()) + publish_recovery_written( + path, + replace, + |out| out.write_all(bytes).map_err(|e| EngineError::Other(format!("{}: {e}", path.display()))), + || false, + || {}, + ) + .map(|_| ()) } /// Serializes the last check for a cancelled write with the rename that publishes it, and with @@ -1298,13 +1345,15 @@ static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// [`publish_recovery_file`], with `write` filling the temporary file: a large document is written /// straight to disk instead of being built in memory first. Returns whether it was published; /// `cancelled` is asked after the bytes are written and before the rename, so a document saved or -/// closed meanwhile leaves nothing behind. +/// closed meanwhile leaves nothing behind. `on_publish` runs right after the rename, before a +/// cancel can. #[cfg(not(target_arch = "wasm32"))] fn publish_recovery_written( path: &Path, replace: bool, write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, cancelled: impl Fn() -> bool, + on_publish: impl FnOnce(), ) -> Result { let Some(dir) = path.parent() else { return Err(EngineError::Other(format!("{} has no parent folder", path.display()))); @@ -1340,6 +1389,7 @@ fn publish_recovery_written( validate_recovery_dir(dir)?; let published = if replace { tmp.persist(path) } else { tmp.persist_noclobber(path) }; published.map_err(|e| EngineError::Other(format!("{}: {}", path.display(), e.error)))?; + on_publish(); } sync_recovery_dir(dir)?; Ok(true) @@ -1406,6 +1456,7 @@ fn publish_recovery_written( _replace: bool, _write: impl FnOnce(&mut std::io::BufWriter<&mut std::fs::File>) -> Result<()>, _cancelled: impl Fn() -> bool, + _on_publish: impl FnOnce(), ) -> Result { Err(EngineError::Other("recovery files are unavailable on the web".into())) } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 2353e476d..c59c5ee76 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -235,6 +235,33 @@ fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken( assert!(list(named.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_edit_after_a_save_is_written_after_the_cancelled_write_stops() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let saved = tempfile::tempdir().unwrap(); + s.execute("file.saveAs", &json!({"path": saved.path().join("saved.designcraft").to_string_lossy()})).unwrap(); + s.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + // The held write was cancelled: the new edit is queued behind it instead of waiting for the + // next timer tick. + let queued = s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + held.release(); + assert_eq!(finished_writes(&mut s), 1); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "the snapshot after the edit was written"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_result_goes_to_the_session_that_queued_it() { From 6fff5328eb59a5fdff5d91df44034212cc07e670 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 11 Nov 2026 20:52:41 -0800 Subject: [PATCH 141/328] Tests: type.align refusal cases name the check that refuses each (#2662) Follows #2645. Its test said a misspelled key used to apply Align Left. Only empty params and a bare string did; the parameter check already refused a misspelled key, and the value parser refused an unknown value. Each case now asserts the refusal message it gets. --- crates/engine/src/cmd/text/format.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/text/format.rs b/crates/engine/src/cmd/text/format.rs index 10bce4841..64f3c17c7 100644 --- a/crates/engine/src/cmd/text/format.rs +++ b/crates/engine/src/cmd/text/format.rs @@ -1080,8 +1080,9 @@ mod align_param_tests { use crate::Session; - /// `type.align` with no `align` applied Align Left, so a script that misspelled the key - /// (`{"alignment": "center"}`) changed the paragraph to the opposite of what it asked for. + /// `type.align` with empty params (`{}`) or a bare value (`"center"`) applied Align Left. + /// A misspelled key and an unknown value were already refused, and each case checks which + /// check refuses it. #[test] fn type_align_without_a_value_is_refused_and_changes_nothing() { let mut s = Session::new(); @@ -1092,8 +1093,16 @@ mod align_param_tests { let align = |s: &mut Session| s.execute("type.selectionAttrs", &json!({})).unwrap()["para"]["align"].clone(); assert_eq!(align(&mut s), json!("right")); let steps = s.doc().unwrap().history.undo.len(); - for params in [json!({}), json!({"alignment": "center"}), json!("center"), json!({"align": "middle"})] { - assert!(s.execute("type.align", ¶ms).is_err(), "{params}"); + // `{}` and `"center"` reach the command without `align`. The parameter check refuses + // `{"alignment": …}` and the value parser refuses `"middle"`. + for (params, refusal) in [ + (json!({}), "`align` required"), + (json!("center"), "`align` required"), + (json!({"alignment": "center"}), "unknown parameter `alignment`"), + (json!({"align": "middle"}), "middle"), + ] { + let err = s.execute("type.align", ¶ms).unwrap_err().to_string(); + assert!(err.contains(refusal), "{params}: {err}"); assert_eq!(align(&mut s), json!("right"), "{params}"); assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{params}: no undo step"); } From f47acd5dfd90ae2ae9bd7900f24a52dab8fa71aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 20:54:37 -0800 Subject: [PATCH 142/328] Object styles: Text Frame General Options set only the General page - An object style's text frame options set the columns, insets, vertical justification, paragraph spacing limit and Ignore Text Wrap. A frame keeps its auto-size, baseline, column rule and Type on a Path settings, and follows an edit of the style while its General options match the style's. - textFrame refuses keys outside the General options, takes one number for all four insets, and checks the values the call gives. - Applying a style that changes nothing records no undo step. - The dialog's Paragraph Spacing Limit reaches the style. - IDML import: a style's Text Frame General Options take the settings its TextFramePreference leaves out from the styles it is based on (by id or bare name), skipping styles that turn the category off. - i18n: Hungarian and Swedish rows for the object style dialog; the duplicate Brazilian Portuguese rows are removed. --- crates/doc/src/item/text_frame.rs | 43 ++++++++++++++ crates/doc/src/styles.rs | 5 +- crates/engine/src/cmd/style.rs | 6 +- crates/engine/src/cmd/style/object.rs | 42 ++++++++++--- crates/engine/src/tests.rs | 72 +++++++++++++++++++++++ crates/idml/src/import/styles.rs | 44 +++++++++----- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++ crates/ui-egui/src/i18n/hu.rs | 13 ++++ crates/ui-egui/src/i18n/pt_br.rs | 2 - crates/ui-egui/src/i18n/sv.rs | 12 ++++ crates/ui-egui/src/object_style_dialog.rs | 39 +++++++++++- 11 files changed, 285 insertions(+), 30 deletions(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index d8f7f29e3..5c01bb21b 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -240,6 +240,49 @@ impl Default for TextFrameOptions { } } +impl TextFrameOptions { + /// The JSON keys of the General options: columns, inset spacing, vertical justification and + /// Ignore Text Wrap. An object style's Text Frame General Options category sets these only. + pub const GENERAL_KEYS: [&str; 9] = [ + "columns", + "columnsKind", + "gutter", + "columnWidth", + "balanceColumns", + "inset", + "verticalJustification", + "vjParagraphSpacingLimit", + "ignoreWrap", + ]; + + /// Whether the General options (see [`Self::GENERAL_KEYS`]) of `self` and `other` are the same. + pub fn general_eq(&self, other: &TextFrameOptions) -> bool { + self.columns == other.columns + && self.columns_kind == other.columns_kind + && self.gutter == other.gutter + && self.column_width == other.column_width + && self.balance_columns == other.balance_columns + && self.inset == other.inset + && self.vertical_justification == other.vertical_justification + && self.vj_paragraph_spacing_limit == other.vj_paragraph_spacing_limit + && self.ignore_wrap == other.ignore_wrap + } + + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, + /// column rule and Type on a Path settings stay as they are. + pub fn set_general(&mut self, from: &TextFrameOptions) { + self.columns = from.columns; + self.columns_kind = from.columns_kind; + self.gutter = from.gutter; + self.column_width = from.column_width; + self.balance_columns = from.balance_columns; + self.inset = from.inset; + self.vertical_justification = from.vertical_justification; + self.vj_paragraph_spacing_limit = from.vj_paragraph_spacing_limit; + self.ignore_wrap = from.ignore_wrap; + } +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum WrapMode { diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 1ba59ef25..98923762c 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -72,7 +72,8 @@ pub struct ObjectStyle { } impl ObjectStyle { - /// Gives `it` the fill, stroke, corners, effects and text frame options this style sets. + /// Gives `it` the fill, stroke, corners, effects and text frame General options this style + /// sets. A text frame keeps its baseline, auto-size, column rule and Type on a Path settings. pub fn apply_to(&self, it: &mut Item) { if let Some(c) = self.corners { it.corners = c.named_to_path(&it.path); @@ -87,7 +88,7 @@ impl ObjectStyle { it.effects = e.clone(); } if let (Some(tf), Some(o)) = (it.text_frame_mut(), &self.text_frame) { - tf.options = o.clone(); + tf.options.set_general(o); } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 64cc8f6f3..5b1ac047d 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -173,7 +173,7 @@ pub fn specs() -> Vec { "Apply Object Style", [], None, - "{name, ids?} — sets the style's fill, stroke, effects and text frame options on the items", + "{name, ids?} — sets the style's fill, stroke, corners, effects and text frame General options on the items, and its paragraph styles on their text; records nothing when the items already have them", super::has_selection, apply_object ), @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns?, columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right], verticalJustification?, ignoreWrap?, …} | null (the options of `document.inspect` text frames; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them → {name, updated}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index fb2467e5f..6c7455099 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -4,6 +4,18 @@ pub(super) fn apply_object(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style.object.apply", "missing name"))?.to_string(); let os = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad("style.object.apply", format!("no object style `{name}`")))?; let ids = crate::cmd::targets(s, p)?; + // Nothing to record when every target already has the style and its attributes, and its text + // the style's paragraph styles. + let d = &s.doc()?.doc; + let unchanged = ids.iter().filter_map(|id| d.item(*id)).all(|it| { + let mut next = it.clone(); + next.object_style = name.clone(); + os.apply_to(&mut next); + next == *it && it.text_frame().and_then(|tf| d.story(tf.story)).is_none_or(|st| os.story_follows(&d.styles, st)) + }); + if unchanged { + return Ok(Value::Null); + } s.edit(|d, _| { let mut stories = Vec::new(); for id in &ids { @@ -170,19 +182,33 @@ fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result, ) -> Result>> { - let tf = group_param(cmd, p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + let general = designcraft_doc::TextFrameOptions::GENERAL_KEYS; + let mut p = p.clone(); + if let Some(Value::Object(o)) = p.get_mut("textFrame") { + if let Some(k) = o.keys().find(|k| !general.contains(&k.as_str())) { + return Err(bad(cmd, format!("textFrame.{k} is not a General option ({})", general.join(", ")))); + } + if let Some(n) = o.get("inset").filter(|v| v.is_number()).cloned() { + o.insert("inset".into(), json!([n, n, n, n])); + } + } + let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; if let Some(Some(o)) = &tf { - if !(1..=40).contains(&o.columns) { + // Only the values given in this call are checked. + let given = |k: &str| p.get("textFrame").is_some_and(|t| t.get(k).is_some()); + if given("columns") && !(1..=40).contains(&o.columns) { return Err(bad(cmd, "text frame columns must be 1–40")); } - let mut lengths = [o.gutter, o.column_width, o.vj_paragraph_spacing_limit, o.first_baseline_min].into_iter().chain(o.inset); + let lengths = [("gutter", o.gutter), ("columnWidth", o.column_width), ("vjParagraphSpacingLimit", o.vj_paragraph_spacing_limit)]; + let mut lengths = lengths.into_iter().filter(|(k, _)| given(k)).map(|(_, v)| v).chain(o.inset.into_iter().filter(|_| given("inset"))); if !lengths.all(|v| v.is_finite() && (0.0..=15552.0).contains(&v)) { return Err(bad(cmd, "a text frame's gutter, widths and insets must be 0–15552 pt")); } @@ -360,7 +386,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) - || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options == *o)) + || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options.general_eq(o))) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -387,9 +413,9 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { } if let Some((o, n)) = &frame && let Some(tf) = it.text_frame_mut() - && tf.options == *o + && tf.options.general_eq(o) { - tf.options = n.clone(); + tf.options.set_general(n); } }, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fad29a1d7..48cb02446 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -882,6 +882,78 @@ fn object_styles_carry_a_paragraph_style_and_text_frame_options() { assert_eq!((styles_of(&s, a), options(&s, a).columns), (vec!["Box Body Text".to_string(); 3], 2)); } +/// An object style's Text Frame General Options set the columns, insets, vertical justification +/// and Ignore Text Wrap only: a frame keeps its auto-size and column rule, follows an edit of the +/// style while its General options are the style's, and keeps the settings through save and open. +/// Applying a style that changes nothing records no undo step, threaded frames share one Next +/// Style chain, and keys outside the General options are refused. +#[test] +fn object_style_text_frame_general_options_leave_the_other_frame_settings() { + use designcraft_doc::{AutoSize, ItemId, VerticalJustification}; + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Lead", "nextStyle": "Body"})).unwrap(); + let name = "Callout"; + s.execute( + "style.object.create", + &json!({"name": name, "fromSelection": false, "paragraphStyle": "Lead", "applyNextStyle": true, + "textFrame": {"inset": 6, "verticalJustification": "center"}}), + ) + .unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 156, 200], "content": "text", "text": "One\nTwo", "caret": false})).unwrap(); + let a = r["id"].as_u64().unwrap(); + let b = s.execute("frame.create", &json!({"rect": [200, 36, 320, 200], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [a], "autoSize": "heightOnly", "columnRule": true})).unwrap(); + s.execute("style.object.apply", &json!({"name": name, "ids": [a]})).unwrap(); + let options = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + let o = options(&s, a); + assert_eq!((o.inset, o.vertical_justification), ([6.0; 4], VerticalJustification::Center)); + assert_eq!((o.auto_size, o.column_rule), (AutoSize::HeightOnly, true), "the frame's own auto-size and column rule stay"); + + // Applying it again changes nothing and records no undo step. + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + s.execute("style.object.apply", &json!({"name": name, "ids": [a]})).unwrap(); + assert_eq!(undo(&s), before, "no undo step when nothing changes"); + + // The frame differs from the style's options only in auto-size, so it follows the edit. + let r = s.execute("style.object.edit", &json!({"name": name, "textFrame": {"inset": [1, 2, 3, 4], "ignoreWrap": true}})).unwrap(); + assert_eq!(r["updated"], 1); + let o = options(&s, a); + assert_eq!((o.inset, o.ignore_wrap, o.auto_size), ([1.0, 2.0, 3.0, 4.0], true, AutoSize::HeightOnly)); + + // Threaded frames: the story's paragraphs take one Next Style chain across both frames. + s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); + s.execute("style.object.apply", &json!({"name": name, "ids": [a, b]})).unwrap(); + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(a)).unwrap().text_frame().unwrap().story; + assert_eq!(d.item(ItemId(b)).unwrap().text_frame().unwrap().story, sid); + assert_eq!(d.story(sid).unwrap().paras.iter().map(|p| p.style.as_str()).collect::>(), ["Lead", "Body"]); + + // Save and open keep the style's General options and Apply Next Style. + let bytes = s.execute("file.serialize", &json!({})).unwrap(); + let mut back = Session::new(); + back.execute("file.openBytes", &json!({"name": "copy", "base64": bytes["base64"]})).unwrap(); + let os = back.doc().unwrap().doc.styles.object_style(name).cloned().unwrap(); + assert!(os.apply_next_style); + assert_eq!(os.text_frame.map(|t| (t.inset, t.ignore_wrap)), Some(([1.0, 2.0, 3.0, 4.0], true))); + + // Keys outside the General options, a misspelled key and a word for the inset are refused. + for bad in [json!({"autoSize": "heightOnly"}), json!({"insets": 4}), json!({"inset": "wide"}), json!({"verticalJustification": "middle"})] { + let p = json!({"name": name, "textFrame": bad}); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + } + // A style that already holds 60 columns (as a file can give it) takes other edits, and 60 + // given again is refused. + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let st = d.styles_mut().object.iter_mut().find(|o| o.name == name).unwrap(); + st.text_frame.as_mut().unwrap().columns = 60; + } + s.execute("style.object.edit", &json!({"name": name, "textFrame": {"inset": 2}})).unwrap(); + assert!(s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 60}})).is_err()); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 5fa1aa87e..e82d8fc0b 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -197,8 +197,16 @@ impl<'r> Importer<'r> { let paragraph_style = enabled("EnableParagraphStyle", "AppliedParagraphStyle") .then(|| e.get("AppliedParagraphStyle").map(|r| self.para_style_ref(r))) .flatten(); + let levels = based_on_levels(e, &objects_by_self); + // Text Frame General Options: each attribute from the nearest style whose + // `TextFramePreference` sets it, among the styles that don't turn the category off. let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") { - e.find("TextFramePreference").map(|t| self.frame_options(&[t])) + let prefs: Vec<&El> = levels + .iter() + .filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false")) + .filter_map(|l| l.find("TextFramePreference")) + .collect(); + (!prefs.is_empty()).then(|| self.frame_options(&prefs)) } else { None }; @@ -207,19 +215,7 @@ impl<'r> Importer<'r> { // that sets some corners takes the others from the styles it is based on, as the style // holds all four. let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false") && corners(e, "").is_some()) - .then(|| { - let mut levels = vec![e]; - let mut next = e.prop("BasedOn"); - while let Some(b) = next.take() - && levels.len() < 16 - && let Some(s) = objects_by_self.get(b.trim()).copied() - && !levels.iter().any(|l| std::ptr::eq(*l, s)) - { - levels.push(s); - next = s.prop("BasedOn"); - } - corners_in(&levels, "") - }) + .then(|| corners_in(&levels, "")) .flatten() .map(|c| CornerOptions { corners: c }); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); @@ -421,3 +417,23 @@ impl<'r> Importer<'r> { } } } + +/// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A +/// `BasedOn` may name a style by its `Self` id or by its bare name. +fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { + let id = |b: String| { + let b = b.trim(); + if b.starts_with("ObjectStyle/") { b.to_string() } else { format!("ObjectStyle/{}", names::escape_id(b)) } + }; + let mut levels = vec![e]; + let mut next = e.prop("BasedOn").map(id); + while let Some(b) = next.take() + && levels.len() < 16 + && let Some(s) = objects_by_self.get(b.as_str()).copied() + && !levels.iter().any(|l| std::ptr::eq(*l, s)) + { + levels.push(s); + next = s.prop("BasedOn").map(id); + } + levels +} diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index faaef4f32..52605d7a0 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -177,6 +177,43 @@ fn object_style_apply_next_style_round_trips() { } } +/// A style's Text Frame General Options take each setting its own `TextFramePreference` leaves out +/// from the style it is based on (named by its id or bare name, and only when that style doesn't +/// turn the category off), and export and import keep the merged options. +#[test] +fn object_style_text_frame_options_inherit_from_the_based_on_style() { + let styles = r#" + $ID/[None] + + + + ObjectStyle/Box + + + + Box + + + + $ID/[None] + + + + ObjectStyle/Off + + "#; + let d = fixture(styles, &[]); + let tf = d.styles.object_style("Inset").and_then(|s| s.text_frame.clone()).expect("Inset sets text frame options"); + assert_eq!((tf.inset, tf.columns, tf.vertical_justification), ([9.0; 4], 2, designcraft_doc::VerticalJustification::Center)); + let bare = d.styles.object_style("Bare").and_then(|s| s.text_frame.clone()).expect("Bare sets text frame options"); + assert_eq!((bare.inset, bare.columns), ([3.0; 4], 2), "a BasedOn given as a bare name"); + let on_off = d.styles.object_style("OnOff").and_then(|s| s.text_frame.clone()).expect("OnOff sets text frame options"); + assert_eq!((on_off.inset, on_off.columns), ([1.0; 4], 1), "a based-on style with the category off gives nothing"); + let back = import_idml(&export_idml(&d)).unwrap(); + let again = back.styles.object_style("Inset").and_then(|s| s.text_frame.clone()).expect("after a round trip"); + assert!(again.general_eq(&tf), "{again:?}"); +} + #[test] fn exported_frames_keep_their_own_values_over_their_object_style() { let mut d = small_doc(); diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index ab30bce8d..bbf3a6ed3 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1979,6 +1979,19 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Measure Tool", "Mérőeszköz"), ("Hand Tool", "Kéz eszköz"), ("Zoom Tool", "Nagyító eszköz"), + ("Apply Next Style", "Következő stílus alkalmazása"), + ("Text Frame General Options", "Szövegkeret általános beállításai"), + ("New Object Style", "Új objektumstílus"), + ("Object Style Options", "Objektumstílus beállításai"), + ("Object Style Options…", "Objektumstílus beállításai…"), + ("Basic Attributes", "Alapattribútumok"), + ("Stroke & Corner Options", "Körvonal- és sarokbeállítások"), + ("Effects for:", "Hatások ehhez:"), + ("Create New Style", "Új stílus létrehozása"), + ("Clear Overrides", "Felülírások törlése"), + ("Shape:", "Alakzat:"), + ("(no attributes)", "(nincsenek attribútumok)"), + ("Enter a style name.", "Adjon meg egy stílusnevet."), ]; pub(super) const CONTEXT: &[(&str, &str, &str)] = diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index f3b0e7df0..2c5f6d356 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -41,7 +41,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Text Frame General Options", "Opções gerais do quadro de texto"), ("New Object Style", "Novo estilo de objeto"), ("Object Style Options", "Opções de estilo de objeto"), - ("Object Style Options…", "Opções de estilo de objeto…"), ("Basic Attributes", "Atributos básicos"), ("Stroke & Corner Options", "Opções de traçado e canto"), ("Effects for:", "Efeitos para:"), @@ -50,7 +49,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Shape:", "Forma:"), ("(no attributes)", "(sem atributos)"), ("Enter a style name.", "Digite um nome de estilo."), - ("Corner Options", "Opções de canto"), ("Keep In Frame", "Manter no quadro"), ("New Paragraph Style", "Novo estilo de parágrafo"), ("New Character Style", "Novo estilo de caractere"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 766ba32da..fe85de091 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -2968,6 +2968,18 @@ pub(super) const TABLE: &[(&str, &str)] = &[ "Links and Images: {found} linked, {modified} changed, {missing} not found", "Länkar och bilder: {found} länkade, {modified} ändrade, {missing} hittades inte", ), + ("Apply Next Style", "Använd nästa stil"), + ("Text Frame General Options", "Allmänna alternativ för textram"), + ("New Object Style", "Ny objektstil"), + ("Object Style Options", "Alternativ för objektstil"), + ("Basic Attributes", "Grundläggande attribut"), + ("Stroke & Corner Options", "Kontur- och hörnalternativ"), + ("Effects for:", "Effekter för:"), + ("Create New Style", "Skapa ny stil"), + ("Clear Overrides", "Rensa lokala ändringar"), + ("Shape:", "Form:"), + ("(no attributes)", "(inga attribut)"), + ("Enter a style name.", "Ange ett stilnamn."), ]; pub(super) const CONTEXT: &[(&str, &str, &str)] = &[ diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 5ce0d56a5..bdac19645 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -153,10 +153,22 @@ fn frame_options(d: &Dialog) -> Result *side = measure(key).ok_or_else(|| bad("an inset is not a measure"))?; } o.vertical_justification = serde_json::from_value(json!(d.s("verticalJustification"))).unwrap_or(o.vertical_justification); + if o.vertical_justification == designcraft_doc::VerticalJustification::Justify { + o.vj_paragraph_spacing_limit = measure("paragraphSpacingLimit").ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; + } o.ignore_wrap = d.b("ignoreWrap"); Ok(Some(o)) } +/// The General options of `o` as the `textFrame` parameter of `style.object.create` and `edit`. +fn general_json(o: &designcraft_doc::TextFrameOptions) -> Value { + let mut v = serde_json::to_value(o).unwrap_or_default(); + if let Value::Object(m) = &mut v { + m.retain(|k, _| designcraft_doc::TextFrameOptions::GENERAL_KEYS.contains(&k.as_str())); + } + v +} + /// OK: the new style (applied to the selection when asked), or the edited one. pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let name = d.s("name").trim().to_string(); @@ -164,7 +176,7 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); } let mut p = attrs(d); - p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| serde_json::to_value(o).unwrap_or_default())); + p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| general_json(&o))); if d.b("new") { p.insert("name".into(), json!(name)); p.insert("fromSelection".into(), json!(false)); @@ -694,6 +706,31 @@ mod tests { assert_eq!(os.text_frame.map(|t| t.columns), Some(2), "2.5 columns changed nothing"); } + /// Text Frame General Options › Vertical Justification: Justify with a Paragraph Spacing Limit + /// sets both on the style and its frame, and the frame keeps its auto-size setting. + #[test] + fn the_general_options_page_sets_the_paragraph_spacing_limit() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 336], "content": "text", "caret": false})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "autoSize": "heightOnly"})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Justified")); + d.fields.insert("verticalJustification".into(), json!("justify")); + d.fields.insert("paragraphSpacingLimit".into(), json!("6 pt")); + } + crate::dialogs::confirm(&mut app).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + let tf = doc.styles.object_style("Justified").and_then(|s| s.text_frame.clone()).unwrap(); + assert_eq!((tf.vertical_justification, tf.vj_paragraph_spacing_limit), (designcraft_doc::VerticalJustification::Justify, 6.0)); + app.run("style.object.apply", json!({"name": "Justified", "ids": [id]})).unwrap(); + let o = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().options.clone(); + assert_eq!((o.vj_paragraph_spacing_limit, o.auto_size), (6.0, designcraft_doc::AutoSize::HeightOnly)); + } + /// `objectStyle.dialog` with a style the document lacks, or `[None]`, is an error and opens /// nothing; without a name it opens New Object Style. #[test] From 966c8a587cce0d2853f1977cb73889ea4d8446d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:01:47 -0800 Subject: [PATCH 143/328] Recovery: a cancel stops a background write at its next chunk A save, revert or close during a background recovery write now stops the write at its next piece of output (at most 1 MiB) instead of after the whole package, and a stopped write is not reported as a failure. --- crates/engine/src/lib.rs | 1 + crates/engine/src/recovery.rs | 41 ++++++++++++++++++++++++++--- crates/engine/src/recovery/tests.rs | 20 ++++++++++++++ 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bb67875b4..363f4e9cd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -414,6 +414,7 @@ pub struct Session { pub recovery_dir: Option, /// This session's number for the background recovery writer, which returns each result to /// the session that queued it. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) recovery_owner: recovery::Owner, /// Copied text with its formatting (a frameless story slice), its plain text, and what pasting /// it needs from its document: a copy holding only the stories its anchored text frames show diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index e2e09a42b..3b4060763 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -725,6 +725,36 @@ struct Written { error: Option, } +/// A writer that fails once `cancelled` says so, checked before each write of at most +/// [`STOP_CHECK_BYTES`]. +struct StopWhen<'a, W, C> { + out: &'a mut W, + cancelled: &'a C, +} + +/// The most [`StopWhen`] writes between two checks for a cancel. +const STOP_CHECK_BYTES: usize = 1 << 20; + +impl bool> std::io::Write for StopWhen<'_, W, C> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if (self.cancelled)() { + return Err(std::io::Error::other("recovery write cancelled")); + } + // A large placed file is written in pieces, so a cancel does not wait for all of it. + self.out.write(&buf[..buf.len().min(STOP_CHECK_BYTES)]) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.out.flush() + } +} + +impl std::io::Seek for StopWhen<'_, W, C> { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.out.seek(pos) + } +} + /// Publish a document's recovery entry before its optional metadata. `cancelled` says whether the /// document was saved, reverted or closed since the write started: its snapshot is then dropped /// instead of published, so a crash cannot offer back a copy older than the saved file. @@ -735,7 +765,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let published = publish_recovery_written( &doc, entry.own, - |out| designcraft_format::write(out, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())), + // A cancel stops the write at its next chunk instead of after the whole package. + |out| { + designcraft_format::write(&mut StopWhen { out, cancelled: &cancelled }, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())) + }, &cancelled, // Written: in a folder that is not this run's own, the entry is now this run's to replace // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the @@ -748,8 +781,10 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { ); match published { Ok(true) => {} - // Cancelled while writing: no snapshot and no metadata for it. + // Cancelled while writing: no snapshot and no metadata for it. A write stopped part way + // reports an error, which is the cancel's and not a failure. Ok(false) => return Written { published: false, error: None }, + Err(_) if cancelled() => return Written { published: false, error: None }, Err(e) => return Written { published: false, error: Some(e) }, } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); @@ -758,7 +793,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { let error = publish_recovery_written( &meta, entry.own, - |out| out.write_all(bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), + |out| std::io::Write::write_all(out, bytes.as_bytes()).map_err(|e| EngineError::Other(format!("{}: {e}", meta.display()))), &cancelled, || {}, ) diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index c59c5ee76..4534c3c37 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -514,6 +514,26 @@ fn a_write_cancelled_midway_publishes_nothing() { ); } +#[test] +fn a_cancel_stops_a_write_before_the_package_is_finished() { + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + // Cancelled once the write has started: the first check passes, every later one fails. + let checks = std::cell::Cell::new(0); + let written = write_snapshot(&entry, || { + checks.set(checks.get() + 1); + checks.get() > 1 + }); + assert!(!written.published && written.error.is_none(), "a stopped write is not an error"); + assert!(checks.get() >= 2, "the write checked again before it finished"); + assert!(!files(dir.path(), entry.uid).0.exists(), "nothing was published"); + assert!( + std::fs::read_dir(dir.path()).unwrap().all(|e| e.is_ok_and(|e| !e.file_name().to_string_lossy().starts_with(".designcraft-recovery-"))), + "no temporary file is left" + ); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn only_a_queued_write_is_cancelled() { From 16d60dc03a54695731c770911ac222ce251074d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:04:28 -0800 Subject: [PATCH 144/328] Object styles: options follow one by one; corner sizes are checked - Editing a style's Text Frame General Options updates each option a frame still shares with the style, so a frame's own inset stays while a new column count reaches it. - style.object.create and edit refuse corner sizes outside 0-10000 pt instead of clamping them. - IDML import: a style that turns Stroke & Corner Options on without corner attributes of its own takes all four corners from the styles it is based on. --- crates/doc/src/item/text_frame.rs | 16 ++++++++++++++++ crates/engine/src/cmd/style/object.rs | 15 +++++++-------- crates/engine/src/tests.rs | 11 +++++++++++ crates/idml/src/import/styles.rs | 23 ++++++++++++++++------- crates/idml/src/tests/object_styles.rs | 12 ++++++++++++ 5 files changed, 62 insertions(+), 15 deletions(-) diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 5c01bb21b..cb437e149 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -268,6 +268,22 @@ impl TextFrameOptions { && self.ignore_wrap == other.ignore_wrap } + /// Each General option that is `old`'s here takes `new`'s; the others stay. `true` when one + /// changed. + pub fn follow_general(&mut self, old: &TextFrameOptions, new: &TextFrameOptions) -> bool { + let mut changed = false; + macro_rules! follow { + ($($f:ident),*) => {$( + if self.$f == old.$f && self.$f != new.$f { + self.$f = new.$f; + changed = true; + } + )*}; + } + follow!(columns, columns_kind, gutter, column_width, balance_columns, inset, vertical_justification, vj_paragraph_spacing_limit, ignore_wrap); + changed + } + /// Copies the General options of `from` (see [`Self::GENERAL_KEYS`]). Baseline, auto-size, /// column rule and Type on a Path settings stay as they are. pub fn set_general(&mut self, from: &TextFrameOptions) { diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 6c7455099..50f38e835 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -293,11 +293,9 @@ fn corners_param( let size = sz.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, "corner size must be a number"))?; c.corners.iter_mut().for_each(|k| k.size = size); } - for k in &mut c.corners { - if !k.size.is_finite() { - return Err(bad(cmd, "corner sizes must be finite")); - } - k.size = k.size.clamp(0.0, 10_000.0); + // Sizes given in this call must be 0–10000 pt. + if (o.contains_key("corners") || o.contains_key("size")) && !c.corners.iter().all(|k| k.size.is_finite() && (0.0..=10_000.0).contains(&k.size)) { + return Err(bad(cmd, "corner sizes must be 0–10000 pt")); } Ok(Some(Some(c))) } @@ -386,7 +384,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) - || frame.as_ref().is_some_and(|(o, _)| it.text_frame().is_some_and(|t| t.options.general_eq(o))) + || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; let updated = d.update_items( |it| it.object_style == new.name && follows(it), @@ -411,11 +409,12 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { { it.corners = n.named_to_path(&it.path); } + // Each General option follows on its own, so a frame's own inset stays while a + // new column count reaches it. if let Some((o, n)) = &frame && let Some(tf) = it.text_frame_mut() - && tf.options.general_eq(o) { - tf.options.set_general(n); + tf.options.follow_general(o, n); } }, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 48cb02446..d559fd7d2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -792,6 +792,12 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // A size outside 0–10000 pt is refused, not changed. + for size in [-1.0, 10_001.0] { + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); + let c = json!({"shape": "rounded", "size": size}); + assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err(), "{size}"); + } // A negative stroke weight is refused when creating a style as when editing one. let styles = s.doc().unwrap().doc.styles.object.len(); for cmd in ["style.object.create", "style.object.edit"] { @@ -921,6 +927,11 @@ fn object_style_text_frame_general_options_leave_the_other_frame_settings() { assert_eq!(r["updated"], 1); let o = options(&s, a); assert_eq!((o.inset, o.ignore_wrap, o.auto_size), ([1.0, 2.0, 3.0, 4.0], true, AutoSize::HeightOnly)); + // Each option follows on its own: the frame's own inset stays and the new column count arrives. + s.execute("object.textFrameOptions", &json!({"ids": [a], "inset": 9})).unwrap(); + s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 3}})).unwrap(); + let o = options(&s, a); + assert_eq!((o.columns, o.inset), (3, [9.0; 4])); // Threaded frames: the story's paragraphs take one Next Style chain across both frames. s.execute("text.thread", &json!({"from": a, "to": b})).unwrap(); diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index e82d8fc0b..e2e11e979 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -211,13 +211,7 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - // Corner options, when the style sets them (Stroke & Corner Options), by name. A style - // that sets some corners takes the others from the styles it is based on, as the style - // holds all four. - let corners = (e.get("EnableStrokeAndCornerOptions") != Some("false") && corners(e, "").is_some()) - .then(|| corners_in(&levels, "")) - .flatten() - .map(|c| CornerOptions { corners: c }); + let corners = style_corners(e, &levels); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { @@ -418,6 +412,21 @@ impl<'r> Importer<'r> { } } +/// Object style `e`'s corner options (Stroke & Corner Options), by name, when it sets them. A style +/// that sets some corners, or turns the category on, takes the others from the styles in `levels` +/// (`e` and the styles it is based on) that don't turn the category off. +fn style_corners(e: &El, levels: &[&El]) -> Option { + match e.get("EnableStrokeAndCornerOptions") { + Some("false") => return None, + Some("true") => {} + _ => { + corners(e, "")?; + } + } + let on: Vec<&El> = levels.iter().copied().filter(|l| l.get("EnableStrokeAndCornerOptions") != Some("false")).collect(); + corners_in(&on, "").map(|c| CornerOptions { corners: c }) +} + /// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A /// `BasedOn` may name a style by its `Self` id or by its bare name. fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 52605d7a0..4ff0fa6bf 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -314,6 +314,18 @@ fn a_style_setting_one_corner_inherits_the_others_and_names_them() { assert_eq!(it.corners.corners.map(|c| c.shape), [CornerShape::Rounded, CornerShape::Rounded, CornerShape::Rounded, CornerShape::Bevel]); } +/// A style that turns Stroke & Corner Options on without corner attributes of its own takes all +/// four corners from the style it is based on. +#[test] +fn a_style_turning_corners_on_inherits_all_four() { + let child = r#" + ObjectStyle/Round + "#; + let d = fixture(&format!("{ROUND}{child}"), &[]); + let c = d.styles.object.iter().find(|s| s.name == "Plain").and_then(|s| s.corners).expect("inherited corners").corners; + assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); +} + /// An object style giving its corners only with the legacy all-corners `CornerOption` and /// `CornerRadius` keeps them, so applying it to another frame rounds it. #[test] From 4973d11569d99ea0b2ad9e6ca7944895218ff4cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:15:03 -0800 Subject: [PATCH 145/328] Object styles: unknown swatches and settings are refused - style.object.create and edit refuse a fill, stroke or gap swatch the document lacks, and a fill or stroke key that is not a setting of it (a misspelled "wieght" no longer succeeds without a change). - fromSelection must be true or false. --- crates/engine/src/cmd/style.rs | 4 +-- crates/engine/src/cmd/style/object.rs | 46 ++++++++++++++++++++++----- crates/engine/src/tests.rs | 15 +++++++++ 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 5b1ac047d..7e55e0529 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …}, corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null, corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 50f38e835..2a8ec7dd3 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -131,7 +131,9 @@ fn merge_json(base: &mut Value, top: Value, depth: usize) { pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { let base = str_param(p, "name").unwrap_or("Object Style 1").to_string(); - let from_sel = p.get("fromSelection").and_then(Value::as_bool).unwrap_or(true); + const CREATE: &str = "style.object.create"; + check_swatches(CREATE, s, p)?; + let from_sel = bool_param(CREATE, p, "fromSelection")?.unwrap_or(true); let src = if from_sel { s.doc()?.selection.items.first().and_then(|i| s.doc().ok()?.doc.item(*i).cloned()) } else { None }; let mut os = ObjectStyle::default(); if let Some(it) = &src { @@ -141,7 +143,6 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { os.text_frame = it.text_frame().map(|t| t.options.clone()); os.effects = Some(it.effects.clone()); } - const CREATE: &str = "style.object.create"; if let Some(f) = fill_param(CREATE, p, os.fill.as_ref())? { os.fill = f; } @@ -171,6 +172,23 @@ pub(super) fn create_object(s: &mut Session, p: &Value) -> Result { }) } +/// The swatches this call gives (`fill` as a name or `fill.swatch`, `stroke.swatch` and +/// `stroke.gapSwatch`) must be swatches of the document. +fn check_swatches(cmd: &str, s: &Session, p: &Value) -> Result<()> { + let doc = &s.doc()?.doc; + let given = [ + ("fill", p.get("fill").and_then(|f| f.as_str().or_else(|| f.get("swatch").and_then(Value::as_str)))), + ("stroke", p.get("stroke").and_then(|f| f.get("swatch")).and_then(Value::as_str)), + ("stroke gap", p.get("stroke").and_then(|f| f.get("gapSwatch")).and_then(Value::as_str)), + ]; + for (key, name) in given { + if let Some(name) = name { + crate::cmd::object::known_swatch(doc, name, cmd, key)?; + } + } + Ok(()) +} + /// `paragraphStyle`: a paragraph style's name, or null (the object style sets none). fn paragraph_style_param(cmd: &str, s: &Session, p: &Value) -> Result>> { match p.get("paragraphStyle") { @@ -200,7 +218,7 @@ fn text_frame_param( o.insert("inset".into(), json!([n, n, n, n])); } } - let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()))?; + let tf = group_param(cmd, &p, "textFrame", base.unwrap_or(&designcraft_doc::TextFrameOptions::default()), &[])?; if let Some(Some(o)) = &tf { // Only the values given in this call are checked. let given = |k: &str| p.get("textFrame").is_some_and(|t| t.get(k).is_some()); @@ -228,7 +246,8 @@ fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { /// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 /// or the tint isn't 0–1. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { - let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()))?; + let optional = ["gapOverprint", "gradientAngle", "gradientVector"]; + let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()), &optional)?; if let Some(Some(st)) = &st { if !(st.weight.is_finite() && st.weight >= 0.0) { return Err(bad(cmd, "stroke weight must be a number ≥ 0")); @@ -241,13 +260,23 @@ fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> } /// `p[key]`, an attribute group of a style, merged field by field over `base`: `None` when not -/// given, `Some(None)` for null (the style no longer sets it). -fn group_param(cmd: &str, p: &Value, key: &str, base: &T) -> Result>> { +/// given, `Some(None)` for null (the style no longer sets it). A field `base` doesn't write and +/// `optional` doesn't name is refused. +fn group_param( + cmd: &str, + p: &Value, + key: &str, + base: &T, + optional: &[&str], +) -> Result>> { match p.get(key) { None => Ok(None), Some(Value::Null) => Ok(Some(None)), - Some(v @ Value::Object(_)) => { + Some(v @ Value::Object(given)) => { let mut cur = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?; + if let Some(k) = given.keys().find(|k| cur.get(k.as_str()).is_none() && !optional.contains(&k.as_str())) { + return Err(bad(cmd, format!("{key}.{k} is not a {key} setting"))); + } merge_json(&mut cur, v.clone(), 0); serde_json::from_value(cur).map(|t| Some(Some(t))).map_err(|e| bad(cmd, format!("{key}: {e}"))) } @@ -260,7 +289,7 @@ fn fill_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Fill>) -> Res if let Some(sw) = p.get("fill").and_then(Value::as_str) { return Ok(Some(Some(designcraft_doc::Fill::swatch(sw)))); } - let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()))?; + let fill = group_param(cmd, p, "fill", base.unwrap_or(&designcraft_doc::Fill::default()), &["gradientAngle", "gradientVector"])?; if let Some(Some(f)) = &fill && !(f.tint.is_finite() && (0.0..=1.0).contains(&f.tint)) { @@ -307,6 +336,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("`{name}` can't be edited"))); } let old = s.doc()?.doc.styles.object_style(&name).cloned().ok_or_else(|| bad(CMD, format!("no object style `{name}`")))?; + check_swatches(CMD, s, p)?; let mut new = old.clone(); if p.get("effects").is_some_and(Value::is_null) { if EFFECT_KEYS.iter().any(|k| p.get(k).is_some()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d559fd7d2..526f421a8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -792,6 +792,21 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); + // An unknown swatch, a misspelled setting and a word for a switch are refused. + for bad in [ + json!({"fill": "Nope"}), + json!({"fill": {"swatch": "Nope"}}), + json!({"stroke": {"swatch": "Nope"}}), + json!({"stroke": {"wieght": 5}}), + json!({"fill": {"tnt": 0.5}}), + ] { + let mut p = bad.clone(); + p["name"] = json!("Framed"); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + p["name"] = json!("Other"); + assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); + } + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); // A size outside 0–10000 pt is refused, not changed. for size in [-1.0, 10_001.0] { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); From 4282f30cf9b85b888898a5a581b0842efc5ca5c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:23:48 -0800 Subject: [PATCH 146/328] Object styles: a stroke added to a style reaches shapes with the default stroke When a style that set no stroke gains one, its frames with no stroke and its drawn shapes still carrying the default 1 pt black stroke take it. A text or graphic frame with its own stroke keeps it. --- crates/engine/src/cmd/style/object.rs | 18 ++++++++++++------ crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 2a8ec7dd3..dc5f81643 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -402,17 +402,23 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { // most frames). An attribute the style no longer sets stays as it is on the items. let effects = (new.effects != old.effects).then_some(new.effects.clone()).flatten().map(|e| (old.effects.clone().unwrap_or_default(), e)); let fill = (new.fill != old.fill).then_some(new.fill.clone()).flatten().map(|f| (old.fill.clone().unwrap_or_default(), f)); - let stroke = (new.stroke != old.stroke) - .then_some(new.stroke.clone()) - .flatten() - .map(|f| (old.stroke.clone().unwrap_or_else(designcraft_doc::Stroke::none), f)); + let stroke = (new.stroke != old.stroke).then_some(new.stroke.clone()).flatten().map(|f| (old.stroke.clone(), f)); + // With no stroke in the style before, an item with no stroke (a frame's default) or a + // 1 pt black one (a drawn shape's default) follows. + let stroke_follows = |it: &Item, old: &Option| match old { + Some(o) => it.stroke == *o, + None => { + it.stroke == designcraft_doc::Stroke::none() + || (matches!(it.content, designcraft_doc::Content::Unassigned) && it.stroke == designcraft_doc::Stroke::default()) + } + }; let corners = (new.corners != old.corners).then_some(new.corners).flatten().map(|c| (old.corners.unwrap_or_default(), c)); let frame = (new.text_frame != old.text_frame).then_some(new.text_frame.clone()).flatten().map(|t| (old.text_frame.clone().unwrap_or_default(), t)); let follows = |it: &Item| { effects.as_ref().is_some_and(|(o, _)| it.effects == *o) || fill.as_ref().is_some_and(|(o, _)| it.fill == *o) - || stroke.as_ref().is_some_and(|(o, _)| it.stroke == *o) + || stroke.as_ref().is_some_and(|(o, _)| stroke_follows(it, o)) || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; @@ -430,7 +436,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { it.fill = n.clone(); } if let Some((o, n)) = &stroke - && it.stroke == *o + && stroke_follows(it, o) { it.stroke = n.clone(); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 526f421a8..a871b70de 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -980,6 +980,28 @@ fn object_style_text_frame_general_options_leave_the_other_frame_settings() { assert!(s.execute("style.object.edit", &json!({"name": name, "textFrame": {"columns": 60}})).is_err()); } +/// A stroke added to a style that set none reaches a drawn shape still carrying its default 1 pt +/// stroke and a frame with none, and leaves a shape or text frame with its own stroke. +#[test] +fn a_stroke_added_to_an_object_style_reaches_default_strokes() { + use designcraft_doc::ItemId; + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Boxed", "fromSelection": false})).unwrap(); + let frame = |s: &mut Session, x: f64, content: &str| { + s.execute("frame.create", &json!({"rect": [x, 36, x + 50.0, 86], "content": content, "caret": false})).unwrap()["id"].as_u64().unwrap() + }; + let (shape, text, own) = (frame(&mut s, 36.0, "unassigned"), frame(&mut s, 100.0, "text"), frame(&mut s, 200.0, "unassigned")); + let stroked_text = frame(&mut s, 300.0, "text"); + s.execute("object.stroke", &json!({"ids": [own], "weight": 9})).unwrap(); + s.execute("object.stroke", &json!({"ids": [stroked_text], "weight": 1})).unwrap(); + s.execute("style.object.apply", &json!({"name": "Boxed", "ids": [shape, text, own, stroked_text]})).unwrap(); + let r = s.execute("style.object.edit", &json!({"name": "Boxed", "stroke": {"weight": 4}})).unwrap(); + assert_eq!(r["updated"], 2, "{r}"); + let weight = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().stroke.weight; + assert_eq!((weight(&s, shape), weight(&s, text), weight(&s, own)), (4.0, 4.0, 9.0)); + assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; From b6d6d7e0911a92dd0a1779a7912ba2fababe8c40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:26:11 -0800 Subject: [PATCH 147/328] Text wrap: relinked images and graphic wraps on anchored frames update the layout - The composition cache compares each Alpha Channel outline by a serial number, so a relink or link update lays the text out again around the new image. - A contour clipped by its frame blocks only the part of the outline the frame shows, even where the two share x positions in one line band. A fragmented frame, or shapes too detailed for a line's budget, keep the intersection of the two projections. - An anchored frame whose wrap is set only on its placed graphic wraps text. - The default alpha threshold is not saved. - docs/typography-parity.md describes the Alpha Channel contour. --- crates/compose/src/cache.rs | 10 +- crates/compose/src/lib.rs | 193 +++++++++++++++++++++++++--- crates/compose/src/tests.rs | 77 +++++++++++ crates/compose/src/wrap.rs | 5 +- crates/doc/src/item/text_frame.rs | 29 ++++- crates/doc/src/lib.rs | 10 ++ crates/engine/src/cmd/alpha_wrap.rs | 38 +++++- docs/typography-parity.md | 2 +- 8 files changed, 337 insertions(+), 27 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..72ef7fff4 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -5,7 +5,8 @@ //! wrapping item on the frames' spreads, and the same for every story whose anchored objects wrap //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers -//! can't be reused by other allocations while the entry lives. +//! can't be reused by other allocations while the entry lives. The document's Alpha Channel +//! outlines count by serial number, which no other outline shares. use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; @@ -85,6 +86,9 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + for o in &doc.alpha_outlines { + o.serial.hash(&mut h); + } h.finish() } @@ -407,6 +411,10 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); + // Alpha Channel outlines: a relink traces one again without changing the story or the items + // that wrap it. + sig.extend(doc.alpha_outlines.iter().flat_map(|o| [(o.serial & 0xffff_ffff) as usize, (o.serial >> 32) as usize])); + sig.push(usize::MAX); let mut keep = Vec::new(); let mut spreads = Vec::new(); for f in &story.frames { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 62e319f36..ac563b616 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -388,6 +388,10 @@ pub struct Contour { /// Points a contour outline may have; a larger outline wraps around its bounding box. pub const MAX_CONTOUR_POINTS: usize = 8192; +/// Edge visits a clipped contour may take for one line band; past it, the line's spans come from +/// the two shapes' projections instead of their intersection. +const MAX_CLIPPED_WORK: usize = 1 << 20; + impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { @@ -448,26 +452,164 @@ impl Contour { } if !self.clip.is_empty() { let clip = rings_band_spans(&self.clip, low, high); - let mut cut = Vec::new(); - let (mut i, mut j) = (0, 0); - while let (Some(&(a, b)), Some(&(c, d))) = (spans.get(i), clip.get(j)) { - let (lo, hi) = (a.max(c), b.min(d)); - // A zero-width span (a vertical open path) is kept where the clip covers it. - if lo < hi || (a == b && lo == hi) { - cut.push((lo, hi)); - } - if b < d { - i += 1; - } else { - j += 1; - } - } - spans = cut; + // A fragmented frame, or shapes too detailed to compare within each line's budget, + // take the common part of the two projections, which can block more than the frame + // shows. + let exact = if clip.len() > 128 { None } else { clipped_band_spans(&self.rings, &self.clip, low, high) }; + spans = exact.unwrap_or_else(|| intersect_spans(&spans, &clip)); } merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) } } +/// The sorted spans in both `a` and `b` (each sorted and merged). A zero-width span (a vertical +/// open path) is kept where the other covers it. +fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { + let mut out = Vec::new(); + let (mut i, mut j) = (0, 0); + while let (Some(&(p, q)), Some(&(r, s))) = (a.get(i), b.get(j)) { + let (lo, hi) = (p.max(r), q.min(s)); + if lo < hi || (lo == hi && (p == q || r == s)) { + out.push((lo, hi)); + } + if q < s { + i += 1; + } else { + j += 1; + } + } + out +} + +/// Occupied intervals across the band `y0..y1` of the part of `rings` inside `clip` (both filled +/// by the non-zero rule). A vertical line through a point of that part either crosses the middle +/// of the band inside both shapes, or stops inside the band on an edge of one shape that lies +/// inside the other. The spans are the middle slice of both shapes and the parts of each +/// shape's edges in the band that lie inside the other, so a part of the outline outside the +/// clip blocks nothing, even where it shares x positions with the clip in the same band. +/// None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(rings: &[Vec], clip: &[Vec], y0: f64, y1: f64) -> Option> { + let middle = y0 * 0.5 + y1 * 0.5; + let mut spans = intersect_spans(&merge_spans(middle_spans(rings, middle)), &merge_spans(middle_spans(clip, middle))); + let mut budget = MAX_CLIPPED_WORK; + edges_inside(rings, clip, y0, y1, &mut budget, &mut spans)?; + edges_inside(clip, rings, y0, y1, &mut budget, &mut spans)?; + Some(merge_spans(spans)) +} + +/// Takes `n` edge visits from `budget`; None when it doesn't hold that many. +fn spend(budget: &mut usize, n: usize) -> Option<()> { + *budget = budget.checked_sub(n)?; + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of `rings`' edges within the band `y0..y1` that lie +/// inside `other` or on its boundary. None when `budget` runs out. +fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = other.iter().map(Vec::len).sum::().max(1); + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, other, n, budget, out)?; + } + a = b; + } + } + Some(()) +} + +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q` inside `rings` (`n` edges) or on +/// their boundary: the segment is split where it meets their edges, and each piece is tested at +/// its middle. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let r = q - p; + let len2 = r.hypot2(); + if !len2.is_finite() { + return Some(()); + } + let at = |t: f64| p + r * t; + spend(budget, n)?; + if len2 < 1e-24 { + if inside_or_on(rings, p) { + out.push((p.x, p.x)); + } + return Some(()); + } + let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); + let mut ts = vec![0.0, 1.0]; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut c = last; + for &d in ring { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { + ts.push(t); + } + } + } + } + c = d; + } + } + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); + for w in ts.windows(2) { + let (u, v) = (w[0], w[1]); + spend(budget, n)?; + if inside_or_on(rings, at(u * 0.5 + v * 0.5)) { + let (x0, x1) = (at(u).x, at(v).x); + out.push((x0.min(x1), x0.max(x1))); + } + } + Some(()) +} + +/// Is `pt` inside `rings` (non-zero rule) or within a hair of one of their edges? +fn inside_or_on(rings: &[Vec], pt: Point) -> bool { + let mut winding = 0i32; + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; + } + } + a = b; + } + } + winding != 0 +} + /// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: /// the wrap offset widens them, and without one they still split the line there. fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { @@ -485,9 +627,7 @@ fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { } fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { - let mut spans = Vec::new(); - let mut crossings = Vec::new(); - let middle = y0 * 0.5 + y1 * 0.5; + let mut spans = middle_spans(rings, y0 * 0.5 + y1 * 0.5); for ring in rings { let Some(&last) = ring.last() else { continue }; let mut a = last; @@ -503,6 +643,21 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { let (x0, x1) = (a.x + t0 * (b.x - a.x), a.x + t1 * (b.x - a.x)); spans.push((x0.min(x1), x0.max(x1))); } + a = b; + } + } + merge_spans(spans) +} + +/// The intervals of the line at height `middle` inside `rings` (non-zero rule), unsorted. +fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { + let mut spans = Vec::new(); + let mut crossings = Vec::new(); + for ring in rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + let dy = b.y - a.y; if (a.y <= middle && middle < b.y) || (b.y <= middle && middle < a.y) { let x = a.x + (middle - a.y) / dy * (b.x - a.x); if x.is_finite() { @@ -524,7 +679,7 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { winding += delta; previous = Some(x); } - merge_spans(spans) + spans } /// The closed polylines of `path` (after `to_inner`), flattened; None if it is empty or too detailed. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3df861733..ab108b03b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -7581,6 +7581,38 @@ fn anchored_object_wraps_another_storys_text() { assert!(lines_in_band(&moved, 200.0, 260.0).iter().all(|l| l.x0 >= left + 100.0 - 1e-6)); } +/// An anchored frame whose wrap is set only on its placed graphic (Direct Selection) wraps +/// another story's text as a wrap set on the frame does. +#[test] +fn anchored_graphic_wrap_wraps_another_storys_text() { + let long = [LOREM; 3].join(" "); + let (mut d, a, fa) = doc_with("Anchor here.", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + let lid = d.default_layer(); + let (_, b) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(320.0, 0.0, 620.0, 400.0), lid, &long, ParaFormat::default()).unwrap(); + let left = all_lines(&compose_story(&d, b, &ComposeOptions::default()))[0].x0; + let area = d.item(fa).unwrap().text_area(); + anchor_box(&mut d, a, 0, left - area.x0, 100.0 - area.y0, false, WrapMode::None); + let wrap = designcraft_doc::TextWrap { mode: WrapMode::BoundingBox, ..Default::default() }; + let obj = std::sync::Arc::make_mut(&mut d.story_mut(a).unwrap().objects[0]); + obj.item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: designcraft_doc::AssetId(1), + size: (100.0, 60.0), + xf: designcraft_geom::Affine::IDENTITY, + clip: None, + auto_fit: designcraft_doc::Fitting::None, + fit_align: 0, + crop: [0.0; 4], + wrap, + fill: Default::default(), + }); + let cs = compose_story(&d, b, &ComposeOptions::default()); + let band = lines_in_band(&cs, 100.0, 160.0); + assert!(!band.is_empty()); + assert!(band.iter().all(|l| l.x0 >= left + 100.0 - 1e-6), "{:?}", band.iter().map(|l| l.x0).collect::>()); + assert!(lines_in_band(&cs, 0.0, 80.0).iter().all(|l| (l.x0 - left).abs() < 1e-6)); +} + /// An anchored object's wrap is built as a page item's: a contour on both sides of an oval sets /// text left and right of it, closer in where the oval narrows. #[test] @@ -8479,6 +8511,51 @@ fn a_vertical_open_path_keeps_its_offset() { assert_eq!(c.band_spans(40.0, 50.0), vec![(10.0, 10.0)]); } +/// An outline counts only where its frame shows it: a part of it in a notch of the frame blocks +/// nothing, even where the frame covers the same x positions lower in the same line band. +#[test] +fn a_clipped_contour_blocks_only_what_its_frame_shows() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // An L-shaped frame with a notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch only. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); + // Reaching below the notch, where the frame shows it from y = 6 to 8. + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 8.0), (20.0, 8.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // A band that crosses both shapes whole keeps their common part, widened by the offset. + let c = Contour::of(&poly(&[(5.0, -10.0), (30.0, -10.0), (30.0, 20.0), (5.0, 20.0)]), id, 2.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(7.0, 9.0), vec![(3.0, 32.0)]); + // A frame in more than 128 pieces across the band takes the common part of the projections. + let mut fragmented = frame.clone(); + for i in 0..200 { + let x = 1000.0 + 2.0 * f64::from(i); + fragmented.extend(poly(&[(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 10.0), (x, 10.0)]).elements().iter().copied()); + } + let c = Contour::of(&poly(&[(20.0, 0.0), (40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]), id, 0.0).unwrap(); + assert_eq!(c.within(&fragmented, id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); + // So does a frame and an outline too detailed to compare within a line's budget: here 2,000 + // points on the frame's bottom edge and on the outline's top edge. + let mut detailed = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0)]; + detailed.extend((1..2000).map(|i| (40.0 - 0.02 * f64::from(i), 10.0))); + detailed.push((0.0, 10.0)); + let mut notch: Vec<(f64, f64)> = (0..2000).map(|i| (20.0 + 0.01 * f64::from(i), 0.0)).collect(); + notch.extend([(40.0, 0.0), (40.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(¬ch), id, 0.0).unwrap(); + assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index 98219b066..6de1d3ace 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -18,7 +18,7 @@ //! is composed at most that many more times (at least [`MIN_PASSES`]), and never more than //! [`MAX_PASSES`]. -use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; +use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId}; use designcraft_geom::Affine; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; @@ -48,8 +48,9 @@ pub(crate) struct Obstacle<'a> { anchor: Option, } +/// The wrap may be set on the frame or on its placed graphic (Direct Selection). fn wraps(o: &AnchoredObject) -> bool { - o.item.wrap.mode != WrapMode::None && !o.item.hidden + o.item.has_wrap() && !o.item.hidden } /// Does `story` have an anchored object whose wrap can push text? diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 62f12eb24..f31f14060 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -272,7 +272,7 @@ pub enum ContourType { BoundingBox, /// Edges detected in the image. Composition follows the frame path. DetectEdges, - /// The image's alpha channel. Composition follows the frame path. + /// The image's alpha channel. Composition follows the outline of the image's visible pixels. AlphaChannel, /// A path saved in the image. Composition follows the frame path. PhotoshopPath, @@ -302,10 +302,16 @@ pub struct TextWrap { /// transparent holes it encloses (off: holes are blocked with the shape around them). #[serde(skip_serializing_if = "std::ops::Not::not")] pub inside_edges: bool, - /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. Saved only + /// when it isn't the default. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] pub alpha_threshold: u8, } +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + /// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; @@ -343,3 +349,22 @@ pub struct TextFrame { #[serde(default)] pub options: TextFrameOptions, } + +#[cfg(test)] +mod tests { + use super::*; + + /// The alpha threshold is saved only when it isn't the default, so a wrap saved before it + /// existed is saved the same way, and reads back as the default. + #[test] + fn the_default_alpha_threshold_is_not_saved() { + let wrap = TextWrap { mode: WrapMode::Contour, ..Default::default() }; + let v = serde_json::to_value(&wrap).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + assert_eq!(serde_json::from_value::(v).unwrap(), wrap); + let set = TextWrap { alpha_threshold: 200, ..wrap }; + let v = serde_json::to_value(&set).unwrap(); + assert_eq!(v["alphaThreshold"], 200); + assert_eq!(serde_json::from_value::(v).unwrap(), set); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8f105457c..f26ef10ad 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -674,9 +674,19 @@ pub struct AlphaOutline { /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image /// data alive, and its address can't be reused by new data while it's held.) pub source: std::sync::Weak>, + /// A number no other outline made in this process has ([`AlphaOutline::next_serial`]). + /// Composition caches compare it: an outline traced again after a relink has a new one, + /// while a dropped outline's address can be reused. + pub serial: u64, } impl AlphaOutline { + /// A serial number not given out before in this process. + pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + /// Traced from `data`, the asset's current image data. pub fn traced_from(&self, data: &Arc>) -> bool { std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index b4009de1d..1ee2919a1 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -62,7 +62,16 @@ pub(crate) fn sync(doc: &mut Document) { /// The empty outline standing for an image `trace` found none in: zero-size, which composition /// takes as no outline, and dropped like a traced one when the asset's data changes. fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { - AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: Arc::downgrade(data), + serial: AlphaOutline::next_serial(), + } } /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that @@ -112,7 +121,8 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio PathData::from_bezpath(&p) }; let source = Arc::downgrade(data); - return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source, serial }); } finer = Some((mask, cols, rows)); grid /= 2; @@ -502,4 +512,28 @@ mod tests { assert!(s.execute("object.textWrap", &bad).is_err()); } } + + /// Replacing the image data under the same asset, as a relink or link update does, lays the + /// text out again around the new outline: neither the story nor the frames change. + #[test] + fn a_relinked_image_lays_the_text_out_again() { + let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the gap between the legs stays open"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + // The new image has no gap: one band across both legs. + let solid = Arc::new(png(|x, _| (8..56).contains(&x))); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = solid.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the new image covers the caption"); + } } diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..599c20b39 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the image's visible pixels within the frame (threshold, Include Inside Edges); Detect Edges and Photoshop Path contours follow the frame's path (composition doesn't read the image) | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From 2e1d17e1fa2dcdab33043ebe204713f3f3304375 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:32:14 +0000 Subject: [PATCH 148/328] Apply review fixes - crates/ui-egui/src/preflight_worker.rs --- crates/ui-egui/src/preflight_worker.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index ddcdffe68..4da6224e5 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -151,7 +151,10 @@ fn issues_at(app: &mut DesignApp, ctx: &egui::Context, now: f64) -> Option Date: Wed, 11 Nov 2026 21:33:24 -0800 Subject: [PATCH 149/328] Object styles: edits reach text frames anchored in stories, cells and notes style.object.edit updates the attributes and paragraph styles of text frames anchored in stories, table cells and notes, as IDML import places them, as it does for frames on spreads. --- crates/engine/src/cmd/style/object.rs | 18 +++++------------- crates/engine/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index dc5f81643..8a156d654 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -422,7 +422,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { || corners.as_ref().is_some_and(|(o, _)| it.corners == o.named_to_path(&it.path)) || frame.as_ref().is_some_and(|(o, n)| it.text_frame().is_some_and(|t| t.options.clone().follow_general(o, n))) }; - let updated = d.update_items( + let updated = d.update_placed_items( |it| it.object_style == new.name && follows(it), |it| { if let Some((o, n)) = &effects @@ -458,18 +458,10 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { // is in the old one's; when the style set none before, all of it does. let mut restyled = 0; if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) { - let mut stories = Vec::new(); - for sp in d.spreads.iter().chain(d.parents.iter()) { - for it in &sp.items { - it.walk(&mut |i| { - if i.object_style == new.name - && let Some(tf) = i.text_frame() - { - stories.push(tf.story); - } - }); - } - } + // Frames on spreads and parents, in groups, and anchored in stories, table cells and + // notes (as IDML import places them). + let mut stories: Vec<_> = + d.placed_items().into_iter().filter(|i| i.object_style == new.name).filter_map(|i| i.text_frame().map(|tf| tf.story)).collect(); stories.sort_unstable(); stories.dedup(); let styles = d.styles.clone(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a871b70de..5824be21c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1002,6 +1002,31 @@ fn a_stroke_added_to_an_object_style_reaches_default_strokes() { assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); } +/// A text frame anchored in a story (as IDML import places one) takes a new paragraph style of +/// its object style like a frame on the page. +#[test] +fn an_object_style_edit_restyles_an_anchored_text_frame() { + use designcraft_doc::ItemId; + let mut s = session(); + s.execute("style.paragraph.create", &json!({"name": "Body"})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Lead"})).unwrap(); + s.execute("style.object.create", &json!({"name": "Sidebar", "fromSelection": false, "paragraphStyle": "Body"})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 136, 86], "content": "text", "text": "Inner", "caret": false})).unwrap(); + let (inner, inner_story) = (ItemId(r["id"].as_u64().unwrap()), designcraft_doc::StoryId(r["story"].as_u64().unwrap())); + s.execute("style.object.apply", &json!({"name": "Sidebar", "ids": [inner.0]})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 200, 400, 400], "content": "text", "text": "Before after.", "caret": false})).unwrap(); + let host = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let it = d.item(inner).unwrap().clone(); + std::sync::Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id != inner); + d.story_mut(host).unwrap().insert_object(7, designcraft_doc::AnchoredObject::new(it, Default::default())); + } + let r = s.execute("style.object.edit", &json!({"name": "Sidebar", "paragraphStyle": "Lead"})).unwrap(); + assert_eq!(r["restyled"], 1, "{r}"); + assert_eq!(s.doc().unwrap().doc.story(inner_story).unwrap().paras[0].style, "Lead"); +} + #[test] fn object_style_effects_reach_grouped_and_anchored_items() { use designcraft_doc::ItemId; From 544ebaf571db68f904a10b896f41e063bba94b96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:33:53 -0800 Subject: [PATCH 150/328] Text wrap: a relinked image's new outline recomposes the text around it - each traced Alpha Channel outline has a serial number, and the composition signatures include the outlines in use, so a relink or link update that changes only the image data no longer leaves text laid out around the old image - a wrap with the default alpha threshold is saved without it, as before thresholds were stored - docs/typography-parity.md says Alpha Channel contours follow the image's visible pixels --- crates/compose/src/cache.rs | 13 ++++++++ crates/doc/src/item/text_frame.rs | 5 +++ crates/doc/src/lib.rs | 9 ++++++ crates/engine/src/cmd/alpha_wrap.rs | 48 +++++++++++++++++++++++++++-- docs/typography-parity.md | 2 +- 5 files changed, 74 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..c1f52d162 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -85,6 +85,18 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + outlines_hash(doc).hash(&mut h); + h.finish() +} + +/// The Alpha Channel outlines text wraps around: a relink traces a new one while the items and +/// stories stay the same. +fn outlines_hash(doc: &Document) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for o in &doc.alpha_outlines { + o.serial.hash(&mut h); + } h.finish() } @@ -405,6 +417,7 @@ fn signature(doc: &Document, story: &Arc) -> (Vec, Vec>) sections_hash(doc) as usize, doc.font_scope as usize, usize::from(g.relative_to == designcraft_doc::GridRelative::TopMargin), + outlines_hash(doc) as usize, ]; sig.extend([g.start, g.increment].into_iter().flat_map(bits)); let mut keep = Vec::new(); diff --git a/crates/doc/src/item/text_frame.rs b/crates/doc/src/item/text_frame.rs index 62f12eb24..2e7506f26 100644 --- a/crates/doc/src/item/text_frame.rs +++ b/crates/doc/src/item/text_frame.rs @@ -303,12 +303,17 @@ pub struct TextWrap { #[serde(skip_serializing_if = "std::ops::Not::not")] pub inside_edges: bool, /// Alpha Channel contour: pixels more opaque than this (0..254) count as the image. + #[serde(skip_serializing_if = "is_default_alpha_threshold")] pub alpha_threshold: u8, } /// DesignCraft's default alpha threshold for Alpha Channel contour wraps. pub const DEFAULT_ALPHA_THRESHOLD: u8 = 25; +fn is_default_alpha_threshold(t: &u8) -> bool { + *t == DEFAULT_ALPHA_THRESHOLD +} + impl Default for TextWrap { fn default() -> Self { TextWrap { diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 8f105457c..2b18c8f47 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -674,9 +674,18 @@ pub struct AlphaOutline { /// under the same id, and the outline is traced again. (Weak, so it doesn't keep old image /// data alive, and its address can't be reused by new data while it's held.) pub source: std::sync::Weak>, + /// A number no other outline traced in this process has ([`AlphaOutline::next_serial`]): + /// composition caches compare it to tell a new outline from the one they used. + pub serial: u64, } impl AlphaOutline { + /// A serial number for a new outline, unique within the process. + pub fn next_serial() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + /// Traced from `data`, the asset's current image data. pub fn traced_from(&self, data: &Arc>) -> bool { std::ptr::eq(self.source.as_ptr(), Arc::as_ptr(data)) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index b4009de1d..585f29350 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -62,7 +62,16 @@ pub(crate) fn sync(doc: &mut Document) { /// The empty outline standing for an image `trace` found none in: zero-size, which composition /// takes as no outline, and dropped like a traced one when the asset's data changes. fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutline { - AlphaOutline { asset, threshold, width: 0, height: 0, outer: Default::default(), holes: Default::default(), source: Arc::downgrade(data) } + AlphaOutline { + asset, + threshold, + width: 0, + height: 0, + outer: Default::default(), + holes: Default::default(), + source: Arc::downgrade(data), + serial: AlphaOutline::next_serial(), + } } /// The outline of the pixels of `data` more opaque than `threshold`. None for an image that @@ -112,7 +121,8 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio PathData::from_bezpath(&p) }; let source = Arc::downgrade(data); - return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source }); + let serial = AlphaOutline::next_serial(); + return Some(AlphaOutline { asset, threshold, width: w, height: h, outer: path(&outer), holes: path(&holes), source, serial }); } finer = Some((mask, cols, rows)); grid /= 2; @@ -428,6 +438,40 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// A wrap with the default threshold saves as it did before thresholds were stored; another + /// threshold is saved. + #[test] + fn the_default_threshold_is_left_out_of_a_saved_wrap() { + let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap(); + assert!(v.get("alphaThreshold").is_none(), "{v}"); + let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap(); + assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD); + let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() }; + assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200); + } + + /// A relink that changes only the image data recomposes the text around the new outline. + #[test] + fn text_is_composed_again_around_a_relinked_images_outline() { + let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(!overset(&s, story), "the left half is visible: the caption on the right is set"); + let Some(designcraft_doc::Content::Graphic(g)) = + s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone()) + else { + panic!("a graphic") + }; + let right = Arc::new(png(|x, _| x >= 32)); + s.edit(|d, _| { + let mut a = (**d.assets.get(&g.asset).unwrap()).clone(); + a.data = right.clone(); + d.assets.insert(g.asset, Arc::new(a)); + Ok(()) + }) + .unwrap(); + assert!(overset(&s, story), "the right half is visible now: it covers the caption"); + } + /// An image anchored in text keeps its outline: anchored objects wrap the lines after their /// anchor, and they are kept in the story, not on the spread. #[test] diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 8e17cd2a9..0b3c030cf 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Detect Edges, Alpha Channel and Photoshop Path contours follow the frame's path (composition doesn't read the image) | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels; Detect Edges and Photoshop Path contours follow the frame's path | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From 6b9c47fdb2a514a1a00829e17f24e8699cf7d6ae Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:37:36 +0000 Subject: [PATCH 151/328] Apply review fixes - crates/ui-egui/src/app/clipboard.rs - docs/egui-037-migration-plan.md --- crates/ui-egui/src/app/clipboard.rs | 2 +- docs/egui-037-migration-plan.md | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index bff5156f7..a50aff456 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -59,7 +59,7 @@ impl DesignApp { if !typing && !ours && !copied_here - && text.is_none_or(is_bare_address) + && text.is_none_or(|t| t.trim().is_empty() || is_bare_address(t)) && let Some(image) = self.services.clipboard_image.as_mut().and_then(|f| f()) { return Pasted::Image(image); diff --git a/docs/egui-037-migration-plan.md b/docs/egui-037-migration-plan.md index 165db7892..dc77c55e7 100644 --- a/docs/egui-037-migration-plan.md +++ b/docs/egui-037-migration-plan.md @@ -494,9 +494,8 @@ Clipboard: freshness, owner/seat changes, empty/absent offers, self-paste, canceled/slow transfers, password exclusion and no unchanged-selection reclaim on wlroots/KWin/Mutter. Native capability evidence is still required; compile-only is not acceptance. -- `Event::PasteImage` is new but DesignCraft has no image-paste contract. Leave it - unhandled rather than inventing a placement path. Add a test that it does not panic and - does not leak into text paste. +- `Event::PasteImage` (an image on the clipboard with no text) pastes through `edit.pasteImage`: in the + selected empty frame, else centered in the view, and never into text being edited. Keyboard layouts: after the fork pin, `RawInput::keyboard_layout_is_latin` and `RawInput::latin_layout_chars` (E19) must preserve tool and command shortcuts on Russian, From 2852a80c3e42f994b74bfe28db3a20644f9a148d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:42:18 -0800 Subject: [PATCH 152/328] Object styles: paragraph styles follow paragraph by paragraph; rename reaches every placement - Editing a style's paragraph style restyles each paragraph still in the old style; a paragraph given another style keeps it. - Renaming a style updates objects anchored in table cells and notes. - corners refuses keys other than shape, size and corners. --- crates/doc/src/styles.rs | 16 ++++++++++++++++ crates/engine/src/cmd/style/object.rs | 19 ++++++++++++++----- crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs index 98923762c..3a5ea58c3 100644 --- a/crates/doc/src/styles.rs +++ b/crates/doc/src/styles.rs @@ -115,6 +115,22 @@ impl ObjectStyle { self.paragraph_styles(styles, st.paras.len()).is_none_or(|want| st.paras.iter().zip(&want).all(|(f, w)| f.style == *w)) } + /// After an edit from `old`: the paragraphs of `st` still in the paragraph style `old` gives + /// them (every paragraph, when `old` set none) with the one this style gives each, where that + /// differs. A paragraph in another style is left out. + pub fn restyle_from(&self, old: &ObjectStyle, styles: &Styles, st: &Story) -> Vec<(usize, String)> { + let n = st.paras.len(); + let Some(want) = self.paragraph_styles(styles, n) else { return Vec::new() }; + let was = old.paragraph_styles(styles, n); + st.paras + .iter() + .zip(want) + .enumerate() + .filter(|(i, (f, w))| was.as_ref().is_none_or(|was| f.style == was[*i]) && f.style != *w) + .map(|(i, (_, w))| (i, w)) + .collect() + } + /// Put a story's paragraphs in the paragraph styles this style gives them; `false` when it /// sets none or they already are. pub fn restyle(&self, styles: &Styles, st: &mut Story) -> bool { diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 8a156d654..69368f82c 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -309,6 +309,9 @@ fn corners_param( return Ok(Some(None)); } let o = v.as_object().ok_or_else(|| bad(cmd, "`corners` must be an object or null"))?; + if let Some(k) = o.keys().find(|k| !["shape", "size", "corners"].contains(&k.as_str())) { + return Err(bad(cmd, format!("corners.{k} is not a corner setting (shape, size, corners)"))); + } let mut c = if o.contains_key("corners") { serde_json::from_value::(v.clone()).map_err(|e| bad(cmd, format!("corners: {e}")))? } else { @@ -395,7 +398,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { *n = r.clone(); } } - d.update_items(|it| it.object_style == name, |it| it.object_style = r.clone()); + d.update_placed_items(|it| it.object_style == name, |it| it.object_style = r.clone()); } // An item follows each attribute the style sets while it has the style's value. When the // style didn't set it before, items with the default follow (the default styles are on @@ -454,8 +457,8 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { } }, ); - // The text of the frames using the style takes a new paragraph style (or chain) while it - // is in the old one's; when the style set none before, all of it does. + // Each paragraph of the frames using the style takes the new paragraph style (or chain) + // while it is in the old one's; when the style set none before, every paragraph does. let mut restyled = 0; if new.paragraph_style.is_some() && (new.paragraph_style != old.paragraph_style || new.apply_next_style != old.apply_next_style) { // Frames on spreads and parents, in groups, and anchored in stories, table cells and @@ -466,10 +469,16 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { stories.dedup(); let styles = d.styles.clone(); for sid in stories { - if d.story(sid).is_some_and(|st| old.story_follows(&styles, st)) + let changes = d.story(sid).map(|st| new.restyle_from(&old, &styles, st)).unwrap_or_default(); + if !changes.is_empty() && let Some(st) = d.story_mut(sid) - && new.restyle(&styles, st) { + for (i, w) in changes { + if let Some(f) = st.paras.get_mut(i) { + f.style = w; + } + } + st.rev = st.rev.wrapping_add(1); restyled += 1; } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5824be21c..37e8939ae 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -799,6 +799,7 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { json!({"stroke": {"swatch": "Nope"}}), json!({"stroke": {"wieght": 5}}), json!({"fill": {"tnt": 0.5}}), + json!({"corners": {"shpae": "rounded"}}), ] { let mut p = bad.clone(); p["name"] = json!("Framed"); @@ -1002,6 +1003,27 @@ fn a_stroke_added_to_an_object_style_reaches_default_strokes() { assert_eq!(weight(&s, stroked_text), 1.0, "a text frame's own 1 pt stroke stays"); } +/// A paragraph-style edit of an object style reaches each paragraph still in the old style, and a +/// paragraph given another style keeps it. +#[test] +fn an_object_style_edit_restyles_paragraph_by_paragraph() { + use designcraft_doc::ItemId; + let mut s = session(); + for n in ["Body", "Lead", "Own"] { + s.execute("style.paragraph.create", &json!({"name": n})).unwrap(); + } + s.execute("style.object.create", &json!({"name": "Boxed", "fromSelection": false, "paragraphStyle": "Body"})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 336, 336], "content": "text", "text": "One\nTwo\nThree", "caret": false})).unwrap(); + let (id, story) = (r["id"].as_u64().unwrap(), r["story"].clone()); + s.execute("style.object.apply", &json!({"name": "Boxed", "ids": [id]})).unwrap(); + s.execute("text.select", &json!({"story": story, "anchor": 4, "focus": 7})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Own"})).unwrap(); + s.execute("style.object.edit", &json!({"name": "Boxed", "paragraphStyle": "Lead"})).unwrap(); + let d = &s.doc().unwrap().doc; + let sid = d.item(ItemId(id)).unwrap().text_frame().unwrap().story; + assert_eq!(d.story(sid).unwrap().paras.iter().map(|p| p.style.as_str()).collect::>(), ["Lead", "Own", "Lead"]); +} + /// A text frame anchored in a story (as IDML import places one) takes a new paragraph style of /// its object style like a frame on the page. #[test] From 113d2e960d04472e068cb16eb0fb12d843346ea9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:44:13 -0800 Subject: [PATCH 153/328] Type: Em Space and En Space go in at an insertion point only With text selected, Type > Insert White Space > Em Space and En Space are disabled, and their shortcuts leave the selection as it is instead of replacing it with the space. --- crates/ui-egui/src/menus/run.rs | 9 +++++++-- crates/ui-egui/src/menus/state.rs | 4 +++- crates/ui-egui/src/menus/tests.rs | 6 ++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index e661b2e11..b6310b88e 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -844,8 +844,13 @@ fn run_ui_part4(app: &mut DesignApp, id: &str, p: &Value) -> Option app.run("text.insert", json!({"text": "\u{e000}", "raw": true})), - "app.insertEmSpace" => app.run("text.insert", json!({"text": "\u{2003}", "raw": true})), - "app.insertEnSpace" => app.run("text.insert", json!({"text": "\u{2002}", "raw": true})), + "app.insertEmSpace" | "app.insertEnSpace" => { + if !menu_enabled(app, id) { + return Some(Err("place the insertion point in text to insert a space".into())); + } + let space = if id == "app.insertEmSpace" { "\u{2003}" } else { "\u{2002}" }; + app.run("text.insert", json!({"text": space, "raw": true})) + } // `panel_docking::command` takes the dock panels (and the Window › Styles group) first. "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties"); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 3cbec35b8..8d41a4a43 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -175,8 +175,10 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool { if id.starts_with("fit.") { return enabled(app, "object.fit"); } + // Em Space and En Space go in at an insertion point only; they do not replace selected text. if matches!(id, "app.insertEmSpace" | "app.insertEnSpace") { - return enabled(app, "text.insert"); + let caret = app.session.active().and_then(|d| d.selection.text).is_some_and(|t| t.is_caret()); + return caret && enabled(app, "text.insert"); } if id == "guide.selectAll" && (!app.ui.guides || app.ui.guides_locked) { return false; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 24ccb02a0..876b5e74d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -2512,6 +2512,12 @@ fn type_shortcuts_insert_spaces_justify_all_lines_and_open_paragraph_rules() { assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); assert_eq!(story_text(&app, &story), "ab"); + // Selected text: the spaces go in at an insertion point only, so the selection stays. + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 2})).unwrap(); + assert!(!menu_enabled(&app, "app.insertEmSpace") && !menu_enabled(&app, "app.insertEnSpace")); + press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); + press(&mut app, &ctx, Key::N, Modifiers::COMMAND | Modifiers::SHIFT); + assert_eq!(story_text(&app, &story), "ab", "a selection is not replaced by a space"); app.run("text.select", json!({"story": story, "anchor": 1, "focus": 1})).unwrap(); assert!(menu_enabled(&app, "app.insertEmSpace") && menu_enabled(&app, "app.insertEnSpace")); press(&mut app, &ctx, Key::M, Modifiers::COMMAND | Modifiers::SHIFT); From 30c72a032eb78658c6db7582047ec883e35d0186 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:44:46 -0800 Subject: [PATCH 154/328] Compose: vertical justification keeps text out of a wrap under it Center, Bottom and Justify moved the lines down without looking at text wraps, so a number aligned to the bottom of its frame was drawn over a bar whose wrap should have kept it above the bar. The lines now move down only as far as the wraps under them allow. A baseline comes down to the top of a wrap under its slot, and a table fragment stops with its bottom there. Contour wraps are checked along the band each line sweeps through, beside the line as well as under it. Only wraps that reach into a line's column count, as when the lines are set. Center and Bottom move the lines together by the least room; Justify keeps the first row in place and limits each later row by the wrap under it. An anchored object that moves with its line is skipped under Center and Bottom. --- crates/compose/src/lib.rs | 192 ++++++++++++++++++++++- crates/compose/src/tests.rs | 297 +++++++++++++++++++++++++++++++++++- 2 files changed, 480 insertions(+), 9 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..9eaafdc5d 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3159,7 +3159,9 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - vertical_justify(ft, f, spanned, &doc.footnote_options); + let anchors: Vec = + if ft.objects.is_empty() { Vec::new() } else { story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect() }; + vertical_justify(ft, f, spanned, &doc.footnote_options, &anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -5483,8 +5485,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin out } -/// `spanned`: a paragraph spans the frame's columns, so the lines move together. -fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions) { +/// `spanned`: a paragraph spans the frame's columns, so the lines move together. `anchors`: the +/// story byte of each anchored object's mark, by object index. +fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &designcraft_doc::FootnoteOptions, anchors: &[usize]) { if ft.lines.is_empty() || f.opts.vertical_justification == VerticalJustification::Top { return; } @@ -5494,6 +5497,18 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { + let rooms = wrap_rooms(ft, f, c, spanned, anchors); + // Center and Bottom move the lines together: the nearest text wrap under them is the + // bottom of the room they move down into. Justify checks each row's room below. + let raised; + let together = f.opts.vertical_justification != VerticalJustification::Justify; + let f = match together.then(|| wrap_bottom(ft, f, c, spanned, &rooms)).flatten() { + Some(y1) => { + raised = FrameSpec { area: Rect { y1, ..f.area }, ..f.clone() }; + &raised + } + None => f, + }; let idx: Vec = ft.lines.iter().enumerate().filter(|(_, l)| spanned || l.column == c).map(|(i, _)| i).collect(); let (Some(&a), Some(_)) = (idx.first(), idx.last()) else { continue }; let bottom = idx.iter().map(|&i| ft.lines[i].baseline + ft.lines[i].descent).fold(f64::NEG_INFINITY, f64::max); @@ -5538,11 +5553,31 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de } let gaps = starts.iter().filter(|s| **s).count(); let limit = f.opts.vj_paragraph_spacing_limit.max(0.0); - let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; - let per = (space - para * gaps as f64) / n as f64; - let mut shift = vec![0.0; n + 1]; - for k in 1..=n { - shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; + let shifts = |space: f64| { + let para = if gaps > 0 && limit > 0.0 { (space / gaps as f64).min(limit) } else { 0.0 }; + let per = (space - para * gaps as f64) / n as f64; + let mut shift = vec![0.0; n + 1]; + for k in 1..=n { + shift[k] = shift[k - 1] + per + if starts[k] { para } else { 0.0 }; + } + shift + }; + // Each row moves no further than a text wrap under it allows; every row's + // shift grows with the space, so the most space that keeps them all clear is + // found by bisection. + let clear = |shift: &[f64]| idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9); + let mut shift = shifts(space); + if !clear(&shift) { + let (mut lo, mut hi) = (0.0, space); + for _ in 0..64 { + let mid = (lo + hi) / 2.0; + if clear(&shifts(mid)) { + lo = mid; + } else { + hi = mid; + } + } + shift = shifts(lo); } for (&i, &k) in idx.iter().zip(&rows) { ft.lines[i].baseline += shift[k]; @@ -5564,6 +5599,147 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de } } +/// The bottom of the room Center and Bottom move the lines of column `c` (every column when +/// `spanned`) down into, when a text wrap under them sits above the text area's bottom (None +/// otherwise): the bottom the lines are aligned by (the lowest descent or table bottom) plus the +/// least of `rooms` (from [`wrap_rooms`]), so the text moves down by that room and no further. +fn wrap_bottom(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, rooms: &[f64]) -> Option { + let in_col = |k: u32| spanned || k == c; + let lines = ft.lines.iter().zip(rooms).filter(|(l, _)| in_col(l.column)); + let room = lines.clone().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); + let bottom = lines + .map(|(l, _)| l.baseline + l.descent) + .chain(ft.tables.iter().filter(|t| in_col(t.column)).map(|t| t.rect.y1)) + .fold(f64::NEG_INFINITY, f64::max); + if !room.is_finite() || !bottom.is_finite() { + return None; + } + let y1 = bottom + room.max(0.0); + (y1 < f.area.y1).then_some(y1) +} + +/// How far each line of column `c` (every column when `spanned`) may move down before a text +/// wrap stops it, by index in `ft.lines` (infinite without one); a table fragment's room counts +/// for its line. No line moves into a wrap under its slot. As when lines are set around a wrap, a +/// line's band runs from its top to its baseline, so a baseline may come down to a wrap's top; a +/// table fragment stops with its bottom there. A wrap without a contour counts by its bounding +/// box. Beside or under a contour, the line moves down only as far as its band stays clear of the +/// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the +/// columns it spans) count, as when the lines are set. An anchored object that moves with the +/// lines being justified (inline, above the line, or positioned from its anchor and not kept +/// within its column) is skipped, except under Justify. Justify keeps the first row in place, so +/// its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by +/// object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> Vec { + const EPS: f64 = 1e-6; + // One-sided wraps also block the column on the other side of the object: the x-range wrap + // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that + // range misses the column). + let sided = |e: &Exclusion, col: Rect, (a, b): (f64, f64)| -> Option<(f64, f64)> { + let r = e.rect; + (a < col.x1 && b > col.x0).then_some(match e.side { + WrapSide::LeftSide => (a, f64::INFINITY), + WrapSide::RightSide => (f64::NEG_INFINITY, b), + WrapSide::LargestArea if r.x0 - col.x0 >= col.x1 - r.x1 => (a, f64::INFINITY), + WrapSide::LargestArea => (f64::NEG_INFINITY, b), + WrapSide::BothSides | WrapSide::TowardsSpine | WrapSide::AwayFromSpine => (a, b), + }) + }; + // The x-range a wrap under the text keeps it out of in column `col`; None when text may stay beside it. + let blocked = |e: &Exclusion, col: Rect| -> Option<(f64, f64)> { + let r = e.rect; + match e.mode { + WrapMode::None => None, + WrapMode::JumpObject | WrapMode::JumpToNextColumn => (r.x0 < col.x1 && r.x1 > col.x0).then_some((f64::NEG_INFINITY, f64::INFINITY)), + WrapMode::BoundingBox | WrapMode::Contour => sided(e, col, (r.x0, r.x1)), + } + }; + let in_col = |k: u32| spanned || k == c; + // An own-story anchored object whose anchor is on one of these lines and whose position + // follows its line moves with the text. Justify moves later lines further than earlier ones, + // so there the object's current top still limits the lines after its anchor. + let moves_with_text = |e: &Exclusion| { + let Some(a) = e.after.filter(|_| f.opts.vertical_justification != VerticalJustification::Justify) else { return false }; + // The object whose mark is the anchor, placed on one of these lines. + let Some(o) = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) else { + return false; + }; + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, + // Kept within the column, it can stop at the column's edge instead of following. + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { + *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column + } + } + }; + // Justify keeps the first row (its segments and a table on them) in place, so wraps under it + // set no limit. + let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); + let fixed = |line: usize| { + f.opts.vertical_justification == VerticalJustification::Justify + && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9) + }; + // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its + // top to its baseline) and table fragment. + let lines = ft + .lines + .iter() + .enumerate() + .filter(|(_, l)| in_col(l.column)) + .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); + let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); + let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { + let Some(&before) = rooms.get(line) else { continue }; + if fixed(line) { + continue; + } + let mut room = before; + // A line that spans columns reaches past its own column. + let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); + let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; + let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; + for e in f.exclusions.iter().filter(|e| e.wraps_line(start) && !moves_with_text(e)) { + let r = e.rect; + if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) + && r.y1 > top + && sided(e, col, (r.x0, r.x1)).is_some_and(meets) + { + // A contour beside or under this line whose box reaches the line's slot (the + // contour stays inside its box). Moved down by `d`, the line's band sweeps from its + // top to its baseline plus `d`; the contour's extent there only grows with `d`, so + // the furthest clear move is found by bisection to 0.01 pt. + let hits = |d: f64| contour.band_extent(top, bottom + d).and_then(|x| sided(e, col, x)).is_some_and(meets); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(room)); + if lo < hi && hits(hi) { + if hits(lo) { + hi = lo; + } + for _ in 0..64 { + if hi - lo <= 0.01 { + break; + } + let mid = (lo + hi) / 2.0; + if hits(mid) { + hi = mid; + } else { + lo = mid; + } + } + room = room.min(lo); + } + } else if r.y0 >= bottom - EPS { + // A wrap at or under this line. + if blocked(e, col).is_some_and(meets) { + room = room.min(r.y0 - bottom); + } + } + } + rooms[line] = room; + } + rooms +} + // ---------- caret and hit testing (Type tool) ---------- /// Two stacked glyphs this far apart in `y` sit on different rows (warichu). diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index f15f1e33d..4354aeb47 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -573,6 +573,301 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// A 60 × 200 pt frame at the origin holding `text` with vertical justification `vj`, and a bar +/// at `bar` whose text wrap `wrap` keeps 1 mm above it: (baseline, descent) of each line, the +/// text area and the wrap's top (None when the bar doesn't wrap the frame). +fn bar_chart_lines( + text: &str, + vj: designcraft_doc::VerticalJustification, + wrap: WrapMode, + side: WrapSide, + bar: Rect, +) -> (Vec<(f64, f64)>, Rect, Option) { + let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = wrap; + it.wrap.side = side; + it.wrap.offsets = [72.0 / 25.4, 0.0, 0.0, 0.0]; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let spec = frame_specs(&d, sid).remove(0); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let lines = all_lines(&cs).iter().map(|l| (l.baseline, l.descent)).collect(); + (lines, spec.area, spec.exclusions.first().map(|e| e.rect.y0)) +} + +/// Bottom, Center and Justify keep the lines out of a text wrap under them: a number aligned to +/// the bottom of its frame sits on the wrap's top offset over a bar instead of on the bar (#1831), +/// with every wrap mode that stops text there. +#[test] +fn vertical_justification_stops_at_a_wrap_under_the_text() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify, Top}; + let bar = Rect::new(0.0, 150.0, 60.0, 300.0); + for wrap in [WrapMode::BoundingBox, WrapMode::Contour, WrapMode::JumpObject, WrapMode::JumpToNextColumn] { + let run = |vj, text| bar_chart_lines(text, vj, wrap, WrapSide::BothSides, bar); + let (top, _, wrap_top) = run(Top, "42"); + let wrap_top = wrap_top.unwrap(); + assert!((wrap_top - (150.0 - 72.0 / 25.4)).abs() < 1e-6, "{wrap:?}: the wrap's top is 1 mm above the bar: {wrap_top}"); + + let (bottom, _, _) = run(Bottom, "42"); + let b = bottom[0].0; + assert!((b - wrap_top).abs() < 1e-6, "{wrap:?}: Bottom put the baseline at {b}, not on the wrap's top at {wrap_top}"); + assert!(b > top[0].0 + 50.0, "{wrap:?}: Bottom moved the line down: {b}, {}", top[0].0); + + // Center takes half the room Bottom takes. + let (center, _, _) = run(Center, "42"); + assert!((center[0].0 - top[0].0 - (b - top[0].0) / 2.0).abs() < 1e-6, "{wrap:?}: Center at {}, Bottom at {b}", center[0].0); + + // Justify keeps the first baseline and puts the last where Bottom puts it. + let (top2, _, _) = run(Top, "12\n34"); + let (bottom2, _, _) = run(Bottom, "12\n34"); + let (justify, _, _) = run(Justify, "12\n34"); + assert_eq!(justify.len(), 2); + assert!((justify[0].0 - top2[0].0).abs() < 1e-6, "{wrap:?}: Justify moved the first line: {justify:?}"); + assert!((justify[1].0 - bottom2[1].0).abs() < 1e-6, "{wrap:?}: Justify {justify:?}, Bottom {bottom2:?}"); + assert!(justify[1].0 <= wrap_top + 1e-6); + } +} + +/// Without a wrap, or beside one, Bottom still moves the text down to the text area's bottom. +#[test] +fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { + use designcraft_doc::VerticalJustification::Bottom; + // Wrap off: the number goes down over the bar. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); + assert!(wrap_top.is_none()); + assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + // A bar on the right half from the frame's top: the number is set beside it and goes down + // beside it. + let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); + assert!(wrap_top.is_some()); + assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); +} + +/// A one-sided wrap in the second column leaves the first column's lines free to go down, as it +/// leaves them when they are set. +#[test] +fn vertical_justification_passes_a_one_sided_wrap_in_another_column() { + let (mut d, sid, fid) = doc_with("One", Rect::new(0.0, 0.0, 400.0, 200.0), ParaAttrs::default()); + let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options; + o.columns = 2; + o.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(250.0, 100.0, 350.0, 300.0)), + ); + it.wrap.mode = WrapMode::BoundingBox; + it.wrap.side = WrapSide::RightSide; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + assert_eq!(l.column, 0); + assert!((l.baseline + l.descent - 200.0).abs() < 1e-6, "baseline {}, descent {}", l.baseline, l.descent); +} + +/// Beside a contour that widens further down, Bottom moves a line only as far as its band stays +/// clear of the contour. +#[test] +fn vertical_justification_stops_where_a_contour_beside_the_text_widens() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Right edge fixed at 60, left edge x = 55 − 50y/190 from y = 0 down to y = 190. + let edge = |y: f64| 55.0 - 50.0 * y / 190.0; + let pts = [Point::new(55.0, 0.0), Point::new(60.0, 0.0), Point::new(60.0, 190.0), Point::new(5.0, 190.0)]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x1) + }; + let (top, x1) = run(Top); + assert!(x1 <= edge(top) + 1e-6, "Top sets the line clear of the contour: x1 {x1}, edge {}", edge(top)); + let (bottom, x1) = run(Bottom); + assert!(bottom >= top - 1e-6 && bottom < 190.0, "Bottom at {bottom}, Top at {top}"); + assert!(x1 <= edge(bottom) + 1e-6, "Bottom moved the line into the contour: baseline {bottom}, x1 {x1}, edge {}", edge(bottom)); +} + +/// Under a contour whose box starts beside the column and which widens into it further down, +/// Bottom moves a line down to where the contour meets its slot, not to the top of the box. +#[test] +fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { + // Left edge x = 70 − 40(y − 100)/90 from y = 100 down to y = 190: it crosses the column's + // right edge (60) at y = 122.5. + let pts = [Point::new(70.0, 100.0), Point::new(80.0, 100.0), Point::new(80.0, 190.0), Point::new(30.0, 190.0)]; + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let b = all_lines(&cs)[0].baseline; + assert!(b <= 122.5 + 1e-6, "Bottom moved the baseline to {b}, past where the contour meets the column at 122.5"); + assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); +} + +/// An object anchored in the text and positioned from its anchor moves down with the lines, so +/// Center places lines above it as it places them without its wrap. +#[test] +fn vertical_justification_passes_an_anchored_object_that_moves_with_the_text() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // Hung 40 pt under the first line's baseline, under the second line. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert_eq!(plain.len(), 2); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// Justify keeps the first line in place, so a wrap between it and the next line does not stop +/// the later lines from spreading down to the text area's bottom. +#[test] +fn vertical_justify_passes_a_wrap_under_the_first_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + let lid = d.default_layer(); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 20.0, 300.0, 40.0)), + ); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + assert!( + lines[0].baseline < 20.0 && lines[1].baseline - lines[1].ascent >= 40.0 - 1e-6, + "{:?}", + lines.iter().map(|l| l.baseline).collect::>() + ); + let last = lines[2]; + assert!((last.baseline + last.descent - 400.0).abs() < 1e-6, "{:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + +/// Justify moves each row by its own share of the space, so a wrap between the second and third +/// rows limits the second row's move, not the third's. +#[test] +fn vertical_justify_limits_each_row_by_the_wrap_under_it() { + use designcraft_doc::VerticalJustification::{Justify, Top}; + let para = ParaAttrs { space_before: Some(40.0), ..Default::default() }; + let run = |vj, bar: Option| { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), para.clone()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + if let Some(bar) = bar { + let lid = d.default_layer(); + let mut it = + designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(bar)); + it.wrap.mode = WrapMode::JumpObject; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| (l.baseline, l.ascent, l.descent)).collect::>() + }; + let top = run(Top, None); + assert_eq!(top.len(), 3); + let b2 = top[1].0; + let (b3, a3, _) = top[2]; + // A bar 20 pt under the second baseline, clear of the third line. + let bar = Rect::new(0.0, b2 + 20.0, 300.0, b2 + 30.0); + assert!(b3 - a3 > bar.y1, "the third line starts under the bar: {top:?}"); + let set = run(Top, Some(bar)); + assert!(set.iter().zip(&top).all(|(a, b)| (a.0 - b.0).abs() < 1e-6), "the bar moves no line: {set:?}"); + let justify = run(Justify, Some(bar)); + assert!((justify[0].0 - top[0].0).abs() < 1e-6, "{justify:?}"); + // The second row's baseline comes down to the bar; the third row moves twice as far. + let moved = justify[1].0 - b2; + assert!((moved - 20.0).abs() < 1e-6, "the second row moved {moved}: {justify:?}"); + assert!((justify[2].0 - b3 - 2.0 * moved).abs() < 1e-6, "{justify:?}"); +} + +/// Each anchored object's own position decides whether its wrap moves with the text: a fixed +/// object without a wrap on the same line leaves the moving one skipped. +#[test] +fn vertical_justification_matches_each_wrap_to_its_anchored_object() { + let baselines = |wrap| { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Center; + // A fixed object from the frame's top, then one hung 40 pt under the first line. + anchor_box(&mut d, sid, 1, 150.0, 0.0, false, WrapMode::None); + anchor_box(&mut d, sid, 1 + OBJECT_LEN, 0.0, 40.0, true, wrap); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(cs.frames[0].objects.len(), 2); + all_lines(&cs).iter().map(|l| l.baseline).collect::>() + }; + let plain = baselines(WrapMode::None); + let wrapped = baselines(WrapMode::BoundingBox); + assert!(plain[0] > 150.0, "Center moved the lines down: {plain:?}"); + assert_eq!(plain.len(), wrapped.len()); + assert!(plain.iter().zip(&wrapped).all(|(a, b)| (a - b).abs() < 1e-6), "without the wrap {plain:?}, with it {wrapped:?}"); +} + +/// An object positioned from its anchor but kept within its column can stop at the column's +/// bottom, so Bottom does not move the lines after its anchor into it. +#[test] +fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Bottom; + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + assert!(bottom <= 400.0 + 1e-6, "the object stays in the column: {top}..{bottom}"); + let l = lines[1]; + assert!( + l.baseline <= top + 1e-6 || l.baseline - l.ascent >= bottom - 1e-6, + "the second line at {} meets the object at {top}..{bottom}", + l.baseline + ); +} + +/// Justify keeps the first line in place and moves later lines further, so an object anchored in +/// the first line and hung under the last one still stops the lines after its anchor. +#[test] +fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 1, 0.0, 50.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[0].baseline - 50.0).abs() < 1e-6, "the object hangs 50 pt under the first line: {top}, {}", lines[0].baseline); + let last = lines[2].baseline; + assert!(last <= top + 1e-6, "Justify moved the last line to {last}, into the object at {top}"); + assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] @@ -2291,7 +2586,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; From ae1de74270e747cddeb60c112487edf3a6c72265 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:45:24 -0800 Subject: [PATCH 155/328] Text wrap: an Alpha Channel contour counts only inside the graphic's clipping path Opaque pixels outside the placed graphic's clipping path (inverted or not) are not drawn, and they no longer push text aside. An outline that only touches a clip's edge blocks nothing. --- crates/compose/src/lib.rs | 237 +++++++++++++++++++++++++----------- crates/compose/src/tests.rs | 56 +++++++++ 2 files changed, 223 insertions(+), 70 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ac563b616..76df87568 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -382,9 +382,36 @@ pub struct Contour { /// The frame path of an outline taken from a placed graphic: the frame clips the graphic, so /// the outline counts only within it (empty: no clip). pub clip: Vec>, + /// The placed graphic's clipping path, for an outline traced from the graphic's pixels: the + /// outline counts only inside it too (empty: none). An inverted clipping path is filled + /// even-odd ([`designcraft_doc::Graphic::clip_region`]). + pub graphic_clip: Vec>, + pub graphic_clip_even_odd: bool, pub offset: f64, } +/// A filled shape: closed polylines and their fill rule (non-zero, or even-odd). +#[derive(Clone, Copy)] +struct Region<'a> { + rings: &'a [Vec], + even_odd: bool, +} + +impl Region<'_> { + fn nonzero(rings: &[Vec]) -> Region<'_> { + Region { rings, even_odd: false } + } + + /// Is a point with this winding number filled? + fn fills(self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } + + fn edges(self) -> usize { + self.rings.iter().map(Vec::len).sum() + } +} + /// Points a contour outline may have; a larger outline wraps around its bounding box. pub const MAX_CONTOUR_POINTS: usize = 8192; @@ -396,7 +423,13 @@ impl Contour { /// The outline of `path` (after `to_inner`), flattened; None if it is empty or too detailed. fn of(path: &designcraft_geom::BezPath, to_inner: designcraft_geom::Affine, offset: f64) -> Option { let rings = flatten_rings(path, to_inner)?; - offset.is_finite().then_some(Contour { rings, clip: Vec::new(), offset: offset.max(0.0) }) + offset.is_finite().then_some(Contour { + rings, + clip: Vec::new(), + graphic_clip: Vec::new(), + graphic_clip_even_odd: false, + offset: offset.max(0.0), + }) } /// This outline counted only within `frame` (after `to_inner`); unclipped if the frame is @@ -408,18 +441,41 @@ impl Contour { } } + /// This outline counted only inside the graphic's clipping region `clip` (after `to_inner`), + /// filled even-odd when `even_odd` is set; unchanged if the region is empty or too detailed. + fn within_graphic_clip(self, clip: &designcraft_geom::BezPath, even_odd: bool, to_inner: designcraft_geom::Affine) -> Contour { + match flatten_rings(clip, to_inner) { + Some(graphic_clip) => Contour { graphic_clip, graphic_clip_even_odd: even_odd, ..self }, + None => self, + } + } + /// The outline mapped by `a`. fn transformed(self, a: designcraft_geom::Affine) -> Contour { let map = |rings: Vec>| rings.into_iter().map(|r| r.into_iter().map(|p| a * p).collect()).collect(); - Contour { rings: map(self.rings), clip: map(self.clip), offset: self.offset } + Contour { + rings: map(self.rings), + clip: map(self.clip), + graphic_clip: map(self.graphic_clip), + graphic_clip_even_odd: self.graphic_clip_even_odd, + offset: self.offset, + } + } + + /// The clips the outline counts within. + fn clips(&self) -> impl Iterator> { + let frame = (!self.clip.is_empty()).then(|| Region::nonzero(&self.clip)); + let graphic = (!self.graphic_clip.is_empty()).then_some(Region { rings: &self.graphic_clip, even_odd: self.graphic_clip_even_odd }); + frame.into_iter().chain(graphic) } fn bounds(&self) -> Rect { - let Some(r) = rings_bounds(&self.rings) else { return Rect::ZERO }; - let r = match rings_bounds(&self.clip) { - Some(c) => r.intersect(c), - None => r, - }; + let Some(mut r) = rings_bounds(&self.rings) else { return Rect::ZERO }; + for c in self.clips() { + if let Some(b) = rings_bounds(c.rings) { + r = r.intersect(b); + } + } r.inflate(self.offset, self.offset) } @@ -429,8 +485,8 @@ impl Contour { fn band_extent(&self, y0: f64, y1: f64) -> Option<(f64, f64)> { let (y0, y1) = (y0 - self.offset, y1 + self.offset); let (mut lo, mut hi) = rings_band_extent(&self.rings, y0, y1)?; - if !self.clip.is_empty() { - let (a, b) = rings_band_extent(&self.clip, y0, y1)?; + for c in self.clips() { + let (a, b) = rings_band_extent(c.rings, y0, y1)?; (lo, hi) = (lo.max(a), hi.min(b)); } (lo <= hi).then_some((lo - self.offset, hi + self.offset)) @@ -444,19 +500,21 @@ impl Contour { if !low.is_finite() || !high.is_finite() || high < low { return self.band_extent(y0, y1).into_iter().collect(); } - let mut spans = rings_band_spans(&self.rings, low, high); + let mut spans = rings_band_spans(Region::nonzero(&self.rings), low, high); // Extremely fragmented imported paths use the conservative outer extent, bounding the // work of subtracting intervals from every line. A traced 128-column mask stays below it. if spans.len() > 128 { return self.band_extent(y0, y1).into_iter().collect(); } - if !self.clip.is_empty() { - let clip = rings_band_spans(&self.clip, low, high); - // A fragmented frame, or shapes too detailed to compare within each line's budget, - // take the common part of the two projections, which can block more than the frame - // shows. - let exact = if clip.len() > 128 { None } else { clipped_band_spans(&self.rings, &self.clip, low, high) }; - spans = exact.unwrap_or_else(|| intersect_spans(&spans, &clip)); + let clips: Vec = self.clips().collect(); + if !clips.is_empty() { + let projected: Vec> = clips.iter().map(|c| rings_band_spans(*c, low, high)).collect(); + // A fragmented clip, or shapes too detailed to compare within each line's budget, + // take the common part of the projections, which can block more than the clips show. + let mut shapes = vec![Region::nonzero(&self.rings)]; + shapes.extend(&clips); + let exact = if projected.iter().any(|p| p.len() > 128) { None } else { clipped_band_spans(&shapes, low, high) }; + spans = exact.unwrap_or_else(|| projected.iter().fold(spans, |s, p| intersect_spans(&s, p))); } merge_spans(spans.into_iter().map(|(a, b)| (a - self.offset, b + self.offset)).collect()) } @@ -481,19 +539,22 @@ fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { out } -/// Occupied intervals across the band `y0..y1` of the part of `rings` inside `clip` (both filled -/// by the non-zero rule). A vertical line through a point of that part either crosses the middle -/// of the band inside both shapes, or stops inside the band on an edge of one shape that lies -/// inside the other. The spans are the middle slice of both shapes and the parts of each -/// shape's edges in the band that lie inside the other, so a part of the outline outside the -/// clip blocks nothing, even where it shares x positions with the clip in the same band. -/// None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. -fn clipped_band_spans(rings: &[Vec], clip: &[Vec], y0: f64, y1: f64) -> Option> { +/// Occupied intervals across the band `y0..y1` of the part of the plane inside every one of +/// `shapes` (an outline and its clips). A vertical line through a point of that part either +/// crosses the middle of the band inside all the shapes, or stops inside the band on an edge of +/// one shape that lies inside the others. The spans are the middle slice of all the shapes and +/// the parts of each shape's edges in the band that lie inside the others, so a part of the +/// outline outside a clip blocks nothing, even where it shares x positions with the clip in the +/// same band. None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { let middle = y0 * 0.5 + y1 * 0.5; - let mut spans = intersect_spans(&merge_spans(middle_spans(rings, middle)), &merge_spans(middle_spans(clip, middle))); + let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); + let first = slices.next()?; + let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); let mut budget = MAX_CLIPPED_WORK; - edges_inside(rings, clip, y0, y1, &mut budget, &mut spans)?; - edges_inside(clip, rings, y0, y1, &mut budget, &mut spans)?; + for k in 0..shapes.len() { + edges_inside(shapes, k, y0, y1, &mut budget, &mut spans)?; + } Some(merge_spans(spans)) } @@ -503,10 +564,12 @@ fn spend(budget: &mut usize, n: usize) -> Option<()> { Some(()) } -/// Pushes to `out` the x-ranges of the parts of `rings`' edges within the band `y0..y1` that lie -/// inside `other` or on its boundary. None when `budget` runs out. -fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { - let n = other.iter().map(Vec::len).sum::().max(1); +/// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` +/// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when +/// `budget` runs out. +fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges()).sum::().max(1); + let rings = shapes.get(k)?.rings; for ring in rings { let Some(&last) = ring.last() else { continue }; let mut a = last; @@ -520,7 +583,7 @@ fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, bu (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) }; let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); - segment_inside(p, q, other, n, budget, out)?; + segment_inside(p, q, shapes, k, n, budget, out)?; } a = b; } @@ -528,26 +591,41 @@ fn edges_inside(rings: &[Vec], other: &[Vec], y0: f64, y1: f64, bu Some(()) } -/// Pushes to `out` the x-ranges of the parts of segment `p`–`q` inside `rings` (`n` edges) or on -/// their boundary: the segment is split where it meets their edges, and each piece is tested at -/// its middle. Each pass over the edges takes `n` from `budget`; None when it runs out. -fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { +/// Pushes to `out` the x-ranges of the parts of segment `p`–`q`, an edge of `shapes[k]`, that +/// bound the part of the plane inside all of `shapes` (`n` edges in all). The segment is split +/// where it meets the other shapes' edges, and each piece is tested at its middle: it counts when +/// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area +/// on either side (an open path), it counts when it is inside the other shapes or on their +/// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. +fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { let r = q - p; let len2 = r.hypot2(); if !len2.is_finite() { return Some(()); } let at = |t: f64| p + r * t; + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(*s, pt)); spend(budget, n)?; if len2 < 1e-24 { - if inside_or_on(rings, p) { + if in_others(p) { out.push((p.x, p.x)); } return Some(()); } + // A step to either side of the segment, well above rounding at page coordinates. + let side = r.turn_90() * (1e-6 / len2.sqrt()); + let bounds_the_part = |m: Point| { + let own = shapes.get(k).copied(); + let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); + let (a, b) = (m + side, m - side); + match (in_own(a), in_own(b)) { + (false, false) => in_others(m), + (ia, ib) => (ia && in_others(a)) || (ib && in_others(b)), + } + }; let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); let mut ts = vec![0.0, 1.0]; - for ring in rings { + for ring in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| s.rings) { let Some(&last) = ring.last() else { continue }; let mut c = last; for &d in ring { @@ -576,8 +654,8 @@ fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &m ts.dedup_by(|a, b| (*a - *b).abs() < 1e-12); for w in ts.windows(2) { let (u, v) = (w[0], w[1]); - spend(budget, n)?; - if inside_or_on(rings, at(u * 0.5 + v * 0.5)) { + spend(budget, 3 * n)?; + if bounds_the_part(at(u * 0.5 + v * 0.5)) { let (x0, x1) = (at(u).x, at(v).x); out.push((x0.min(x1), x0.max(x1))); } @@ -585,10 +663,10 @@ fn segment_inside(p: Point, q: Point, rings: &[Vec], n: usize, budget: &m Some(()) } -/// Is `pt` inside `rings` (non-zero rule) or within a hair of one of their edges? -fn inside_or_on(rings: &[Vec], pt: Point) -> bool { +/// Is `pt` inside `shape` or within a hair of one of its edges? +fn inside_or_on(shape: Region, pt: Point) -> bool { let mut winding = 0i32; - for ring in rings { + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -607,7 +685,7 @@ fn inside_or_on(rings: &[Vec], pt: Point) -> bool { a = b; } } - winding != 0 + shape.fills(winding) } /// Sorted, overlapping spans joined. Zero-width spans (a vertical edge of an open path) are kept: @@ -626,9 +704,9 @@ fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> { out } -fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { - let mut spans = middle_spans(rings, y0 * 0.5 + y1 * 0.5); - for ring in rings { +fn rings_band_spans(shape: Region, y0: f64, y1: f64) -> Vec<(f64, f64)> { + let mut spans = middle_spans(shape, y0 * 0.5 + y1 * 0.5); + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -649,11 +727,11 @@ fn rings_band_spans(rings: &[Vec], y0: f64, y1: f64) -> Vec<(f64, f64)> { merge_spans(spans) } -/// The intervals of the line at height `middle` inside `rings` (non-zero rule), unsorted. -fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { +/// The intervals of the line at height `middle` inside `shape`, unsorted. +fn middle_spans(shape: Region, middle: f64) -> Vec<(f64, f64)> { let mut spans = Vec::new(); let mut crossings = Vec::new(); - for ring in rings { + for ring in shape.rings { let Some(&last) = ring.last() else { continue }; let mut a = last; for &b in ring { @@ -671,7 +749,7 @@ fn middle_spans(rings: &[Vec], middle: f64) -> Vec<(f64, f64)> { let mut winding = 0i32; let mut previous = None; for (x, delta) in crossings { - if winding != 0 + if shape.fills(winding) && let Some(start) = previous { spans.push((start, x)); @@ -782,7 +860,7 @@ fn nothing_visible_wraps_nothing(doc: &Document, it: &Item, wrap: &designcraft_d fn wrap_exclusion( wrap: &designcraft_doc::TextWrap, b: Rect, - outline: impl FnOnce() -> Option<(designcraft_geom::BezPath, Option)>, + outline: impl FnOnce() -> Option, xf: Affine, inv: Affine, left_page: bool, @@ -802,24 +880,42 @@ fn wrap_exclusion( let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; } - let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { - let c = Contour::of(&path, inv * xf, o[0])?; - Some(match frame { - Some(frame) => c.within(&frame, inv * xf), - None => c, - }) + let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|src| { + let mut c = Contour::of(&src.path, inv * xf, o[0])?; + if let Some(frame) = &src.frame { + c = c.within(frame, inv * xf); + } + if let Some((clip, even_odd)) = &src.graphic_clip { + c = c.within_graphic_clip(clip, *even_odd, inv * xf); + } + Some(c) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); Exclusion { rect, mode: wrap.mode, side, contour, after: None } } -/// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and -/// for an outline taken from the placed graphic, the frame path that clips it. Bounding Box -/// follows the part of the placed graphic the frame shows; Same As Clipping follows the graphic's -/// clipping path when it has one; Alpha Channel follows the image's traced outline when the -/// engine has traced one; detected edges and image paths follow the frame's path (as other -/// frames do). -fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> (designcraft_geom::BezPath, Option) { +/// The outline a contour wrap follows, in the frame's inner space, with what clips it. +struct Outline { + path: designcraft_geom::BezPath, + /// For an outline taken from the placed graphic: the frame path that clips it. + frame: Option, + /// For an outline traced from the graphic's pixels: the graphic's clipping region, and + /// whether it is filled even-odd. + graphic_clip: Option<(designcraft_geom::BezPath, bool)>, +} + +impl Outline { + fn clipped_by(path: designcraft_geom::BezPath, frame: designcraft_geom::BezPath) -> Outline { + Outline { path, frame: Some(frame), graphic_clip: None } + } +} + +/// The outline a contour wrap of `kind` around frame `it` follows. Bounding Box follows the part +/// of the placed graphic the frame shows; Same As Clipping follows the graphic's clipping path +/// when it has one; Alpha Channel follows the image's traced outline when the engine has traced +/// one, within the graphic's clipping path too; detected edges and image paths follow the frame's +/// path (as other frames do). +fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> Outline { let frame = designcraft_geom::corners::apply(&it.path, &it.corners); let kind = wrap.contour; if kind == designcraft_doc::ContourType::AlphaChannel @@ -833,19 +929,20 @@ fn contour_path(doc: &Document, it: &Item, wrap: &designcraft_doc::TextWrap) -> if wrap.inside_edges { path.extend(o.holes.to_bezpath().iter()); } - return (g.xf * to_graphic * path, Some(frame)); + // The clipping path hides the pixels outside it. + return Outline { graphic_clip: g.clip_region(), ..Outline::clipped_by(g.xf * to_graphic * path, frame) }; } if kind == designcraft_doc::ContourType::SameAsClipping && let Some((path, _)) = it.graphic().and_then(|g| g.clip_region()) { - return (path, Some(frame)); + return Outline::clipped_by(path, frame); } if kind == designcraft_doc::ContourType::BoundingBox && let Some(r) = it.graphic().and_then(|g| g.shown_bounds(it.inner_bounds())) { - return (designcraft_geom::kurbo::Shape::to_path(&r, 0.1), Some(frame)); + return Outline::clipped_by(designcraft_geom::kurbo::Shape::to_path(&r, 0.1), frame); } - (frame, None) + Outline { path: frame, frame: None, graphic_clip: None } } /// One frame of the thread, ready for composition. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ab108b03b..e8fb2aac8 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -573,6 +573,62 @@ fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() { assert!(!cs.is_overset()); } +/// An Alpha Channel contour counts only where the graphic's clipping path shows the image: here +/// the visible pixels are in the right half and the clipping path shows the left half, so the +/// image wraps nothing; inverted, the clipping path shows the right half and the image wraps. +#[test] +fn an_alpha_channel_contour_stops_at_the_clipping_path() { + use designcraft_geom::{PathData, Point, SubPath}; + let rect = |x0: f64, x1: f64| { + PathData::single(SubPath::polyline(&[Point::new(x0, 0.0), Point::new(x1, 0.0), Point::new(x1, 200.0), Point::new(x0, 200.0)], true)) + }; + let lines_beside = |invert: bool| { + let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default()); + let lid = d.default_layer(); + let asset = designcraft_doc::AssetId(d.alloc()); + let mut it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)), + ); + let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, rect(0.0, 75.0)); + clip.invert = invert; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset, + size: (150.0, 200.0), + xf: designcraft_geom::Affine::translate((150.0, 100.0)), + clip: Some(std::sync::Arc::new(clip)), + auto_fit: Default::default(), + fit_align: 0, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::LeftSide; + it.wrap.contour = designcraft_doc::ContourType::AlphaChannel; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d.alpha_outlines.push(std::sync::Arc::new(designcraft_doc::AlphaOutline { + asset, + threshold: designcraft_doc::DEFAULT_ALPHA_THRESHOLD, + width: 150, + height: 200, + outer: rect(75.0, 150.0), + holes: PathData::default(), + source: std::sync::Weak::new(), + serial: designcraft_doc::AlphaOutline::next_serial(), + })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).map(|l| l.x1).collect::>() + }; + let shown_left = lines_beside(false); + assert!(!shown_left.is_empty() && shown_left.iter().all(|x| *x > 260.0), "nothing visible wraps nothing: {shown_left:?}"); + let shown_right = lines_beside(true); + assert!(!shown_right.is_empty() && shown_right.iter().all(|x| *x <= 225.0 + 1e-6), "the right half wraps: {shown_right:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] From e2c6d7b36c55ce42a40533633f02fd9e3726d239 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:47:33 -0800 Subject: [PATCH 156/328] Object styles: a null fromSelection or applyNextStyle is refused --- crates/engine/src/cmd/style/object.rs | 2 +- crates/engine/src/tests.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index 69368f82c..b22388372 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -237,7 +237,7 @@ fn text_frame_param( /// A true/false parameter, when given. fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { match p.get(key) { - None | Some(Value::Null) => Ok(None), + None => Ok(None), Some(Value::Bool(b)) => Ok(Some(*b)), Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 37e8939ae..5a8fc30e6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -808,6 +808,8 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); } assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": null})).is_err()); + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "applyNextStyle": null})).is_err()); // A size outside 0–10000 pt is refused, not changed. for size in [-1.0, 10_001.0] { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); From bdabdc8155cfc69fe793240cfa83e2d418c70e53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:51:37 -0800 Subject: [PATCH 157/328] Preflight: show a pending first check as checking, and rebuild document indexes on grid changes - The status bar and the Preflight panel show a gray light and "Checking" until the active document's first check ends, instead of a green "No errors". - The cross-reference and running-header indexes are keyed on the baseline grid and the font scope as well, so a change to either builds them again, in a cache and in a cache over it. - The test helper that waits for the preflight worker fails when the worker ends without a result. --- crates/compose/src/cache.rs | 3 ++ crates/compose/src/tests.rs | 26 ++++++++++++ crates/ui-egui/src/chrome/status_bar.rs | 17 +++++--- crates/ui-egui/src/panels.rs | 10 +++-- crates/ui-egui/src/panels/properties/links.rs | 17 ++++++-- crates/ui-egui/src/preflight_worker.rs | 8 ---- crates/ui-egui/src/preflight_worker/tests.rs | 41 ++++++++++++++++++- 7 files changed, 101 insertions(+), 21 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 9cf96e497..dd7180915 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -88,6 +88,9 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); format!("{:?}", doc.text_variables).hash(&mut h); sections_hash(doc).hash(&mut h); + // The compositions the indexes are built from also depend on these (see `signature`). + let g = &doc.settings.baseline_grid; + (doc.font_scope, g.relative_to == designcraft_doc::GridRelative::TopMargin, g.start.to_bits(), g.increment.to_bits()).hash(&mut h); h.finish() } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 900bced97..7f900dd5b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8175,6 +8175,32 @@ fn a_cache_over_another_reads_it_without_writing_to_it() { assert!(base.composed_for(&old, sid).is_none(), "the base holds nothing of the older state"); } +/// The cross-reference and running-header indexes are built from compositions that depend on the +/// baseline grid and the font scope, so a change to either builds them again, in a cache and in a +/// cache over it. +#[test] +fn the_document_indexes_are_rebuilt_when_the_grid_or_font_scope_changes() { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (d, _, _) = doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 600.0), para); + let base = Arc::new(Cache::new()); + let (xrefs, running) = (base.xref_index(&d), base.running_index(&d)); + let mut grid = d.clone(); + grid.settings.baseline_grid.increment = 30.0; + let mut scope = d.clone(); + scope.font_scope += 1; + for (changed, what) in [(&grid, "grid"), (&scope, "font scope")] { + let reader = Cache::over(Arc::clone(&base)); + assert!(!Arc::ptr_eq(&reader.xref_index(changed), &xrefs), "{what}: the base's cross-reference index is not used"); + assert!(!Arc::ptr_eq(&reader.running_index(changed), &running), "{what}: the base's running-header index is not used"); + let own = Cache::new(); + let (x, r) = (own.xref_index(&d), own.running_index(&d)); + assert!(!Arc::ptr_eq(&own.xref_index(changed), &x), "{what}: cross-reference index rebuilt"); + assert!(!Arc::ptr_eq(&own.running_index(changed), &r), "{what}: running-header index rebuilt"); + } + let reader = Cache::over(Arc::clone(&base)); + assert!(Arc::ptr_eq(&reader.xref_index(&d), &xrefs), "the same state uses the base's index"); +} + /// Two single pages 618 pt tall, top margins 36 and 48, each with an overset 11/13 story aligned /// to a baseline grid (start 0, increment 13) and a frame filling its margin box (bottom 582). fn grid_margin_doc(relative_to: designcraft_doc::GridRelative) -> (Document, [StoryId; 2]) { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index c602b1721..765ec66fc 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -169,19 +169,24 @@ pub fn status_bar(app: &mut DesignApp, ui: &mut egui::Ui) { ui.painter().circle_filled( r.center(), 4.0, - if errors == 0 { Color32::from_rgb(60, 200, 90) } else { Color32::from_rgb(235, 50, 50) }, + match errors { + None => t.text_dim, + Some(0) => Color32::from_rgb(60, 200, 90), + Some(_) => Color32::from_rgb(235, 50, 50), + }, ); - let count = if errors == 0 { - format!("{} ▾", crate::i18n::tr(&app.ui.language, "No errors")) - } else { - format!( + let count = match errors { + // The active document's first check hasn't ended. + None => format!("{} ▾", crate::i18n::tr(&app.ui.language, "Checking")), + Some(0) => format!("{} ▾", crate::i18n::tr(&app.ui.language, "No errors")), + Some(errors) => format!( "{} ▾", crate::i18n::count_label( &app.ui.language, if errors == 1 && !crate::i18n::category_first(&app.ui.language) { "error" } else { "errors" }, errors ) - ) + ), }; // As in InDesign, the count opens a menu that leads to the Preflight panel. let menu = crate::menus::menu_button(ui, egui::RichText::new(count).font(small.clone()), |ui| { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 45606f4cd..33d9bd3c4 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -299,9 +299,13 @@ pub fn text_attrs(app: &mut DesignApp) -> Option { if v.is_null() { None } else { Some(serde_json::to_value(v).ok()?) } } -/// Count the preflight errors last found for the active document (0 until its first check ends). -pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> usize { - crate::preflight_worker::issues(app, ctx).map_or(0, |issues| issues.iter().filter(|i| i.severity == "error").count()) +/// Count the preflight errors last found for the active document: `None` until its first check +/// ends, and 0 with no document open. +pub fn preflight_errors(app: &mut DesignApp, ctx: &egui::Context) -> Option { + match crate::preflight_worker::issues(app, ctx) { + Some(issues) => Some(issues.iter().filter(|i| i.severity == "error").count()), + None => app.session.active().is_none().then_some(0), + } } /// Height of one swatch-menu row. diff --git a/crates/ui-egui/src/panels/properties/links.rs b/crates/ui-egui/src/panels/properties/links.rs index 7a1a6f0d0..f161f35f4 100644 --- a/crates/ui-egui/src/panels/properties/links.rs +++ b/crates/ui-egui/src/panels/properties/links.rs @@ -300,18 +300,29 @@ pub fn info_panel(app: &mut DesignApp, ui: &mut egui::Ui) { pub fn preflight_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let issues = crate::preflight_worker::issues(app, ui.ctx()).unwrap_or_default(); + let found = crate::preflight_worker::issues(app, ui.ctx()); + // The active document's first check hasn't ended. + let checking = found.is_none() && app.session.active().is_some(); + let issues = found.unwrap_or_default(); let errors = issues.iter().filter(|i| i.severity == "error").count(); ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(vec2(10.0, 10.0), egui::Sense::hover()); ui.painter().circle_filled( r.center(), 4.5, - if errors == 0 { egui::Color32::from_rgb(60, 200, 90) } else { egui::Color32::from_rgb(235, 50, 50) }, + if checking { + t.text_dim + } else if errors == 0 { + egui::Color32::from_rgb(60, 200, 90) + } else { + egui::Color32::from_rgb(235, 50, 50) + }, ); crate::rtl::label( ui, - if issues.is_empty() { + if checking { + crate::i18n::tr(&app.ui.language, "Checking").to_string() + } else if issues.is_empty() { crate::i18n::tr(&app.ui.language, "No errors").to_string() } else { format!( diff --git a/crates/ui-egui/src/preflight_worker.rs b/crates/ui-egui/src/preflight_worker.rs index 4da6224e5..02b27832e 100644 --- a/crates/ui-egui/src/preflight_worker.rs +++ b/crates/ui-egui/src/preflight_worker.rs @@ -420,13 +420,5 @@ pub(crate) fn start_worker(app: &mut DesignApp, ctx: &egui::Context) { app.preflight.worker.channels = spawn(ctx.clone(), &app.preflight.worker.live); } -/// Waits in a test for the worker's next result and keeps it, as a frame that polls would. -#[cfg(all(test, not(target_arch = "wasm32")))] -pub(crate) fn wait_for_worker(app: &mut DesignApp) { - if let Some(found) = app.preflight.worker.wait() { - app.preflight.keep(found); - } -} - #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/preflight_worker/tests.rs b/crates/ui-egui/src/preflight_worker/tests.rs index 9cc9a394b..ba0bfad67 100644 --- a/crates/ui-egui/src/preflight_worker/tests.rs +++ b/crates/ui-egui/src/preflight_worker/tests.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use egui::vec2; +use egui_kittest::kittest::Queryable; use serde_json::json; use super::Checked; @@ -30,6 +31,14 @@ fn found(app: &crate::DesignApp) -> Option<(usize, bool)> { Some((f.issues.iter().filter(|i| i.severity == "error").count(), f.of.same(&now))) } +/// Waits for the worker's next result and keeps it, as a frame that polls would. Panics when the +/// worker has ended without one. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_worker(app: &mut crate::DesignApp) { + let Some(found) = app.preflight.worker.wait() else { panic!("the preflight worker ended before it sent a result") }; + app.preflight.keep(found); +} + /// A worker whose thread never takes a job: the test reads the queue. fn stalled_worker(app: &mut crate::DesignApp) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { let (tx, jobs) = std::sync::mpsc::sync_channel(1); @@ -298,9 +307,39 @@ fn the_worker_checks_and_the_interface_thread_does_not() { assert_eq!(h.state().app.preflight.inline_checks, 0, "no check ran on the interface thread"); // The last frame handed the current state to the worker, whose last answer is for it. while found(&h.state().app) != Some((1, true)) { - super::wait_for_worker(&mut h.state_mut().app); + wait_for_worker(&mut h.state_mut().app); } let issues = super::issues(&mut h.state_mut().app, &ctx).unwrap(); assert_eq!(issues.iter().filter(|i| i.severity == "error").count(), 1); assert_eq!(h.state().app.preflight.inline_checks, 0, "the worker's answer is kept, not checked again"); } + +/// Until the active document's first check ends, the status bar and the Preflight panel show that +/// it is being checked, not a clean result. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_first_check_shows_as_checking() { + let (mut app, _) = overset_app(); + app.ui.dock_tab = "properties".into(); + let (_jobs, _done) = stalled_worker(&mut app); + let mut h = test_window::open(app, vec2(1200.0, 700.0)); + h.state_mut().app.run("window.panel", json!({"panel": "preflight"})).unwrap(); + h.run_steps(5); + assert!(h.state().app.preflight.found.is_empty(), "nothing found yet"); + assert_eq!(h.state().app.preflight.inline_checks, 0); + assert!(h.query_by_label("Checking ▾").is_some(), "the status bar shows the check"); + assert!(h.query_by_label("No errors ▾").is_none()); + assert!(h.query_by_label("Checking").is_some(), "the Preflight panel shows the check"); + assert!(h.query_by_label("No errors").is_none()); +} + +/// Waiting for a worker that ended before it answered fails the test instead of leaving it +/// waiting. +#[cfg(not(target_arch = "wasm32"))] +#[test] +#[should_panic(expected = "the preflight worker ended before it sent a result")] +fn waiting_for_a_worker_that_ended_fails() { + let (mut app, _) = overset_app(); + drop(stalled_worker(&mut app)); + wait_for_worker(&mut app); +} From 68549972945974011ace631f428ea283a1f2f72e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:53:45 -0800 Subject: [PATCH 158/328] Render: a feathered object's bevel and inner effects fade with it A basic, directional or gradient feather faded only the object's body. Its bevel, inner glow, inner shadow and satin were drawn afterwards over the whole shape, so where the feather let the page show through, the bevel's highlight and the inner glow screened whatever lay behind the object. Text under the feathered edge of a beveled frame turned lighter until the frame was moved off it. Each inner effect is now faded by the same feathers before it blends with what is behind the object, so a feathered object fades to transparent at its edge with its effects. --- crates/render/src/fx.rs | 565 +++++++++++++++++++++++++--------------- 1 file changed, 349 insertions(+), 216 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..f9b40ba9b 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -15,7 +15,8 @@ //! - Inner glow, bevel and emboss, satin: built like the inner shadow (an offset inverse of the //! shape, blurred and clipped) with screen / multiply blending; satin XORs two offset copies. //! - Feather: the object is masked by its shape inset by half the width and blurred, so the -//! edge fades from ~0 at the path to full strength `width` inside. +//! edge fades from ~0 at the path to full strength `width` inside. The basic, directional and +//! gradient feathers fade the inner effects with the object. use designcraft_doc::Item; use designcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; @@ -46,6 +47,17 @@ pub(crate) fn outset(it: &Item) -> f64 { o } +/// Whether `it` has a basic feather: a width on a closed shape. +fn basic_feather(it: &Item) -> bool { + it.effects.feather > 0.0 && it.path.is_closed() +} + +/// Whether any of `it`'s feathers (basic, directional, gradient) fades it. +fn fades(it: &Item) -> bool { + let e = &it.effects; + basic_feather(it) || e.directional_feather.on && e.directional_feather.widths.iter().any(|w| *w > 0.0) || e.gradient_feather.on +} + /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { let size = bound(size).max(0.0); @@ -149,17 +161,245 @@ impl Renderer { ctx.pop_layer(); } } - // Gradient feather: the object (feathered or not) drawn in its own layer, then kept as - // much as the opacity gradient says. - let gf = &e.gradient_feather; - let directional = e.directional_feather.on && e.directional_feather.widths.iter().any(|w| *w > 0.0); - if gf.on || directional { + // The object, feathered or not, drawn in its own layer and faded there. A basic feather + // clips the body to the shape at device resolution; only its blurred mask may be drawn + // offscreen at a lower one. + let fading = fades(it); + let basic = basic_feather(it); + if fading { ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, None, None, None, None); } - // The object, feathered or not. Choke keeps that much of the width opaque (a shorter - // fade); Sharp and Rounded corners follow the inset shape more tightly than Diffused. - if e.feather > 0.0 && it.path.is_closed() { + if basic { + ctx.set_transform(f.view * xf); + ctx.push_clip_layer(bp); + } + self.draw_body(ctx, f, it, bp, xf, page); + if basic { + ctx.pop_layer(); + } + if fading { + self.fade(ctx, f, it, bp, xf, reach); + ctx.pop_layer(); + } + if !it.path.is_closed() { + return; + } + // The feathers fade the inner effects with the object: each one is faded in its own + // layer before it blends with what is behind. + let fade = fading.then_some(it); + // An image's edge is where it is opaque, not the frame: inner shadows, glows and bevels + // follow what is painted when the frame holds a graphic. + let painted = matches!(it.content, designcraft_doc::Content::Graphic(_)).then_some((it, page)); + // Inner shadow, clipped to the shape. + if e.inner_shadow.on + && let Some(c) = doc.resolve_color(&e.inner_shadow.color, 1.0) + { + let s = &e.inner_shadow; + let (sigma, choke) = split(s.size, s.choke); + let off = offset(doc.light_angle(s.angle, s.global_light), s.distance); + self.inner_edge( + ctx, + f, + reach, + bp, + xf, + off, + sigma, + choke, + color_of(&c, s.opacity.clamp(0.0, 1.0)), + crate::blend_mode(s.mode).mix, + painted, + fade, + ); + } + // Inner glow: from the edges inwards (or out from the centre), screened over the object. + if e.inner_glow.on + && let Some(c) = doc.resolve_color(&e.inner_glow.color, 1.0) + { + let g = &e.inner_glow; + let (sigma, choke) = split(g.size, g.choke); + // Precise keeps the glow close to the edge: a tighter blur. + let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; + let mix = crate::blend_mode(g.mode).mix; + let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); + if g.center { + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(fr.view * xf); + c.set_paint(paint); + c.fill_path(bp); + // Fade towards the edge: cut a band of the glow's size away. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); + c.set_transform(fr.view * xf); + c.set_paint(peniko::Color::BLACK); + c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); + c.stroke_path(bp); + c.pop_layer(); + c.pop_layer(); + }); + } else { + self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix, painted, fade); + } + } + // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. + if e.satin.on + && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) + { + let st = &e.satin; + let off = offset(st.angle, st.distance / 2.0); + let sigma = bound(st.size).max(0.0) / 2.0; + let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); + let invert = st.invert; + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + if invert { + c.set_transform(fr.view * xf); + c.set_paint(paint); + c.fill_path(bp); + } + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); + c.set_transform(fr.view * Affine::translate(off) * xf); + c.set_paint(paint); + c.fill_path(bp); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); + c.set_transform(fr.view * Affine::translate(-off) * xf); + c.fill_path(bp); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + }); + } + // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. + if e.bevel.on { + let b = &e.bevel; + let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); + let sigma = bound(b.size).max(0.0) / 2.0; + if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { + // The inverse shape moved away from the light lights the edges facing it. + let paint = color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)); + self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, paint, Mix::Screen, painted, fade); + } + if let Some(c) = doc.resolve_color(&b.shadow, 1.0) { + let paint = color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)); + self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, paint, Mix::Multiply, painted, fade); + } + } + } + + /// An inner shadow-like edge: everything outside the shape moved by `off`, blurred by + /// `sigma`, clipped to the shape and blended with `mix`. With `painted` (an object and the + /// page it shows on), the shape is what the object paints, so a transparent part of an image + /// is outside it: the edge runs along the image's opaque pixels, not the frame. With `fade`, + /// the edge fades with that object's feathers. + #[allow(clippy::too_many_arguments)] + fn inner_edge( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + reach: Rect, + bp: &BezPath, + xf: Affine, + off: Vec2, + sigma: f64, + choke: f64, + paint: peniko::Color, + mix: Mix, + painted: Option<(&Item, ShownOn)>, + fade: Option<&Item>, + ) { + let sigma = bound(sigma).max(0.0); + let choke = bound(choke); + if let Some((it, page)) = painted { + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |me, c, fr| { + let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; + let area = reach.inflate(pad, pad); + // The colour everywhere but under the painted pixels moved by `off`, blurred, ... + c.set_transform(fr.view); + c.push_layer(None, None, None, None, None); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_paint(paint); + c.fill_rect(&area); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); + let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; + me.draw_body(c, &moved, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + // ... kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + }); + return; + } + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), fade, |_, c, fr| { + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + // Everything outside the offset shape, so the colour bleeds in from the edges. + let m = Affine::translate(off) * xf; + let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; + let mut inv = m.transform_rect_bbox(bp.bounding_box()).inflate(pad, pad).to_path(0.1); + let mut shape = bp.clone(); + shape.apply_affine(m); + inv.extend(shape.iter()); + c.set_paint(paint); + c.set_fill_rule(peniko::Fill::EvenOdd); + c.fill_path(&inv); + c.set_fill_rule(peniko::Fill::NonZero); + if choke > 0.0 { + c.set_stroke(kurbo::Stroke::new(choke * 2.0).with_join(kurbo::Join::Round)); + c.stroke_path(&shape); + } + c.pop_layer(); + }); + } + + /// [`Renderer::with_filters`] clipped to `clip` (a path and its spread transform), blended with + /// `mix`. The effect's blend must see the object's backdrop, outside its clipping and offscreen + /// filter layers. Putting it inside the clip blends with transparent pixels instead. With + /// `fade`, what `draw` paints is faded by that object's feathers before it blends. + #[allow(clippy::too_many_arguments)] + fn with_blended_filters( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + reach: Rect, + sigma: f64, + mix: Mix, + clip: (&BezPath, Affine), + fade: Option<&Item>, + draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), + ) { + let layered = mix != Mix::Normal || fade.is_some(); + if layered { + ctx.set_transform(Affine::IDENTITY); + ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); + } + self.with_filters(ctx, f, reach, sigma, Some(clip), draw); + if let Some(it) = fade { + self.fade(ctx, f, it, clip.0, clip.1, reach); + } + if layered { + ctx.pop_layer(); + } + } + + /// Fade what was drawn in the current layer by `it`'s feathers: the basic feather's blurred + /// inset shape, a ramp for each directional feather side and the gradient feather. `bp` and + /// `xf` are the object's shape and spread transform, `reach` (spread space) what it paints. + fn fade(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, reach: Rect) { + let e = &it.effects; + // Choke keeps that much of the width opaque (a shorter fade); Sharp and Rounded corners + // follow the inset shape more tightly than Diffused. + if basic_feather(it) { let fo = &e.feather_options; let w = bound(e.feather) * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01); let (sigma, join) = match fo.corners { @@ -167,12 +407,7 @@ impl Renderer { designcraft_doc::FeatherCorners::Rounded => (w / 3.0, kurbo::Join::Round), designcraft_doc::FeatherCorners::Sharp => (w / 6.0, kurbo::Join::Miter), }; - // The body and its clip stay at device resolution; only the blurred mask may be drawn - // offscreen at a lower one. - ctx.set_transform(f.view * xf); - ctx.push_clip_layer(bp); - self.draw_body(ctx, f, it, bp, xf, page); - // Keep the body where the blurred inset silhouette is. + // Keep what was drawn where the blurred inset silhouette is. ctx.set_transform(Affine::IDENTITY); ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); self.with_filters(ctx, f, reach, sigma, None, |_, c, fr| { @@ -190,9 +425,6 @@ impl Renderer { c.pop_layer(); }); ctx.pop_layer(); - ctx.pop_layer(); - } else { - self.draw_body(ctx, f, it, bp, xf, page); } // Directional feather: one fading ramp per side, multiplied in. let df = &e.directional_feather; @@ -222,206 +454,9 @@ impl Renderer { ctx.pop_layer(); } } - if gf.on { + if e.gradient_feather.on { gradient_feather_mask(ctx, f, it, xf); } - if gf.on || directional { - ctx.pop_layer(); - } - if !it.path.is_closed() { - return; - } - // An image's edge is where it is opaque, not the frame: inner shadows, glows and bevels - // follow what is painted when the frame holds a graphic. - let painted = matches!(it.content, designcraft_doc::Content::Graphic(_)).then_some((it, page)); - // Inner shadow, clipped to the shape. - if e.inner_shadow.on - && let Some(c) = doc.resolve_color(&e.inner_shadow.color, 1.0) - { - let s = &e.inner_shadow; - let (sigma, choke) = split(s.size, s.choke); - let off = offset(doc.light_angle(s.angle, s.global_light), s.distance); - self.inner_edge( - ctx, - f, - reach, - bp, - xf, - off, - sigma, - choke, - color_of(&c, s.opacity.clamp(0.0, 1.0)), - crate::blend_mode(s.mode).mix, - painted, - ); - } - // Inner glow: from the edges inwards (or out from the centre), screened over the object. - if e.inner_glow.on - && let Some(c) = doc.resolve_color(&e.inner_glow.color, 1.0) - { - let g = &e.inner_glow; - let (sigma, choke) = split(g.size, g.choke); - // Precise keeps the glow close to the edge: a tighter blur. - let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; - let mix = crate::blend_mode(g.mode).mix; - let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); - if g.center { - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); - // Fade towards the edge: cut a band of the glow's size away. - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); - c.set_transform(fr.view * xf); - c.set_paint(peniko::Color::BLACK); - c.set_stroke(kurbo::Stroke::new((bound(g.size) - choke).max(0.5) * 2.0).with_join(kurbo::Join::Round)); - c.stroke_path(bp); - c.pop_layer(); - c.pop_layer(); - }); - } else { - self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix, painted); - } - } - // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. - if e.satin.on - && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) - { - let st = &e.satin; - let off = offset(st.angle, st.distance / 2.0); - let sigma = bound(st.size).max(0.0) / 2.0; - let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); - let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - if invert { - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); - } - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - c.set_transform(fr.view * Affine::translate(off) * xf); - c.set_paint(paint); - c.fill_path(bp); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - c.set_transform(fr.view * Affine::translate(-off) * xf); - c.fill_path(bp); - c.pop_layer(); - c.pop_layer(); - c.pop_layer(); - }); - } - // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. - if e.bevel.on { - let b = &e.bevel; - let off = offset(doc.light_angle(b.angle, b.global_light), bound(b.size) * (b.depth / 100.0).clamp(0.01, 10.0) * 0.5); - let sigma = bound(b.size).max(0.0) / 2.0; - if let Some(c) = doc.resolve_color(&b.highlight, 1.0) { - // The inverse shape moved away from the light lights the edges facing it. - self.inner_edge(ctx, f, reach, bp, xf, off, sigma, 0.0, color_of(&c, b.highlight_opacity.clamp(0.0, 1.0)), Mix::Screen, painted); - } - if let Some(c) = doc.resolve_color(&b.shadow, 1.0) { - self.inner_edge(ctx, f, reach, bp, xf, -off, sigma, 0.0, color_of(&c, b.shadow_opacity.clamp(0.0, 1.0)), Mix::Multiply, painted); - } - } - } - - /// An inner shadow-like edge: everything outside the shape moved by `off`, blurred by - /// `sigma`, clipped to the shape and blended with `mix`. With `painted` (an object and the - /// page it shows on), the shape is what the object paints, so a transparent part of an image - /// is outside it: the edge runs along the image's opaque pixels, not the frame. - #[allow(clippy::too_many_arguments)] - fn inner_edge( - &mut self, - ctx: &mut RenderContext, - f: &Frame, - reach: Rect, - bp: &BezPath, - xf: Affine, - off: Vec2, - sigma: f64, - choke: f64, - paint: peniko::Color, - mix: Mix, - painted: Option<(&Item, ShownOn)>, - ) { - let sigma = bound(sigma).max(0.0); - let choke = bound(choke); - if let Some((it, page)) = painted { - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { - let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; - let area = reach.inflate(pad, pad); - // The colour everywhere but under the painted pixels moved by `off`, blurred, ... - c.set_transform(fr.view); - c.push_layer(None, None, None, None, None); - c.push_layer(None, None, None, None, Some(blur(sigma))); - c.set_paint(paint); - c.fill_rect(&area); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestOut)), None, None, None); - let moved = Frame { view: fr.view * Affine::translate(off), ..*fr }; - me.draw_body(c, &moved, it, bp, xf, page); - c.pop_layer(); - c.pop_layer(); - // ... kept only where the object paints. - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); - me.draw_body(c, fr, it, bp, xf, page); - c.pop_layer(); - c.pop_layer(); - }); - return; - } - self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { - c.set_transform(fr.view); - c.push_layer(None, None, None, None, Some(blur(sigma))); - // Everything outside the offset shape, so the colour bleeds in from the edges. - let m = Affine::translate(off) * xf; - let pad = sigma * 4.0 + choke + off.hypot() + 4.0 * fr.px; - let mut inv = m.transform_rect_bbox(bp.bounding_box()).inflate(pad, pad).to_path(0.1); - let mut shape = bp.clone(); - shape.apply_affine(m); - inv.extend(shape.iter()); - c.set_paint(paint); - c.set_fill_rule(peniko::Fill::EvenOdd); - c.fill_path(&inv); - c.set_fill_rule(peniko::Fill::NonZero); - if choke > 0.0 { - c.set_stroke(kurbo::Stroke::new(choke * 2.0).with_join(kurbo::Join::Round)); - c.stroke_path(&shape); - } - c.pop_layer(); - }); - } - - /// [`Renderer::with_filters`] clipped to `clip` (a path and its spread transform), blended with - /// `mix`. The effect's blend must see the object's backdrop, outside its clipping and offscreen - /// filter layers. Putting it inside the clip blends with transparent pixels instead. - #[allow(clippy::too_many_arguments)] - fn with_blended_filters( - &mut self, - ctx: &mut RenderContext, - f: &Frame, - reach: Rect, - sigma: f64, - mix: Mix, - clip: (&BezPath, Affine), - draw: impl FnOnce(&mut Self, &mut RenderContext, &Frame), - ) { - if mix != Mix::Normal { - ctx.set_transform(Affine::IDENTITY); - ctx.push_layer(None, Some(BlendMode::new(mix, Compose::SrcOver)), None, None, None); - } - self.with_filters(ctx, f, reach, sigma, Some(clip), draw); - if mix != Mix::Normal { - ctx.pop_layer(); - } } /// Run `draw`, which pushes filter layers. Single-threaded contexts draw directly. On a @@ -607,4 +642,102 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A feathered object fades to transparent at its edge, its bevel and inner glow included: where + /// the feather shows what is behind the object, the highlight and shadow leave it as it is. + #[test] + fn feathers_fade_the_inner_effects_with_the_object() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, Fill, SpreadRef}; + let doc = |image: bool, feather: u8, inner: u8| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut back = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 350.0, 350.0)), + ); + back.fill = Fill::swatch("C=0 M=100 Y=0 K=0"); + d.insert_item(SpreadRef::Doc(0), back, None).unwrap(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), + ); + if image { + let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([40, 160, 90, 255])); + let mut png = Vec::new(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let aid = designcraft_doc::AssetId(d.alloc()); + d.assets.insert( + aid, + std::sync::Arc::new(designcraft_doc::Asset { + id: aid, + name: "green.png".into(), + mime: "image/png".into(), + data: std::sync::Arc::new(png), + pixels: Some((20, 20)), + ..Default::default() + }), + ); + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (200.0, 200.0), + xf: Affine::translate((100.0, 100.0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + } else { + it.fill = Fill::swatch("C=100 M=0 Y=0 K=0"); + } + let e = &mut it.effects; + match feather { + 0 => e.feather = 30.0, + 1 => (e.directional_feather.on, e.directional_feather.widths) = (true, [30.0; 4]), + _ => e.gradient_feather.on = true, + } + match inner { + 0 => {} + 1 => (e.bevel.on, e.bevel.size) = (true, 12.0), + _ => (e.inner_glow.on, e.inner_glow.color, e.inner_glow.opacity, e.inner_glow.size) = (true, "[Paper]".into(), 1.0, 20.0), + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d + }; + let px = |d: &Document, threads: u16, x: u32| { + let mut r = Renderer::new(); + r.threads = threads; + r.render_page(d, &crate::Cache::new(), 0, 1.0, false, &crate::RenderOptions::default()).unwrap().pixel(x, 200) + }; + let diff = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).map(|(p, q)| u32::from(p.abs_diff(q))).sum::(); + for image in [false, true] { + for feather in 0..3 { + for threads in [0, 4] { + let plain = doc(image, feather, 0); + // The object's faded edges: the left and right ones for the basic and directional + // feathers, the right one for the gradient feather (opaque on the left). + let edges: &[u32] = if feather == 2 { &[299] } else { &[100, 299] }; + for &x in edges { + let behind = px(&plain, threads, 70); + let faded = px(&plain, threads, x); + assert!(diff(faded, behind) < 40, "image {image} feather {feather}: the edge at {x} shows what is behind"); + for inner in [1, 2] { + let with = px(&doc(image, feather, inner), threads, x); + assert!( + diff(with, faded) < 30, + "image {image} feather {feather} inner {inner} threads {threads}: {with:?} over the faded edge at {x}, {faded:?} without" + ); + } + } + } + } + } + } } From eda934fff0e4c0df47bd18e92499cc4dfdecbbe0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:54:27 -0800 Subject: [PATCH 159/328] Compose: vertical justification keeps moved lines inside a shaped frame Center, Bottom and Justify moved the lines of a shaped frame without testing them against the outline, so in a frame that narrows towards the bottom a line set in a wide band ended up crossing the outline. Each moved line's slot is now tested against the outline over its new band, as when the line was fitted, and the text goes only as far down as every slot fits. In a frame that narrows and widens again, the search scans the rooms from the most down (every point, at most 512 steps) before halving, so the text can still reach a lower part past a narrow waist. --- crates/compose/src/lib.rs | 39 +++++++++++++++++++--- crates/compose/src/tests.rs | 65 +++++++++++++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 72c0f69cb..0188ee1cf 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5514,7 +5514,8 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // frames as in rectangular ones. Above footnotes, and in vertical frames, the descenders // stay inside the text area, as when the lines are fitted. // `space`: the room under the bottom of the text. - let space = if f.vertical || note_top <= f.area.y1 { limit - ink_bottom } else { limit - last_baseline }; + let inside = f.vertical || note_top <= f.area.y1; + let space = if inside { limit - ink_bottom } else { limit - last_baseline }; if space <= 0.0 { continue; } @@ -5560,14 +5561,42 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de }; // Only the last row's descenders hang below the bottom of the text: an earlier line whose // ink reaches below the last baseline (tight leading) isn't moved past the text area. - let fits = |shift: &[f64]| { - idx.iter().zip(&rows).all(|(&i, &k)| k == n || shift[k] <= 0.0 || ft.lines[i].baseline + ft.lines[i].descent + shift[k] <= limit + 1e-9) + // In a shaped frame each moved line's slot stays inside the outline over its new band, as + // when the line was fitted: a frame that narrows towards the bottom holds the text higher. + let in_outline = |l: &Line, last: bool, dy: f64| match &f.outline { + Some(o) => { + let b = l.baseline + dy; + let desc = if last && !inside { 0.0 } else { l.descent.max(0.0) }; + let tol = 1e-6; + o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) + } + None => true, }; - // Every row moves no less as `space` grows, so the most room that fits is found by halving. + // The lowest lines are tested first: they are the ones a narrowing outline stops. + let fits = |shift: &[f64]| { + idx.iter().zip(&rows).rev().all(|(&i, &k)| { + let l = &ft.lines[i]; + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, k == n, shift[k])) + }) + }; + // Every row moves no less as `space` grows, so in a rectangular frame the most room that + // fits is found by halving. A shaped frame can narrow and widen again further down: there + // the rooms are scanned from the most down to none, every point (at most 512 steps, each + // usually stopped by the lowest line), and the step between the first that fits and the + // one above it is then halved. let mut shift = shifts(space); if !fits(&shift) { + let steps = if f.outline.is_some() { space.ceil().clamp(64.0, 512.0) as usize } else { 1 }; let (mut lo, mut hi) = (0.0, space); - for _ in 0..60 { + for j in 1..steps { + let s = space * (steps - j) as f64 / steps as f64; + if fits(&shifts(s)) { + lo = s; + break; + } + hi = s; + } + for _ in 0..50 { let mid = (lo + hi) / 2.0; if fits(&shifts(mid)) { lo = mid; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b94d94000..77eb0a076 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2429,8 +2429,9 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { } // A corner radius doesn't change where Bottom and Justify put the last baseline: on the - // bottom inset, as in a rectangular frame, with the descenders in the inset. - for insets in [[6.0; 4], [0.0, 0.0, 12.0, 0.0]] { + // bottom inset, as in a rectangular frame, with the descenders in the inset. Each radius is + // smaller than the inset, so the rounded corner stays clear of the text area. + for (insets, big) in [([6.0; 4], 4.0), ([0.0, 0.0, 12.0, 0.0], 6.0)] { for mode in [Bottom, Justify] { let compose_frame = |radius: f64| { let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 200.0, 100.0), ParaAttrs::default()); @@ -2444,7 +2445,7 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { (area, all_lines(&cs).iter().map(|l| l.baseline).collect::>()) }; let (area, square) = compose_frame(0.0); - for radius in [0.1 * mm, 6.0] { + for radius in [0.1 * mm, big] { let (_, rounded) = compose_frame(radius); assert_eq!(rounded.len(), square.len()); for (r, s) in rounded.iter().zip(&square) { @@ -2457,6 +2458,64 @@ fn a_corner_radius_keeps_a_cap_height_line_in_place() { } } +/// In a shaped frame, Center, Bottom and Justify keep each moved line's slot inside the outline: +/// a triangle that narrows downward holds the lines where their slots still fit, and one that +/// widens downward lets Bottom put the last baseline on the frame's bottom. +#[test] +fn vertical_justification_keeps_lines_inside_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let r = Rect::new(0.0, 0.0, 300.0, 300.0); + let compose_with = |tri: [Point; 3], mode: VerticalJustification| { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: tri.iter().map(|&p| Anchor::corner(p)).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + let spec = frame_specs(&d, sid).remove(0); + assert!(spec.outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines: Vec = all_lines(&cs).into_iter().cloned().collect(); + assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); + (spec.area, lines) + }; + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, the last line's + // descenders left out. + let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; + for mode in [Center, Bottom, Justify] { + let (area, lines) = compose_with(down, mode); + for (k, l) in lines.iter().enumerate() { + let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let top = (l.baseline - l.ascent).max(area.y0); + for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { + assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); + } + } + } + // Widening downward: moving down keeps every slot inside, so Bottom goes all the way. + let up = [Point::new(150.0, 0.0), Point::new(300.0, 300.0), Point::new(0.0, 300.0)]; + let (area, lines) = compose_with(up, Bottom); + let last = lines[lines.len() - 1].baseline; + assert!((last - area.y1).abs() < 1e-6, "Bottom: last baseline at {last}, frame bottom at {}: {lines:?}", area.y1); + + // Narrowing at a waist, full width again from 200 to 260 pt, then a point: Bottom sets the + // lines in the lower full-width part, past the waist. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 260.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 260.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let (mut d, sid, fid) = doc_with("Typography\ngypsy", r, ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = Bottom; + o.inset = [0.0; 4]; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let (first, last) = (lines[0], lines[lines.len() - 1]); + assert!(first.baseline - first.ascent >= 200.0 - 1e-6, "Bottom: first line top at {}", first.baseline - first.ascent); + assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); +} + #[test] fn table_rows_clear_footnotes_and_continue_in_the_next_column() { for span in [false, true] { From ffcd4e215fcc5c26485c536b33ded3539ab171b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:55:29 -0800 Subject: [PATCH 160/328] Object styles: a rename that is not a name is refused --- crates/engine/src/cmd/style/object.rs | 3 ++ crates/engine/src/tests.rs | 59 ++++++++++++++++----------- 2 files changed, 38 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index b22388372..a8572a3fa 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -367,6 +367,9 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { if let Some(tf) = text_frame_param(CMD, p, old.text_frame.as_ref())? { new.text_frame = tf; } + if p.get("rename").is_some_and(|r| !r.is_string()) { + return Err(bad(CMD, "`rename` must be a style name")); + } let rename = str_param(p, "rename").map(str::trim).filter(|r| *r != name).map(str::to_string); if let Some(r) = &rename { let builtin = name.starts_with('[') && name.ends_with(']'); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5a8fc30e6..8ffd9fc1e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -752,6 +752,41 @@ fn object_style_effects_follow_the_style_until_overridden() { assert_eq!(s.doc().unwrap().revision, rev); } +/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting, a word or null +/// for a switch, a rename that isn't a name and a corner size outside 0–10000 pt. +#[test] +fn object_style_parameters_are_checked() { + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Framed", "fromSelection": false})).unwrap(); + for bad in [ + json!({"fill": "Nope"}), + json!({"fill": {"swatch": "Nope"}}), + json!({"stroke": {"swatch": "Nope"}}), + json!({"stroke": {"wieght": 5}}), + json!({"fill": {"tnt": 0.5}}), + json!({"corners": {"shpae": "rounded"}}), + json!({"corners": {"size": -1}}), + json!({"corners": {"size": 10_001}}), + json!({"applyNextStyle": null}), + ] { + let mut p = bad.clone(); + p["name"] = json!("Framed"); + assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); + p["name"] = json!("Other"); + assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); + } + let c = json!({"shape": "rounded", "size": -1}); + assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err()); + for from in [json!("yes"), json!(null)] { + assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": from})).is_err(), "{from}"); + } + for rename in [json!(3), json!(null), json!(true)] { + assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": rename})).is_err(), "{rename}"); + } + let names: Vec<_> = s.doc().unwrap().doc.styles.object.iter().map(|o| o.name.clone()).collect(); + assert!(!names.iter().any(|n| n == "Other" || n == "Odd"), "{names:?}"); +} + /// The course's "Rounded Corner Image, White Stroke" style: made from a frame with rounded corners /// and a paper stroke, applied to another frame, then edited (a thicker stroke, bigger corners): /// the frames that follow the style change, one with its own stroke keeps it; a rename follows. @@ -792,30 +827,6 @@ fn object_styles_carry_corners_and_their_stroke_and_corners_can_be_edited() { assert!(s.execute("style.object.edit", &json!({"name": "Framed", "rename": "[Basic Text Frame]"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "[Basic Graphics Frame]", "rename": "Mine"})).is_err()); assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": "big"}})).is_err()); - // An unknown swatch, a misspelled setting and a word for a switch are refused. - for bad in [ - json!({"fill": "Nope"}), - json!({"fill": {"swatch": "Nope"}}), - json!({"stroke": {"swatch": "Nope"}}), - json!({"stroke": {"wieght": 5}}), - json!({"fill": {"tnt": 0.5}}), - json!({"corners": {"shpae": "rounded"}}), - ] { - let mut p = bad.clone(); - p["name"] = json!("Framed"); - assert!(s.execute("style.object.edit", &p).is_err(), "{bad}"); - p["name"] = json!("Other"); - assert!(s.execute("style.object.create", &p).is_err(), "{bad}"); - } - assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": "yes"})).is_err()); - assert!(s.execute("style.object.create", &json!({"name": "Other", "fromSelection": null})).is_err()); - assert!(s.execute("style.object.edit", &json!({"name": "Framed", "applyNextStyle": null})).is_err()); - // A size outside 0–10000 pt is refused, not changed. - for size in [-1.0, 10_001.0] { - assert!(s.execute("style.object.edit", &json!({"name": "Framed", "corners": {"size": size}})).is_err(), "{size}"); - let c = json!({"shape": "rounded", "size": size}); - assert!(s.execute("style.object.create", &json!({"name": "Odd", "corners": {"corners": [c, c, c, c]}})).is_err(), "{size}"); - } // A negative stroke weight is refused when creating a style as when editing one. let styles = s.doc().unwrap().doc.styles.object.len(); for cmd in ["style.object.create", "style.object.edit"] { From 8463cef4a9c5837dd07fe1073941112cac6434f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:59:10 -0800 Subject: [PATCH 161/328] Paste: refuse damaged clipboard images and journal one entry per paste - edit.pasteImage decodes the whole raster before it stores the image, so a file whose pixels are cut off after a whole header is refused. - edit.pasteImage is the only journal entry for a paste; the file.place it runs no longer adds a second one, so a replay places the image once. - Empty clipboard text beside an image counts as no text, so Edit > Paste pastes the image. - With a native menu, a pasted image event is ignored while the clipboard still holds what it held when objects were copied here. --- crates/engine/src/cmd/paste_image.rs | 52 ++++++++++++++++++++++++++-- crates/ui-egui/src/app/clipboard.rs | 27 ++++++++++----- crates/ui-egui/src/canvas/tests.rs | 28 +++++++++++++++ 3 files changed, 97 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index d5197a90c..b5e1003ac 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -96,6 +96,11 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { let bytes = super::base64_decode(b64); let (pw, ph) = raster_size(&bytes).ok_or_else(|| bad(ID, "the clipboard doesn't hold an image DesignCraft can read"))?; check_pasted_size(pw, ph).map_err(|e| bad(ID, e))?; + // The header can be whole while the pixels after it are cut off: decode the whole raster so + // a damaged image is refused instead of stored. + if designcraft_images::decode_rgba(&bytes).is_none() { + return Err(bad(ID, "the image on the clipboard is damaged and can't be read")); + } let sr = spread_param(p, ID)?; let at = match p.get("at") { None | Some(Value::Null) => None, @@ -116,7 +121,7 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { _ => None, }; if let Some(frame) = empty_frame { - return s.execute("file.place", &json!({"base64": b64, "name": name, "frame": frame})); + return place(s, &json!({"base64": b64, "name": name, "frame": frame})); } let d = &s.doc()?.doc; let sp = d.spread(sr).ok_or_else(|| bad(ID, "no such spread"))?; @@ -130,7 +135,16 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { let w = nw.min(d.settings.page_width * 0.6); let h = nh * w / nw; let spread = p.get("spread").cloned().unwrap_or(Value::Null); - s.execute("file.place", &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) + place(s, &json!({"base64": b64, "name": name, "spread": spread, "x": center.x - w / 2.0, "y": center.y - h / 2.0})) +} + +/// Runs `file.place` inside this command. Only `edit.pasteImage` stays in the journal, so a +/// replay of the journal places the image once. +fn place(s: &mut Session, params: &Value) -> Result { + let journal = s.journal.len(); + let r = s.execute("file.place", params); + s.journal.truncate(journal); + r } #[cfg(test)] @@ -239,6 +253,40 @@ mod tests { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); } + #[test] + fn a_damaged_image_with_a_whole_header_is_refused() { + let mut s = doc(); + let whole = png(40, 30); + let cut = &whole[..whole.len() / 2]; + assert_eq!(raster_size(cut), Some((40, 30)), "the header still reads"); + let (undo, assets) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.assets.len()); + let e = s.execute(ID, &json!({"base64": base64_encode(cut)})).unwrap_err().to_string(); + assert!(e.contains("damaged"), "{e}"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.doc.assets.len()), (undo, assets), "nothing stored"); + } + + #[test] + fn each_paste_is_one_journal_entry_and_replays_once() { + let mut s = doc(); + let frame = s.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap()["id"].as_u64().unwrap(); + s.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + let start = s.journal.len(); + let b64 = base64_encode(&png(10, 10)); + s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap(); + s.execute(ID, &json!({"base64": b64, "at": [500, 500]})).unwrap(); + let entries = s.journal[start..].to_vec(); + assert_eq!(entries.iter().map(|(id, _)| id.as_str()).collect::>(), [ID, ID], "the frame and the new-frame paths"); + let items = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len(); + let mut t = doc(); + t.execute("frame.create", &json!({"rect": [100, 100, 200, 300]})).unwrap(); + t.execute("selection.set", &json!({"ids": [frame]})).unwrap(); + for (id, p) in &entries { + t.execute(id, p).unwrap(); + } + assert_eq!(items(&t), items(&s), "the replay places each image once"); + } + #[test] fn images_beyond_the_pixel_limit_are_refused_before_they_are_encoded() { let e = pasted_png(9000, 8000, Vec::new()).unwrap_err(); diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index bff5156f7..faddd6f5b 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -31,18 +31,14 @@ impl DesignApp { if !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") || !(typing || id == "edit.paste") { return Pasted::Params(params); } + // Empty text counts as no text, so an image beside it still pastes. if params.get("text").is_none() - && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()) + && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f()).filter(|t| !t.is_empty()) && let Some(o) = params.as_object_mut() { o.insert("text".into(), Value::String(text)); } - // Nothing was copied to the clipboard since objects were copied here (native menu, where - // the system raises a change count with every copy). - let unchanged = match self.object_clip_change { - Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), - None => true, - }; + let unchanged = self.clipboard_unchanged_since_object_copy(); // Still what an object copy put there: paste those objects, not the placeholder text. let norm = |t: &str| t.replace("\r\n", "\n"); let ours = unchanged @@ -76,9 +72,24 @@ impl DesignApp { Pasted::Params(params) } + /// Nothing was copied to the clipboard since objects were copied here (native menu, where + /// the system raises a change count with every copy). + fn clipboard_unchanged_since_object_copy(&mut self) -> bool { + match self.object_clip_change { + Some(at_copy) => self.services.clipboard_change.as_mut().and_then(|f| f()) == Some(at_copy), + None => true, + } + } + /// Paste an image from the system clipboard as a placed image (`edit.pasteImage`), centered - /// in the view or in the selected empty frame. Text being edited takes no image. + /// in the view or in the selected empty frame. Text being edited takes no image. An image the + /// clipboard held before objects were copied here (native menu) is not pasted: the menu's + /// Paste pastes those objects. pub(crate) fn paste_clipboard_image(&mut self, image: ClipboardImage) -> Result { + let user = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed); + if user && self.session.clipboard.is_some() && self.object_clip_change.is_some() && self.clipboard_unchanged_since_object_copy() { + return Ok(Value::Null); + } let typing = self.session.active().is_some_and(|d| d.selection.text.is_some()); let file = if typing { Err("To paste the image, stop editing the text first (Esc).".to_string()) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0937904d9..5b3f796dc 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1108,6 +1108,10 @@ fn edit_paste_from_the_menu_places_the_clipboard_image() { copy_elsewhere(&clip, Some("https://example.com/cat.png"), Some((8, 6))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((8, 6))); + // Empty text beside the image counts as no text. + copy_elsewhere(&clip, Some(""), Some((12, 9))); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((12, 9))); // Other text wins over a picture of it. copy_elsewhere(&clip, Some("Some words"), Some((8, 6))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); @@ -1150,6 +1154,30 @@ fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); } +#[test] +fn a_paste_image_event_after_an_object_copy_does_not_paste_the_older_image() { + // A native menu: Copy leaves the older image on the system clipboard. + let (clip, services) = fake_clipboard(None, Some((40, 30))); + let mut app = DesignApp::new(designcraft_engine::Session::new(), services); + app.native_menu = true; + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [100, 100, 200, 200], "content": "text"})).unwrap()["id"].clone(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + app.run("selection.set", json!({"ids": []})).unwrap(); + let mut h = harness(app); + let image = |w, h| egui::Event::PasteImage(std::sync::Arc::new(egui::ColorImage::filled([w, h], egui::Color32::RED))); + let items = h.state().session.doc().unwrap().doc.spreads[0].items.len(); + h.input_mut().events.push(image(40, 30)); + h.run_steps(2); + assert_eq!(h.state().session.doc().unwrap().doc.spreads[0].items.len(), items, "the older image is not pasted"); + // An image copied since then pastes. + copy_elsewhere(&clip, None, Some((20, 10))); + h.input_mut().events.push(image(20, 10)); + h.run_steps(2); + assert_eq!(pasted_image(h.state()).map(|(px, _)| px), Some((20, 10))); +} + #[test] fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From ad828bd6503f92992f4751b50e2960153bc191b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:00:14 -0800 Subject: [PATCH 162/328] Text wrap: an opaque image's Alpha Channel contour is its rectangle Before, an image with no transparency wrapped like its frame, so a smaller image or one moved within its frame kept text out of the frame's empty part. --- crates/engine/src/cmd/alpha_wrap.rs | 61 +++++++++++++++-------------- 1 file changed, 32 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 585f29350..6ca0e78f9 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -52,7 +52,7 @@ pub(crate) fn sync(doc: &mut Document) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; - // An image with no outline (opaque, unreadable, too large) is remembered as an empty + // An image with no outline (unreadable, too large) is remembered as an empty // one, so later edits don't decode it again; the contour is then the frame's. let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); doc.alpha_outlines.push(Arc::new(o)); @@ -74,8 +74,8 @@ fn no_outline(data: &Arc>, asset: AssetId, threshold: u8) -> AlphaOutlin } } -/// The outline of the pixels of `data` more opaque than `threshold`. None for an image that -/// can't be read, is too large, or has no transparency (its contour is its rectangle). +/// The outline of the pixels of `data` more opaque than `threshold`: an image with no +/// transparency gives its rectangle. None for an image that can't be read or is too large. pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Option { let (w, h) = designcraft_images::pixel_size(data)?; if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS { @@ -92,13 +92,7 @@ pub(crate) fn trace(data: &Arc>, asset: AssetId, threshold: u8) -> Optio let (cols, rows) = (w.min(grid), h.min(grid)); let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) { Some(m) => m, - None => { - let (mask, transparent) = occupancy(img.as_raw(), w, h, cols, rows, threshold); - if !transparent { - return None; - } - mask - } + None => occupancy(img.as_raw(), w, h, cols, rows, threshold), }; // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close. @@ -152,11 +146,9 @@ fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option (Vec, bool) { +/// opaque than `threshold` (a cell is visible when any of its pixels is). +fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec { let mut mask = vec![false; (cols as usize) * (rows as usize)]; - let mut transparent = false; // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out. for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() { @@ -168,16 +160,14 @@ fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) - edge += u64::from(w); } acc += u64::from(cols); - let alpha = px[3]; - transparent |= alpha < 255; - if alpha > threshold + if px[3] > threshold && let Some(c) = mask.get_mut(base + gx) { *c = true; } } } - (mask, transparent) + mask } /// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of @@ -305,8 +295,10 @@ mod tests { let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap()); assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0)); assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0)); - // An opaque image has no alpha outline. - assert!(trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).is_none()); + // An opaque image's outline is its rectangle. + let o = trace(&Arc::new(png(|_, _| true)), AssetId(1), 25).unwrap(); + let a = o.outer.bounds().unwrap(); + assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0)); } /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a @@ -331,13 +323,13 @@ mod tests { } } } - assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), (expect, true), "{cols} x {rows}"); + assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}"); } - let (fine, _) = occupancy(&rgba, w, h, 256, 256, 25); - assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + let fine = occupancy(&rgba, w, h, 256, 256, 25); + assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); // Same count on one side, twice on the other. - let (fine, _) = occupancy(&rgba, w, h, 128, 256, 25); - assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25).0)); + let fine = occupancy(&rgba, w, h, 128, 256, 25); + assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25))); // Any other ratio is read from the pixels. assert_eq!(coarsen(&fine, 128, 256, 100, 128), None); } @@ -366,10 +358,9 @@ mod tests { assert!(s.doc().unwrap().doc.alpha_outlines.is_empty()); } - /// An image with no outline (here opaque) is remembered as an empty one: later edits don't - /// trace it again, and the contour is the frame's. + /// An outline is traced once: later edits keep it. #[test] - fn an_image_with_no_outline_is_not_traced_on_every_edit() { + fn an_outline_is_not_traced_on_every_edit() { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); let data = png(|_, _| true); @@ -380,12 +371,24 @@ mod tests { s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap(); let first = s.doc().unwrap().doc.alpha_outlines.clone(); assert_eq!(first.len(), 1, "remembered"); - assert_eq!((first[0].width, first[0].height), (0, 0), "as no outline"); s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap(); let after = &s.doc().unwrap().doc.alpha_outlines; assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again"); } + /// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its + /// frame, it leaves the empty part of the frame to the text. + #[test] + fn an_opaque_image_wraps_its_rectangle() { + let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]); + s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap(); + assert!(overset(&s, story), "the image covers the caption"); + // The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty. + s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap(); + s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap(); + assert!(!overset(&s, story), "the empty part of the frame takes the caption"); + } + /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and /// traced again when the image's data changes under the same asset (relink, link update). #[test] From 4122adc65f60eb79402e3a73e9ed07aeb65e9a87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:04:10 -0800 Subject: [PATCH 163/328] Text wrap: Alpha Channel outlines in use are looked up in sets --- crates/engine/src/cmd/alpha_wrap.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 6ca0e78f9..86b864a61 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -3,6 +3,7 @@ //! The outline is traced once per image and threshold, in the image's pixel space, and kept on //! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's //! current transform, so it follows the image when it is moved, scaled or refitted. +use std::collections::BTreeSet; use std::sync::Arc; use designcraft_doc::{AlphaOutline, AssetId, ContourType, Document, Item, WrapMode}; @@ -18,14 +19,14 @@ const MAX_EDGES: usize = 1 << 16; /// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when /// nothing changed: tracing happens only for an image and threshold not seen before. pub(crate) fn sync(doc: &mut Document) { - let mut wanted: Vec<(AssetId, u8)> = Vec::new(); + let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new(); // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on // its placed graphic (Direct Selection sets the graphic's). let mut want = |it: &Item| { let Some(g) = it.graphic() else { return }; for w in [&it.wrap, &g.wrap] { - if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel && !wanted.contains(&(g.asset, w.alpha_threshold)) { - wanted.push((g.asset, w.alpha_threshold)); + if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel { + wanted.insert((g.asset, w.alpha_threshold)); } } }; @@ -47,8 +48,9 @@ pub(crate) fn sync(doc: &mut Document) { // An outline traced from data the asset no longer has (relinked or updated) is traced again. let assets = &doc.assets; doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); + let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); for (asset, threshold) in wanted { - if doc.alpha_outline(asset, threshold).is_some() { + if traced.contains(&(asset, threshold)) { continue; } let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue }; From b1a514fc51606ba4b26390400f38b6abeff97973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:05:16 -0800 Subject: [PATCH 164/328] Paste: ui.paste checks the image's size before decoding it ui.paste {image} refuses base64 longer than the 256 MB file limit before it decodes the data, with the same check edit.pasteImage uses. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/paste_image.rs | 25 ++++++++++++++++++++++--- crates/ui-egui/src/control.rs | 3 +++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 20260a5ad..739072d78 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -378,6 +378,6 @@ pub use file::{ DOCUMENT_SNIFF_BYTES, RecentPreview, base64_decode, base64_encode, from_bytes, is_document, recent_preview, to_bytes, with_document_extension, }; pub use layout::chapter_numbering; -pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_size, pasted_pixels, pasted_png}; +pub use paste_image::{IMAGE_EXTENSIONS, MAX_PASTED_PIXELS, PASTED_IMAGE_NAME, check_pasted_base64, check_pasted_size, pasted_pixels, pasted_png}; pub use paste_svg::is_svg_markup; pub(crate) use place_text::autoflow as place_text_autoflow; diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index b5e1003ac..ec29d78b0 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -47,6 +47,19 @@ pub fn check_pasted_size(width: u32, height: u32) -> std::result::Result<(), Str Ok(()) } +/// Whether an image file given as base64 is small enough to paste, checked before it is +/// decoded; the error says why not. +pub fn check_pasted_base64(b64: &str) -> std::result::Result<(), String> { + check_pasted_base64_len(b64.len()) +} + +fn check_pasted_base64_len(len: usize) -> std::result::Result<(), String> { + if len / 4 * 3 > MAX_PASTED_BYTES { + return Err(format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20)); + } + Ok(()) +} + /// Unpremultiplied RGBA pixels from the clipboard, rows top to bottom, as a PNG file for /// [`edit.pasteImage`](specs). pub fn pasted_png(width: u32, height: u32, rgba: Vec) -> std::result::Result, String> { @@ -80,9 +93,7 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(ID, "`base64` must be a non-empty string")), None => return Err(bad(ID, "missing base64")), }; - if b64.len() / 4 * 3 > MAX_PASTED_BYTES { - return Err(bad(ID, format!("the image is larger than {} MB", MAX_PASTED_BYTES >> 20))); - } + check_pasted_base64(b64).map_err(|e| bad(ID, e))?; let name = match p.get("name") { None | Some(Value::Null) => PASTED_IMAGE_NAME, Some(Value::String(n)) if !n.trim().is_empty() => n.as_str(), @@ -253,6 +264,14 @@ mod tests { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); } + #[test] + fn base64_past_the_file_limit_is_refused_by_its_length() { + let limit = MAX_PASTED_BYTES / 3 * 4; + assert!(check_pasted_base64_len(limit).is_ok()); + let e = check_pasted_base64_len(limit + 4).unwrap_err(); + assert!(e.contains("larger than 256 MB"), "{e}"); + } + #[test] fn a_damaged_image_with_a_whole_header_is_refused() { let mut s = doc(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9a8e23900..0b8fbb6d5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -279,6 +279,9 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest let event = match (s("text"), s("image")) { (Some(text), None) => egui::Event::Paste(text.to_string()), (None, Some(image)) => { + if let Err(e) = designcraft_engine::cmd::check_pasted_base64(image) { + return err(format!("`image`: {e}")); + } let bytes = designcraft_engine::cmd::base64_decode(image); let Some((w, h, rgba)) = designcraft_engine::cmd::pasted_pixels(&bytes) else { return err("`image` is not an image file that can be pasted"); From 1eda04663b84f2aa87a4f72953b99efa9ed97476 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:07:30 -0800 Subject: [PATCH 165/328] Recovery: a clean document stops its background writes; a failed folder sync keeps the snapshot tracked - recovery::save cancels the background writes the session queued for a clean document and removes what a finished one left, so an older snapshot is not published after Undo returns the document to its saved state. - Cancelling a document's writes leaves a write another session queued to follow in place. - When the folder sync fails after the rename, the snapshot is reported as published with the error, so it is tracked and Save or Close removes it. --- crates/engine/src/recovery.rs | 45 ++++++++++- crates/engine/src/recovery/tests.rs | 115 ++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 3b4060763..d6e434a4a 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -580,6 +580,12 @@ pub fn save(s: &Session, dir: &Path) -> Result { for d in &s.docs { // New Document's preview is not a document until Create makes it one. if !d.is_dirty() || s.new_document_preview() == Some(d.uid) { + // A background write this session queued of an older state must not publish after + // this discard, and what one already wrote in another folder is removed too. + #[cfg(not(target_arch = "wasm32"))] + for other in worker::cancel_document(d.uid, s.recovery_owner.0) { + discard(&other, d.uid); + } discard(dir, d.uid); continue; } @@ -762,6 +768,8 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { #[cfg(any(test, feature = "testing"))] testing::gate(&entry.dir); let (doc, meta) = files(&entry.dir, entry.uid); + // Set at the rename: an error after it (syncing the folder) leaves the entry on disk. + let landed = std::cell::Cell::new(false); let published = publish_recovery_written( &doc, entry.own, @@ -774,6 +782,7 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the // rename, so a cleanup after it can remove the entry. || { + landed.set(true); if !entry.own { WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); } @@ -785,6 +794,8 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { // reports an error, which is the cancel's and not a failure. Ok(false) => return Written { published: false, error: None }, Err(_) if cancelled() => return Written { published: false, error: None }, + // Renamed into place, then the folder sync failed: the entry is there to track and clean up. + Err(e) if landed.get() => return Written { published: true, error: Some(e) }, Err(e) => return Written { published: false, error: Some(e) }, } let metadata = json!({"path": entry.path, "title": entry.title, "saved": designcraft_doc::vars::now()}); @@ -1048,10 +1059,15 @@ mod worker { let mut dirs = Vec::new(); if let Ok(mut running) = self.running.lock() { let mut keys = Vec::new(); - for (key, q) in running.iter_mut().filter(|((_, u), q)| *u == uid && q.owner == owner) { - keys.push(key.clone()); - dirs.push(q.dir.clone()); - q.next = None; + for (key, q) in running.iter_mut().filter(|((_, u), _)| *u == uid) { + // A write another session queued to follow stays queued. + if q.next.as_ref().is_some_and(|n| n.owner == owner) { + q.next = None; + } + if q.owner == owner { + keys.push(key.clone()); + dirs.push(q.dir.clone()); + } } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); @@ -1315,6 +1331,23 @@ pub mod testing { w.wait_until_idle(); } } + + static FAIL_SYNC: Mutex> = Mutex::new(None); + + /// Make the next folder sync after a recovery file is renamed into `dir` fail. + pub fn fail_next_sync(dir: &Path) { + *FAIL_SYNC.lock().unwrap_or_else(PoisonError::into_inner) = Some(dir.to_path_buf()); + } + + /// Whether this sync of `dir` is the one [`fail_next_sync`] asked to fail. + pub(super) fn sync_fails(dir: &Path) -> bool { + let mut slot = FAIL_SYNC.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_deref() == Some(dir) { + *slot = None; + return true; + } + false + } } #[cfg(not(target_arch = "wasm32"))] @@ -1460,6 +1493,10 @@ fn is_link_like(metadata: &std::fs::Metadata) -> bool { #[cfg(not(target_arch = "wasm32"))] fn sync_recovery_dir(dir: &Path) -> Result<()> { validate_recovery_dir(dir)?; + #[cfg(any(test, feature = "testing"))] + if testing::sync_fails(dir) { + return Err(EngineError::Other(format!("{}: sync failed", dir.display()))); + } #[cfg(unix)] { diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 4534c3c37..d58f31fd6 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -466,6 +466,121 @@ fn a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { assert!(s.docs[0].recovery_entries.is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_snapshot_whose_folder_sync_failed_is_still_the_documents_to_remove() { + // The rename put the snapshot in place before the folder sync failed: it is tracked, so Save + // removes it. + let root = tempfile::tempdir().unwrap(); + let dir = run_dir(root.path()).unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.clone()); + let uid = s.docs[0].uid; + let (document, _) = files(&dir, uid); + testing::fail_next_sync(&dir); + let err = save_tracked(&mut s, &dir).unwrap_err(); + assert!(err.to_string().contains("sync failed"), "{err}"); + assert!(document.exists(), "the snapshot landed"); + assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && same_directory(d, &dir)), "and is tracked"); + let saved = root.path().join("saved.designcraft"); + s.execute("file.saveAs", &json!({"path": saved.to_string_lossy()})).unwrap(); + assert!(!document.exists(), "Save removed the snapshot"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_undone_to_its_saved_state_while_its_write_is_held_leaves_no_snapshot() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + let held = testing::hold_next_write(dir.path()); + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.docs[0].is_dirty(), "back to the state it had"); + // A save of recovery data now drops the clean document's checkpoint, and the held write of + // the older state must not publish after it. + save(&s, dir.path()).unwrap(); + held.release(); + testing::wait_until_idle(); + assert!(!files(dir.path(), uid).0.exists(), "the older snapshot was not published"); + let _ = s.execute("file.recovery.progress", &json!({})); + assert!(list(dir.path()).is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_document_undone_to_its_saved_state_loses_the_snapshot_a_finished_write_left_in_another_folder() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let other = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(other.path().to_path_buf()); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + // Written, but its result not yet taken by the session. + testing::wait_until_idle(); + assert!(files(other.path(), uid).0.exists()); + s.execute("edit.undo", &json!({})).unwrap(); + save(&s, dir.path()).unwrap(); + assert!(!files(other.path(), uid).0.exists(), "the snapshot of the older state is removed"); + let _ = s.execute("file.recovery.progress", &json!({})); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut a = dirty_session(); + a.recovery_dir = Some(dir.path().to_path_buf()); + let uid = a.docs[0].uid; + let mut b = dirty_session(); + b.recovery_dir = Some(dir.path().to_path_buf()); + b.docs[0].uid = uid; + b.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let held = testing::hold_next_write(dir.path()); + a.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + // A write now cancels the held one; the other session's write is queued to follow it. + a.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); + b.execute("file.recovery.save", &json!({"background": true})).unwrap(); + a.execute("edit.undo", &json!({})).unwrap(); + assert!(!a.docs[0].is_dirty()); + save(&a, dir.path()).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut b), 1, "the other session's write ran"); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 2, "its snapshot was kept"); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_clean_document_in_another_session_leaves_this_sessions_write_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid, clean, in another session. + let mut other = Session::new(); + other.execute("file.new", &json!({})).unwrap(); + other.docs[0].uid = uid; + assert!(!other.docs[0].is_dirty()); + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + save(&other, dir.path()).unwrap(); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "the other session's save did not cancel this write"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_background_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { From 61428f05d9b4981755dfdee2ef99c627d3b666b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:15:31 -0800 Subject: [PATCH 166/328] Compose: Justify keeps later lines out of an object anchored in an earlier line An object anchored in a line that Justify moves goes down with that line. The lines after it now stop where the object ends up, so the last line no longer runs into it. The Bottom tests also check that a wrap that does not stop the text leaves the last line on the text area's bottom. --- crates/compose/src/lib.rs | 89 +++++++++++++++++++++++++------------ crates/compose/src/tests.rs | 22 ++++++++- crates/compose/src/wrap.rs | 6 ++- 3 files changed, 86 insertions(+), 31 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9eaafdc5d..009ba6c68 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -364,6 +364,9 @@ pub struct Exclusion { /// An anchored object in the frame's own story: it wraps only lines that start after this /// story byte (its anchor). pub after: Option, + /// For an anchored object in the frame's own story: the baseline of the line holding its + /// anchor when the exclusion was taken from it. + pub anchor_baseline: Option, } impl Exclusion { @@ -531,7 +534,7 @@ fn wrap_exclusion( if let Some(custom) = wrap.path.as_ref().and_then(|p| Contour::of(&p.to_bezpath(), inv * xf, 0.0)) { let rect = custom.bounds(); let contour = matches!(wrap.mode, WrapMode::BoundingBox | WrapMode::Contour).then_some(custom); - return Exclusion { rect, mode: wrap.mode, side, contour, after: None }; + return Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None }; } let contour = if wrap.mode == WrapMode::Contour { outline() } else { None }.and_then(|(path, frame)| { let c = Contour::of(&path, inv * xf, o[0])?; @@ -541,7 +544,7 @@ fn wrap_exclusion( }) }); let rect = contour.as_ref().map_or_else(|| inv.transform_rect_bbox(r), Contour::bounds); - Exclusion { rect, mode: wrap.mode, side, contour, after: None } + Exclusion { rect, mode: wrap.mode, side, contour, after: None, anchor_baseline: None } } /// The outline a contour wrap of `kind` around frame `it` follows, in the frame's inner space, and @@ -5497,7 +5500,7 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Per column (or all lines together). let ncols = if spanned { 1 } else { ft.columns.len().max(1) as u32 }; for c in 0..ncols { - let rooms = wrap_rooms(ft, f, c, spanned, anchors); + let (rooms, follow) = wrap_rooms(ft, f, c, spanned, anchors); // Center and Bottom move the lines together: the nearest text wrap under them is the // bottom of the room they move down into. Justify checks each row's room below. let raised; @@ -5565,7 +5568,20 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de // Each row moves no further than a text wrap under it allows; every row's // shift grows with the space, so the most space that keeps them all clear is // found by bisection. - let clear = |shift: &[f64]| idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9); + // An object that moves with its anchor's row limits how much further than + // that row a later row moves. + let mut row_of = vec![None; ft.lines.len()]; + for (&i, &k) in idx.iter().zip(&rows) { + row_of[i] = Some(k); + } + let follow: Vec<(usize, usize, f64)> = follow + .iter() + .filter_map(|&(i, a, room)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0)))) + .collect(); + let clear = |shift: &[f64]| { + idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) + && follow.iter().all(|&(k, m, room)| shift[k] - shift[m] <= room + 1e-9) + }; let mut shift = shifts(space); if !clear(&shift) { let (mut lo, mut hi) = (0.0, space); @@ -5627,10 +5643,12 @@ fn wrap_bottom(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, rooms: &[f6 /// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the /// columns it spans) count, as when the lines are set. An anchored object that moves with the /// lines being justified (inline, above the line, or positioned from its anchor and not kept -/// within its column) is skipped, except under Justify. Justify keeps the first row in place, so -/// its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by -/// object index. -fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> Vec { +/// within its column) is skipped, except under Justify, where it moves with the row of its +/// anchor's line: its wrap is taken where the object sits before the lines move, and its rooms go +/// in the second list as (line, anchor's line, room), so a line moves down at most that much +/// further than the anchor's row. Justify keeps the first row in place, so its room stays +/// infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64)>) { const EPS: f64 = 1e-6; // One-sided wraps also block the column on the other side of the object: the x-range wrap // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that @@ -5655,30 +5673,29 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } }; let in_col = |k: u32| spanned || k == c; + let justify = f.opts.vertical_justification == VerticalJustification::Justify; // An own-story anchored object whose anchor is on one of these lines and whose position - // follows its line moves with the text. Justify moves later lines further than earlier ones, - // so there the object's current top still limits the lines after its anchor. - let moves_with_text = |e: &Exclusion| { - let Some(a) = e.after.filter(|_| f.opts.vertical_justification != VerticalJustification::Justify) else { return false }; + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how + // much lower that line was when the wrap was taken (an earlier pass placed the object after + // moving the lines). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { + let a = e.after?; // The object whose mark is the anchor, placed on one of these lines. - let Some(o) = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) else { - return false; - }; - match &o.object.position { + let o = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column)))?; + let follows = match &o.object.position { designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, // Kept within the column, it can stop at the column's edge instead of following. designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column } - } + }; + let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); + follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) }; // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); - let fixed = |line: usize| { - f.opts.vertical_justification == VerticalJustification::Justify - && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9) - }; + let fixed = |line: usize| justify && ft.lines.get(line).zip(first).is_some_and(|(l, b)| (l.baseline - b).abs() <= 1e-9); // (line, story byte, column, slot x-range, top, bottom) of each line (its band runs from its // top to its baseline) and table fragment. let lines = ft @@ -5689,6 +5706,7 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u .map(|(i, l)| (i, l.range.start, l.column, l.x0, l.x1, l.baseline - l.ascent, l.baseline)); let tables = ft.tables.iter().filter(|t| in_col(t.column)).map(|t| (t.line, t.anchor, t.column, t.rect.x0, t.rect.x1, t.rect.y0, t.rect.y1)); let mut rooms = vec![f64::INFINITY; ft.lines.len()]; + let mut follow = Vec::new(); for (line, start, k, x0, x1, top, bottom) in lines.chain(tables) { let Some(&before) = rooms.get(line) else { continue }; if fixed(line) { @@ -5699,8 +5717,18 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; - for e in f.exclusions.iter().filter(|e| e.wraps_line(start) && !moves_with_text(e)) { - let r = e.rect; + for e in f.exclusions.iter().filter(|e| e.wraps_line(start)) { + let anchor = moves_with_text(e); + if anchor.is_some() && !justify { + continue; + } + // The wrap where its object sits before the lines move (moved up by `dy`), and how + // far it lets this line move down (relative to its anchor's row for an object that + // moves with the text). + let dy = anchor.map_or(0.0, |(_, dy)| dy); + let cap = if anchor.is_some() { f64::INFINITY } else { room }; + let mut room_e = f64::INFINITY; + let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; if let (WrapMode::BoundingBox | WrapMode::Contour, Some(contour)) = (e.mode, &e.contour) && r.y1 > top && sided(e, col, (r.x0, r.x1)).is_some_and(meets) @@ -5709,8 +5737,8 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u // contour stays inside its box). Moved down by `d`, the line's band sweeps from its // top to its baseline plus `d`; the contour's extent there only grows with `d`, so // the furthest clear move is found by bisection to 0.01 pt. - let hits = |d: f64| contour.band_extent(top, bottom + d).and_then(|x| sided(e, col, x)).is_some_and(meets); - let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(room)); + let hits = |d: f64| contour.band_extent(top + dy, bottom + d + dy).and_then(|x| sided(e, col, x)).is_some_and(meets); + let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); if lo < hi && hits(hi) { if hits(lo) { hi = lo; @@ -5726,18 +5754,23 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u lo = mid; } } - room = room.min(lo); + room_e = lo; } } else if r.y0 >= bottom - EPS { // A wrap at or under this line. if blocked(e, col).is_some_and(meets) { - room = room.min(r.y0 - bottom); + room_e = r.y0 - bottom; } } + match anchor { + Some((a, _)) if room_e.is_finite() => follow.push((line, a, room_e)), + Some(_) => {} + None => room = room.min(room_e), + } } rooms[line] = room; } - rooms + (rooms, follow) } // ---------- caret and hit testing (Type tool) ---------- diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 4354aeb47..9d7619c14 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -513,6 +513,7 @@ fn hostile_wrap_geometry_terminates() { side: WrapSide::BothSides, contour: None, after: None, + anchor_baseline: None, }; let f = &mut specs[0]; f.exclusions.push(ex(f64::NAN, f64::NAN, f64::NAN, f64::NAN, WrapMode::JumpObject)); @@ -639,12 +640,12 @@ fn vertical_justification_passes_wraps_that_do_not_stop_the_text() { // Wrap off: the number goes down over the bar. let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::None, WrapSide::BothSides, Rect::new(0.0, 150.0, 60.0, 300.0)); assert!(wrap_top.is_none()); - assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + assert!((lines[0].0 + lines[0].1 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); // A bar on the right half from the frame's top: the number is set beside it and goes down // beside it. let (lines, area, wrap_top) = bar_chart_lines("42", Bottom, WrapMode::BoundingBox, WrapSide::BothSides, Rect::new(30.0, 0.0, 60.0, 300.0)); assert!(wrap_top.is_some()); - assert!(lines[0].0 > 150.0 && lines[0].0 <= area.y1 + 1e-6, "{lines:?}"); + assert!((lines[0].0 + lines[0].1 - area.y1).abs() < 1e-6, "{lines:?}, bottom {}", area.y1); } /// A one-sided wrap in the second column leaves the first column's lines free to go down, as it @@ -868,6 +869,23 @@ fn vertical_justify_stops_at_an_object_anchored_above_the_lines_it_wraps() { assert!(last > lines[0].baseline + 40.0, "Justify spread the lines: {:?}", lines.iter().map(|l| l.baseline).collect::>()); } +/// Justify moves an object anchored in the second line with that line, so the third line spreads +/// down until it meets the object where it ends up, not where it started. +#[test] +fn vertical_justify_follows_an_object_anchored_in_a_later_line() { + let (mut d, sid, fid) = doc_with("One\nTwo\nSix", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + anchor_box(&mut d, sid, 5, 0.0, 40.0, true, WrapMode::BoundingBox); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 3); + let baselines = lines.iter().map(|l| l.baseline).collect::>(); + let top = cs.frames[0].objects[0].origin.y; + assert!((top - lines[1].baseline - 40.0).abs() < 1e-6, "the object hangs 40 pt under the second line: {top}, {baselines:?}"); + let last = lines[2].baseline; + assert!((top - last).abs() < 1e-6, "Justify moved the last line to {last}, not down to the object at {top}: {baselines:?}"); +} + /// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens /// downwards, text reaches further in at the narrow top than at the wide bottom. #[test] diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index f28bba424..a8495bd46 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -46,6 +46,8 @@ pub(crate) struct Obstacle<'a> { xf: Affine, /// Story byte of the anchor, for obstacles in their own story. anchor: Option, + /// Baseline of the line holding the anchor, for obstacles in their own story. + anchor_baseline: Option, } fn wraps(o: &AnchoredObject) -> bool { @@ -126,7 +128,8 @@ pub(crate) fn obstacles<'a>(doc: &Document, story: &'a Story, cs: &ComposedStory } else { None }; - out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor }); + let anchor_baseline = anchor.and_then(|_| ft.lines.get(o.line)).map(|l| l.baseline); + out.push(Obstacle { spread: loc.spread, item: &obj.item, xf, anchor, anchor_baseline }); } } out @@ -157,6 +160,7 @@ pub(crate) fn exclusions(doc: &Document, specs: &[FrameSpec], obs: &[Obstacle]) let r = e.rect; if r.is_finite() && r.x0 < a.x1 && r.x1 > a.x0 && r.y0 < a.y1 && r.y1 > a.y0 { e.after = ob.anchor; + e.anchor_baseline = ob.anchor_baseline; ex.push(e); } } From 23eb593498364037fb7d95a5efc052ae1b07799f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:18:21 -0800 Subject: [PATCH 167/328] Render: the feather test checks the inner effects still draw inside The edge comparisons pass when a bevel or inner glow is not drawn at all. A pixel inside the bevel and glow bands now has to differ from the same object without the effect, for every feather kind. --- crates/render/src/fx.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index f9b40ba9b..8fd4b0d1d 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -736,6 +736,16 @@ mod tests { ); } } + // Inside the bevel and glow bands the effect still shows, faded with the object + // where the feather reaches. + let inside = px(&plain, threads, 110); + for inner in [1, 2] { + let with = px(&doc(image, feather, inner), threads, 110); + assert!( + diff(with, inside) > 0, + "image {image} feather {feather} inner {inner} threads {threads}: {with:?} at 110, {inside:?} without the effect" + ); + } } } } From d20ffcc055aab088e7c25af259c73f5fdbbfd4db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:23:34 -0800 Subject: [PATCH 168/328] Render: satin on an image follows its painted edge Satin on a frame holding an image used the frame's shape. Where the image is transparent, the satin color multiplied over whatever lay behind the frame, so text under a transparent part of the image turned darker. Satin now builds its two offset copies from what the object paints and keeps the result to the painted pixels, as the inner shadow, inner glow and bevel already do. --- crates/render/src/fx.rs | 118 ++++++++++++++++++++++++++++++++-------- 1 file changed, 94 insertions(+), 24 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..501333471 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -287,6 +287,7 @@ impl Renderer { } } // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. + // With a graphic, the shape is what the object paints, as for the inner shadow. if e.satin.on && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) { @@ -295,25 +296,56 @@ impl Renderer { let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { + // One copy of the shape moved by `by`: the shape in the satin colour, or what the + // object paints (coloured below). + let copy = |me: &mut Renderer, c: &mut RenderContext, by: Vec2| match painted { + Some((it, page)) => { + let moved = Frame { view: fr.view * Affine::translate(by), ..*fr }; + me.draw_body(c, &moved, it, bp, xf, page); + } + None => { + c.set_transform(fr.view * Affine::translate(by) * xf); + c.set_paint(paint); + c.fill_path(bp); + } + }; c.set_transform(fr.view); + if painted.is_some() { + c.push_layer(None, None, None, None, None); + } c.push_layer(None, None, None, None, Some(blur(sigma))); + if painted.is_some() { + c.push_layer(None, None, None, None, None); + } if invert { - c.set_transform(fr.view * xf); - c.set_paint(paint); - c.fill_path(bp); + copy(me, c, Vec2::ZERO); } c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - c.set_transform(fr.view * Affine::translate(off) * xf); - c.set_paint(paint); - c.fill_path(bp); + copy(me, c, off); c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - c.set_transform(fr.view * Affine::translate(-off) * xf); - c.fill_path(bp); + copy(me, c, -off); c.pop_layer(); c.pop_layer(); + if let Some((it, page)) = painted { + // The satin colour where the copies cover, ... + let pad = sigma * 4.0 + off.hypot() + 4.0 * fr.px; + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); + c.set_transform(fr.view); + c.set_paint(paint); + c.fill_rect(&reach.inflate(pad, pad)); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + // ... blurred and kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + } c.pop_layer(); }); } @@ -548,8 +580,52 @@ mod tests { /// lines the image's opaque part (its edge in the middle of the frame), not only the frame. #[test] fn an_inner_shadow_follows_a_transparent_images_edge() { + let (d, mut it) = half_image_frame(); + let s = &mut it.effects.inner_shadow; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.distance = 0.0; + s.size = 20.0; + let lum = render_row(d, it); + // The image's opaque part starts at x = 200: just inside it the shadow darkens it; in its + // middle (x = 250, 50 pt from every edge but the frame's right one) it stays light. + assert!(lum(204) + 60 < lum(250), "shadow at the image's own edge: {} vs {}", lum(204), lum(250)); + // The transparent half shows the page: no shadow painted there. + assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + } + + /// Satin on a frame holding an image whose left half is transparent multiplies only over the + /// image's opaque part, plain or inverted: the page shows through the transparent half. + #[test] + fn satin_follows_a_transparent_images_edge() { + for invert in [false, true] { + let (d, mut it) = half_image_frame(); + let s = &mut it.effects.satin; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.angle = 0.0; + s.distance = 100.0; + s.size = 4.0; + s.invert = invert; + let lum = render_row(d, it); + // The copies are 50 pt to each side. Over the frame they leave the satin on 100 to 150 + // (plain) or 150 to 250 (inverted), over the transparent half of the image. + let clear = if invert { 175 } else { 125 }; + assert!(lum(clear) > 700, "invert {invert}: satin over the transparent part at x = {clear}: {}", lum(clear)); + // Over the image's opaque part the copies (150 to 250 and 250 to 350) leave plain satin on + // all of it and inverted satin on none of it. + let shaded = lum(225) < 100; + assert_eq!(shaded, !invert, "invert {invert}: lum at x = 225 is {}", lum(225)); + } + } + + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an + /// opaque white right half, in a new document. + fn half_image_frame() -> (designcraft_doc::Document, Item) { + use designcraft_doc::Document; use designcraft_doc::build::NewDocument; - use designcraft_doc::{Document, SpreadRef}; let mut d = Document::new(&NewDocument::default()); let lid = d.default_layer(); // 20 × 20: transparent left half, opaque white right half. @@ -586,25 +662,19 @@ mod tests { wrap: Default::default(), fill: Default::default(), }); - let s = &mut it.effects.inner_shadow; - s.on = true; - s.color = "[Black]".into(); - s.opacity = 1.0; - s.distance = 0.0; - s.size = 20.0; - d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + (d, it) + } + + /// The first page with `it` added, rendered at 100%: the sum of R, G and B at x on row 200. + fn render_row(mut d: designcraft_doc::Document, it: Item) -> impl Fn(u32) -> u32 { + d.insert_item(designcraft_doc::SpreadRef::Doc(0), it, None).unwrap(); let cache = crate::Cache::new(); let mut r = Renderer::new(); r.threads = 0; let page = r.render_page(&d, &cache, 0, 1.0, false, &crate::RenderOptions::default()).unwrap(); - let lum = |x: u32| { + move |x: u32| { let p = page.pixel(x, 200); u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]) - }; - // The image's opaque part starts at x = 200: just inside it the shadow darkens it; in its - // middle (x = 250, 50 pt from every edge but the frame's right one) it stays light. - assert!(lum(204) + 60 < lum(250), "shadow at the image's own edge: {} vs {}", lum(204), lum(250)); - // The transparent half shows the page: no shadow painted there. - assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + } } } From c9cc76e6ad2b568981652e96fb4344065f2633e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:45:44 -0800 Subject: [PATCH 169/328] CMYK view: the conversion returns the number of bands it converted With more render threads than bands of 32 rows fit evenly, the rows split into fewer bands than requested, and the returned count was the requested one. It is now the number of bands converted. --- crates/render/src/blendspace.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 1d992c6fd..4eafc1d89 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -285,7 +285,7 @@ fn srgb_in(table: &[[f32; 3]], cmyk: [f32; 4]) -> [f32; 3] { out } -/// Rows of the ink passes' area one conversion thread takes at least. +/// Rows of the ink passes' area one conversion thread takes at least; the last band can hold fewer. const MIN_BAND_ROWS: usize = 32; /// The blended inks, the C/M/Y complements in `cmy` and the K complement in `black` (`width` @@ -334,7 +334,7 @@ fn inks_to_screen(cmy: &mut [PremulRgba8], black: &[PremulRgba8], width: usize, convert(c, k); } } - bands + parts.len() } impl Renderer { @@ -742,6 +742,18 @@ mod tests { assert_eq!(four.pixels, one.pixels); } + /// The returned count is the number of bands converted: 1,281 rows on 40 threads split into + /// bands of 33 rows, which makes 39 bands. + #[test] + fn ink_conversion_returns_the_bands_it_converted() { + let rows = 1281; + let mut cmy = vec![PremulRgba8 { r: 0, g: 255, b: 255, a: 255 }; rows]; + let black = vec![PremulRgba8 { r: 255, g: 255, b: 255, a: 255 }; rows]; + assert_eq!(inks_to_screen(&mut cmy, &black, 1, false, 40), 39); + assert!(cmy.iter().all(|c| *c == cmy[0]), "every band is converted"); + assert_ne!(cmy[0], PremulRgba8 { r: 0, g: 255, b: 255, a: 255 }); + } + #[test] fn cmyk_nonseparable_modes_use_the_existing_rgb_approximation() { let mut doc = document(); From 7a5924e971b82043b5619dbb212c544d238fbbe0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 22:52:07 -0800 Subject: [PATCH 170/328] Render: center inner glow on an image follows its painted edge Inner glow from the center on a frame holding an image filled the frame's shape, so it painted over the transparent parts of the image. It now draws the object's coverage once offscreen, shrinks it by the glow's band, colors and blurs it, and keeps the result to the painted pixels. Partly transparent pixels keep their coverage. --- crates/render/src/fx.rs | 99 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 501333471..6e49577e4 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -265,7 +265,48 @@ impl Renderer { let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma }; let mix = crate::blend_mode(g.mode).mix; let paint = color_of(&c, g.opacity.clamp(0.0, 1.0)); - if g.center { + if g.center + && let Some((it, page)) = painted + { + // With a graphic, the glow fills what the object paints, shrunk by the band: the + // object's coverage is drawn once offscreen and eroded by the band there. + let band = (bound(g.size) - choke).max(0.5); + self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { + let spread = (sigma * 3.0 + band) / fr.px + 2.0; + let Some(o) = offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); + let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; + me.draw_body(&mut off, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); + off.flush(); + let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + off.render(&mut pm, &mut me.resources); + let mask = erode(&pm, band / (fr.px * o.scale)); + // The eroded coverage in the glow color, ... + c.set_transform(fr.view); + c.push_layer(None, None, None, None, None); + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); + c.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(mask)), + sampler: peniko::ImageSampler::default(), + }); + c.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); + let pad = sigma * 4.0 + band + 4.0 * fr.px; + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); + c.set_transform(fr.view); + c.set_paint(paint); + c.fill_rect(&reach.inflate(pad, pad)); + c.pop_layer(); + c.pop_layer(); + // ... blurred and kept only where the object paints. + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); + me.draw_body(c, fr, it, bp, xf, page); + c.pop_layer(); + c.pop_layer(); + }); + } else if g.center { self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| { c.set_transform(fr.view); c.push_layer(None, None, None, None, Some(blur(sigma))); @@ -542,6 +583,30 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option= 1.0 && h >= 1.0).then_some(Offscreen { x0, y0, scale, width: w as u16, height: h as u16 }) } +/// `pm`'s coverage shrunk by `r` pixels: each pixel takes the smallest alpha among itself and the +/// points on circles of `r` and `r / 2` around it, as white premultiplied by that alpha. Pixels +/// outside `pm` count as transparent. +fn erode(pm: &vello_cpu::Pixmap, r: f64) -> vello_cpu::Pixmap { + let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); + let src = pm.data(); + let mut taps = vec![(0_i64, 0_i64)]; + for k in 0..16_u8 { + let d = if k % 2 == 0 { r } else { r / 2.0 }; + let a = f64::from(k) * std::f64::consts::PI / 8.0; + taps.push(((a.cos() * d).round() as i64, (a.sin() * d).round() as i64)); + } + taps.dedup(); + let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0 } else { src[(y * w + x) as usize].a }; + let mut data = Vec::with_capacity(src.len()); + for y in 0..h { + for x in 0..w { + let a = taps.iter().map(|&(dx, dy)| alpha(x.saturating_add(dx), y.saturating_add(dy))).min().unwrap_or(0); + data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + } + } + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + #[cfg(test)] mod tests { #[test] @@ -621,6 +686,38 @@ mod tests { } } + /// An inner glow from the center on a frame holding an image whose left half is transparent + /// fills only the image's opaque part, fading toward that part's own edge. + #[test] + fn a_center_inner_glow_follows_a_transparent_images_edge() { + let (d, mut it) = half_image_frame(); + let g = &mut it.effects.inner_glow; + g.on = true; + g.center = true; + g.color = "[Black]".into(); + g.opacity = 1.0; + g.size = 20.0; + g.mode = Default::default(); + let lum = render_row(d, it); + // The transparent half shows the page: no glow painted there. + assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); + // The opaque part runs from x = 200 to 300: dark in its middle, light at its own left edge. + assert!(lum(250) + 60 < lum(204), "glow fades toward the image's own edge: {} vs {}", lum(250), lum(204)); + } + + /// Eroding keeps a half-transparent area at half coverage away from its edge and clears the + /// band along the edge. + #[test] + fn erosion_keeps_partial_coverage_and_clears_the_edge_band() { + let half = vello_cpu::color::PremulRgba8 { r: 128, g: 128, b: 128, a: 128 }; + let pm = vello_cpu::Pixmap::from_parts(vec![half; 40 * 40], 40, 40); + let out = erode(&pm, 5.0); + assert_eq!(out.sample(20, 20).a, 128); + assert_eq!(out.sample(2, 20).a, 0); + assert_eq!(out.sample(20, 37).a, 0); + assert_eq!(out.sample(6, 20).a, 128); + } + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { From c4b2d730627ac1e8e1bc8b1f8c14411a66afa663 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:02:32 -0800 Subject: [PATCH 171/328] Recovery: a shared folder's entry is removed or replaced only by the session that wrote it Entries written or recovered in a recovery folder that is not the run's own were tracked per folder and uid only, so another session in the same process with a document of that uid could replace or remove them; a recovered entry keeps the uid it was written under. Each entry now carries the session that wrote or recovered it, and only that session may replace or remove it. A write queued while its entry was the session's is recorded again when it lands, so a cleanup that dropped the record in between no longer leaves the snapshot on disk after Save. --- crates/engine/src/recovery.rs | 77 ++++++++++++++++++----------- crates/engine/src/recovery/tests.rs | 59 +++++++++++++++++++++- 2 files changed, 104 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index d6e434a4a..f7f4dcda2 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -272,30 +272,39 @@ fn relock(dir: &Path, created: bool) -> Result { } /// Entries this process wrote or recovered in folders that are not its run's own: (canonical -/// folder, uid). Document uids start at 1 in every process, so a shared folder's entry under -/// one of this run's uids may be another run's. -static WRITTEN: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); +/// folder, uid), with the session that wrote or recovered each ([`Session::recovery_owner`]). +/// Document uids start at 1 in every process, so a shared folder's entry under one of this run's +/// uids may be another run's; and a recovered entry keeps the uid it was written under, which a +/// document of another session can have. +static WRITTEN: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); -/// What this run may do in a recovery folder. +/// What a session may do in a recovery folder. struct Access { /// This run's own folder (`run_dir`): every entry in it is this run's. own: bool, key: PathBuf, + /// The session asking ([`Session::recovery_owner`]). + owner: u64, } impl Access { fn owns(&self, uid: u64) -> bool { - self.own || WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&(self.key.clone(), uid)) + self.own || WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&(self.key.clone(), uid)) == Some(&self.owner) } fn record(&self, uid: u64) { if !self.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((self.key.clone(), uid)); + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((self.key.clone(), uid), self.owner); } } + /// Drop the record of an entry this session wrote or recovered; another session's stays. fn forget(&self, uid: u64) { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&(self.key.clone(), uid)); + let mut written = WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let key = (self.key.clone(), uid); + if written.get(&key) == Some(&self.owner) { + written.remove(&key); + } } /// Refuse an entry of another run before anything is written: this run never replaces it. @@ -319,9 +328,9 @@ impl Access { } } -/// Check what this run may do in `dir`. A folder that is not this run's own may be the folder -/// of another running app, whose lock that app holds: this run leaves it alone. -fn access(dir: &Path, created: bool) -> Result { +/// Check what session `owner` may do in `dir`. A folder that is not this run's own may be the +/// folder of another running app, whose lock that app holds: this run leaves it alone. +fn access(dir: &Path, created: bool, owner: u64) -> Result { #[cfg(not(target_arch = "wasm32"))] let own = relock(dir, created)?; #[cfg(not(target_arch = "wasm32"))] @@ -333,7 +342,7 @@ fn access(dir: &Path, created: bool) -> Result { let _ = created; false }; - Ok(Access { own, key: directory_key(dir)? }) + Ok(Access { own, key: directory_key(dir)?, owner }) } #[cfg(not(target_arch = "wasm32"))] @@ -485,13 +494,13 @@ fn read_entry_file(path: &Path) -> std::io::Result> { } /// Remove a document's recovery entry (it was saved or closed). In a folder that is not this -/// run's own, only an entry this run wrote or recovered is removed. -pub fn discard(dir: &Path, uid: u64) { +/// run's own, only an entry session `owner` wrote or recovered is removed. +pub fn discard(dir: &Path, uid: u64, owner: u64) { #[cfg(not(target_arch = "wasm32"))] if validate_recovery_dir(dir).is_err() { return; } - let Ok(access) = access(dir, false) else { return }; + let Ok(access) = access(dir, false, owner) else { return }; if !access.owns(uid) { return; } @@ -504,6 +513,7 @@ pub fn discard(dir: &Path, uid: u64) { /// Consume this document's checkpoint provenance after Save/Close/Revert. A default-directory /// uid may also be another live recovered document's retained source after a failed republish. pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Option<&Path>) { + let owner = s.recovery_owner.0; let Some(doc) = s.docs.get_mut(index) else { return }; let uid = doc.uid; // A completed Save/Close/Revert consumes the provenance, even when removal fails. A stale @@ -518,7 +528,7 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio // `file.recovery.save {dir}` is not in its entries until the write's result is taken): none // may publish after this point, and what one already published is removed below. #[cfg(not(target_arch = "wasm32"))] - for dir in worker::cancel_document(uid, s.recovery_owner.0) { + for dir in worker::cancel_document(uid, owner) { if !entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) { entries.push((dir, uid)); } @@ -532,7 +542,7 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio // A write of it still running must not publish its snapshot after this point. #[cfg(not(target_arch = "wasm32"))] worker::cancel(&dir, uid); - discard(&dir, uid); + discard(&dir, uid, owner); } } } @@ -563,7 +573,7 @@ fn prepare_save(s: &Session, dir: &Path) -> Result { // coincides with an unrelated live document in a manually configured recovery directory. protect_retained_sources(s, dir)?; let created = secure_recovery_dir(dir)?; - let access = access(dir, created)?; + let access = access(dir, created, s.recovery_owner.0)?; // New Document's preview is never written. let preview = s.new_document_preview(); for document in s.docs.iter().filter(|d| d.is_dirty() && preview != Some(d.uid)) { @@ -584,9 +594,9 @@ pub fn save(s: &Session, dir: &Path) -> Result { // this discard, and what one already wrote in another folder is removed too. #[cfg(not(target_arch = "wasm32"))] for other in worker::cancel_document(d.uid, s.recovery_owner.0) { - discard(&other, d.uid); + discard(&other, d.uid, s.recovery_owner.0); } - discard(dir, d.uid); + discard(dir, d.uid, s.recovery_owner.0); continue; } // The caller asked for this write now: nothing has cancelled it. @@ -676,7 +686,9 @@ struct Snapshot { title: String, /// Whether this run may replace an entry already in the folder. own: bool, - /// The folder's canonical key, for recording that a shared entry is this run's now. + /// The folder is not this run's own: the entry, once written, is recorded as the session's. + shared: bool, + /// The folder's canonical key, for recording that a shared entry is this session's now. key: PathBuf, /// The session that queued a background write ([`Session::recovery_owner`]), which takes its /// result. @@ -716,8 +728,9 @@ impl Snapshot { title: d.title(), // An entry this run did not write is never replaced, even one made since it checked. own: access.owns(d.uid), + shared: !access.own, key: access.key.clone(), - owner: 0, + owner: access.owner, } } } @@ -778,13 +791,15 @@ fn write_snapshot(entry: &Snapshot, cancelled: impl Fn() -> bool) -> Written { designcraft_format::write(&mut StopWhen { out, cancelled: &cancelled }, &entry.doc, None).map_err(|e| EngineError::Other(e.to_string())) }, &cancelled, - // Written: in a folder that is not this run's own, the entry is now this run's to replace - // and remove (Save and Close must clean up the snapshot they wrote). Recorded with the - // rename, so a cleanup after it can remove the entry. + // Written: in a folder that is not this run's own, the entry is now this session's to + // replace and remove (Save and Close must clean up the snapshot they wrote). Recorded with + // the rename, so a cleanup after it can remove the entry, and recorded even when the + // entry was this session's as the write was queued: a cleanup since may have dropped that + // record. || { landed.set(true); - if !entry.own { - WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid)); + if entry.shared { + WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert((entry.key.clone(), entry.uid), entry.owner); } }, ); @@ -867,6 +882,7 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { /// whether a checkpoint was recorded. #[cfg(not(target_arch = "wasm32"))] fn record_checkpoint(s: &mut Session, dir: PathBuf, uid: u64) -> bool { + let owner = s.recovery_owner.0; match s.docs.iter_mut().find(|doc| doc.uid == uid) { Some(doc) if doc.is_dirty() => { if !has_checkpoint(doc, &dir) { @@ -878,7 +894,7 @@ fn record_checkpoint(s: &mut Session, dir: PathBuf, uid: u64) -> bool { // crash, and the timer writes only when a document is dirty, so nothing else would // remove it. Some(_) | None => { - discard(&dir, uid); + discard(&dir, uid, owner); false } } @@ -1604,10 +1620,11 @@ pub fn open(s: &mut Session, dir: &Path) -> Result> { fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Path, &[u8]) -> Result<()>) -> Result> { #[cfg(not(target_arch = "wasm32"))] validate_recovery_dir(dir)?; - let source = access(dir, false)?; + let owner = s.recovery_owner.0; + let source = access(dir, false, owner)?; let destination = s.recovery_dir.clone().unwrap_or_else(|| dir.to_path_buf()); let created = secure_recovery_dir(&destination)?; - let target = access(&destination, created)?; + let target = access(&destination, created, owner)?; let source_key = source.key.clone(); let destination_key = target.key.clone(); let mut opened = Vec::new(); @@ -1665,7 +1682,7 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat let meta = json!({"path": state.path, "title": state.title(), "saved": designcraft_doc::vars::now()}); match publish(&metadata, meta.to_string().as_bytes()) { Ok(()) => { - discard(dir, uid); + discard(dir, uid, owner); state.recovery_entries = vec![(destination.clone(), state.uid)]; } Err(e) => log::warn!("recovery entry {uid} kept: {e}"), diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index d58f31fd6..1a4881a1d 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -1,5 +1,12 @@ use super::*; +/// [`super::discard`] as the session that wrote or recovered the entry, if one did. +fn discard(dir: &Path, uid: u64) { + let key = directory_key(dir).ok().map(|key| (key, uid)); + let owner = key.and_then(|key| WRITTEN.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key).copied()); + super::discard(dir, uid, owner.unwrap_or(0)); +} + fn dirty_session() -> Session { let mut session = Session::new(); session.execute("file.new", &json!({})).unwrap(); @@ -440,6 +447,51 @@ fn a_snapshot_that_finishes_after_the_save_is_dropped() { assert!(s.docs[0].recovery_entries.iter().any(|(d, u)| *u == uid && d == dir.path())); } +#[test] +fn a_shared_folders_entry_is_only_its_writing_sessions() { + // A recovered entry keeps the uid it was written under, which a document of another session + // in the same process can have. + let dir = tempfile::tempdir().unwrap(); + let writer = dirty_session(); + let uid = writer.docs[0].uid; + assert_eq!(save(&writer, dir.path()).unwrap(), 1); + let (file, _) = files(dir.path(), uid); + let snapshot = std::fs::read(&file).unwrap(); + // Another session's clean document with that uid: its discard leaves the entry alone. + let mut clean = Session::new(); + clean.execute("file.new", &json!({})).unwrap(); + clean.docs[0].uid = uid; + assert_eq!(save(&clean, dir.path()).unwrap(), 0); + assert!(file.exists(), "another session's discard removed the entry"); + // Another session's edited document with that uid: it does not write over the entry. + let mut edited = dirty_session(); + edited.docs[0].uid = uid; + assert!(save(&edited, dir.path()).is_err()); + assert_eq!(std::fs::read(&file).unwrap(), snapshot, "another session wrote over the entry"); + super::discard(dir.path(), uid, writer.recovery_owner.0); + assert!(!file.exists(), "the writing session removes its entry"); +} + +#[test] +fn a_snapshot_queued_as_the_sessions_own_is_recorded_when_it_lands() { + // A write taken while the shared folder's entry was this session's, published after a cleanup + // dropped that record: Save and Close must still remove what it put there. + let dir = tempfile::tempdir().unwrap(); + let s = dirty_session(); + let uid = s.docs[0].uid; + let owner = s.recovery_owner.0; + assert_eq!(save(&s, dir.path()).unwrap(), 1); + let entry = Snapshot::of(&prepare_save(&s, dir.path()).unwrap(), dir.path(), &s.docs[0]); + assert!(entry.own); + super::discard(dir.path(), uid, owner); + let (file, _) = files(dir.path(), uid); + assert!(!file.exists()); + let written = write_snapshot(&entry, || false); + assert!(written.published && written.error.is_none(), "the snapshot landed"); + super::discard(dir.path(), uid, owner); + assert!(!file.exists(), "the snapshot it wrote is the session's to remove"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_snapshot_whose_metadata_failed_is_still_the_documents_to_remove() { @@ -544,12 +596,15 @@ fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { let held = testing::hold_next_write(dir.path()); a.execute("file.recovery.save", &json!({"background": true})).unwrap(); held.wait_until_held(); - // A write now cancels the held one; the other session's write is queued to follow it. + // A write now cancels the held one. The other session does not write over the entry it left. a.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap(); - b.execute("file.recovery.save", &json!({"background": true})).unwrap(); + let err = b.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("did not write"), "{err}"); a.execute("edit.undo", &json!({})).unwrap(); assert!(!a.docs[0].is_dirty()); save(&a, dir.path()).unwrap(); + // Once that entry is gone, the other session's write is queued to follow the held one. + b.execute("file.recovery.save", &json!({"background": true})).unwrap(); held.release(); assert_eq!(finished_writes(&mut b), 1, "the other session's write ran"); let mut reopened = Session::new(); From b9cba43f89cdaa574a1a1b40248bb3b67225eaa9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:09:49 -0800 Subject: [PATCH 172/328] Recovery: closing or saving a document cancels only its own session's background writes Discarding a document's recovery entries cancelled every background write of that uid in the folder, so another session's write of a document with the same uid was dropped without a replacement. The cancel now covers only writes the session itself queued. --- crates/engine/src/recovery.rs | 32 ++++++++++++++++++++--------- crates/engine/src/recovery/tests.rs | 24 ++++++++++++++++++++++ 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index f7f4dcda2..2a0422417 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -539,9 +539,10 @@ pub(crate) fn discard_document(s: &mut Session, index: usize, default_dir: Optio if !s.docs.iter().enumerate().any(|(other_index, owner)| { other_index != index && owner.recovery_entries.iter().any(|(entry_dir, entry_uid)| *entry_uid == uid && same_directory(entry_dir, &dir)) }) { - // A write of it still running must not publish its snapshot after this point. + // A write of it this session still runs must not publish its snapshot after this + // point; another session's write of the same uid is its own. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(&dir, uid); + worker::cancel_owned(&dir, uid, owner); discard(&dir, uid, owner); } } @@ -1041,22 +1042,26 @@ mod worker { /// Do not publish the snapshot being written for `dir`/`uid`: the document was saved, /// reverted or closed. Only a write that is queued or running is marked, so the set stays - /// as small as the work in flight. - fn cancel(&self, dir: &Path, uid: u64) { + /// as small as the work in flight. With `owner`, only writes that session queued are + /// marked: another session's write of the same uid stays. + fn cancel(&self, dir: &Path, uid: u64, owner: Option) { let canonical = key(dir, uid); + let mine = |queued_by: u64| owner.is_none_or(|owner| owner == queued_by); // A rename under way finishes first, so the caller's cleanup comes after it; a later // one sees the mark. let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); // The folder's canonical path, or its name as given: a link in the path may lead // elsewhere now than when the write was queued. let Ok(mut running) = self.running.lock() else { return }; - let keys: Vec<(PathBuf, u64)> = - running.iter().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)).map(|(k, _)| k.clone()).collect(); - // A write queued to follow it is older than what the caller has now, too. - for k in &keys { - if let Some(q) = running.get_mut(k) { + let mut keys = Vec::new(); + for (k, q) in running.iter_mut().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) { + // A write queued to follow it is older than what the caller has now, too. + if q.next.as_ref().is_some_and(|n| mine(n.owner)) { q.next = None; } + if mine(q.owner) { + keys.push(k.clone()); + } } if let Ok(mut cancelled) = self.cancelled.lock() { cancelled.extend(keys); @@ -1181,7 +1186,14 @@ mod worker { /// Do not publish the snapshot being written for `dir`/`uid` (see [`Writer::cancel`]). pub(super) fn cancel(dir: &Path, uid: u64) { if let Some(w) = started() { - w.cancel(dir, uid); + w.cancel(dir, uid, None); + } + } + + /// [`cancel`] for the writes session `owner` queued. + pub(super) fn cancel_owned(dir: &Path, uid: u64, owner: u64) { + if let Some(w) = started() { + w.cancel(dir, uid, Some(owner)); } } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 1a4881a1d..d1d03f162 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -312,6 +312,30 @@ fn saving_in_one_session_leaves_another_sessions_write_alone() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn saving_in_one_session_leaves_another_sessions_write_to_the_same_folder_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid and recovery folder in another session. + let mut other = dirty_session(); + other.recovery_dir = Some(dir.path().to_path_buf()); + other.docs[0].uid = uid; + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let elsewhere = tempfile::tempdir().unwrap(); + other.execute("file.saveAs", &json!({"path": elsewhere.path().join("other.designcraft").to_string_lossy()})).unwrap(); + assert!(!worker::cancelled(dir.path(), uid), "the other session's save cancelled this write"); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + assert!(files(dir.path(), uid).0.exists(), "this session's snapshot was kept"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { From c3a7deb21a34dc119198318049bff119aa32694a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:23:50 -0800 Subject: [PATCH 173/328] Render: satin on an image compares partial coverage Satin on a frame holding a graphic draws the object's coverage once offscreen and compares the two shifted copies pixel by pixel, taking the difference of their coverages. A partly transparent area that both copies cover equally gets no plain satin, so a uniformly half-transparent image no longer shows satin across its middle. Inverted satin keeps the object's coverage where the copies agree. The offscreen coverage for satin and for a center inner glow on a graphic now covers its whole area at a lower resolution when it would be wider than the largest raster side or hold more than 4096 x 4096 pixels. --- crates/render/src/fx.rs | 204 +++++++++++++++++++++++++++++++--------- 1 file changed, 162 insertions(+), 42 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 6e49577e4..ec4e1e60a 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -13,7 +13,8 @@ //! opacity rides on the filter colour's alpha. //! - Inner shadow: the inverse of the offset shape, blurred, clipped to the shape, on top. //! - Inner glow, bevel and emboss, satin: built like the inner shadow (an offset inverse of the -//! shape, blurred and clipped) with screen / multiply blending; satin XORs two offset copies. +//! shape, blurred and clipped) with screen / multiply blending; satin shows where two offset +//! copies' coverages differ. //! - Feather: the object is masked by its shape inset by half the width and blurred, so the //! edge fades from ~0 at the path to full strength `width` inside. @@ -273,7 +274,7 @@ impl Renderer { let band = (bound(g.size) - choke).max(0.5); self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |me, c, fr| { let spread = (sigma * 3.0 + band) / fr.px + 2.0; - let Some(o) = offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let Some(o) = mask_offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; let mut off = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; me.draw_body(&mut off, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); @@ -337,41 +338,32 @@ impl Renderer { let sigma = bound(st.size).max(0.0) / 2.0; let paint = color_of(&c, st.opacity.clamp(0.0, 1.0)); let invert = st.invert; - self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { - // One copy of the shape moved by `by`: the shape in the satin colour, or what the - // object paints (coloured below). - let copy = |me: &mut Renderer, c: &mut RenderContext, by: Vec2| match painted { - Some((it, page)) => { - let moved = Frame { view: fr.view * Affine::translate(by), ..*fr }; - me.draw_body(c, &moved, it, bp, xf, page); - } - None => { - c.set_transform(fr.view * Affine::translate(by) * xf); - c.set_paint(paint); - c.fill_path(bp); - } - }; - c.set_transform(fr.view); - if painted.is_some() { + if let Some((it, page)) = painted { + // With a graphic, the object's coverage is drawn once offscreen and the two shifted + // copies are compared there, pixel by pixel, so a partly transparent pixel that + // both copies cover equally gets no satin. + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |me, c, fr| { + // The copies' shift on the device. + let shift = fr.view * off.to_point() - fr.view * kurbo::Point::ZERO; + let spread = (sigma * 3.0) / fr.px + shift.hypot() + 2.0; + let Some(o) = mask_offscreen(fr.view.transform_rect_bbox(reach), spread, c.width(), c.height()) else { return }; + let mut off_ctx = RenderContext::new_with(o.width, o.height, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); + let view = Affine::scale(1.0 / o.scale) * Affine::translate((-o.x0, -o.y0)) * fr.view; + me.draw_body(&mut off_ctx, &Frame { mt: false, view, px: fr.px * o.scale, ..*fr }, it, bp, xf, page); + off_ctx.flush(); + let mut pm = vello_cpu::Pixmap::new(o.width, o.height); + off_ctx.render(&mut pm, &mut me.resources); + let mask = satin_mask(&pm, shift / o.scale, invert); + // The satin colour where the copies differ, ... + c.set_transform(fr.view); c.push_layer(None, None, None, None, None); - } - c.push_layer(None, None, None, None, Some(blur(sigma))); - if painted.is_some() { - c.push_layer(None, None, None, None, None); - } - if invert { - copy(me, c, Vec2::ZERO); - } - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); - copy(me, c, off); - c.set_transform(Affine::IDENTITY); - c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); - copy(me, c, -off); - c.pop_layer(); - c.pop_layer(); - if let Some((it, page)) = painted { - // The satin colour where the copies cover, ... + c.push_layer(None, None, None, None, Some(blur(sigma))); + c.set_transform(Affine::translate((o.x0, o.y0)) * Affine::scale(o.scale)); + c.set_paint(vello_cpu::Image { + image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(mask)), + sampler: peniko::ImageSampler::default(), + }); + c.fill_rect(&Rect::new(0.0, 0.0, f64::from(o.width), f64::from(o.height))); let pad = sigma * 4.0 + off.hypot() + 4.0 * fr.px; c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::SrcIn)), None, None, None); @@ -380,15 +372,37 @@ impl Renderer { c.fill_rect(&reach.inflate(pad, pad)); c.pop_layer(); c.pop_layer(); - c.pop_layer(); // ... blurred and kept only where the object paints. c.set_transform(Affine::IDENTITY); c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None); me.draw_body(c, fr, it, bp, xf, page); c.pop_layer(); - } - c.pop_layer(); - }); + c.pop_layer(); + }); + } else { + self.with_blended_filters(ctx, f, reach, sigma, Mix::Multiply, (bp, xf), |_, c, fr| { + // One copy of the shape in the satin colour, moved by `by`. + let copy = |c: &mut RenderContext, by: Vec2| { + c.set_transform(fr.view * Affine::translate(by) * xf); + c.set_paint(paint); + c.fill_path(bp); + }; + c.set_transform(fr.view); + c.push_layer(None, None, None, None, Some(blur(sigma))); + if invert { + copy(c, Vec2::ZERO); + } + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, if invert { Compose::DestOut } else { Compose::SrcOver })), None, None, None); + copy(c, off); + c.set_transform(Affine::IDENTITY); + c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::Xor)), None, None, None); + copy(c, -off); + c.pop_layer(); + c.pop_layer(); + c.pop_layer(); + }); + } } // Bevel and Emboss (inner bevel): highlight from the lit side, shadow from the other. if e.bevel.on { @@ -583,6 +597,26 @@ fn offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option= 1.0 && h >= 1.0).then_some(Offscreen { x0, y0, scale, width: w as u16, height: h as u16 }) } +/// The most pixels a coverage mask drawn offscreen ([`mask_offscreen`]) holds: 4096 × 4096. +const MAX_MASK_PIXELS: f64 = 4096.0 * 4096.0; + +/// The offscreen image an object's coverage is drawn in to build an effect's mask: `reach` (device +/// pixels) widened by `spread`, within the window widened the same way, as [`offscreen`] finds it, +/// at a resolution low enough that the whole area fits within [`crate::MAX_SIDE`] a side and +/// [`MAX_MASK_PIXELS`] in all. `None` when none of it shows. +fn mask_offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option { + let screen = Rect::new(0.0, 0.0, f64::from(width), f64::from(height)).inflate(spread, spread); + let r = reach.inflate(spread, spread).intersect(screen); + let (x0, y0) = (r.x0.floor(), r.y0.floor()); + let (w, h) = (r.x1.ceil() - x0, r.y1.ceil() - y0); + if !(w >= 1.0 && h >= 1.0) { + return None; + } + let scale = (spread / MAX_BLUR_SPREAD).max(1.0).max(w.max(h) / crate::MAX_SIDE as f64).max((w * h / MAX_MASK_PIXELS).sqrt()); + let side = |len: f64| (len / scale).ceil().clamp(1.0, crate::MAX_SIDE as f64); + Some(Offscreen { x0, y0, scale, width: side(w) as u16, height: side(h) as u16 }) +} + /// `pm`'s coverage shrunk by `r` pixels: each pixel takes the smallest alpha among itself and the /// points on circles of `r` and `r / 2` around it, as white premultiplied by that alpha. Pixels /// outside `pm` count as transparent. @@ -607,6 +641,35 @@ fn erode(pm: &vello_cpu::Pixmap, r: f64) -> vello_cpu::Pixmap { vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) } +/// The satin coverage of `pm`'s two copies moved by `shift` and `-shift` pixels: at each pixel, +/// how much the copies' coverages differ, or with `invert`, `pm`'s own coverage where they +/// agree, as white premultiplied by that amount. Copies are sampled bilinearly; pixels outside +/// `pm` count as transparent. +fn satin_mask(pm: &vello_cpu::Pixmap, shift: Vec2, invert: bool) -> vello_cpu::Pixmap { + let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); + let src = pm.data(); + let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0.0 } else { f64::from(src[(y * w + x) as usize].a) / 255.0 }; + let sample = |x: f64, y: f64| { + let (fx, fy) = (x.floor(), y.floor()); + let (tx, ty) = (x - fx, y - fy); + let (ix, iy) = (fx as i64, fy as i64); + let top = alpha(ix, iy) * (1.0 - tx) + alpha(ix.saturating_add(1), iy) * tx; + let bottom = alpha(ix, iy.saturating_add(1)) * (1.0 - tx) + alpha(ix.saturating_add(1), iy.saturating_add(1)) * tx; + top * (1.0 - ty) + bottom * ty + }; + let mut data = Vec::with_capacity(src.len()); + for y in 0..h { + for x in 0..w { + let (px, py) = (x as f64, y as f64); + let diff = (sample(px - shift.x, py - shift.y) - sample(px + shift.x, py + shift.y)).abs(); + let v = if invert { alpha(x, y) * (1.0 - diff) } else { diff }; + let a = (v.clamp(0.0, 1.0) * 255.0).round() as u8; + data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + } + } + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + #[cfg(test)] mod tests { #[test] @@ -641,6 +704,21 @@ mod tests { assert_eq!(offscreen(object, 15_002.0, 1440, 900), Some(wide)); } + /// A coverage mask covers the whole widened area at a lower resolution when it is wider than + /// `MAX_SIDE` or holds more than `MAX_MASK_PIXELS`; a small one stays at full resolution. + #[test] + fn a_coverage_mask_covers_its_whole_area_within_its_pixel_budget() { + let small = Offscreen { x0: 140.0, y0: 140.0, scale: 1.0, width: 220, height: 220 }; + assert_eq!(mask_offscreen(Rect::new(150.0, 150.0, 350.0, 350.0), 10.0, 1440, 900), Some(small)); + for (reach, w, h) in [(Rect::new(0.0, 0.0, 65_535.0, 100.0), u16::MAX, 100), (Rect::new(0.0, 0.0, 20_000.0, 20_000.0), 20_000, 20_000)] { + let o = mask_offscreen(reach, 10.0, w, h).unwrap(); + assert_eq!((o.x0, o.y0), (-10.0, -10.0)); + assert!(o.x0 + f64::from(o.width) * o.scale >= reach.x1 + 10.0, "{o:?}"); + assert!(o.y0 + f64::from(o.height) * o.scale >= reach.y1 + 10.0, "{o:?}"); + assert!(f64::from(o.width) * f64::from(o.height) <= MAX_MASK_PIXELS + f64::from(o.width) + f64::from(o.height), "{o:?}"); + } + } + /// An inner shadow on a frame holding an image whose left half is transparent: the shadow /// lines the image's opaque part (its edge in the middle of the frame), not only the frame. #[test] @@ -686,6 +764,43 @@ mod tests { } } + /// Satin on a frame holding a uniformly half-transparent image: where both copies cover the + /// same partial coverage (all of the image with a distance of 0, its middle with a short one), + /// plain satin leaves the image as it is; inverted satin shades it. + #[test] + fn satin_leaves_a_uniform_half_transparent_image_plain() { + for (distance, invert) in [(0.0, false), (40.0, false), (0.0, true)] { + let (d, mut it) = image_frame(|_| image::Rgba([255, 255, 255, 128])); + let s = &mut it.effects.satin; + s.on = true; + s.color = "[Black]".into(); + s.opacity = 1.0; + s.angle = 0.0; + s.distance = distance; + s.size = 4.0; + s.invert = invert; + let lum = render_row(d, it); + // The image is white over a white page; satin multiplies black over it. + let shaded = lum(200) < 700; + assert_eq!(shaded, invert, "distance {distance}, invert {invert}: lum at x = 200 is {}", lum(200)); + } + } + + /// The satin mask is the difference of the shifted coverages: none where both copies cover the + /// same half coverage, half along an edge only one copy reaches, and the inverse keeps the + /// pixmap's own coverage where they agree. + #[test] + fn the_satin_mask_compares_partial_coverage() { + let half = vello_cpu::color::PremulRgba8 { r: 128, g: 128, b: 128, a: 128 }; + let pm = vello_cpu::Pixmap::from_parts(vec![half; 40 * 40], 40, 40); + let plain = satin_mask(&pm, Vec2::new(3.0, 0.0), false); + assert_eq!(plain.sample(20, 20).a, 0); + assert_eq!(plain.sample(1, 20).a, 128); + let inverted = satin_mask(&pm, Vec2::new(3.0, 0.0), true); + assert_eq!(inverted.sample(20, 20).a, 128); + assert_eq!(inverted.sample(1, 20).a, 64); + } + /// An inner glow from the center on a frame holding an image whose left half is transparent /// fills only the image's opaque part, fading toward that part's own edge. #[test] @@ -721,12 +836,17 @@ mod tests { /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { + image_frame(|x| if x < 10 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([255, 255, 255, 255]) }) + } + + /// A 200 pt frame at (100, 100) holding a 20 × 20 image whose pixels in column x are + /// `pixel(x)`, in a new document. + fn image_frame(pixel: impl Fn(u32) -> image::Rgba) -> (designcraft_doc::Document, Item) { use designcraft_doc::Document; use designcraft_doc::build::NewDocument; let mut d = Document::new(&NewDocument::default()); let lid = d.default_layer(); - // 20 × 20: transparent left half, opaque white right half. - let img = image::RgbaImage::from_fn(20, 20, |x, _| if x < 10 { image::Rgba([0, 0, 0, 0]) } else { image::Rgba([255, 255, 255, 255]) }); + let img = image::RgbaImage::from_fn(20, 20, |x, _| pixel(x)); let mut png = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let aid = designcraft_doc::AssetId(d.alloc()); From 8b7fea42fba13445b8f96d9693172f5b8a64bb6d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:39:39 -0800 Subject: [PATCH 174/328] Recovery: a write now leaves another session's background write of the same uid alone `recovery::save` and the tracked save cancelled every background write of the document's folder and uid, including one another session in the same process had queued. Both now cancel only their own session's writes, refuse while another session's write of that uid is queued or running, and keep other sessions' background writes of it from queuing until the write now is done. --- crates/engine/src/recovery.rs | 122 +++++++++++++++++++++++++--- crates/engine/src/recovery/tests.rs | 52 +++++++++++- 2 files changed, 161 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 2a0422417..4f774b8d3 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -583,10 +583,33 @@ fn prepare_save(s: &Session, dir: &Path) -> Result { Ok(access) } +/// Refuse a write now while another session's background write of one of the dirty documents' +/// uids to `dir` is queued or running. A write now cancels only this session's writes. +#[cfg(not(target_arch = "wasm32"))] +fn check_no_other_write(s: &Session, dir: &Path) -> Result<()> { + let preview = s.new_document_preview(); + for document in s.docs.iter().filter(|d| d.is_dirty() && preview != Some(d.uid)) { + if worker::queued_by_other(dir, document.uid, s.recovery_owner.0) { + return Err(still_being_written(dir)); + } + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn still_being_written(dir: &Path) -> EngineError { + EngineError::Other(format!( + "{}: another document's recovery data is still being written here; try again or choose another recovery folder", + dir.display() + )) +} + /// Write recovery entries for dirty documents and drop clean checkpoints. Returns how many /// were written. Command callers use the tracked variant without configuring automatic recovery. pub fn save(s: &Session, dir: &Path) -> Result { let access = prepare_save(s, dir)?; + #[cfg(not(target_arch = "wasm32"))] + check_no_other_write(s, dir)?; let mut n = 0; for d in &s.docs { // New Document's preview is not a document until Create makes it one. @@ -601,9 +624,10 @@ pub fn save(s: &Session, dir: &Path) -> Result { continue; } // The caller asked for this write now: nothing has cancelled it. - // A background write of an older state must not land over this one. + // A background write of an older state this session queued must not land over this one, + // and no other session's write of the uid is queued until it is done. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(dir, d.uid); + let _now = worker::write_now(dir, d.uid, s.recovery_owner.0).ok_or_else(|| still_being_written(dir))?; if let Some(e) = write_snapshot(&Snapshot::of(&access, dir, d), || false).error { return Err(e); } @@ -617,6 +641,8 @@ pub fn save(s: &Session, dir: &Path) -> Result { pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { reject_overfull_checkpoints(s, dir)?; let access = prepare_save(s, dir)?; + #[cfg(not(target_arch = "wasm32"))] + check_no_other_write(s, dir)?; let mut n = 0; let preview = s.new_document_preview(); for index in 0..s.docs.len() { @@ -629,9 +655,10 @@ pub(crate) fn save_tracked(s: &mut Session, dir: &Path) -> Result { continue; } let Some(document) = s.docs.get(index) else { continue }; - // A background write of an older state must not land over this one. + // A background write of an older state this session queued must not land over this one, + // and no other session's write of the uid is queued until it is done. #[cfg(not(target_arch = "wasm32"))] - worker::cancel(dir, document.uid); + let _now = worker::write_now(dir, document.uid, s.recovery_owner.0).ok_or_else(|| still_being_written(dir))?; let entry = Snapshot::of(&access, dir, document); let written = write_snapshot(&entry, || false); // The primary is the recovery data; its metadata is optional. Track the primary before @@ -980,6 +1007,9 @@ mod worker { /// A document saved, reverted or closed while its write was queued or running: the /// snapshot it is producing must not be published. cancelled: Mutex>, + /// Documents a session is writing now on its own thread, with that session: no background + /// write of one is queued until it is done (see [`write_now`]). + writing_now: Mutex>, /// Notified each time a write finishes and leaves `running`. idle: Condvar, } @@ -1131,6 +1161,48 @@ mod worker { dirs } + /// Whether a session other than `owner` has a write of `dir`/`uid` queued or running that + /// is not cancelled, or queued to follow one. + fn queued_by_other(&self, dir: &Path, uid: u64, owner: u64) -> bool { + let running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + self.other_in_flight(&running, dir, uid, owner) + } + + /// [`Writer::queued_by_other`] with `running` held, counting writes now as well. + fn other_in_flight(&self, running: &BTreeMap<(PathBuf, u64), Queued>, dir: &Path, uid: u64, owner: u64) -> bool { + let canonical = key(dir, uid); + running + .iter() + .filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) + .any(|(k, q)| (q.owner != owner && !self.cancelled(k)) || q.next.as_ref().is_some_and(|n| n.owner != owner)) + || self.writing_now.lock().is_ok_and(|now| now.get(&canonical).is_some_and(|by| *by != owner)) + } + + /// Start a write now of `dir`/`uid` by session `owner`. Returns `None` while another + /// session's write of it is in flight. Otherwise cancels this session's writes of it (as + /// [`Writer::cancel`]) and records the write now under the returned key, all under one + /// hold of `running`. + fn write_now(&self, dir: &Path, uid: u64, owner: u64) -> Option<(PathBuf, u64)> { + let canonical = key(dir, uid); + let _publishing = super::PUBLISH.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut running = self.running.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if self.other_in_flight(&running, dir, uid, owner) { + return None; + } + let mut keys = Vec::new(); + for (k, q) in running.iter_mut().filter(|(k, q)| **k == canonical || (k.1 == uid && q.dir == dir)) { + q.next = None; + keys.push(k.clone()); + } + if let Ok(mut cancelled) = self.cancelled.lock() { + cancelled.extend(keys); + } + if let Ok(mut now) = self.writing_now.lock() { + now.insert(canonical.clone(), owner); + } + Some(canonical) + } + /// `key` as in [`Writer::finish`]. fn cancelled(&self, key: &(PathBuf, u64)) -> bool { self.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(key)) @@ -1172,6 +1244,7 @@ mod worker { undelivered: Mutex::new(Vec::new()), running: Mutex::new(BTreeMap::new()), cancelled: Mutex::new(BTreeSet::new()), + writing_now: Mutex::new(BTreeMap::new()), idle: Condvar::new(), }) }) @@ -1183,20 +1256,41 @@ mod worker { WRITER.get().and_then(Option::as_ref) } - /// Do not publish the snapshot being written for `dir`/`uid` (see [`Writer::cancel`]). - pub(super) fn cancel(dir: &Path, uid: u64) { - if let Some(w) = started() { - w.cancel(dir, uid, None); - } - } - - /// [`cancel`] for the writes session `owner` queued. + /// Do not publish the snapshot session `owner` is having written for `dir`/`uid` (see + /// [`Writer::cancel`]). pub(super) fn cancel_owned(dir: &Path, uid: u64, owner: u64) { if let Some(w) = started() { w.cancel(dir, uid, Some(owner)); } } + /// A write now in progress; dropping it lets background writes of its document queue again. + pub(super) struct WriteNow(Option<(PathBuf, u64)>); + + impl Drop for WriteNow { + fn drop(&mut self) { + if let (Some(key), Some(w)) = (self.0.take(), started()) + && let Ok(mut now) = w.writing_now.lock() + { + now.remove(&key); + } + } + } + + /// See [`Writer::write_now`]. `None` while another session's write of `dir`/`uid` is in + /// flight. Without a writer thread there are no background writes to wait for. + pub(super) fn write_now(dir: &Path, uid: u64, owner: u64) -> Option { + match writer() { + Some(w) => w.write_now(dir, uid, owner).map(|key| WriteNow(Some(key))), + None => Some(WriteNow(None)), + } + } + + /// See [`Writer::queued_by_other`]. + pub(super) fn queued_by_other(dir: &Path, uid: u64, owner: u64) -> bool { + started().is_some_and(|w| w.queued_by_other(dir, uid, owner)) + } + /// See [`Writer::pending_folders`]. pub(super) fn pending_folders(uid: u64, owner: u64) -> Vec { started().map(|w| w.pending_folders(uid, owner)).unwrap_or_default() @@ -1238,6 +1332,10 @@ mod worker { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); + // A session is writing this document now: this write waits for a later turn. + if w.writing_now.lock().is_ok_and(|now| now.contains_key(&key)) { + return Some(false); + } if let Some(q) = running.get_mut(&key) { // The write in flight was cancelled (the document was saved since), so it holds // nothing to recover: this one follows it, in place of any that was waiting. diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index d1d03f162..a45cea1ce 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -336,6 +336,56 @@ fn saving_in_one_session_leaves_another_sessions_write_to_the_same_folder_alone( discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_write_now_in_one_session_leaves_another_sessions_write_of_the_same_uid_alone() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut queued_by = dirty_session(); + queued_by.recovery_dir = Some(dir.path().to_path_buf()); + let uid = queued_by.docs[0].uid; + // The same uid in another session, with two objects instead of one. + let mut other = dirty_session(); + other.docs[0].uid = uid; + other.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + let held = testing::hold_next_write(dir.path()); + queued_by.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + let err = save(&other, dir.path()).unwrap_err(); + assert!(err.to_string().contains("still being written"), "{err}"); + let err = other.execute("file.recovery.save", &json!({"dir": dir.path().to_string_lossy()})).unwrap_err(); + assert!(err.to_string().contains("still being written"), "{err}"); + assert!(!worker::cancelled(dir.path(), uid), "the other session's write now cancelled this write"); + held.release(); + assert_eq!(finished_writes(&mut queued_by), 1); + let mut reopened = Session::new(); + assert_eq!(open(&mut reopened, dir.path()).unwrap().len(), 1); + assert_eq!(reopened.doc().unwrap().doc.spreads[0].items.len(), 1, "the queued session's snapshot was kept"); + discard(dir.path(), reopened.doc().unwrap().uid); + discard(dir.path(), uid); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn no_other_sessions_write_of_the_uid_is_queued_during_a_write_now() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let writing = dirty_session(); + let uid = writing.docs[0].uid; + let mut other = dirty_session(); + other.recovery_dir = Some(dir.path().to_path_buf()); + other.docs[0].uid = uid; + let now = worker::write_now(dir.path(), uid, writing.recovery_owner.0).expect("nothing else is in flight"); + let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 0, "another session's write was queued during the write now: {queued}"); + assert!(worker::write_now(dir.path(), uid, other.recovery_owner.0).is_none(), "a second write now of the uid started"); + drop(now); + let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); + assert_eq!(queued["queued"], 1, "{queued}"); + assert_eq!(finished_writes(&mut other), 1); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_write_now_cancels_a_background_write_to_the_same_folder_spelled_another_way() { @@ -733,7 +783,7 @@ fn a_cancel_stops_a_write_before_the_package_is_finished() { fn only_a_queued_write_is_cancelled() { // A mark for a document with no write in flight would stay in the writer's set for ever. let dir = tempfile::tempdir().unwrap(); - worker::cancel(dir.path(), 7); + worker::cancel_owned(dir.path(), 7, 1); assert!(!worker::cancelled(dir.path(), 7), "nothing was queued for it"); } From 7af4d75539a3618ed0fbddabf5e044777101e748 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:00:46 -0800 Subject: [PATCH 175/328] Render: plain satin with no distance on an image is not drawn Both shifted copies are the same at distance 0, so the coverage mask is empty. The effect is now skipped before the image is drawn offscreen and scanned. --- crates/render/src/fx.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index ec4e1e60a..9fae7d2e1 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -329,8 +329,10 @@ impl Renderer { } } // Satin: the shape shifted both ways along the angle, blurred, where exactly one covers. - // With a graphic, the shape is what the object paints, as for the inner shadow. + // With a graphic, the shape is what the object paints, as for the inner shadow. Plain + // satin on a graphic with no distance compares two equal copies and is not drawn. if e.satin.on + && !(painted.is_some() && !e.satin.invert && e.satin.distance == 0.0) && let Some(c) = doc.resolve_color(&e.satin.color, 1.0) { let st = &e.satin; From 5932810b1f302d2de2f957afd3f7a576aa3038ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:04:46 -0800 Subject: [PATCH 176/328] Render: a center inner glow on an image fades around small transparent holes The coverage was eroded by sampling two rings of points, which could miss a hole smaller than the gaps between them. Erosion now takes the smallest alpha within an octagon of the band's radius, in four passes along the axes and the diagonals. --- crates/render/src/fx.rs | 91 +++++++++++++++++++++++++++++++++-------- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 9fae7d2e1..e74630644 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -619,28 +619,67 @@ fn mask_offscreen(reach: Rect, spread: f64, width: u16, height: u16) -> Option vello_cpu::Pixmap { - let (w, h) = (i64::from(pm.width()), i64::from(pm.height())); - let src = pm.data(); - let mut taps = vec![(0_i64, 0_i64)]; - for k in 0..16_u8 { - let d = if k % 2 == 0 { r } else { r / 2.0 }; - let a = f64::from(k) * std::f64::consts::PI / 8.0; - taps.push(((a.cos() * d).round() as i64, (a.sin() * d).round() as i64)); + let (w, h) = (pm.width() as usize, pm.height() as usize); + let radius = r.max(0.0).round().min(f64::from(u16::MAX)) as usize; + // The octagon is a square of half-width `side` widened by `diag` diagonal steps each way along + // both diagonals, so it reaches `radius` along the axes and about `radius` diagonally. + let diag = (radius as f64 * (1.0 - std::f64::consts::FRAC_1_SQRT_2)).round() as usize; + let side = radius.saturating_sub(2 * diag); + let mut alpha: Vec = pm.data().iter().map(|p| p.a).collect(); + for (step, k) in [((1, 0), side), ((0, 1), side), ((1, 1), diag), ((1, -1), diag)] { + alpha = erode_lines(&alpha, w, h, step, k); } - taps.dedup(); - let alpha = |x: i64, y: i64| if x < 0 || y < 0 || x >= w || y >= h { 0 } else { src[(y * w + x) as usize].a }; - let mut data = Vec::with_capacity(src.len()); - for y in 0..h { - for x in 0..w { - let a = taps.iter().map(|&(dx, dy)| alpha(x.saturating_add(dx), y.saturating_add(dy))).min().unwrap_or(0); - data.push(vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }); + let data = alpha.into_iter().map(|a| vello_cpu::color::PremulRgba8 { r: a, g: a, b: a, a }).collect(); + vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) +} + +/// `src` (`w` × `h`, row by row) with each value replaced by the smallest within `k` steps of it +/// along the lines that `step` walks. Steps past the edge count as 0. +fn erode_lines(src: &[u8], w: usize, h: usize, step: (isize, isize), k: usize) -> Vec { + if k == 0 { + return src.to_vec(); + } + let inside = |x: isize, y: isize| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h; + let mut out = vec![0; src.len()]; + let mut line = Vec::new(); + let mut window = std::collections::VecDeque::new(); + for y in 0..h as isize { + for x in 0..w as isize { + // Each line starts at the pixel whose step back leaves the image. + if inside(x - step.0, y - step.1) { + continue; + } + line.clear(); + let (mut cx, mut cy) = (x, y); + while inside(cx, cy) { + line.push(cy as usize * w + cx as usize); + (cx, cy) = (cx + step.0, cy + step.1); + } + // A running minimum over each pixel's window, with the values still in it in rising order. + window.clear(); + let mut next = 0; + for i in 0..line.len() { + while next < line.len() && next <= i + k { + let v = src[line[next]]; + while window.back().is_some_and(|&(_, b)| b >= v) { + window.pop_back(); + } + window.push_back((next, v)); + next += 1; + } + while window.front().is_some_and(|&(j, _)| j + k < i) { + window.pop_front(); + } + let whole = i >= k && i + k < line.len(); + out[line[i]] = if whole { window.front().map_or(0, |&(_, v)| v) } else { 0 }; + } } } - vello_cpu::Pixmap::from_parts(data, pm.width(), pm.height()) + out } /// The satin coverage of `pm`'s two copies moved by `shift` and `-shift` pixels: at each pixel, @@ -835,6 +874,22 @@ mod tests { assert_eq!(out.sample(6, 20).a, 128); } + /// Eroding clears every pixel within the radius of a one-pixel hole, along the axes and the + /// diagonals, and keeps the pixels beyond it. + #[test] + fn erosion_clears_around_a_small_hole() { + let opaque = vello_cpu::color::PremulRgba8 { r: 255, g: 255, b: 255, a: 255 }; + let mut data = vec![opaque; 40 * 40]; + data[20 * 40 + 20] = vello_cpu::color::PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }; + let out = erode(&vello_cpu::Pixmap::from_parts(data, 40, 40), 5.0); + for (x, y) in [(20, 20), (24, 20), (16, 20), (20, 24), (20, 16), (23, 23), (17, 17), (23, 17), (17, 23)] { + assert_eq!(out.sample(x, y).a, 0, "({x}, {y}) is within 5 pixels of the hole"); + } + for (x, y) in [(27, 20), (20, 13), (25, 25), (14, 14)] { + assert_eq!(out.sample(x, y).a, 255, "({x}, {y}) is more than 5 pixels from the hole"); + } + } + /// A 200 pt frame at (100, 100) holding a 20 × 20 image with a transparent left half and an /// opaque white right half, in a new document. fn half_image_frame() -> (designcraft_doc::Document, Item) { From 915be8561e804b9a4dd278cd7a47ca19ad5eb054 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:05:58 -0800 Subject: [PATCH 177/328] Paste: an image past the size limit is refused before its pixels are copied ClipboardImage::from_color_image checks the size before it copies the pixels, so an image egui delivers with Ctrl/Cmd+V that is over 64 million pixels is not copied before the paste refuses it. --- crates/ui-egui/src/canvas/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/services.rs | 9 +++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 5b3f796dc..88a526d9d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1200,6 +1200,26 @@ fn the_paste_keys_place_an_image_in_the_selected_empty_frame_but_not_in_text() { assert!(h.state().ui.status.contains("stop editing the text"), "{}", h.state().ui.status); } +#[test] +fn a_paste_keys_image_past_the_size_limit_is_refused_without_copying_its_pixels() { + // The size says 72 million pixels; the four pixels it holds are not copied. + let big = egui::ColorImage { size: [9000, 8000], source_size: egui::vec2(9000.0, 8000.0), pixels: vec![egui::Color32::RED; 4] }; + let image = crate::ClipboardImage::from_color_image(&big); + let crate::ClipboardImage::Pixels { width, height, rgba } = &image else { panic!("a bitmap") }; + assert_eq!((*width, *height, rgba.len()), (9000, 8000, 0)); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + assert!(app.paste_clipboard_image(image).is_err()); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items); + assert!(app.ui.status.contains("64 million"), "{}", app.ui.status); + // An image within the limit keeps its pixels. + let small = crate::ClipboardImage::from_color_image(&egui::ColorImage::filled([3, 2], egui::Color32::RED)); + let crate::ClipboardImage::Pixels { width, height, rgba } = small else { panic!("a bitmap") }; + assert_eq!((width, height), (3, 2)); + assert_eq!(rgba, [255, 0, 0, 255].repeat(6)); +} + #[test] fn selected_merged_owners_paint_the_same_row_and_column_targets() { for column in [true, false] { diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index fd529ac42..c2a181be1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -21,10 +21,15 @@ pub enum ClipboardImage { } impl ClipboardImage { - /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). + /// An image egui delivered with Ctrl/Cmd+V (`Event::PasteImage`). The pixels of an image + /// past the paste limit are not copied, and pasting it is refused by its size. pub fn from_color_image(image: &egui::ColorImage) -> Self { - let rgba = image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect(); let [w, h] = image.size.map(|n| u32::try_from(n).unwrap_or(u32::MAX)); + let rgba = if designcraft_engine::cmd::check_pasted_size(w, h).is_ok() { + image.pixels.iter().flat_map(|c| c.to_srgba_unmultiplied()).collect() + } else { + Vec::new() + }; ClipboardImage::Pixels { width: w, height: h, rgba } } } From 3efde54ae9354f02adf61de979697931a49d1d24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:08:50 -0800 Subject: [PATCH 178/328] Recovery: opening the recovery folder leaves this session's unfinished background writes alone A background write that is running, or that finished before the session took its result, is not in the document's entries yet. Opening recovery from that folder reopened it as a second copy of the live document. It is now skipped. The PUBLISH doc comment names the functions that take the lock. --- crates/engine/src/recovery.rs | 8 +++++++- crates/engine/src/recovery/tests.rs | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index 4f774b8d3..d045b2415 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -1532,7 +1532,7 @@ fn publish_recovery_file(path: &Path, bytes: &[u8], replace: bool) -> Result<()> } /// Serializes the last check for a cancelled write with the rename that publishes it, and with -/// [`worker::cancel`]. +/// [`worker::cancel_owned`] and [`worker::cancel_document`]. #[cfg(not(target_arch = "wasm32"))] static PUBLISH: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -1755,6 +1755,12 @@ fn open_with_publisher(s: &mut Session, dir: &Path, mut publish: impl FnMut(&Pat }) { continue; } + // A background write of this session that is running, or finished with its result not + // taken yet, is a live document's checkpoint, not an entry to recover. + #[cfg(not(target_arch = "wasm32"))] + if worker::pending_folders(uid, owner).iter().any(|pending| directory_key(pending).is_ok_and(|key| key == source_key)) { + continue; + } #[cfg(not(target_arch = "wasm32"))] validate_recovery_dir(dir)?; let (doc, _) = files(dir, uid); diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index a45cea1ce..f66d28879 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -242,6 +242,24 @@ fn saving_removes_a_finished_write_to_a_named_folder_whose_result_was_not_taken( assert!(list(named.path()).is_empty()); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn opening_recovery_leaves_a_finished_background_write_whose_result_was_not_taken() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut s = dirty_session(); + s.recovery_dir = Some(dir.path().to_path_buf()); + let uid = s.docs[0].uid; + s.execute("file.recovery.save", &json!({"background": true})).unwrap(); + testing::wait_until_idle(); + assert!(files(dir.path(), uid).0.exists(), "the write finished"); + assert!(open(&mut s, dir.path()).unwrap().is_empty(), "the live document's own snapshot is not recovered"); + assert_eq!(s.docs.len(), 1); + assert_eq!(finished_writes(&mut s), 1); + assert_eq!(list(dir.path()).len(), 1); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn an_edit_after_a_save_is_written_after_the_cancelled_write_stops() { From 346a0b24a291b41c4d68f8aa35fda234fd1e630e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:12:21 -0800 Subject: [PATCH 179/328] Paste: objects copied over empty clipboard text paste from the menu With a native menu, Copy saved the clipboard's empty text as the copy's text, so the next Paste took the older image, which the paste then skipped, and nothing was pasted. Empty text now counts as no text at the copy, as it does at the paste. --- crates/ui-egui/src/app/commands.rs | 3 ++- crates/ui-egui/src/canvas/tests.rs | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index dc0326172..0255bd189 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -53,7 +53,8 @@ impl DesignApp { self.object_clip_text.clone() } None => { - self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()); + // Empty text counts as no text, as Paste reads it. + self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f()).filter(|t| !t.is_empty()); self.object_clip_change = self.services.clipboard_change.as_mut().and_then(|f| f()); None } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 88a526d9d..7bca97710 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1152,6 +1152,14 @@ fn objects_copied_here_still_paste_as_objects_until_another_image_is_copied() { copy_elsewhere(&clip, Some(url), Some((5, 5))); crate::menus::activate(&mut app, "edit.paste", &Value::Null); assert_eq!(pasted_image(&app).map(|(px, _)| px), Some((5, 5)), "the image copied again with the same address"); + // Empty text beside the older image counts as no text at the copy too. + copy_elsewhere(&clip, Some(""), Some((7, 7))); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + crate::menus::activate(&mut app, "edit.copy", &Value::Null); + let items = app.session.doc().unwrap().doc.spreads[0].items.len(); + crate::menus::activate(&mut app, "edit.paste", &Value::Null); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), items + 1, "the copied text frame is pasted"); + assert_eq!(pasted_image(&app), None); } #[test] From ed9980fec243e286368011f7fff16c9a55dd6bd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:39:11 -0800 Subject: [PATCH 180/328] Paste: params text gives the pasted image's size as one point per pixel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit edit.pasteImage sizes a new frame as File › Place does, which reads a raster at one point per pixel and does not read a stored resolution. The params text and the comment said otherwise. --- crates/engine/src/cmd/paste_image.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/paste_image.rs b/crates/engine/src/cmd/paste_image.rs index ec29d78b0..6040d1b9e 100644 --- a/crates/engine/src/cmd/paste_image.rs +++ b/crates/engine/src/cmd/paste_image.rs @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Paste Image", [], None, - "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at its stored resolution (72 ppi when none) and at most 60% of the page width", + "{base64: an image file (PNG/JPEG/GIF/WebP/TIFF/BMP) as base64, name?: its name in the Links panel ending in an image extension (default \"Pasted image.png\"), spread?, at?: [x, y] (spread coords of the image's center; default the first page's center)} → {id, asset} — embedded; a selected empty frame takes the image, otherwise a new frame holds it at one point per pixel, as File › Place sizes an image, and at most 60% of the page width", has_doc, paste_image )] @@ -140,8 +140,8 @@ fn paste_image(s: &mut Session, p: &Value) -> Result { Some(at) => at, None => sp.pages.first().map_or(Point::ZERO, |pg| pg.bounds().center()), }; - // The size File › Place gives it: the stored resolution (72 ppi when none), at most 60% of - // the page width. + // The size File › Place gives it: one point per pixel (`designcraft_images::natural_size`), at + // most 60% of the page width. let (nw, nh) = designcraft_render::natural_size(&bytes, 0).unwrap_or((f64::from(pw), f64::from(ph))); let w = nw.min(d.settings.page_width * 0.6); let h = nh * w / nw; From f87c24a1cda25c64ac49b575548e40fca9585065 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:18 -0500 Subject: [PATCH 181/328] PPTX export: bound the retained glyph-to-character maps * PPTX export: keep only the last four faces' glyph-to-character maps --- crates/pptx/src/fonts.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/pptx/src/fonts.rs b/crates/pptx/src/fonts.rs index 27c976aaf..ed02ff297 100644 --- a/crates/pptx/src/fonts.rs +++ b/crates/pptx/src/fonts.rs @@ -15,6 +15,9 @@ pub struct RunFont { pub italic: bool, } +/// Faces whose glyph-to-character map is kept at once. +const MAX_REVERSE_MAPS: usize = 4; + #[derive(Default)] pub struct Fonts { names: HashMap, @@ -116,6 +119,11 @@ impl Fonts { /// The character a glyph shows (the lowest code point mapping to it). pub fn char_of(&mut self, face: &FontFace, gid: u32) -> Option { + // A face's reverse map can hold over a million entries; keeping one per face a bundle uses + // is unbounded, so only the last few stay (a rebuilt map answers the same). + if !self.reverse.contains_key(&face.id()) && self.reverse.len() >= MAX_REVERSE_MAPS { + self.reverse.clear(); + } let map = self.reverse.entry(face.id()).or_insert_with(|| { let mut m = HashMap::new(); for (c, g) in face.chars() { @@ -216,3 +224,26 @@ pub fn eot(face: &FontFace) -> Result, NoEmbed> { h.extend_from_slice(data); Ok(h) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_few_reverse_maps_are_kept_and_answers_do_not_change() { + let db = designcraft_fonts::FontDb::global(); + let mut fonts = Fonts::default(); + let mut last = None; + for style in ["Regular", "Bold", "Italic", "Bold Italic", "Semibold", "Light", "Black", "ExtraLight", "Medium", "SemiBold Italic"] { + let face = db.face("Source Serif 4", style); + let gid = face.glyph_for('A'); + assert_eq!(fonts.char_of(&face, gid), Some('A'), "{style}"); + assert!(fonts.reverse.len() <= MAX_REVERSE_MAPS); + last = Some((face, gid)); + } + // The map evicted earlier is rebuilt on demand with the same answer. + if let Some((face, gid)) = last { + assert_eq!(fonts.char_of(&face, gid), Some('A')); + } + } +} From 23465223bc655a4177282f8c3a33a55693751226 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:24 -0500 Subject: [PATCH 182/328] xtask: refuse an oversized corpus archive before extracting it * xtask: refuse a corpus archive that expands past the cap before extracting it * address review: a within-cap answer needs tar to exit successfully * Apply review fixes - xtask/src/main.rs --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- xtask/src/main.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 19f8557ad..0ce6b1974 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -273,6 +273,30 @@ fn dir_bytes(dir: &std::path::Path) -> u64 { total } +/// Whether the file bytes of the tar.gz at `tgz` add up to at most `max`, found by streaming them +/// through `tar -xzOf` and counting: nothing is written to disk, and a decompression bomb is cut +/// off (the child is killed) as soon as it passes `max`. +fn expands_within(tgz: &Path, max: u64) -> Result { + use std::io::Read; + let mut child = Command::new("tar") + .arg("-xzOf") + .arg(tgz) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| format!("tar -xzOf: failed to spawn: {e}"))?; + let Some(out) = child.stdout.take() else { return Err("tar -xzOf: no stdout".into()) }; + let n = std::io::copy(&mut out.take(max.saturating_add(1)), &mut std::io::sink()).map_err(|e| format!("tar -xzOf: {e}"))?; + if n > max { + let _ = child.kill(); + let _ = child.wait(); + return Ok(false); + } + // Within the cap only counts when tar read the whole archive: an early exit proves nothing. + let status = child.wait().map_err(|e| format!("tar -xzOf: {e}"))?; + if status.success() { Ok(true) } else { Err(format!("tar -xzOf {} failed ({status}); archive refused", tgz.display())) } +} + fn cmd_corpus(download: bool) -> Result<(), String> { let corpus = root().join("corpus"); println!( @@ -309,6 +333,11 @@ Tests that use a corpus skip cleanly when it is absent. if !listing.status.success() || listing.stdout.iter().filter(|b| **b == b'\n').count() > PNGSUITE_MAX_ENTRIES { return refuse(format!("the PngSuite download isn't a tar.gz of at most {PNGSUITE_MAX_ENTRIES} entries")); } + match expands_within(&tgz, PNGSUITE_MAX_EXTRACTED) { + Ok(true) => {} + Ok(false) => return refuse(format!("the PngSuite archive expands to more than {PNGSUITE_MAX_EXTRACTED} bytes; nothing was extracted")), + Err(e) => return refuse(e), + } let mut tar = Command::new("tar"); tar.arg("-xzf").arg(&tgz).arg("-C").arg(&dest); if let Err(e) = run(tar, "tar -xzf PngSuite-2017jul19.tgz") { @@ -324,3 +353,26 @@ Tests that use a corpus skip cleanly when it is absent. println!("PngSuite: {n} PNG files in {}", dest.display()); if n == 0 { Err("no PNG files extracted".into()) } else { Ok(()) } } + +#[cfg(test)] +mod corpus_tests { + use super::*; + + #[test] + fn a_tarball_that_expands_past_the_cap_is_refused_without_extracting() { + let dir = std::env::temp_dir().join(format!("dc-xtask-corpus-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("big"), vec![0u8; 100_000]).unwrap(); + let tgz = dir.join("a.tgz"); + let made = Command::new("tar").arg("-czf").arg(&tgz).arg("-C").arg(&dir).arg("big").status(); + if made.is_ok_and(|s| s.success()) { + assert_eq!(expands_within(&tgz, 100_000), Ok(true)); + assert_eq!(expands_within(&tgz, 99_999), Ok(false)); + // A truncated archive makes tar fail: not a within-cap answer. + let bytes = std::fs::read(&tgz).unwrap(); + std::fs::write(&tgz, &bytes[..bytes.len() / 2]).unwrap(); + assert!(expands_within(&tgz, 1 << 20).is_err()); + } + let _ = std::fs::remove_dir_all(&dir); + } +} From eb0ea78d9ad8fbea22361c1812f55303fbabe550 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:29 -0500 Subject: [PATCH 183/328] Images: a WebP with an ICC chunk longer than the file is read without its profile * Images: a WebP whose ICC chunk declares more than the file holds is read without it --- crates/images/src/lib.rs | 23 +++++++++++++++++++++++ crates/images/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/pdf/src/export/images.rs | 6 ++++++ 3 files changed, 56 insertions(+) diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 83c540e6e..98c058aa6 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -433,9 +433,32 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than +/// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads +/// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. +pub fn webp_icc_is_sane(bytes: &[u8]) -> bool { + if bytes.get(0..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WEBP") { + return true; + } + let mut pos = 12usize; + while let Some(head) = bytes.get(pos..pos.saturating_add(8)) { + let size = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize; + let body = pos + 8; + if &head[..4] == b"ICCP" { + return size <= colour::MAX_ICC_BYTES && body.saturating_add(size) <= bytes.len(); + } + // Chunks are padded to an even size. + pos = body.saturating_add(size).saturating_add(size & 1); + } + true +} + /// The ICC profile embedded in a PNG, JPEG, TIFF or WebP. fn embedded_icc(bytes: &[u8]) -> Option> { use image::ImageDecoder; + if !webp_icc_is_sane(bytes) { + return None; + } let mut d = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?; d.icc_profile().ok().flatten() } diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 3e5daf8ab..cd577f09a 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -534,3 +534,30 @@ fn gif_tone_and_cmyk_inks_check_the_rgba_budget() { assert!(too_large_to_decode(&tiff)); assert_eq!(decode_cmyk_tiff(&tiff), None); } + +fn webp_with(chunks: &[(&[u8; 4], u32, &[u8])]) -> Vec { + let mut v = b"RIFF\0\0\0\0WEBP".to_vec(); + for (id, declared, body) in chunks { + v.extend_from_slice(*id); + v.extend_from_slice(&declared.to_le_bytes()); + v.extend_from_slice(body); + if body.len() % 2 == 1 { + v.push(0); + } + } + v +} + +/// A WebP that declares an `ICCP` chunk larger than the file (or than the ICC cap) never reaches the +/// decoder's profile read, which would size a buffer from the declared length. +#[test] +fn a_webp_icc_chunk_that_declares_more_than_it_holds_is_refused_before_decoding() { + assert!(webp_icc_is_sane(&webp_with(&[(b"VP8X", 10, &[0; 10]), (b"ICCP", 4, &[1; 4])]))); + // An odd-sized chunk before it is padded to even. + assert!(webp_icc_is_sane(&webp_with(&[(b"EXIF", 3, &[0; 3]), (b"ICCP", 4, &[1; 4])]))); + assert!(!webp_icc_is_sane(&webp_with(&[(b"VP8X", 10, &[0; 10]), (b"ICCP", u32::MAX, &[1; 4])]))); + assert!(!webp_icc_is_sane(&webp_with(&[(b"ICCP", 100, &[1; 4])]))); + assert!(embedded_icc(&webp_with(&[(b"ICCP", u32::MAX, &[1; 4])])).is_none()); + assert!(webp_icc_is_sane(b"\x89PNG not a webp")); + assert!(webp_icc_is_sane(&webp_with(&[(b"VP8L", 6, &[0; 6])]))); +} diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index ec7c76fd6..b50c6b20a 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -47,6 +47,9 @@ pub(super) struct RasterMode { /// The ICC profile embedded in an image file, if it has one. pub(super) fn embedded_icc(data: &[u8]) -> Option> { use image::ImageDecoder; + if !designcraft_images::webp_icc_is_sane(data) { + return None; + } let mut dec = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?.into_decoder().ok()?; dec.icc_profile().ok().flatten() } @@ -89,6 +92,9 @@ pub(super) fn jpeg(data: krilla::Data, icc: impl FnOnce() -> Option>, mo /// its own. fn untagged_rgb(data: &[u8]) -> bool { use image::ImageDecoder; + if !designcraft_images::webp_icc_is_sane(data) { + return false; + } let Some(mut dec) = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok().and_then(|r| r.into_decoder().ok()) else { return false; }; From a41fc046f395696df98c2cce6524177c2cd31d9f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:35 -0500 Subject: [PATCH 184/328] Data merge: a record range stops expanding once the limit is met * Data merge: a record range stops expanding once the limit or the record count is met --- crates/engine/src/cmd/datamerge/parse.rs | 15 ++++++++++++--- crates/engine/src/cmd/datamerge/tests.rs | 10 ++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/parse.rs b/crates/engine/src/cmd/datamerge/parse.rs index dfc49e842..20b57e39a 100644 --- a/crates/engine/src/cmd/datamerge/parse.rs +++ b/crates/engine/src/cmd/datamerge/parse.rs @@ -159,7 +159,11 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: let i = record_index(one, count)?; idx.push(i); } - "range" => select_range(range, count, &mut idx, &mut seen)?, + "range" => { + // Past this many records nothing more can be kept, so later ranges are only validated. + let keep = limit.filter(|l| *l > 0).map_or(count, |l| count.min(l as usize)); + select_range(range, count, keep, &mut idx, &mut seen)? + } other => return Err(format!("unknown records value \"{other}\"")), } if let Some(limit) = limit { @@ -175,7 +179,9 @@ pub fn select_records(count: usize, records: &str, one: u32, range: &str, limit: } /// Expand a comma-separated list of record numbers and `a-b` ranges into `idx`, skipping repeats. -fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { +/// Every token is still checked, but once `idx` holds `keep` records no more are expanded, so +/// repeated or overlapping ranges cost nothing past that point. +fn select_range(range: &str, count: usize, keep: usize, idx: &mut Vec, seen: &mut std::collections::HashSet) -> Result<(), String> { if range.trim().is_empty() { return Err("no records".into()); } @@ -194,8 +200,11 @@ fn select_range(range: &str, count: usize, idx: &mut Vec, seen: &mut std: if a > b { return Err(format!("range {a}-{b} is reversed")); } + // Both ends in range means every record between them is. + record_index(a, count)?; + record_index(b, count)?; let mut n = a; - while n <= b { + while n <= b && idx.len() < keep { let i = record_index(n, count)?; if seen.insert(i) { idx.push(i); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 4793aac17..bcad97bb5 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1310,3 +1310,13 @@ fn merged_records_give_anchored_objects_their_own_ids() { doc.check().unwrap(); designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } + +#[test] +fn select_records_stops_expanding_once_the_limit_is_met_but_still_checks_every_range() { + // 4 billion records in a range would not finish if it were expanded; the limit stops it. + let idx = parse::select_records(u32::MAX as usize, "range", 1, "1-3,1-4294967295,2-4294967295", Some(5)).unwrap(); + assert_eq!(idx, vec![0, 1, 2, 3, 4]); + // A later token that is out of range is still an error. + assert!(parse::select_records(10, "range", 1, "1-10,5-11", Some(2)).is_err()); + assert!(parse::select_records(10, "range", 1, "1-2,0", Some(2)).is_err()); +} From 26d5c8941c4d8b7dd6e013ce02c4aef407f360f2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:41 -0500 Subject: [PATCH 185/328] IDML: story export and object-style overlay in linear time, embedded image budget * idml: story runs and marker offsets found once, object-style overlay by position, embedded image budget * address review: saturating embedded-bytes counter * address review: IDML export past the embed limit succeeds and warns for each image written as a link * address review: an unlinked image is always embedded, only linked ones fall back to their link --- crates/engine/src/cmd/interchange.rs | 14 +++-- crates/idml/src/export.rs | 26 ++++++++- crates/idml/src/export/item.rs | 12 +++- crates/idml/src/export/story.rs | 76 +++++++++++++++++++++----- crates/idml/src/import/object_style.rs | 30 ++++++---- crates/idml/src/lib.rs | 2 +- crates/idml/src/tests/assets.rs | 39 +++++++++++++ 7 files changed, 165 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs index 47b36b776..e84c28103 100644 --- a/crates/engine/src/cmd/interchange.rs +++ b/crates/engine/src/cmd/interchange.rs @@ -17,7 +17,7 @@ use crate::{DocState, EngineError, Result, Session}; pub fn specs() -> Vec { vec![ cmd!(query "file.exportIdml", "Export IDML…", [], None, - "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path", + "{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path; `warnings` names each image written as a link because the embedded-image limit was reached", has_doc, export_idml), cmd!(noundo "file.openIdml", "Open IDML", [], None, "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped, GREP styles whose pattern can't compile}", @@ -29,15 +29,19 @@ fn export_idml(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let opts = designcraft_idml::ExportOptions { embed_images: p.get("embedImages").and_then(Value::as_bool).unwrap_or(true) }; let layer_doc = with_pdf_layer_variants(&st.doc, opts.embed_images)?; - let bytes = designcraft_idml::export_idml_with(layer_doc.as_ref().unwrap_or(&st.doc), &opts); - match str_param(p, "path") { + let (bytes, warnings) = designcraft_idml::export_idml_report(layer_doc.as_ref().unwrap_or(&st.doc), &opts); + let mut out = match str_param(p, "path") { Some(path) => { #[cfg(not(target_arch = "wasm32"))] crate::io::write_file(path, &bytes).map_err(EngineError::Other)?; - Ok(json!({"path": path, "bytes": bytes.len()})) + json!({"path": path, "bytes": bytes.len()}) } - None => Ok(json!({"base64": base64_encode(&bytes), "bytes": bytes.len()})), + None => json!({"base64": base64_encode(&bytes), "bytes": bytes.len()}), + }; + if !warnings.is_empty() { + out["warnings"] = json!(warnings); } + Ok(out) } /// Whether a placement holds an Object Layer Options choice an export can still apply: a graphic diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 717bb5d6c..fccbc7c2f 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -65,9 +65,20 @@ pub fn export_idml(doc: &Document) -> Vec { /// Export with options, using the index sort-key conflict policy of [`export_idml`]. pub fn export_idml_with(doc: &Document, opts: &ExportOptions) -> Vec { + export_idml_report(doc, opts).0 +} + +/// [`export_idml_with`] and its warnings: an image written as a link only because the export's +/// embedded-image limit was reached is named in one, so the package is not silently incomplete. +pub fn export_idml_report(doc: &Document, opts: &ExportOptions) -> (Vec, Vec) { + export_with_limit(doc, opts, MAX_EMBEDDED_BYTES) +} + +pub(crate) fn export_with_limit(doc: &Document, opts: &ExportOptions, embed_limit: usize) -> (Vec, Vec) { let mut ex = Ex::new(doc, opts); + ex.embed_limit = embed_limit; let parts = ex.build(); - zip_parts(&parts) + (zip_parts(&parts), ex.warnings) } fn zip_parts(parts: &[(String, Vec)]) -> Vec { @@ -106,8 +117,18 @@ struct Ex<'a> { /// Index topic path → first serialized sort key; See / See also cross-references. index_topics: BTreeMap, String>, index_xrefs: Vec<(Vec, &'static str, String)>, + /// Bytes of image data written into `` so far (see [`MAX_EMBEDDED_BYTES`]). + embedded: usize, + embed_limit: usize, + /// Images written as links because the embed limit was reached (one line per placement). + warnings: Vec, } +/// Image bytes one export embeds, counting each placement (IDML holds a copy per placement): past +/// it a graphic that has a link of its own is written as that link without its contents (an +/// image with no link is always embedded: it has nowhere else to live). +const MAX_EMBEDDED_BYTES: usize = 512 * 1024 * 1024; + impl<'a> Ex<'a> { fn new(d: &'a Document, opts: &'a ExportOptions) -> Self { let mut ex = Ex { @@ -121,6 +142,9 @@ impl<'a> Ex<'a> { link_text_sources: Vec::new(), index_topics: BTreeMap::new(), index_xrefs: Vec::new(), + embedded: 0, + embed_limit: MAX_EMBEDDED_BYTES, + warnings: Vec::new(), }; ex.assign_swatch_ids(); for s in d.stories.values() { diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 457172253..ca27a8ca0 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -268,9 +268,19 @@ impl<'a> Ex<'a> { el.set("FillColor", id.clone()); el.set("FillTint", pct(g.fill.tint as f64)); } - let embed = !asset.data.is_empty() && (self.opts.embed_images || asset.link.is_none()); + let wanted = !asset.data.is_empty() && (self.opts.embed_images || asset.link.is_none()); + // An image with no link of its own has nowhere else to live, so it is always embedded + // (dropping its data would lose it); only an image with a real link can fall back to it. + let embed = wanted && (asset.link.is_none() || self.embedded.saturating_add(asset.data.len()) <= self.embed_limit); + if wanted && !embed { + self.warnings.push(format!( + "image {} is written as a link, not embedded: the package already holds {} bytes of images (limit {})", + asset.name, self.embedded, self.embed_limit + )); + } let mut props = Vec::new(); if embed { + self.embedded = self.embedded.saturating_add(asset.data.len()); let mut c = El::new("Contents"); c.children.push(Node::CData(base64_encode(&asset.data))); props.push(c); diff --git a/crates/idml/src/export/story.rs b/crates/idml/src/export/story.rs index 437376190..7ca41e231 100644 --- a/crates/idml/src/export/story.rs +++ b/crates/idml/src/export/story.rs @@ -278,7 +278,14 @@ impl<'a> Ex<'a> { None } - fn apply_tracked_changes(&mut self, s: &Story, f: &CharFormat, csrs: &mut [El], para_br: bool, para_end: usize) { + fn apply_tracked_changes( + &mut self, + f: &CharFormat, + csrs: &mut [El], + para_br: bool, + runs: &[(std::ops::Range, &CharFormat)], + para_end: usize, + ) { // Tracked changes wrap the text they mark. if let Some(kind) = change_type(f.over.change) { for c in csrs.iter_mut().filter(|c| c.name == "CharacterStyleRange" && !c.children.is_empty()) { @@ -288,7 +295,10 @@ impl<'a> Ex<'a> { } } if para_br && let Some(c) = csrs.last_mut() { - let nl = s.runs().find(|(rr, _)| rr.contains(¶_end)).and_then(|(_, nf)| change_type(nf.over.change)); + let nl = runs + .get(runs.partition_point(|(rr, _)| rr.end <= para_end)) + .filter(|(rr, _)| rr.start <= para_end) + .and_then(|(_, nf)| change_type(nf.over.change)); match nl { None => c.push(El::new("Br")), Some(kind) => match c.children.last_mut() { @@ -307,17 +317,27 @@ impl<'a> Ex<'a> { pub(super) fn story_paras(&mut self, s: &Story) -> Vec { let ranges = s.para_ranges(); let n = ranges.len(); - ranges.into_iter().enumerate().map(|(pi, r)| self.story_para(s, pi, r, pi + 1 == n)).collect() + // The runs and the marker offsets, once: each paragraph (and each marker) searched them from the start. + let runs: Vec<(std::ops::Range, &CharFormat)> = s.runs().collect(); + let marks = Marks::of(s); + ranges.into_iter().enumerate().map(|(pi, r)| self.story_para(s, pi, r, pi + 1 == n, &runs, &marks)).collect() } - fn paragraph_runs(s: &Story, r: &std::ops::Range) -> Vec<(std::ops::Range, CharFormat)> { - // Character runs intersecting the paragraph. + fn paragraph_runs( + s: &Story, + r: &std::ops::Range, + runs: &[(std::ops::Range, &CharFormat)], + ) -> Vec<(std::ops::Range, CharFormat)> { + // Character runs intersecting the paragraph (they ascend: the first is a search away). let mut segs: Vec<(std::ops::Range, CharFormat)> = Vec::new(); - for (rr, f) in s.runs() { + for (rr, f) in &runs[runs.partition_point(|(rr, _)| rr.end <= r.start)..] { + if rr.start >= r.end { + break; + } let a = rr.start.max(r.start); let b = rr.end.min(r.end); if a < b { - segs.push((a..b, f.clone())); + segs.push((a..b, (*f).clone())); } } if segs.is_empty() { @@ -354,11 +374,19 @@ impl<'a> Ex<'a> { } } - fn story_para(&mut self, s: &Story, pi: usize, r: std::ops::Range, last: bool) -> El { + fn story_para( + &mut self, + s: &Story, + pi: usize, + r: std::ops::Range, + last: bool, + runs: &[(std::ops::Range, &CharFormat)], + marks: &Marks, + ) -> El { let pf = s.paras.get(pi).cloned().unwrap_or_default(); let mut psr = self.psr_el(&pf); let ends_with_break = s.text.get(r.clone()).and_then(|t| t.chars().next_back()).is_some_and(st::is_break_char); - let segs = Self::paragraph_runs(s, &r); + let segs = Self::paragraph_runs(s, &r, runs); // A hyperlink on a run of text is written as a `HyperlinkTextSource` around the // ranges it covers, so the runs are cut at its edges first (#1446). let (links, segs) = self.cut_runs_at_links(s, &r, segs); @@ -414,7 +442,7 @@ impl<'a> Ex<'a> { } else if ch == designcraft_doc::ANCHOR_MARK { flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::ANCHOR_MARK).count(); + let k = marks.anchor.partition_point(|&at| at < seg_start + ci); if let Some(a) = s.anchors.get(k) { out.push(Node::El( El::new("HyperlinkTextDestination") @@ -428,14 +456,14 @@ impl<'a> Ex<'a> { // An anchored object: the item inside the range with its anchoring settings. flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::OBJECT_MARK).count(); + let k = marks.object.partition_point(|&at| at < seg_start + ci); if let Some(el) = self.anchored_object(s, k) { out.push(Node::El(el)); } } else if ch == designcraft_doc::INDEX_MARK { flush_text(&mut cur, &mut pending); flush_content(&mut pending, &mut out); - let k = s.text[..seg_start + ci].matches(designcraft_doc::INDEX_MARK).count(); + let k = marks.index.partition_point(|&at| at < seg_start + ci); if let Some(el) = self.index_reference(s, k) { out.push(Node::El(el)); } @@ -448,7 +476,7 @@ impl<'a> Ex<'a> { c.children.append(&mut out); csrs.push(c); } - let k = s.text[..seg_start + ci].matches(designcraft_doc::XREF_MARK).count(); + let k = marks.xref.partition_point(|&at| at < seg_start + ci); if let Some(x) = s.xrefs.get(k) { let me = self.fresh(); let fmt = self.d.xref_formats.iter().position(|ff| ff.name == x.format).map_or("n".to_string(), xref_format_self); @@ -525,7 +553,7 @@ impl<'a> Ex<'a> { c.children.extend(out); csrs.push(c); } - self.apply_tracked_changes(s, &f, &mut csrs, para_br, r.end); + self.apply_tracked_changes(&f, &mut csrs, para_br, runs, r.end); let link = links.iter().find(|(_, l)| l.contains(&seg_start) || (l.start == seg_start && l.start == l.end)).map(|(i, _)| *i); for c in csrs { psr_csrs.push((link, c)); @@ -655,3 +683,23 @@ pub(super) fn with_list_tab(mut a: ParaAttrs, resolved: impl FnOnce() -> (design a.tabs = Some(tabs); a } + +/// Byte offsets of a story's anchor, object, index and cross-reference markers, in text order. +pub(super) struct Marks { + anchor: Vec, + object: Vec, + index: Vec, + xref: Vec, +} + +impl Marks { + fn of(s: &Story) -> Self { + let at = |c: char| s.text.match_indices(c).map(|(i, _)| i).collect::>(); + Marks { + anchor: at(designcraft_doc::ANCHOR_MARK), + object: at(designcraft_doc::OBJECT_MARK), + index: at(designcraft_doc::INDEX_MARK), + xref: at(designcraft_doc::XREF_MARK), + } + } +} diff --git a/crates/idml/src/import/object_style.rs b/crates/idml/src/import/object_style.rs index 343e67211..6af6f845e 100644 --- a/crates/idml/src/import/object_style.rs +++ b/crates/idml/src/import/object_style.rs @@ -242,9 +242,11 @@ fn overlay(base: &mut El, top: &El, depth: usize) { *base = top.clone(); return; } + // Where `base`'s Properties child is, once (a search per attribute otherwise). + let props = base.children.iter().position(|n| matches!(n, Node::El(p) if p.local() == "Properties")); for (k, v) in &top.attrs { base.set(k, v); - if let Some(Node::El(p)) = base.children.iter_mut().find(|n| matches!(n, Node::El(p) if p.local() == "Properties")) { + if let Some(Node::El(p)) = props.and_then(|at| base.children.get_mut(at)) { p.children.retain(|n| !matches!(n, Node::El(x) if x.local() == k)); } } @@ -259,22 +261,26 @@ fn overlay(base: &mut El, top: &El, depth: usize) { // The k-th child of a name merges with the k-th child of that name in `base` (repeated elements // such as gradient stops pair up in order). let mut seen: HashMap<&str, usize> = HashMap::new(); + // Positions in `base.children` of its elements, by name, in order: the k-th is a lookup, not a + // scan from the first child (many repeated names made the scans quadratic). + let mut at: HashMap> = HashMap::new(); + for (i, b) in base.children.iter().enumerate() { + if let Node::El(b) = b { + at.entry(b.local().to_string()).or_default().push(i); + } + } for n in &top.children { match n { Node::El(c) => { let k = seen.entry(c.local()).or_insert(0); - let slot = base - .children - .iter_mut() - .filter_map(|b| match b { - Node::El(b) if b.local() == c.local() => Some(b), - _ => None, - }) - .nth(*k); + let slot = at.get(c.local()).and_then(|v| v.get(*k)).copied(); *k += 1; - match slot { - Some(b) => overlay(b, c, depth + 1), - None => base.children.push(n.clone()), + match slot.and_then(|i| base.children.get_mut(i)) { + Some(Node::El(b)) => overlay(b, c, depth + 1), + _ => { + at.entry(c.local().to_string()).or_default().push(base.children.len()); + base.children.push(n.clone()); + } } } Node::Text(_) | Node::CData(_) if has_text => base.children.push(n.clone()), diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs index 8f7b22ff9..0c024dfab 100644 --- a/crates/idml/src/lib.rs +++ b/crates/idml/src/lib.rs @@ -57,7 +57,7 @@ mod xml; #[cfg(test)] mod tests; -pub use export::{ExportOptions, export_idml, export_idml_with}; +pub use export::{ExportOptions, export_idml, export_idml_report, export_idml_with}; pub use import::{Imported, import_idml, import_idml_report, import_idml_report_with_previews, import_idml_with}; /// The IDML package mimetype (content of the first, stored `mimetype` entry). diff --git a/crates/idml/src/tests/assets.rs b/crates/idml/src/tests/assets.rs index 48875c256..265183540 100644 --- a/crates/idml/src/tests/assets.rs +++ b/crates/idml/src/tests/assets.rs @@ -393,3 +393,42 @@ fn the_swatch_applied_to_an_image_is_kept() { assert!(!images.iter().any(|e| e.contains("Swatch/None")), "{images:?}"); assert_eq!(fills(&import_idml_with(&out, &reader).unwrap()), want); } + +/// Past the embedded-image limit an export still succeeds: the images that no longer fit are +/// written as links, and each is named in a warning. +#[test] +fn export_past_the_embed_limit_warns_for_each_image_written_as_a_link() { + let bytes = vec![42u8; 300]; + let reader = |p: &str| p.ends_with("couple.jpg").then(|| bytes.clone()); + let frames = vec![ + frame(1, 0.0, 1.0, &image(1, PHOTO, None)), + frame(2, 100.0, 2.0, &image(2, PHOTO, None)), + frame(3, 200.0, 3.0, &image(3, PHOTO, None)), + frame(4, 300.0, 4.0, &image(4, "file:/elsewhere/copy.jpg", Some(&bytes))), + ]; + let d = import_idml_with(&package(&frames), &reader).unwrap(); + let opts = ExportOptions { embed_images: true }; + // Four placements of 300 bytes each; the limit holds two. + let (out, warnings) = crate::export::export_with_limit(&d, &opts, 700); + assert_eq!(warnings.len(), 2, "{warnings:?}"); + assert!(warnings.iter().all(|w| w.contains("written as a link")), "{warnings:?}"); + assert_eq!(import_idml_with(&out, &reader).unwrap().assets.len(), 2); + assert!(crate::export::export_with_limit(&d, &opts, 1200).1.is_empty()); +} + +/// An image with no link of its own is embedded even past the limit: it has no other home, and +/// dropping its data would lose it. +#[test] +fn an_unlinked_image_is_embedded_past_the_embed_limit() { + let bytes = vec![42u8; 300]; + let reader = |p: &str| p.ends_with("couple.jpg").then(|| bytes.clone()); + let frames = vec![frame(1, 0.0, 1.0, &image(1, PHOTO, None)), frame(2, 100.0, 2.0, &image(2, PHOTO, None))]; + let mut d = import_idml_with(&package(&frames), &reader).unwrap(); + for a in d.assets.values_mut() { + std::sync::Arc::make_mut(a).link = None; + } + let (out, warnings) = crate::export::export_with_limit(&d, &ExportOptions { embed_images: true }, 100); + assert!(warnings.is_empty(), "{warnings:?}"); + let back = import_idml_with(&out, &|_: &str| None).unwrap(); + assert!(!back.assets.is_empty() && back.assets.values().all(|a| a.data.as_slice() == bytes.as_slice())); +} From 665fe2a8e42a97c881d8d80dd2bf37d34f168b70 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:47 -0500 Subject: [PATCH 186/328] Format: a failed entry read counts against the archive budget * format: bytes a failed entry read inflated count against the archive budget * address review: mutate the payload bytes explicitly in the checksum test * address review: charge a failed read to the budget it belongs to (stored vs deflated) --- crates/format/src/lib.rs | 11 +++++++++-- crates/format/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 8f9d8856e..a03667209 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -224,10 +224,17 @@ fn read_entry( return Err(too_big()); } let mut v = Vec::new(); - if f.take(limit.saturating_add(1)).read_to_end(&mut v).is_err() { + let read = f.take(limit.saturating_add(1)).read_to_end(&mut v); + let n = v.len() as u64; + // What a failed read produced was inflated all the same: it counts against the archive's budget. + if read.is_err() { + if stored { + *stored_left = stored_left.saturating_sub(n); + } else { + *left = left.saturating_sub(n); + } return Ok(None); } - let n = v.len() as u64; if n > limit { return Err(too_big()); } diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index ca57c7770..0e6f613cd 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -3,6 +3,25 @@ use designcraft_doc::build::NewDocument; use designcraft_doc::geom::Rect; use designcraft_doc::{Asset, ParaFormat, SpreadRef}; +/// An entry that fails after inflating (a bad checksum) still uses up the archive's byte budget. +#[test] +fn a_failed_read_is_charged_to_the_budget() { + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + z.start_file("a", stored).unwrap(); + z.write_all(&[7u8; 1000]).unwrap(); + let mut bytes = z.finish().unwrap().into_inner(); + // Flip a data byte: the entry reads in full, then fails its checksum. + // The payload is the only run of 1,000 consecutive 7s in the archive. + let start = bytes.windows(1000).position(|w| w.iter().all(|b| *b == 7)).expect("payload"); + bytes[start] = 8; + let mut archive = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let (mut left, mut stored_left) = (5000, 5000); + assert_eq!(read_entry(&mut archive, "a", 4000, &mut left, &mut stored_left).unwrap(), None); + // A failed stored read is charged to the stored budget only. + assert_eq!((left, stored_left), (5000, 4000)); +} + fn png_asset(d: &mut Document, data: &[u8]) -> AssetId { let aid = AssetId(d.alloc()); let a = From 568f25fa9f2b2e50097bb1f76499f24355b18fa1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:53 -0500 Subject: [PATCH 187/328] Fonts: cap decoded names, bound outline flattening, cache fallback coverage * fonts: cap decoded names, outline flatten tolerance by size, coverage cache for system fallback * Apply review fixes - crates/fonts/src/fontdb/system.rs - crates/fonts/src/fontdb/names.rs * Apply review fixes - crates/fonts/src/fontdb/system.rs * address review: cap flattened edges in has_serifs * address review: check alias blankness before capping --------- Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com> --- crates/fonts/src/fontdb/fallback.rs | 9 +++ crates/fonts/src/fontdb/names.rs | 40 +++++++++++++- crates/fonts/src/fontdb/outline.rs | 26 ++++++++- crates/fonts/src/fontdb/system.rs | 85 +++++++++++++++++++++++++++-- 4 files changed, 150 insertions(+), 10 deletions(-) diff --git a/crates/fonts/src/fontdb/fallback.rs b/crates/fonts/src/fontdb/fallback.rs index 73a2e0a25..7291cb343 100644 --- a/crates/fonts/src/fontdb/fallback.rs +++ b/crates/fonts/src/fontdb/fallback.rs @@ -10,8 +10,17 @@ pub(super) struct SysFallback { pub(super) misses: std::collections::HashSet, /// CJK chain families already looked up in the catalog (loaded, or not installed). pub(super) chain_tried: std::collections::HashSet<&'static str>, + /// The code points each installed file covers (as ranges), by path, valid for the file's + /// stamp: one character after another is looked up without reading every file again. + pub(super) coverage: std::collections::HashMap>)>, + /// Ranges held in `coverage` (it stops growing at [`MAX_COVERAGE_RANGES`]). + pub(super) coverage_ranges: usize, } +/// Most coverage ranges kept across all files (8 bytes each). +#[cfg(not(target_arch = "wasm32"))] +pub(super) const MAX_COVERAGE_RANGES: usize = 4 * 1024 * 1024; + #[cfg(all(test, target_os = "linux"))] pub(super) struct FallbackSnapshotHook { pub(super) reached: std::sync::mpsc::SyncSender<()>, diff --git a/crates/fonts/src/fontdb/names.rs b/crates/fonts/src/fontdb/names.rs index af5f14cc3..6c2610824 100644 --- a/crates/fonts/src/fontdb/names.rs +++ b/crates/fonts/src/fontdb/names.rs @@ -3,16 +3,42 @@ use super::face::FontFace; use super::system::CatalogEntry; use super::{Arc, MetadataProvider, StringId}; +/// Characters kept of one decoded name: a name record can be 64 KB, and a font has many of them, +/// kept for every face (a real family or style name is far shorter). +const MAX_NAME_CHARS: usize = 256; + +fn capped(name: impl std::fmt::Display) -> String { + use std::fmt::Write as _; + let mut out = String::new(); + // Stops decoding at the cap: the name is never built in full. + let mut room = MAX_NAME_CHARS; + struct Cap<'a>(&'a mut String, &'a mut usize); + impl std::fmt::Write for Cap<'_> { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if *self.1 == 0 { + return Err(std::fmt::Error); + } + *self.1 -= 1; + self.0.push(c); + } + Ok(()) + } + } + let _ = write!(Cap(&mut out, &mut room), "{name}"); + out +} + pub(super) fn aliases(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Vec { let mut names: Vec = - ids.iter().flat_map(|id| font.localized_strings(*id)).take(256).map(|name| name.to_string()).filter(|name| !name.trim().is_empty()).collect(); + ids.iter().flat_map(|id| font.localized_strings(*id)).take(256).filter(|name| !name.chars().all(char::is_whitespace)).map(capped).collect(); names.sort(); names.dedup(); names } pub(super) fn name(font: &skrifa::FontRef<'_>, ids: &[StringId]) -> Option { - ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(|s| s.to_string()).filter(|s| !s.is_empty())) + ids.iter().find_map(|id| font.localized_strings(*id).english_or_first().map(capped).filter(|s| !s.is_empty())) } /// A face's family and style names (the default instance's style for a variable font). @@ -116,3 +142,13 @@ pub(super) fn style_italic(style: &str) -> bool { let s = norm(style); s.contains("italic") || s.contains("oblique") || s == "it" } + +#[cfg(test)] +mod tests { + #[test] + fn decoded_names_are_capped() { + assert_eq!(super::capped("Arial"), "Arial"); + let long = "é".repeat(10_000); + assert_eq!(super::capped(&long).chars().count(), super::MAX_NAME_CHARS); + } +} diff --git a/crates/fonts/src/fontdb/outline.rs b/crates/fonts/src/fontdb/outline.rs index 30e328be4..0b07f3b3f 100644 --- a/crates/fonts/src/fontdb/outline.rs +++ b/crates/fonts/src/fontdb/outline.rs @@ -11,28 +11,48 @@ pub(super) fn has_serifs(face: &FontFace) -> Option { if bbox.height().is_nan() || bbox.height() <= 1.0 { return None; } + // Flattened segments kept: an "l" has a few dozen; a hostile outline has no such limit of its own. + const MAX_EDGES: usize = 1 << 20; let mut edges = Vec::new(); + let mut over = false; let mut last = None; let mut start = None; - kurbo::flatten(&path, 1.0, |el| match el { + // A tolerance of one unit is fine for outlines of normal size; a transform that blows one up + // gets a tolerance in proportion, so the subdivision stays bounded (4096 units stay at 1). + let tol = (bbox.width().max(bbox.height()) / 4096.0).max(1.0); + if !tol.is_finite() { + return None; + } + kurbo::flatten(&path, tol, |el| match el { kurbo::PathEl::MoveTo(p) => { last = Some(p); start = Some(p); } kurbo::PathEl::LineTo(p) => { if let Some(a) = last { - edges.push((a, p)); + if edges.len() < MAX_EDGES { + edges.push((a, p)); + } else { + over = true; + } } last = Some(p); } kurbo::PathEl::ClosePath => { if let (Some(a), Some(b)) = (last, start) { - edges.push((a, b)); + if edges.len() < MAX_EDGES { + edges.push((a, b)); + } else { + over = true; + } } last = start; } _ => {} }); + if over { + return None; + } // The outline is y-down: the foot is near bbox.y1 (the baseline). let width_at = |y: f64| { let xs: Vec = edges diff --git a/crates/fonts/src/fontdb/system.rs b/crates/fonts/src/fontdb/system.rs index 2a367b894..84916807e 100644 --- a/crates/fonts/src/fontdb/system.rs +++ b/crates/fonts/src/fontdb/system.rs @@ -38,6 +38,60 @@ fn file_stamp(path: &std::path::Path) -> Option { std::fs::metadata(path).ok().map(|m| (m.len(), m.modified().ok())) } +/// The code points any face of a font file maps, as sorted inclusive ranges. +#[cfg(not(target_arch = "wasm32"))] +fn coverage_ranges(data: &[u8]) -> Vec<(u32, u32)> { + // One bit per code point: memory stays fixed however many faces (or named instances of one face) map however much. + let mut bits = vec![0u64; 0x110000 / 64]; + let mut last = None; + for (i, _, _, _) in enumerate_faces(data) { + if last.replace(i) == Some(i) { + continue; + } + if let Ok(f) = skrifa::FontRef::from_index(data, i) { + for (cp, _) in f.charmap().mappings() { + if let Some(w) = bits.get_mut((cp / 64) as usize) { + *w |= 1u64 << (cp % 64); + } + } + } + } + let mut out: Vec<(u32, u32)> = Vec::new(); + for (wi, &w) in bits.iter().enumerate() { + if w == 0 { + continue; + } + for b in 0..64u32 { + if (w >> b) & 1 == 0 { + continue; + } + let cp = wi as u32 * 64 + b; + match out.last_mut() { + Some(last) if last.1 + 1 == cp => last.1 = cp, + _ => out.push((cp, cp)), + } + } + } + out +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod coverage_tests { + #[test] + fn coverage_ranges_match_the_charmap() { + let data = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); + let ranges = super::coverage_ranges(data); + let f = skrifa::FontRef::new(data).unwrap(); + use skrifa::MetadataProvider as _; + let in_ranges = |c: char| ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&u32::from(c))); + assert!(in_ranges('a') && !in_ranges('\u{10FFFE}')); + for c in ['a', 'Z', 'é', '\u{4E2D}', '\u{1F600}'] { + assert_eq!(in_ranges(c), f.charmap().map(c).is_some(), "{c:?}"); + } + assert!(ranges.windows(2).all(|w| w[0].1 + 1 < w[1].0), "sorted and merged"); + } +} + /// What [`FontDb::reload_fonts`] did: the faces cataloged by the rescan, and the installed font /// files that changed or were removed since they were read (their faces are read again, from the /// new file, the next time they are looked up). @@ -272,6 +326,8 @@ impl FontDb { sys.generation = sys.generation.wrapping_add(1); sys.misses.clear(); sys.chain_tried.clear(); + sys.coverage.clear(); + sys.coverage_ranges = 0; count } @@ -564,13 +620,32 @@ impl FontDb { } } for p in paths { - if std::fs::metadata(&p).map(|m| m.len() > 40 << 20).unwrap_or(true) { + let Some(stamp) = file_stamp(&p).filter(|s| s.0 <= 40 << 20) else { continue }; + let cached = + self.sys.lock().unwrap_or_else(PoisonError::into_inner).coverage.get(&p).filter(|(s, _)| *s == stamp).map(|(_, r)| r.clone()); + let mut data = None; + let ranges = match cached { + Some(r) => r, + None => { + let Some(d) = self.read_installed(&p) else { continue }; + let r = Arc::new(coverage_ranges(&d)); + let mut sys = self.sys.lock().unwrap_or_else(PoisonError::into_inner); + if sys.coverage_ranges + r.len() <= super::fallback::MAX_COVERAGE_RANGES { + sys.coverage_ranges += r.len(); + if let Some((_, old)) = sys.coverage.insert(p.clone(), (stamp, r.clone())) { + sys.coverage_ranges -= old.len(); + } + } + data = Some(d); + r + } + }; + let cp = u32::from(c); + if !ranges.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp)) { continue; } - let Some(data) = self.read_installed(&p) else { continue }; - let hit = - enumerate_faces(&data).iter().any(|(i, _, _, _)| skrifa::FontRef::from_index(&data, *i).is_ok_and(|f| f.charmap().map(c).is_some())); - if hit && self.add_faces(data, FontSource::Installed(p)) > 0 && covered(self) { + let Some(data) = data.or_else(|| self.read_installed(&p)) else { continue }; + if self.add_faces(data, FontSource::Installed(p)) > 0 && covered(self) { return true; } } From b7174dc92dca0129ae82969bbf7cf4c5dbc0128e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:27:59 -0500 Subject: [PATCH 188/328] Engine: bounded DTD validation, compound-path hole orientation * dtd: bounded matching steps, element depth and problem count * address review: stop DTD matching when a step charge fails; refuse hole orientation past its budget * Apply review fixes - crates/engine/src/dtd.rs --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/engine/src/cmd/paths.rs | 62 ++++++++++++++-- crates/engine/src/dtd.rs | 130 +++++++++++++++++++++++++++++---- 2 files changed, 174 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 7800b3189..946da4215 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use designcraft_doc::{Content, Document, Fill, Item, ItemId, Selection, Shape, SpreadRef, Stroke}; -use designcraft_geom::{Affine, BezPath, PathData, SubPath}; +use designcraft_geom::{Affine, BezPath, PathData, Shape as _, SubPath}; use serde_json::{Value, json}; use super::{CommandSpec, bad, cmd, has_selection, point_param, targets}; @@ -75,20 +75,40 @@ fn spread_xf(d: &Document, id: ItemId) -> Option<(SpreadRef, Affine)> { Some((loc.spread, d.parent_xf(&loc) * d.item_at(&loc)?.xf)) } +/// Containment tests `orient_holes` makes at most (after the bounding-box filter). A compound path +/// of thousands of nested contours would otherwise take quadratic time; past this the command is +/// refused rather than leave later subpaths with the wrong direction. +const MAX_HOLE_TESTS: usize = 4_000_000; + /// Orient subpaths so those nested an odd number of times run against the others: with the /// non-zero rule they become holes. -fn orient_holes(path: &mut PathData) { +fn orient_holes(path: &mut PathData, command: &str) -> Result<()> { + orient_holes_within(path, command, MAX_HOLE_TESTS) +} + +fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> Result<()> { let beziers: Vec = path.subpaths.iter().map(|s| PathData::single(s.clone()).to_bezpath()).collect(); + // A point outside a contour's box is outside the contour: most pairs are skipped without a winding count. + let boxes: Vec<_> = beziers.iter().map(BezPath::bounding_box).collect(); let n = path.subpaths.len(); + let mut tests = 0usize; for i in 0..n { let Some(p) = path.subpaths[i].anchors.first().map(|a| a.p) else { continue }; - let depth = (0..n).filter(|&j| j != i && designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)).count(); + let mut depth = 0; + for j in (0..n).filter(|&j| j != i && boxes[j].inflate(1e-6, 1e-6).contains(p)) { + tests += 1; + if tests > max_tests { + return Err(bad(command, "too many nested contours to tell holes from fills")); + } + depth += usize::from(designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)); + } let sp = &mut path.subpaths[i]; let cw = sp.area() > 0.0; if cw == (depth % 2 == 1) { sp.reverse(); } } + Ok(()) } fn make_compound(s: &mut Session, p: &Value) -> Result { @@ -115,7 +135,7 @@ fn make_compound(s: &mut Session, p: &Value) -> Result { } let it = d.item_mut(base_id).ok_or(designcraft_doc::DocError::NoItem(base_id))?; it.path = PathData::new(subpaths); - orient_holes(&mut it.path); + orient_holes(&mut it.path, "object.makeCompoundPath")?; it.shape = Shape::Path; *sel = Selection::items(vec![base_id]); Ok(json!({"id": base_id.0})) @@ -159,7 +179,7 @@ fn pathfinder(s: &mut Session, p: &Value) -> Result { } let it = d.item_mut(keep).ok_or(designcraft_doc::DocError::NoItem(keep))?; it.path = result.transformed(kxf.inverse()); - orient_holes(&mut it.path); + orient_holes(&mut it.path, "object.pathfinder")?; it.shape = Shape::Path; it.corners = Default::default(); *sel = Selection::items(vec![keep]); @@ -409,6 +429,38 @@ mod tests { s.doc().unwrap().doc.check().unwrap(); } + #[test] + fn orient_holes_alternates_nested_contours_and_skips_distant_ones() { + use designcraft_geom::{Rect, shapes::rectangle}; + let mut subs: Vec = Vec::new(); + for k in 0..3 { + let o = 10.0 * f64::from(k); + subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths); + } + // Thousands of separate contours cost no winding counts (their boxes miss each other). + for k in 0..3000 { + let x = 200.0 + 20.0 * f64::from(k); + subs.extend(rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)).subpaths); + } + let mut path = PathData::new(subs); + orient_holes(&mut path, "test").unwrap(); + let cw: Vec = path.subpaths.iter().map(|s| s.area() > 0.0).collect(); + assert_eq!(cw[..3], [true, false, true]); + assert!(cw[3..].iter().all(|c| *c)); + } + + #[test] + fn orient_holes_refuses_past_its_budget_instead_of_half_orienting() { + use designcraft_geom::{Rect, shapes::rectangle}; + let mut subs: Vec = Vec::new(); + for k in 0..4 { + let o = 10.0 * f64::from(k); + subs.extend(rectangle(Rect::new(o, o, 100.0 - o, 100.0 - o)).subpaths); + } + assert!(orient_holes_within(&mut PathData::new(subs.clone()), "test", 3).is_err()); + assert!(orient_holes_within(&mut PathData::new(subs), "test", 100).is_ok()); + } + #[test] fn pathfinder_subtracts_front_from_back() { let mut s = Session::new(); diff --git a/crates/engine/src/dtd.rs b/crates/engine/src/dtd.rs index 6b48ba3ab..7128ba84e 100644 --- a/crates/engine/src/dtd.rs +++ b/crates/engine/src/dtd.rs @@ -309,7 +309,39 @@ pub fn parse(src: &str) -> Result { /// What `ends` has worked out for one sequence of children: the end positions of a group (by the /// address of its node, which lives as long as the model) from a position. -type EndsMemo = HashMap<(usize, usize), Vec>; +struct EndsMemo { + map: HashMap<(usize, usize), Vec>, + /// Matching steps left (shared by a whole validation); at zero `ends` stops and `over` is set. + left: usize, + /// End positions held in `map`; past [`MAX_STORED_ENDS`] results are no longer kept. + stored: usize, + over: bool, +} + +/// Matching steps one validation may take across all its elements (a step is a position handled or +/// compared). Valid documents with thousands of children per element use a small fraction. +const MAX_MATCH_STEPS: usize = 8 * 1024 * 1024; +/// End positions the memo may hold at once (8 bytes each). +const MAX_STORED_ENDS: usize = 4 * 1024 * 1024; +/// Element nesting depth: `check` recurses and keeps each level's full path. +const MAX_XML_DEPTH: usize = 256; +/// Elements in the document being validated. +const MAX_XML_NODES: usize = 4 * 1024 * 1024; +/// Problems reported before the list stops. +const MAX_PROBLEMS: usize = 10_000; + +impl EndsMemo { + /// Spend `n` steps; false once the budget is gone. + fn spend(&mut self, n: usize) -> bool { + if self.over || n > self.left { + self.left = 0; + self.over = true; + return false; + } + self.left -= n; + true + } +} /// End positions after `cp` matches a prefix of `seq[i..]`. /// @@ -321,8 +353,16 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { return if seq.get(i) == Some(&n.as_str()) { vec![i + 1] } else { vec![] }; } let key = (std::ptr::from_ref(cp) as usize, i); - if let Some(done) = memo.get(&key) { - return done.clone(); + if let Some(done) = memo.map.get(&key) { + // Charged before the clone, and a failed charge ends the match. + let len = done.len(); + if !memo.spend(len) { + return vec![]; + } + return memo.map.get(&key).cloned().unwrap_or_default(); + } + if !memo.spend(1) { + return vec![]; } let mut out: Vec = match cp { Cp::Name(_) => vec![], @@ -334,6 +374,9 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { for p in at { next.extend(ends(c, seq, p, memo)); } + if !memo.spend(next.len()) { + return vec![]; + } next.sort_unstable(); next.dedup(); at = next; @@ -349,16 +392,21 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { } Cp::Rep(c, r) => { let mut all = if *r == '+' { vec![] } else { vec![i] }; + // `all` as a set too: a list search per position made long repeats quadratic. + let mut have: std::collections::HashSet = all.iter().copied().collect(); let mut frontier = ends(c, seq, i, memo); if *r == '?' { all.extend(frontier); } else { while !frontier.is_empty() { - let new: Vec = frontier.iter().copied().filter(|p| !all.contains(p)).collect(); + if !memo.spend(frontier.len()) { + break; + } + let new: Vec = frontier.iter().copied().filter(|p| have.insert(*p)).collect(); all.extend(&new); let mut next = Vec::new(); for p in new.into_iter().filter(|&p| p > i) { - next.extend(ends(c, seq, p, memo).into_iter().filter(|p| !all.contains(p))); + next.extend(ends(c, seq, p, memo).into_iter().filter(|p| !have.contains(p))); } // Two paths to one position are one position: kept apart they multiply per round. next.sort_unstable(); @@ -371,7 +419,10 @@ fn ends(cp: &Cp, seq: &[&str], i: usize, memo: &mut EndsMemo) -> Vec { }; out.sort_unstable(); out.dedup(); - memo.insert(key, out.clone()); + if !memo.over && memo.stored + out.len() <= MAX_STORED_ENDS { + memo.stored += out.len(); + memo.map.insert(key, out.clone()); + } out } @@ -396,6 +447,7 @@ fn read_tree(xml: &str) -> Result { use quick_xml::events::Event; let mut r = quick_xml::Reader::from_str(xml); let mut stack: Vec = Vec::new(); + let mut count = 0usize; let node = |e: &quick_xml::events::BytesStart| Node { name: String::from_utf8_lossy(e.name().as_ref()).to_string(), attrs: e.attributes().flatten().map(|a| String::from_utf8_lossy(a.key.as_ref()).to_string()).collect(), @@ -403,8 +455,20 @@ fn read_tree(xml: &str) -> Result { text: false, }; loop { - match r.read_event().map_err(|e| e.to_string())? { - Event::Start(e) => stack.push(node(&e)), + let event = r.read_event().map_err(|e| e.to_string())?; + if matches!(event, Event::Start(_) | Event::Empty(_)) { + count += 1; + if count > MAX_XML_NODES { + return Err(format!("more than {MAX_XML_NODES} elements")); + } + } + match event { + Event::Start(e) => { + if stack.len() >= MAX_XML_DEPTH { + return Err(format!("elements nested more than {MAX_XML_DEPTH} deep")); + } + stack.push(node(&e)); + } Event::Empty(e) => { let n = node(&e); match stack.last_mut() { @@ -437,8 +501,15 @@ fn read_tree(xml: &str) -> Result { } } -fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { - let mut problem = |m: String| out.push(Problem { path: path.to_string(), message: m }); +fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec, steps: &mut usize) { + if out.len() >= MAX_PROBLEMS { + return; + } + let mut problem = |m: String| { + if out.len() < MAX_PROBLEMS { + out.push(Problem { path: path.to_string(), message: m }); + } + }; match dtd.model(&n.name) { None => problem(format!("`{}` isn't declared in the DTD", n.name)), Some(Model::Any) => {} @@ -459,7 +530,12 @@ fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { problem(format!("`{}` can't contain text", n.name)); } let seq: Vec<&str> = n.children.iter().map(|c| c.name.as_str()).collect(); - if !ends(cp, &seq, 0, &mut EndsMemo::new()).contains(&seq.len()) { + let mut memo = EndsMemo { map: HashMap::new(), left: *steps, stored: 0, over: false }; + let matched = ends(cp, &seq, 0, &mut memo).contains(&seq.len()); + *steps = memo.left; + if memo.over { + problem(format!("`{}` has too many children to check against its content model", n.name)); + } else if !matched { let got = if seq.is_empty() { "nothing".to_string() } else { seq.join(", ") }; problem(format!("`{}` contains {got}; the DTD asks for {}", n.name, show(cp))); } @@ -474,7 +550,7 @@ fn check(dtd: &Dtd, n: &Node, path: &str, out: &mut Vec) { for c in &n.children { let k = seen.entry(c.name.as_str()).or_default(); *k += 1; - check(dtd, c, &format!("{path}/{}[{k}]", c.name), out); + check(dtd, c, &format!("{path}/{}[{k}]", c.name), out, steps); } } @@ -484,7 +560,10 @@ pub fn validate(dtd: &Dtd, xml: &str) -> Vec { Ok(root) => { let mut out = Vec::new(); let path = root.name.clone(); - check(dtd, &root, &path, &mut out); + check(dtd, &root, &path, &mut out, &mut { MAX_MATCH_STEPS }); + if out.len() >= MAX_PROBLEMS { + out.push(Problem { path: String::new(), message: "further problems are not listed".into() }); + } out } Err(e) => vec![Problem { path: String::new(), message: format!("not well-formed XML: {e}") }], @@ -743,4 +822,29 @@ mod tests { assert_eq!(problems.len(), 1, "{problems:?}"); assert!(problems[0].message.starts_with("`r` contains a, a, a"), "{problems:?}"); } + + #[test] + fn nested_repeats_over_many_children_stop_at_the_step_budget() { + let dtd = parse("").unwrap(); + assert_eq!(validate(&dtd, &format!("{}", "".repeat(1000))), vec![]); + let problems = validate(&dtd, &format!("{}", "".repeat(20_000))); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert!(problems[0].message.contains("too many children"), "{problems:?}"); + } + + #[test] + fn xml_nesting_is_bounded() { + let dtd = parse("").unwrap(); + let deep = |n: usize| format!("{}{}", "".repeat(n), "".repeat(n)); + assert_eq!(validate(&dtd, &deep(MAX_XML_DEPTH)), vec![]); + let problems = validate(&dtd, &deep(MAX_XML_DEPTH + 1)); + assert!(problems[0].message.contains("nested more than"), "{problems:?}"); + } + + #[test] + fn problems_are_capped() { + let dtd = parse("").unwrap(); + let problems = validate(&dtd, &format!("{}", "".repeat(MAX_PROBLEMS + 50))); + assert!(problems.len() <= MAX_PROBLEMS + 1, "{}", problems.len()); + } } From ff0463e299c65a74c0191909cdadc6f16f8092be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:28:07 -0500 Subject: [PATCH 189/328] Exports: leave out text the page doesn't show (inherited conditions, deletions, hidden layers) * fix(export): leave out text hidden by inherited conditions or deletion in every exporter * address review: skip hidden frames in page text and hidden article items; first visible paragraph as nav label; read table anchor's own format * address review: skip nonprinting frames and non-printable layers in fixed-layout page text * Apply review fixes - crates/epub/src/html.rs - crates/engine/src/cmd/export/formats.rs * Apply review fixes - crates/epub/src/html.rs - crates/engine/src/cmd/export/formats.rs * address review: fixed-layout page text skips frames in inactive object states * address review: place a threaded story at its first shown frame; skip it only when every frame is hidden --------- Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com> --- crates/doc/src/lib.rs | 46 +++++++++++++ crates/engine/src/cmd/export/formats.rs | 21 +++++- crates/engine/src/cmd/export/text_tests.rs | 19 +++++ crates/epub/src/chapters.rs | 5 +- crates/epub/src/html.rs | 51 ++++++++++++-- crates/epub/src/story_writer.rs | 32 +++++++-- crates/epub/src/tests.rs | 69 +++++++++++++++++++ crates/epub/tests/it/grouped_reading_order.rs | 5 +- crates/textimport/src/export.rs | 62 ++++++++++++----- crates/textimport/src/tagged.rs | 4 +- 10 files changed, 281 insertions(+), 33 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index d9ee6d3e9..4ebcd665b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -251,6 +251,52 @@ impl Document { pub fn conditions_hide(&self, conds: &[String]) -> bool { !conds.is_empty() && conds.iter().all(|c| self.conditions.iter().any(|x| x.name == *c && !x.visible)) } + + /// Is text with character format `f`, in a paragraph whose base character attributes are + /// `base` (`Styles::resolve_para`), left off the page: hidden by its effective conditions + /// (the paragraph's and character style's included) or marked deleted? Exports leave it out + /// as composition does. + pub fn hides_run(&self, base: &CharProps, f: &CharFormat) -> bool { + let props = self.styles.resolve_char(base, f); + props.change == ChangeMark::Deleted || self.conditions_hide(&props.conditions) + } + + /// The byte ranges of `st` that show, in order: the runs [`Self::hides_run`] hides left out. + /// Paragraphs and runs are walked together, once; take it once per story. + pub fn visible_spans(&self, st: &Story) -> Vec> { + let mut out: Vec> = Vec::new(); + let runs: Vec<(std::ops::Range, &CharFormat)> = st.runs().collect(); + let mut k = 0; + for (pi, pr) in st.para_ranges().iter().enumerate() { + let base = st.paras.get(pi).map(|pf| self.styles.resolve_para(pf).1).unwrap_or_default(); + while runs.get(k).is_some_and(|(rr, _)| rr.end <= pr.start) { + k += 1; + } + for (rr, f) in runs.iter().skip(k).take_while(|(rr, _)| rr.start < pr.end) { + let (a, b) = (rr.start.max(pr.start), rr.end.min(pr.end)); + if a >= b || self.hides_run(&base, f) { + continue; + } + match out.last_mut() { + Some(last) if last.end == a => last.end = b, + _ => out.push(a..b), + } + } + } + out + } + + /// The text of `st` within `range` that lies in `spans` ([`Self::visible_spans`] of `st`). + pub fn visible_text(st: &Story, spans: &[std::ops::Range], range: std::ops::Range) -> String { + let first = spans.partition_point(|s| s.end <= range.start); + let mut out = String::new(); + for s in spans.iter().skip(first).take_while(|s| s.start < range.end) { + if let Some(t) = st.text.get(s.start.max(range.start)..s.end.min(range.end)) { + out.push_str(t); + } + } + out + } } /// Ink Manager settings for output, by swatch name. Output applies them through a diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index a25553d69..4474d8ae7 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -142,7 +142,7 @@ pub(super) fn export_text(s: &mut Session, p: &Value) -> Result { let text = match format { "rtf" => designcraft_textimport::export::rtf(doc, story), "tagged" => designcraft_textimport::tagged::tagged_text(doc, story), - _ => designcraft_textimport::export::plain_text(story), + _ => designcraft_textimport::export::plain_text(doc, story), }; match path { Some(path) => { @@ -159,13 +159,30 @@ fn page_text(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, let mut out = String::new(); for st in d.stories.values() { let cs = cache.get(d, st.id, None); + let spans = d.visible_spans(st); for ft in &cs.frames { if d.page_of_item(ft.frame) != Some(abs) { continue; } + // Pages render printing-only: a hidden or nonprinting frame or group around it, or a top-level item on a hidden or non-printable layer (members draw on its layer), isn't on the rendered page. + // Inside a multi-state object only the active state is drawn. + if d.find(ft.frame).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + d.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }).is_some_and(|it| { + it.hidden + || it.nonprinting + || n == 1 && d.layers.iter().any(|l| (!l.visible || !l.printable) && l.id == it.layer) + || n < loc.path.len() && !it.states.is_empty() && loc.path[n] != it.active_state + }) + }) + }) { + continue; + } for l in &ft.lines { let r = l.range.start.min(st.text.len())..l.range.end.min(st.text.len()); - let t: String = st.text[r].chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); + // The line's text as it shows: hidden conditional text and deletions left out. + let t: String = + designcraft_doc::Document::visible_text(st, &spans, r).chars().filter(|c| !('\u{E000}'..='\u{F8FF}').contains(c)).collect(); if !t.trim().is_empty() { out.push_str(t.trim_end_matches('\n')); out.push('\n'); diff --git a/crates/engine/src/cmd/export/text_tests.rs b/crates/engine/src/cmd/export/text_tests.rs index b1b791d3b..48e255ef7 100644 --- a/crates/engine/src/cmd/export/text_tests.rs +++ b/crates/engine/src/cmd/export/text_tests.rs @@ -92,6 +92,25 @@ fn epub_cover_and_fixed_layout() { assert!(p1.contains("width=612, height=792") && p1.contains("Page one words"), "{p1}"); } +/// Fixed-layout page text leaves out frames in a multi-state object's inactive states. +#[test] +fn fixed_epub_text_skips_inactive_states() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let a = s.execute("frame.create", &json!({"rect": [72, 72, 200, 100], "content": "text", "text": "Active words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = + s.execute("frame.create", &json!({"rect": [72, 300, 200, 100], "content": "text", "text": "Inactive words", "caret": false})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("states.create", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("file.exportFixedEpub", &json!({})).unwrap(); + let mut z = unzip(r["base64"].as_str().unwrap()); + let p1 = read(&mut z, "OEBPS/page1.xhtml"); + assert!(p1.contains("Active words") && !p1.contains("Inactive words"), "{p1}"); +} + /// #775: the fallback follows the font's class, and embedFonts packages the stylesheet's fonts /// (and reports those it can't). #[test] diff --git a/crates/epub/src/chapters.rs b/crates/epub/src/chapters.rs index ede96f390..b9b6e6183 100644 --- a/crates/epub/src/chapters.rs +++ b/crates/epub/src/chapters.rs @@ -99,7 +99,8 @@ pub(crate) fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, Strin continue; } let Some(st) = doc.story(*sid) else { continue }; - let first = label(st.text.split('\n').next().unwrap_or("")); + let spans = doc.visible_spans(st); + let first = st.para_ranges().into_iter().map(|r| label(&Document::visible_text(st, &spans, r))).find(|t| !t.is_empty()).unwrap_or_default(); if !first.is_empty() { firsts.push((format!("s{k}"), first, 1)); } @@ -107,7 +108,7 @@ pub(crate) fn toc_entries(doc: &Document, order: &[Block]) -> Vec<(String, Strin let Some(pf) = st.paras.get(pi) else { continue }; let (tag, _) = export_mapping(&doc.styles, &pf.style, false, &pc); let Some(level) = heading_level(tag).filter(|l| *l <= 3) else { continue }; - let text = label(st.text.get(r.clone()).unwrap_or("")); + let text = label(&Document::visible_text(st, &spans, r.clone())); if !text.is_empty() { headings.push((format!("s{k}-p{pi}"), text, level)); } diff --git a/crates/epub/src/html.rs b/crates/epub/src/html.rs index 6442d5045..233c2764e 100644 --- a/crates/epub/src/html.rs +++ b/crates/epub/src/html.rs @@ -14,11 +14,22 @@ pub enum Block { pub fn reading_order(doc: &Document) -> Vec { // Articles, when there are any to export, decide the order (and what's included). if doc.articles.iter().any(|a| a.export) { + let hidden_layers: Vec<_> = doc.layers.iter().filter(|l| !l.visible).map(|l| l.id).collect(); let mut out = Vec::new(); let mut seen = Vec::new(); for a in doc.articles.iter().filter(|a| a.export) { for id in &a.items { let Some(top) = doc.item(*id) else { continue }; + // A hidden item or group hides everything in it. The layer that counts is the + // top-level item's: pages draw a group's members on the group's layer. + if doc.find(*id).is_some_and(|loc| { + (1..=loc.path.len()).any(|n| { + doc.item_at(&designcraft_doc::ItemLoc { spread: loc.spread, path: loc.path[..n].to_vec() }) + .is_some_and(|g| g.hidden || n == 1 && hidden_layers.contains(&g.layer)) + }) + }) { + continue; + } let mut push = |it: &Item| match &it.content { Content::Text(tf) if !seen.contains(&tf.story) => { seen.push(tf.story); @@ -27,11 +38,21 @@ pub fn reading_order(doc: &Document) -> Vec { Content::Graphic(_) => out.push(Block::Image(it.id)), _ => {} }; - top.walk(&mut |i| push(i)); + // Hidden items (with everything in them) aren't on the page. + let mut stack = vec![top]; + while let Some(it) = stack.pop() { + if it.hidden { + continue; + } + push(it); + stack.extend(it.children().iter().rev().map(|c| &**c)); + } } } return out; } + let hidden_layers: Vec<_> = doc.layers.iter().filter(|l| !l.visible).map(|l| l.id).collect(); + let shown = shown_items(doc, &hidden_layers); let mut keyed: Vec<((usize, i64, i64), Block)> = Vec::new(); let mut seen_stories = Vec::new(); for (si, sp) in doc.spreads.iter().enumerate() { @@ -45,7 +66,8 @@ pub fn reading_order(doc: &Document) -> Vec { continue; }; let xf = *parent * it.xf; - if it.hidden { + // Hidden items, and top-level items on hidden layers (with everything in them), aren't on the page. + if it.hidden || stack.len() == 1 && hidden_layers.contains(&it.layer) { continue; } let children = it.children(); @@ -55,8 +77,13 @@ pub fn reading_order(doc: &Document) -> Vec { let block = match &it.content { Content::Text(tf) => { let Some(story) = doc.story(tf.story) else { continue }; - // A story is placed where its first frame is. - if story.frames.first() != Some(&it.id) || seen_stories.contains(&tf.story) || story.text.trim().is_empty() { + // A story is placed where its first frame on the page is: a story is left out + // only when every frame of it is hidden, and a hidden first frame does not hide + // the rest of the thread. + if story.frames.iter().find(|f| shown.contains(f)) != Some(&it.id) + || seen_stories.contains(&tf.story) + || story.text.trim().is_empty() + { continue; } seen_stories.push(tf.story); @@ -78,6 +105,22 @@ pub fn reading_order(doc: &Document) -> Vec { keyed.into_iter().map(|(_, b)| b).collect() } +/// The items the page shows: not hidden themselves, in a hidden group, or (top level) on a hidden layer. +fn shown_items(doc: &Document, hidden_layers: &[designcraft_doc::LayerId]) -> std::collections::HashSet { + let mut shown = std::collections::HashSet::new(); + for sp in &doc.spreads { + let mut stack: Vec<(&Item, bool)> = sp.items.iter().map(|i| (&**i, true)).collect(); + while let Some((it, top)) = stack.pop() { + if it.hidden || top && hidden_layers.contains(&it.layer) { + continue; + } + shown.insert(it.id); + stack.extend(it.children().iter().map(|c| (&**c, false))); + } + } + shown +} + /// Package path of an asset: `{dir}/{name}-{id}.{ext}`, the name from its original file name /// (lowercase ASCII, so the package stays readable) and the id keeping two assets of the same /// name apart. diff --git a/crates/epub/src/story_writer.rs b/crates/epub/src/story_writer.rs index d6fb05159..31ca17ebc 100644 --- a/crates/epub/src/story_writer.rs +++ b/crates/epub/src/story_writer.rs @@ -120,9 +120,15 @@ impl<'a, 'f> StoryWriter<'a, 'f> { let mut lead = lead; let mut list: Option<&str> = None; let mut pre: Option<(String, bool)> = None; + let runs: Vec<(std::ops::Range, &story::CharFormat)> = st.runs().collect(); for (pi, (r, pf)) in st.para_ranges().into_iter().zip(&st.paras).enumerate() { let Some(text) = st.text.get(r.clone()) else { continue }; - let table = pf.table.and_then(|id| st.tables.get(&id)).filter(|_| text.contains(story::TABLE_ANCHOR)); + let base = doc.styles.resolve_para(pf).1; + // A table whose anchor is hidden or deleted is off the page, so it stays out. + let table = pf + .table + .and_then(|id| st.tables.get(&id)) + .filter(|_| text.find(story::TABLE_ANCHOR).is_some_and(|at| !doc.hides_run(&base, st.char_format_of(r.start + at)))); let only_table = table.is_some() && text.chars().all(|c| c == story::TABLE_ANCHOR || c.is_whitespace()); if !only_table || !lead.is_empty() { // Export Tagging: the style's element and class. @@ -167,7 +173,7 @@ impl<'a, 'f> StoryWriter<'a, 'f> { lead = ""; let mut after = String::new(); if !only_table { - self.runs(st, r, depth, out, &mut after); + self.runs(st, &runs, r, &base, depth, out, &mut after); } if tag == "pre" { // Closed when the next paragraph isn't a line of the same block. @@ -224,17 +230,29 @@ impl<'a, 'f> StoryWriter<'a, 'f> { t } - /// The runs of paragraph `para` of `st`; footnotes go to `after`. - fn runs(&mut self, st: &Story, para: std::ops::Range, depth: usize, out: &mut String, after: &mut String) { + /// The runs of paragraph `para` of `st` (`runs`: the story's, collected once; `base`: the + /// paragraph's base character attributes); footnotes go to `after`. + #[allow(clippy::too_many_arguments)] + fn runs( + &mut self, + st: &Story, + runs: &[(std::ops::Range, &story::CharFormat)], + para: std::ops::Range, + base: &designcraft_doc::CharProps, + depth: usize, + out: &mut String, + after: &mut String, + ) { let doc = self.doc; - for (rr, f) in st.runs() { + let first = runs.partition_point(|(rr, _)| rr.end <= para.start); + for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < para.end).map(|(rr, f)| (rr.clone(), *f)) { let a = rr.start.max(para.start); let b = rr.end.min(para.end); if a >= b { continue; } - // Hidden conditional text isn't exported. - if f.over.conditions.as_deref().is_some_and(|c| doc.conditions_hide(c)) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) { + // Hidden conditional text (the styles' conditions included) and deletions aren't exported. + if doc.hides_run(base, f) { continue; } let Some(raw) = st.text.get(a..b) else { continue }; diff --git a/crates/epub/src/tests.rs b/crates/epub/src/tests.rs index 62683f91a..62195aec0 100644 --- a/crates/epub/src/tests.rs +++ b/crates/epub/src/tests.rs @@ -1025,3 +1025,72 @@ fn hidden_group_children_are_not_exported() { assert!(html::reading_order(&grouped_text(true)).is_empty()); assert_eq!(html::reading_order(&grouped_text(false)).len(), 1); } + +/// Text hidden by a condition the paragraph style carries, and text marked deleted, are off the +/// page: neither the HTML body nor the navigation labels show them. A frame on a hidden layer +/// isn't exported at all. +#[test] +fn text_hidden_by_inherited_conditions_or_deletion_is_not_exported() { + use designcraft_doc::{ChangeMark, CharAttrs, Condition, ParagraphStyle}; + let mut d = Document::new(&NewDocument::default()); + d.conditions.push(Condition { name: "Secret".into(), color: [0, 0, 0], visible: false }); + d.styles_mut().paragraph.push(ParagraphStyle { + name: "Classified".into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs { conditions: Some(vec!["Secret".into()]), ..Default::default() }, + shortcut: String::new(), + }); + let lid = d.default_layer(); + let (_, sid) = d + .add_text_frame( + SpreadRef::Doc(0), + Rect::new(36.0, 36.0, 300.0, 100.0), + lid, + "Public heading\nclassified line\nkept dropped", + ParaFormat::default(), + ) + .unwrap(); + let st = d.story_mut(sid).unwrap(); + let c = st.text.find("classified").unwrap(); + st.format_paras(c..c + 1, |p| p.style = "Classified".into()); + let g = st.text.find(" dropped").unwrap(); + st.format_chars(g..g + 8, |f| f.over = CharAttrs { change: Some(ChangeMark::Deleted), ..Default::default() }); + let hidden_layer = designcraft_doc::LayerId(d.alloc()); + d.layers.push(designcraft_doc::Layer { + id: hidden_layer, + name: "Hidden".into(), + color: [0, 0, 0], + visible: false, + locked: false, + printable: true, + show_guides: true, + suppress_wrap_when_hidden: false, + }); + d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 300.0), hidden_layer, "On a hidden layer", ParaFormat::default()).unwrap(); + let html = html::export_html(&d, &html::HtmlOptions::default()); + assert!(html.contains("Public heading") && html.contains("kept"), "{html}"); + for gone in ["classified line", "dropped", "On a hidden layer"] { + assert!(!html.contains(gone), "{gone} must not be exported: {html}"); + } + let labels: Vec = chapters::toc_entries(&d, &html::reading_order(&d)).into_iter().map(|(_, label, _)| label).collect(); + assert_eq!(labels, ["Public heading"]); +} + +/// A threaded story is left out only when every one of its frames is hidden: a hidden first +/// frame does not hide the frames after it. +#[test] +fn a_threaded_story_is_skipped_only_when_every_frame_is_hidden() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "first", ParaFormat::default()).unwrap(); + let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 300.0), lid, "second", ParaFormat::default()).unwrap(); + d.thread(a, b).unwrap(); + let story = |d: &Document| html::reading_order(d).iter().filter(|x| **x == html::Block::Story(sid)).count(); + assert_eq!(story(&d), 1); + d.item_mut(a).unwrap().hidden = true; + assert_eq!(story(&d), 1, "the visible second frame keeps the story"); + d.item_mut(b).unwrap().hidden = true; + assert_eq!(story(&d), 0); +} diff --git a/crates/epub/tests/it/grouped_reading_order.rs b/crates/epub/tests/it/grouped_reading_order.rs index c4689cf20..eb820883a 100644 --- a/crates/epub/tests/it/grouped_reading_order.rs +++ b/crates/epub/tests/it/grouped_reading_order.rs @@ -145,10 +145,13 @@ fn articles_keep_their_explicit_order_and_exclusions() { let (c, _) = text(&mut doc, 0, 36.0, 10.0, "Article third"); let (omitted, _) = text(&mut doc, 0, 36.0, 5.0, "Excluded story"); doc.articles.push(Article { name: "Unused".into(), items: vec![omitted], export: false }); - doc.articles.push(Article { name: "Chosen".into(), items: vec![grouped, c, grouped], export: true }); + let (hidden, _) = text(&mut doc, 0, 36.0, 1.0, "Hidden in article"); + doc.item_mut(hidden).unwrap().hidden = true; + doc.articles.push(Article { name: "Chosen".into(), items: vec![grouped, c, grouped, hidden], export: true }); assert_output_order(&doc, &["Article first", "Article second", "Article third"]); for output in outputs(&doc) { assert!(!output.contains("Excluded story")); + assert!(!output.contains("Hidden in article")); } } diff --git a/crates/textimport/src/export.rs b/crates/textimport/src/export.rs index 2493f7f98..8d38780d1 100644 --- a/crates/textimport/src/export.rs +++ b/crates/textimport/src/export.rs @@ -20,33 +20,35 @@ fn plain_char(c: char) -> Option<&'static str> { } } -fn table_text(story: &Story, id: u64, nl: &str) -> String { +/// Cells of table `id` as rows of tab-separated cell text (the cells' visible text, nested +/// tables and notes left out), `nl` between rows. +fn table_text(doc: &Document, story: &Story, id: u64, nl: &str) -> String { let Some(t) = story.tables.get(&id) else { return String::new() }; (0..t.nrows()) - .map(|r| (0..t.ncols()).map(|c| t.cell(r, c).map(|x| x.text.text.replace('\n', " ")).unwrap_or_default()).collect::>().join("\t")) + .map(|r| { + (0..t.ncols()) + .map(|c| t.cell(r, c).map(|x| plain_text(doc, &x.text).replace("\r\n", " ").replace('\n', " ")).unwrap_or_default()) + .collect::>() + .join("\t") + }) .collect::>() .join(nl) } -/// Text Only: the story's text, CRLF between paragraphs. -pub fn plain_text(story: &Story) -> String { - // Tracked deletions aren't part of the text. - let deleted: Vec> = - story.runs().filter(|(_, f)| f.over.change == Some(designcraft_doc::ChangeMark::Deleted)).map(|(r, _)| r).collect(); +/// Text Only: the story's text as it shows (hidden conditional text and tracked deletions left +/// out), CRLF between paragraphs. +pub fn plain_text(doc: &Document, story: &Story) -> String { let mut out = String::with_capacity(story.text.len() + 16); + let spans = doc.visible_spans(story); for (i, r) in story.para_ranges().into_iter().enumerate() { if i > 0 { out.push_str("\r\n"); } - let start = r.start; - for (ci, c) in story.text[r].char_indices() { - if deleted.iter().any(|d| d.contains(&(start + ci))) { - continue; - } + for c in Document::visible_text(story, &spans, r).chars() { match (c, plain_char(c)) { (TABLE_ANCHOR, _) => { if let Some(id) = story.paras.get(i).and_then(|p| p.table) { - out.push_str(&table_text(story, id, "\r\n")); + out.push_str(&table_text(doc, story, id, "\r\n")); } } (_, Some("")) => out.push(c), @@ -178,7 +180,7 @@ pub fn rtf(doc: &Document, story: &Story) -> String { match c { TABLE_ANCHOR => { if let Some(id) = table { - for ch in table_text(story, *id, "\u{2028}").chars() { + for ch in table_text(doc, story, *id, "\u{2028}").chars() { rtf_escape(&mut out, ch); } } @@ -214,14 +216,42 @@ mod tests { #[test] fn text_variable_markers_are_dropped() { let st = Story::with_text(StoryId(1), "Page \u{E100} of", Default::default()); - assert_eq!(plain_text(&st), "Page of"); + assert_eq!(plain_text(&Document::new(&NewDocument::default()), &st), "Page of"); let r = rtf(&Document::new(&NewDocument::default()), &st); assert!(!r.contains("\\u-7936") && r.contains("Page of"), "{r}"); } #[test] fn text_only() { - assert_eq!(plain_text(&story()), "Plain bold {x}\r\nCafé\ntwo"); + assert_eq!(plain_text(&Document::new(&NewDocument::default()), &story()), "Plain bold {x}\r\nCafé\ntwo"); + } + + /// Text hidden by a condition set on the paragraph style, and text marked deleted, don't + /// reach Text Only: not in the story and not in a table cell. + #[test] + fn text_only_leaves_out_hidden_and_deleted_text() { + let mut doc = Document::new(&NewDocument::default()); + doc.conditions.push(designcraft_doc::Condition { name: "Secret".into(), color: [0, 0, 0], visible: false }); + doc.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle { + name: "Hidden".into(), + based_on: None, + next_style: None, + para: Default::default(), + chars: CharAttrs { conditions: Some(vec!["Secret".into()]), ..Default::default() }, + shortcut: String::new(), + }); + let mut st = Story::with_text(StoryId(1), "shown\nhidden by style\nkept gone", Default::default()); + let h = st.text.find("hidden").unwrap(); + st.format_paras(h..h + 1, |p| p.style = "Hidden".into()); + let g = st.text.find(" gone").unwrap(); + st.format_chars(g..g + 5, |f| f.over = CharAttrs { change: Some(designcraft_doc::ChangeMark::Deleted), ..Default::default() }); + assert_eq!(plain_text(&doc, &st), "shown\r\n\r\nkept"); + let mut outer = Story::with_text(StoryId(2), &TABLE_ANCHOR.to_string(), Default::default()); + let mut t = designcraft_doc::Table::new(7, 1, 1, 0, 0, 100.0); + t.cells[0].text = st.clone(); + outer.tables.insert(7, std::sync::Arc::new(t)); + outer.paras[0].table = Some(7); + assert_eq!(plain_text(&doc, &outer), "shown kept"); } #[test] diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index c3668614d..572c732c8 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -74,13 +74,15 @@ pub fn tagged_text(doc: &Document, story: &Story) -> String { out.push_str("\r\n"); } let pf = story.paras.get(i).cloned().unwrap_or_default(); + let base = doc.styles.resolve_para(&pf).1; let _ = write!(out, "", escape_value(&pf.style)); for (rr, f) in story.runs() { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); if a >= b { continue; } - if doc.conditions_hide(f.over.conditions.as_deref().unwrap_or(&[])) || f.over.change == Some(designcraft_doc::ChangeMark::Deleted) { + // Hidden conditional text (the styles' conditions included) and deletions aren't exported. + if doc.hides_run(&base, f) { continue; } let mut open = Vec::new(); From 027bbae9cb3b157750e9213254f03e7192dc10c9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:28:15 -0500 Subject: [PATCH 190/328] Engine: index style, tag, swatch and run lookups; bound polygon sides, Change All and spelling candidates * fix(engine): index lookups that were quadratic in a document's styles, tags, swatches and runs * address review: first swatch per name in book sync; bound spelling input before collecting * address review: keep the last source style per name in book sync; bound GREP replacement bytes while generating them * address review: write GREP replacements into a byte-bounded buffer; gate keep_last test off wasm * merge main into fix/sec-engine-linear-lookups * address review: make the suggestion length-cap test deterministic --- crates/compose/src/grep.rs | 58 ++++++++++++++++++++++++--- crates/engine/src/cmd/book.rs | 51 ++++++++++++++++++----- crates/engine/src/cmd/find.rs | 26 +++++++----- crates/engine/src/cmd/find/tests.rs | 18 +++++++++ crates/engine/src/cmd/paste_svg.rs | 51 ++++++++++++++++++----- crates/engine/src/cmd/select.rs | 3 +- crates/engine/src/cmd/spelling.rs | 20 +++++++++ crates/engine/src/cmd/table/styles.rs | 7 +++- crates/engine/src/cmd/text/edit.rs | 7 +++- crates/engine/src/cmd/xml.rs | 17 +++++--- crates/engine/src/dtd.rs | 14 ++++++- 11 files changed, 229 insertions(+), 43 deletions(-) diff --git a/crates/compose/src/grep.rs b/crates/compose/src/grep.rs index b387384f9..5a56920dc 100644 --- a/crates/compose/src/grep.rs +++ b/crates/compose/src/grep.rs @@ -432,15 +432,36 @@ impl Grep { Ok((out, more)) } - /// Matches in `text` and their replacements, `template` expanded per match (`$1`…; see - /// [`translate_replacement`]). Stops after the first match when `first_only`. - pub fn replacements(&self, text: &str, template: &str, first_only: bool) -> Result, String)>, GrepError> { + /// Matches in `text` that `keep` accepts and their replacements, `template` expanded per match + /// (`$1`…; see [`translate_replacement`]). Stops after the first kept match when `first_only`, + /// and with an error once the expanded replacements pass `max_bytes` in all (before any more + /// are made). + pub fn replacements( + &self, + text: &str, + template: &str, + first_only: bool, + max_bytes: usize, + keep: impl Fn(&Range) -> bool, + ) -> Result, String)>, GrepError> { let exp = fancy_regex::Expander::default(); let mut out = Vec::new(); + let mut bytes = 0usize; for caps in self.re.captures_iter(text) { let caps = caps.map_err(run_err)?; let Some(m) = caps.get(0) else { continue }; - out.push((m.range(), exp.expansion(template, &caps))); + if !keep(&m.range()) { + continue; + } + // Written into a buffer that refuses bytes past the budget, so an oversized + // expansion is rejected before it is allocated. + let mut w = BoundedBuf { buf: Vec::new(), left: max_bytes.saturating_sub(bytes) }; + if exp.write_expansion(&mut w, template, &caps).is_err() { + return Err(err(format!("the replacements would put more than {max_bytes} bytes in"))); + } + bytes += w.buf.len(); + let expanded = String::from_utf8(w.buf).map_err(|_| err("the replacement is not valid UTF-8".to_string()))?; + out.push((m.range(), expanded)); if first_only { break; } @@ -449,6 +470,27 @@ impl Grep { } } +/// A byte sink that fails a write that would pass its remaining budget (nothing is copied then). +struct BoundedBuf { + buf: Vec, + left: usize, +} + +impl std::io::Write for BoundedBuf { + fn write(&mut self, data: &[u8]) -> std::io::Result { + if data.len() > self.left { + return Err(std::io::ErrorKind::OutOfMemory.into()); + } + self.left -= data.len(); + self.buf.extend_from_slice(data); + Ok(data.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + fn run_err(e: fancy_regex::Error) -> GrepError { err(format!("GREP search stopped: {e}")) } @@ -520,7 +562,13 @@ mod tests { assert_eq!(g.find_all("axb A.B a.b", 1).unwrap().first(), Some(&(4..7))); let g = grep(r"(\d+)\h(\l+)"); let tpl = translate_replacement(r"$2~S$1x\r\$$"); - assert_eq!(g.replacements("5 kg", &tpl, false).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + assert_eq!(g.replacements("5 kg", &tpl, false, usize::MAX, |_| true).unwrap(), [(0..4, "kg\u{A0}5x\n$$".to_string())]); + // The total expanded size is bounded while the replacements are made, over the matches kept. + let g = grep("a"); + assert!(g.replacements("aaaa", "xxxx", false, 15, |_| true).is_err()); + assert_eq!(g.replacements("aaaa", "xxxx", false, 16, |_| true).unwrap().len(), 4); + assert_eq!(g.replacements("aaaa", "xxxx", false, 8, |m| m.start < 2).unwrap().len(), 2); + assert_eq!(g.replacements("aaaa", "xxxx", true, 4, |m| m.start >= 2).unwrap(), [(2..3, "xxxx".to_string())]); } #[test] diff --git a/crates/engine/src/cmd/book.rs b/crates/engine/src/cmd/book.rs index a4217f825..29f95741d 100644 --- a/crates/engine/src/cmd/book.rs +++ b/crates/engine/src/cmd/book.rs @@ -1,6 +1,8 @@ //! Books (File › New / Open Book): an ordered list of documents with continuous page numbers, //! styles synchronised from a style source, and one PDF for the whole book. Saved as `.dcbook`. +use std::collections::{HashMap, HashSet}; + use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -177,6 +179,15 @@ fn paginate(s: &Session) -> Result { Ok(json!({"pages": next - 1, "chapters": chapters})) } +/// `list` with only the last entry of each name, in the order of those last entries. +#[cfg(not(target_arch = "wasm32"))] +fn keep_last(list: &[T], name: impl Fn(&T) -> &str) -> Vec<&T> { + let mut seen = HashSet::new(); + let mut out: Vec<&T> = list.iter().rev().filter(|x| seen.insert(name(x))).collect(); + out.reverse(); + out +} + #[cfg(not(target_arch = "wasm32"))] fn sync_styles(s: &Session) -> Result { let b = s.book.as_ref().ok_or_else(no_book)?; @@ -187,6 +198,11 @@ fn sync_styles(s: &Session) -> Result { let styles = src.styles.clone(); let swatches = src.swatches.clone(); drop(src); + // A name the source defines twice keeps its last definition, at its last position. + let paragraph = keep_last(&styles.paragraph, |x| x.name.as_str()); + let character = keep_last(&styles.character, |x| x.name.as_str()); + let (paragraph_names, character_names): (HashSet<&str>, HashSet<&str>) = + (paragraph.iter().map(|x| x.name.as_str()).collect(), character.iter().map(|x| x.name.as_str()).collect()); let mut n = 0; for (i, path) in paths.iter().enumerate() { if i == b.style_source { @@ -195,21 +211,27 @@ fn sync_styles(s: &Session) -> Result { writable_chapter(s, path, "book.syncStyles")?; let mut d = load(path)?; { + // The source's styles replace the chapter's of the same names and go last, in the + // source's order (one pass over each list, not one per style). let st = d.styles_mut(); - for ps in &styles.paragraph { - st.paragraph.retain(|x| x.name != ps.name); - st.paragraph.push(ps.clone()); - } - for cs in &styles.character { - st.character.retain(|x| x.name != cs.name); - st.character.push(cs.clone()); - } + st.paragraph.retain(|x| !paragraph_names.contains(x.name.as_str())); + st.paragraph.extend(paragraph.iter().map(|x| (*x).clone())); + st.character.retain(|x| !character_names.contains(x.name.as_str())); + st.character.extend(character.iter().map(|x| (*x).clone())); + } + // First index per name, as Document::swatch resolves colours. + let mut at: HashMap = HashMap::new(); + for (i, w) in d.swatches.iter().enumerate() { + at.entry(w.name.clone()).or_insert(i); } for sw in &swatches { - match d.swatches.iter_mut().find(|w| w.name == sw.name) { + match at.get(&sw.name).and_then(|i| d.swatches.get_mut(*i)) { Some(w) if !w.locked => *w = sw.clone(), Some(_) => {} - None => d.swatches.push(sw.clone()), + None => { + at.insert(sw.name.clone(), d.swatches.len()); + d.swatches.push(sw.clone()); + } } } batch.stage(path, &d)?; @@ -431,4 +453,13 @@ mod tests { assert_eq!(t.execute("book.open", &json!({"path": p("book.dcbook")})).unwrap()["documents"], 2); std::fs::remove_dir_all(&dir).ok(); } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_source_style_defined_twice_keeps_its_last_definition() { + let list = [("a", 1), ("b", 2), ("a", 3), ("c", 4)]; + let kept: Vec<_> = super::keep_last(&list, |x| x.0).into_iter().copied().collect(); + // As the one-style-at-a-time loop left them: each name once, at its last position. + assert_eq!(kept, [("b", 2), ("a", 3), ("c", 4)]); + } } diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs index b9ab42550..63a1debb9 100644 --- a/crates/engine/src/cmd/find.rs +++ b/crates/engine/src/cmd/find.rs @@ -316,19 +316,27 @@ impl Search { ) -> Result, String)>> { let limit = if first_only { 1 } else { usize::MAX }; match (&self.re, self.spans(d, sid, cell, r)) { - (Some(re), None) if grep => re.replacements(text, rep, first_only).map_err(|e| bad("find.change", e)), - (Some(re), Some(spans)) if grep => Ok(re - .replacements(text, rep, false) - .map_err(|e| bad("find.change", e))? - .into_iter() - .filter(|(m, _)| within(&spans, m)) - .take(limit) - .collect()), - _ => Ok(self.find_all(d, sid, cell, r, text, limit)?.into_iter().map(|m| (m, rep.to_string())).collect()), + (Some(re), spans) if grep => re + .replacements(text, rep, first_only, MAX_CHANGE_BYTES, |m| spans.as_ref().is_none_or(|s| within(s, m))) + .map_err(|e| bad("find.change", e)), + _ => { + let found = self.find_all(d, sid, cell, r, text, limit)?; + // Every match gets its own copy of the change: bounded before any is made. + if found.len().saturating_mul(rep.len()) > MAX_CHANGE_BYTES { + return Err(bad( + "find.change", + format!("changing {} matches to {} bytes each would put more than {MAX_CHANGE_BYTES} bytes in", found.len(), rep.len()), + )); + } + Ok(found.into_iter().map(|m| (m, rep.to_string())).collect()) + } } } } +/// The most text one Change All may put into a story: the matches times the change's length. +const MAX_CHANGE_BYTES: usize = 64 << 20; + #[derive(Clone, Debug, PartialEq, Eq)] enum Domain { Document, diff --git a/crates/engine/src/cmd/find/tests.rs b/crates/engine/src/cmd/find/tests.rs index 348acd294..edea872ad 100644 --- a/crates/engine/src/cmd/find/tests.rs +++ b/crates/engine/src/cmd/find/tests.rs @@ -959,3 +959,21 @@ fn change_takes_any_selection_find_next_made() { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, if grep { "a" } else { "ab" }); } } + +/// Change All with a long change and many matches is refused before any copy of the change is +/// made, not after the memory for all of them has gone. +#[test] +fn change_all_is_bounded_by_what_it_would_put_in() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "x ".repeat(2048); + s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": text})).unwrap(); + let huge = "y".repeat(40_000); + let e = s.execute("find.change", &json!({"find": "x", "change": huge})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + // GREP replacements are held to the same total while they are made. + let e = s.execute("find.change", &json!({"find": "x", "change": huge, "grep": true})).unwrap_err().to_string(); + assert!(e.contains("would put more than"), "{e}"); + let r = s.execute("find.change", &json!({"find": "x", "change": "yy"})).unwrap(); + assert_eq!(r["count"], 2048); +} diff --git a/crates/engine/src/cmd/paste_svg.rs b/crates/engine/src/cmd/paste_svg.rs index a5d738cef..fa3c1cffc 100644 --- a/crates/engine/src/cmd/paste_svg.rs +++ b/crates/engine/src/cmd/paste_svg.rs @@ -3,6 +3,8 @@ //! clipboard as SVG markup; each path becomes a DesignCraft path with its fill and stroke, groups //! stay groups, and text comes in as outlines. +use std::collections::{HashMap, HashSet}; + use designcraft_doc::{Content, Fill, Item, ItemId, Selection, Shape, Stroke, StrokeType}; use designcraft_geom::{Affine, BezPath, PathData, Point, Rect}; use designcraft_images::usvg; @@ -201,16 +203,46 @@ fn bounds(art: &[Art]) -> Option { .reduce(|a, b| a.union(b)) } +/// The document's RGB colour swatches by colour and its swatch names, looked up once per paste +/// (a pasted SVG can hold tens of thousands of colours). +struct PasteSwatches { + by_rgb: HashMap<[u32; 3], String>, + names: HashSet, +} + +impl PasteSwatches { + /// An RGB colour as a key: equal colours, equal keys (`+ 0.0` makes -0 and 0 one key). + fn key(r: f32, g: f32, b: f32) -> [u32; 3] { + [(r + 0.0).to_bits(), (g + 0.0).to_bits(), (b + 0.0).to_bits()] + } + + fn new(d: &designcraft_doc::Document) -> Self { + use designcraft_color::swatch::SwatchValue; + let mut by_rgb = HashMap::new(); + for w in &d.swatches { + if let SwatchValue::Color { color: designcraft_color::Color::Rgb { r, g, b }, .. } = &w.value { + // The first swatch of a colour is the one, as a search from the start finds it. + by_rgb.entry(Self::key(*r, *g, *b)).or_insert_with(|| w.name.clone()); + } + } + Self { by_rgb, names: d.swatches.iter().map(|w| w.name.clone()).collect() } + } +} + /// The swatch holding exactly `rgb`: an existing process colour, else a new unnamed one (hidden /// from the Swatches panel until Add to Swatches), as InDesign does for pasted colours. -fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String { +fn swatch_for(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, rgb: [u8; 3]) -> String { use designcraft_color::swatch::{Swatch, SwatchValue}; let color = designcraft_color::Color::rgb8(rgb[0], rgb[1], rgb[2]); - if let Some(w) = d.swatches.iter().find(|w| matches!(&w.value, SwatchValue::Color { color: c, .. } if *c == color)) { - return w.name.clone(); + let designcraft_color::Color::Rgb { r, g, b } = color else { return String::new() }; + let key = PasteSwatches::key(r, g, b); + if let Some(name) = known.by_rgb.get(&key) { + return name.clone(); } let base = format!("R={} G={} B={}", rgb[0], rgb[1], rgb[2]); - let name = designcraft_doc::Styles::unique_name(|n| d.swatch(n).is_some(), &base); + let name = designcraft_doc::Styles::unique_name(|n| known.names.contains(n), &base); + known.names.insert(name.clone()); + known.by_rgb.insert(key, name.clone()); d.swatches.push(Swatch { name: name.clone(), value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process }, @@ -221,7 +253,7 @@ fn swatch_for(d: &mut designcraft_doc::Document, rgb: [u8; 3]) -> String { name } -fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_doc::LayerId, shift: Affine) -> Vec { +fn build(d: &mut designcraft_doc::Document, known: &mut PasteSwatches, art: Vec, layer: designcraft_doc::LayerId, shift: Affine) -> Vec { let mut out = Vec::new(); for a in art { match a { @@ -239,12 +271,12 @@ fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_do let paint = fill.map(|f| f.opacity).or(stroke.as_ref().map(|(c, _)| c.opacity)).unwrap_or(1.0); let mut it = Item::new(ItemId(d.alloc()), layer, if line { Shape::GraphicLine } else { Shape::Path }, data); it.fill = match fill { - Some(f) => Fill::swatch(&swatch_for(d, f.rgb)), + Some(f) => Fill::swatch(&swatch_for(d, known, f.rgb)), None => Fill::none(), }; it.stroke = match stroke { Some((c, s)) => Stroke { - swatch: swatch_for(d, c.rgb), + swatch: swatch_for(d, known, c.rgb), weight: s.width, cap: s.cap, join: s.join, @@ -258,7 +290,7 @@ fn build(d: &mut designcraft_doc::Document, art: Vec, layer: designcraft_do out.push(it); } Art::Group(items, opacity) => { - let children = build(d, items, layer, shift); + let children = build(d, known, items, layer, shift); if children.is_empty() { continue; } @@ -312,7 +344,8 @@ fn paste_svg(s: &mut Session, p: &Value) -> Result { warnings.push(format!("{} embedded image(s) left out (place images with File › Place)", notes.images)); } s.edit(|d, sel| { - let items = build(d, art, layer, shift); + let mut known = PasteSwatches::new(d); + let items = build(d, &mut known, art, layer, shift); let mut ids = Vec::new(); for it in items { ids.push(it.id); diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 0f77d5372..e351fe837 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -133,7 +133,8 @@ fn convert_shape(s: &mut Session, p: &Value) -> Result { const ID: &str = "object.convertShape"; let to = str_param(p, "to").ok_or_else(|| bad(ID, "`to` required"))?.to_string(); let ids = targets(s, p)?; - let sides = s.prefs.polygon_sides; + // The preference as object.polygon takes it: 3–100 sides, whatever prefs.set was given. + let sides = s.prefs.polygon_sides.clamp(3, 100); let inset = s.prefs.star_inset; s.edit(|d, _| { let mut changed = 0; diff --git a/crates/engine/src/cmd/spelling.rs b/crates/engine/src/cmd/spelling.rs index 4a43ab752..8ff9ac94d 100644 --- a/crates/engine/src/cmd/spelling.rs +++ b/crates/engine/src/cmd/spelling.rs @@ -161,6 +161,9 @@ const COMMON: &[&str] = &[ "yay", ]; +/// Longest word [`suggest`] makes candidates for. +pub const MAX_SUGGEST_CHARS: usize = 40; + /// Is `w` (lowercase) a known word, allowing common inflections of dictionary stems? pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool { // A typographer's apostrophe (don’t, we’re) is the word list's straight one. @@ -207,6 +210,11 @@ pub fn known(dict: &Dictionary, user: &[String], w: &str) -> bool { /// Up to 6 suggestions at edit distance 1, ranked: transpositions, replacements, deletions, insertions. pub fn suggest(dict: &Dictionary, w: &str) -> Vec { + // Each candidate is a copy of the word: 53 per position, quadratic in its length. No word of + // a dictionary is this long, so no edit of such a "word" is one either. Checked before collecting. + if w.chars().take(MAX_SUGGEST_CHARS + 1).count() > MAX_SUGGEST_CHARS { + return Vec::new(); + } let chars: Vec = w.chars().collect(); let mut out: Vec = Vec::new(); let mut push = |c: Vec| { @@ -325,6 +333,18 @@ mod tests { assert!(known(d, &["designcraft".into()], "designcraft")); } + /// A "word" longer than any in the dictionary gets no candidates: there would be more than + /// fifty copies of it per character. + #[test] + fn very_long_words_get_no_suggestions() { + // The dictionary holds the longest allowed word, so deleting one letter of the 41-letter + // input would be a hit if the length cap were not applied. + let d = Dictionary::from_entries(vec![("a".repeat(MAX_SUGGEST_CHARS), 0)]); + assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS)), Vec::::new()); + assert_eq!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS - 1)), vec!["a".repeat(MAX_SUGGEST_CHARS)]); + assert!(suggest(&d, &"a".repeat(MAX_SUGGEST_CHARS + 1)).is_empty()); + } + #[test] fn user_dictionary_replaces_and_counts() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/table/styles.rs b/crates/engine/src/cmd/table/styles.rs index fa3717977..046904fef 100644 --- a/crates/engine/src/cmd/table/styles.rs +++ b/crates/engine/src/cmd/table/styles.rs @@ -133,6 +133,11 @@ fn reapply_cell_styles(d: &mut Document, names: &[String]) { /// Include descendants when editing an inherited style, with the resolver's depth limit. fn dependent_styles<'a>(name: &str, styles: impl Iterator)>) -> Vec { let styles: Vec<_> = styles.collect(); + // The first style of a name is the one, as the resolver's lookup finds it. + let mut based_on: std::collections::HashMap<&str, Option<&str>> = std::collections::HashMap::new(); + for (n, base) in &styles { + based_on.entry(n).or_insert(*base); + } styles .iter() .filter(|(candidate, _)| { @@ -142,7 +147,7 @@ fn dependent_styles<'a>(name: &str, styles: impl Iterator Result { let mut changes = Vec::new(); for seg in segs.iter().rev() { let old = st.slice(seg.clone()).to_string(); - let new: String = starts.iter().zip(&mapped).filter(|(b, _)| seg.contains(b)).map(|(_, m)| m.as_str()).collect(); + // The characters in this run: `starts` is sorted, so a search finds the slice. + let (from, to) = (starts.partition_point(|b| *b < seg.start), starts.partition_point(|b| *b < seg.end)); + let new: String = mapped.get(from..to).unwrap_or_default().iter().map(String::as_str).collect(); if new != old { delta += new.len() as isize - old.len() as isize; st.replace(seg.clone(), &new); // Per-character changes (back to front), so ranges inside the run keep their boundaries. - for (i, (b, m)) in starts.iter().zip(&mapped).enumerate().rev().filter(|(_, (b, _))| seg.contains(b)) { + for i in (from..to.min(mapped.len())).rev() { + let (b, m) = (&starts[i], &mapped[i]); let ce = starts.get(i + 1).copied().unwrap_or(r.end); if m.len() != ce - b { changes.push((*b..ce, m.len())); diff --git a/crates/engine/src/cmd/xml.rs b/crates/engine/src/cmd/xml.rs index 81b57b5b3..949d96436 100644 --- a/crates/engine/src/cmd/xml.rs +++ b/crates/engine/src/cmd/xml.rs @@ -60,10 +60,13 @@ fn plain(t: &str) -> String { } /// A paragraph's text with inline-tagged runs as elements. -fn para_xml(st: &designcraft_doc::Story, r: std::ops::Range) -> String { +/// `runs` are the story's runs in order (collected once per story): only those reaching the +/// paragraph are visited, found by binary search. +fn para_xml(st: &designcraft_doc::Story, runs: &[(std::ops::Range, &designcraft_doc::CharFormat)], r: std::ops::Range) -> String { let mut out = String::new(); let mut open: Option = None; - for (rr, f) in st.runs() { + let first = runs.partition_point(|(rr, _)| rr.end <= r.start); + for (rr, f) in runs.iter().skip(first).take_while(|(rr, _)| rr.start < r.end) { let (a, b) = (rr.start.max(r.start), rr.end.min(r.end)); if a >= b { continue; @@ -97,8 +100,10 @@ pub fn export_xml(d: &Document) -> String { let Some(st) = d.story(tf.story) else { continue }; let mapped = |style: &str| d.xml.style_map.iter().find(|(s, _)| s == style).map(|(_, t)| t.clone()); // Paragraph text with inline tags already escaped. - let paras: Vec<(Option, String)> = - st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, r))).collect(); + let paras: Vec<(Option, String)> = { + let runs: Vec<_> = st.runs().collect(); + st.para_ranges().into_iter().enumerate().map(|(i, r)| (mapped(&st.paras[i].style), para_xml(st, &runs, r))).collect() + }; if paras.iter().any(|(m, _)| m.is_some()) { out.push_str(&format!(" <{tag}>\n")); for (m, text) in paras { @@ -341,8 +346,10 @@ pub fn specs() -> Vec { let dtd = crate::dtd::parse(&text).map_err(|e| bad("xml.loadDtd", e))?; let names: Vec = dtd.element_names().map(str::to_string).collect(); s.edit(|d, _| { + // The tags there are, then those added: one set, not a search per element. + let mut known: std::collections::HashSet = d.xml.tags.iter().map(|t| t.name.clone()).collect(); for n in &names { - if valid_name(n) && !d.xml.tags.iter().any(|t| t.name == *n) { + if valid_name(n) && known.insert(n.clone()) { let color = COLORS[d.xml.tags.len() % COLORS.len()]; d.xml.tags.push(XmlTag { name: n.clone(), color }); } diff --git a/crates/engine/src/dtd.rs b/crates/engine/src/dtd.rs index 7128ba84e..c0d45d820 100644 --- a/crates/engine/src/dtd.rs +++ b/crates/engine/src/dtd.rs @@ -29,6 +29,8 @@ enum Model { #[derive(Clone, Debug, Default)] pub struct Dtd { elements: Vec<(String, Model)>, + /// Each declared name's first declaration (which wins), by name. + index: HashMap, /// Element → its `#REQUIRED` attributes. required: HashMap>, } @@ -47,7 +49,7 @@ impl Dtd { } fn model(&self, name: &str) -> Option<&Model> { - self.elements.iter().find(|(n, _)| n == name).map(|(_, m)| m) + self.elements.get(*self.index.get(name)?).map(|(_, m)| m) } } @@ -252,6 +254,7 @@ pub fn parse(src: &str) -> Result { let rest = rest.trim_start(); let name: String = rest.chars().take_while(|c| !c.is_whitespace()).collect(); let model = parse_model(&rest[name.len()..]).map_err(|e| format!(": {e}"))?; + dtd.index.entry(name.clone()).or_insert(dtd.elements.len()); dtd.elements.push((name, model)); } else if let Some(rest) = d.strip_prefix("ATTLIST") { // name (attr type default)*; only `#REQUIRED` matters here. @@ -609,6 +612,15 @@ mod tests { assert!(parse("just text").is_err()); } + /// An element declared twice keeps its first model (the index points there). + #[test] + fn the_first_declaration_of_an_element_wins() { + let dtd = parse("\n\n").unwrap(); + assert_eq!(dtd.element_names().collect::>(), ["a", "b", "a"]); + assert_eq!(validate(&dtd, ""), vec![]); + assert!(!validate(&dtd, "").is_empty()); + } + /// A few hundred bytes of nested parameter entities used to inflate multiplicatively across /// the eight wholly-string-replacing passes (#713); expansion is capped. #[test] From 95fdb96680e8133af05b90c3dd329126e206d858 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:19:22 -0800 Subject: [PATCH 191/328] Text wrap: a clipped contour visits only the edges in each line band A clipped contour now looks only at the edges of the outline and its clips that reach a line band, and charges its work budget for those alone. An outline with thousands of points elsewhere no longer exhausts the budget and falls back to the projections' common part. The Text wrap row of docs/typography-parity.md notes that an image over 40 megapixels, or one that can't be decoded, follows the frame's path. --- crates/compose/src/lib.rs | 150 ++++++++++++++++++++---------------- crates/compose/src/tests.rs | 30 ++++++++ docs/typography-parity.md | 2 +- 3 files changed, 115 insertions(+), 67 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 76df87568..4224b793f 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -406,10 +406,6 @@ impl Region<'_> { fn fills(self, winding: i32) -> bool { if self.even_odd { winding % 2 != 0 } else { winding != 0 } } - - fn edges(self) -> usize { - self.rings.iter().map(Vec::len).sum() - } } /// Points a contour outline may have; a larger outline wraps around its bounding box. @@ -545,19 +541,56 @@ fn intersect_spans(a: &[(f64, f64)], b: &[(f64, f64)]) -> Vec<(f64, f64)> { /// one shape that lies inside the others. The spans are the middle slice of all the shapes and /// the parts of each shape's edges in the band that lie inside the others, so a part of the /// outline outside a clip blocks nothing, even where it shares x positions with the clip in the -/// same band. None when that takes more than [`MAX_CLIPPED_WORK`] edge visits. +/// same band. Only the edges that reach the band are visited. None when that takes more than +/// [`MAX_CLIPPED_WORK`] edge visits. fn clipped_band_spans(shapes: &[Region], y0: f64, y1: f64) -> Option> { let middle = y0 * 0.5 + y1 * 0.5; let mut slices = shapes.iter().map(|s| merge_spans(middle_spans(*s, middle))); let first = slices.next()?; let mut spans = slices.fold(first, |a, b| intersect_spans(&a, &b)); + let banded: Vec = shapes.iter().map(|s| BandEdges::of(*s, y0, y1)).collect(); let mut budget = MAX_CLIPPED_WORK; - for k in 0..shapes.len() { - edges_inside(shapes, k, y0, y1, &mut budget, &mut spans)?; + for k in 0..banded.len() { + edges_inside(&banded, k, y0, y1, &mut budget, &mut spans)?; } Some(merge_spans(spans)) } +/// The edges of a shape that reach a line band, with a margin above and below. Every point +/// [`segment_inside`] tests lies within the margin, and an edge that doesn't reach a point's y +/// neither crosses the ray from it nor passes within a hair of it, so these edges give the same +/// inside and on-edge answers as the whole shape for those points. +struct BandEdges { + edges: Vec<(Point, Point)>, + even_odd: bool, +} + +impl BandEdges { + /// Margin added above and below the band; well above the side step in [`segment_inside`]. + const MARGIN: f64 = 1e-3; + + fn of(shape: Region, y0: f64, y1: f64) -> BandEdges { + let (lo, hi) = (y0 - Self::MARGIN, y1 + Self::MARGIN); + let mut edges = Vec::new(); + for ring in shape.rings { + let Some(&last) = ring.last() else { continue }; + let mut a = last; + for &b in ring { + if a.y.max(b.y) >= lo && a.y.min(b.y) <= hi { + edges.push((a, b)); + } + a = b; + } + } + BandEdges { edges, even_odd: shape.even_odd } + } + + /// Is a point with this winding number filled? + fn fills(&self, winding: i32) -> bool { + if self.even_odd { winding % 2 != 0 } else { winding != 0 } + } +} + /// Takes `n` edge visits from `budget`; None when it doesn't hold that many. fn spend(budget: &mut usize, n: usize) -> Option<()> { *budget = budget.checked_sub(n)?; @@ -567,25 +600,19 @@ fn spend(budget: &mut usize, n: usize) -> Option<()> { /// Pushes to `out` the x-ranges of the parts of the edges of `shapes[k]` within the band `y0..y1` /// that bound the part of the plane inside all of `shapes` ([`segment_inside`]). None when /// `budget` runs out. -fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { - let n = shapes.iter().map(|o| o.edges()).sum::().max(1); - let rings = shapes.get(k)?.rings; - for ring in rings { - let Some(&last) = ring.last() else { continue }; - let mut a = last; - for &b in ring { - let dy = b.y - a.y; - if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { - let (t0, t1) = if dy.abs() < 1e-12 { - (0.0, 1.0) - } else { - let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); - (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) - }; - let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); - segment_inside(p, q, shapes, k, n, budget, out)?; - } - a = b; +fn edges_inside(shapes: &[BandEdges], k: usize, y0: f64, y1: f64, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { + let n = shapes.iter().map(|o| o.edges.len()).sum::().max(1); + for &(a, b) in &shapes.get(k)?.edges { + let dy = b.y - a.y; + if a.y.max(b.y) >= y0 && a.y.min(b.y) <= y1 { + let (t0, t1) = if dy.abs() < 1e-12 { + (0.0, 1.0) + } else { + let (u, v) = ((y0 - a.y) / dy, (y1 - a.y) / dy); + (u.min(v).clamp(0.0, 1.0), u.max(v).clamp(0.0, 1.0)) + }; + let (p, q) = (a + (b - a) * t0, a + (b - a) * t1); + segment_inside(p, q, shapes, k, n, budget, out)?; } } Some(()) @@ -597,14 +624,14 @@ fn edges_inside(shapes: &[Region], k: usize, y0: f64, y1: f64, budget: &mut usiz /// the points just beside it on one side are inside all the shapes. Where `shapes[k]` has no area /// on either side (an open path), it counts when it is inside the other shapes or on their /// boundary. Each pass over the edges takes `n` from `budget`; None when it runs out. -fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { +fn segment_inside(p: Point, q: Point, shapes: &[BandEdges], k: usize, n: usize, budget: &mut usize, out: &mut Vec<(f64, f64)>) -> Option<()> { let r = q - p; let len2 = r.hypot2(); if !len2.is_finite() { return Some(()); } let at = |t: f64| p + r * t; - let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(*s, pt)); + let in_others = |pt: Point| shapes.iter().enumerate().all(|(i, s)| i == k || inside_or_on(s, pt)); spend(budget, n)?; if len2 < 1e-24 { if in_others(p) { @@ -615,7 +642,7 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud // A step to either side of the segment, well above rounding at page coordinates. let side = r.turn_90() * (1e-6 / len2.sqrt()); let bounds_the_part = |m: Point| { - let own = shapes.get(k).copied(); + let own = shapes.get(k); let in_own = |pt: Point| own.is_some_and(|s| inside_or_on(s, pt)); let (a, b) = (m + side, m - side); match (in_own(a), in_own(b)) { @@ -625,29 +652,24 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud }; let (ylo, yhi) = (p.y.min(q.y), p.y.max(q.y)); let mut ts = vec![0.0, 1.0]; - for ring in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| s.rings) { - let Some(&last) = ring.last() else { continue }; - let mut c = last; - for &d in ring { - if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { - let e = d - c; - let denom = r.cross(e); - let w = c - p; - if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { - let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); - if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + for &(c, d) in shapes.iter().enumerate().filter(|(i, _)| *i != k).flat_map(|(_, s)| &s.edges) { + if c.y.max(d.y) >= ylo - 1e-9 && c.y.min(d.y) <= yhi + 1e-9 { + let e = d - c; + let denom = r.cross(e); + let w = c - p; + if denom.abs() > 1e-12 * (len2 * e.hypot2()).sqrt() { + let (t, u) = (w.cross(e) / denom, w.cross(r) / denom); + if (-1e-9..=1.0 + 1e-9).contains(&u) && (0.0..=1.0).contains(&t) { + ts.push(t); + } + } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { + // Collinear: the edge's ends split the segment. + for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { + if (0.0..=1.0).contains(&t) { ts.push(t); } - } else if w.cross(r).abs() <= 1e-9 * len2.sqrt() { - // Collinear: the edge's ends split the segment. - for t in [w.dot(r) / len2, (d - p).dot(r) / len2] { - if (0.0..=1.0).contains(&t) { - ts.push(t); - } - } } } - c = d; } } ts.sort_by(f64::total_cmp); @@ -663,26 +685,22 @@ fn segment_inside(p: Point, q: Point, shapes: &[Region], k: usize, n: usize, bud Some(()) } -/// Is `pt` inside `shape` or within a hair of one of its edges? -fn inside_or_on(shape: Region, pt: Point) -> bool { +/// Is `pt`, a point within the band of `shape`'s edges, inside the shape or within a hair of one +/// of its edges? +fn inside_or_on(shape: &BandEdges, pt: Point) -> bool { let mut winding = 0i32; - for ring in shape.rings { - let Some(&last) = ring.last() else { continue }; - let mut a = last; - for &b in ring { - let e = b - a; - let len2 = e.hypot2(); - let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; - if (a + e * t - pt).hypot2() < 1e-18 { - return true; + for &(a, b) in &shape.edges { + let e = b - a; + let len2 = e.hypot2(); + let t = if len2 > 0.0 { ((pt - a).dot(e) / len2).clamp(0.0, 1.0) } else { 0.0 }; + if (a + e * t - pt).hypot2() < 1e-18 { + return true; + } + if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { + let x = a.x + (pt.y - a.y) / e.y * e.x; + if x > pt.x { + winding += if e.y > 0.0 { 1 } else { -1 }; } - if (a.y <= pt.y && pt.y < b.y) || (b.y <= pt.y && pt.y < a.y) { - let x = a.x + (pt.y - a.y) / e.y * e.x; - if x > pt.x { - winding += if e.y > 0.0 { 1 } else { -1 }; - } - } - a = b; } } shape.fills(winding) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e8fb2aac8..8ea0fe3cc 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8612,6 +8612,36 @@ fn a_clipped_contour_blocks_only_what_its_frame_shows() { assert_eq!(c.within(&poly(&detailed), id).band_spans(0.0, 10.0), vec![(20.0, 40.0)]); } +/// Edges far above or below a line band cost a clipped contour nothing there: an outline with +/// 7,000 points well below the band still gets the exact spans, not the projections' common part. +#[test] +fn a_clipped_contours_budget_counts_only_edges_in_the_band() { + let poly = |pts: &[(f64, f64)]| { + let mut p = designcraft_geom::BezPath::new(); + p.move_to(pts[0]); + for &q in &pts[1..] { + p.line_to(q); + } + p.close_path(); + p + }; + let id = designcraft_geom::Affine::IDENTITY; + // The L-shaped frame of the test above, with its notch at x 10..40 above y = 6. + let frame = poly(&[(0.0, 0.0), (10.0, 0.0), (10.0, 6.0), (40.0, 6.0), (40.0, 10.0), (0.0, 10.0)]); + // An outline in the notch and to the right of the frame, with 40 teeth along its top in the + // band and a 7,000-point zigzag along its bottom at y = 200. + let mut pts = vec![(20.0, 0.0)]; + for i in 0..40 { + let x = 40.0 + 0.5 * f64::from(i); + pts.extend([(x, 0.0), (x + 0.25, 0.5)]); + } + pts.push((60.0, 0.0)); + pts.extend((0..7000).map(|i| (60.0 - 10.0 * f64::from(i) / 6999.0, if i % 2 == 0 { 200.0 } else { 201.0 }))); + pts.extend([(50.0, 4.0), (20.0, 4.0)]); + let c = Contour::of(&poly(&pts), id, 0.0).unwrap(); + assert_eq!(c.within(&frame, id).band_spans(0.0, 10.0), Vec::<(f64, f64)>::new(), "the frame shows none of it"); +} + /// Rule Above's offset runs from the first line's baseline up to the rule's bottom edge, as in /// InDesign: a rule set clear of the cap height sits between the rows, not across the row above /// (an INDD project list whose rules crossed the previous paragraph's text). diff --git a/docs/typography-parity.md b/docs/typography-parity.md index 0b3c030cf..323e028dc 100644 --- a/docs/typography-parity.md +++ b/docs/typography-parity.md @@ -59,7 +59,7 @@ Fidelity: **unmeasured** unless stated. | Paragraph rules, borders, shading | ✓ | ✓ | ✓ | | | Balance ragged lines | ✓ | ✓ | ✓ | | | Optical margin alignment | per story with a size, Ignore Optical Margin per paragraph and style | ✓ (hang table of our own, scaled by the story's size; Story panel; IDML `StoryPreference`, `IgnoreEdgeAlignment`) | ~ | hang amounts are ours, InDesign's unknown (#947) | -| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels; Detect Edges and Photoshop Path contours follow the frame's path | +| Text wrap | bounding box, shape, jump object/column, wrap sides (text on both sides of an object), contour options, on page items and anchored objects | ✓ | ~ | Alpha Channel contours follow the outline of the image's visible pixels (an image over 40 megapixels, or one that can't be decoded, follows the frame's path); Detect Edges and Photoshop Path contours follow the frame's path | | Anchored objects | inline, above line, custom | ✓ | ~ | anchored objects in table cells not drawn (#163) | | Footnotes, endnotes | ✓ | ✓ | ~ | footnotes don't split across columns yet | | Type on a path | ✓ | ✓ | ✓ | | From fad00dd646298479046accd3102ee21e776f3914 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:55:38 -0800 Subject: [PATCH 192/328] Data merge: an image field in a table cell or a note is refused by name With the insertion point in a table cell or a note, data.placeholder.add with an image field returned "a hyperlink field can't go in a table cell or a note". It now returns a message about image fields that names the two ways on: bind the field to a frame, or pass role text to merge its path. Nothing is inserted on the error, and role text still puts the marker in the cell. Docs: docs/agents.md and the command's params text. --- crates/engine/src/cmd/datamerge.rs | 10 +++++++++- crates/engine/src/cmd/datamerge/tests.rs | 19 +++++++++++++++++++ docs/agents.md | 4 +++- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index 213b3d1cb..e03da2d05 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Insert Field", [], None, - "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder)", + "{field, role?: text|image|qr|hyperlink, story?, at?, end?, item?} → {id}; an image field at a text insertion point merges as an inline image; with the insertion point in a table cell or a note → {cell: true, marker} (a typed marker, not an anchored placeholder; an image field there is an error unless role is text)", has_doc, placeholder_add ), @@ -535,6 +535,14 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) && let Some(t) = sel.text && let Some(pressed) = t.cell { + // The merge fills such a text with the record's value as text, so an image there + // would merge as its path. + if role == PlaceholderRole::Image { + return Err(bad( + "data.placeholder.add", + "an image field can't go in a table cell or a note; bind it to a frame, or insert it with role text to merge its path", + )); + } if role != PlaceholderRole::Text { return Err(bad("data.placeholder.add", "a hyperlink field can't go in a table cell or a note; insert it as text")); } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index e5cf28497..5f5c4a118 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1605,6 +1605,25 @@ fn a_field_named_with_angle_brackets_is_refused_in_a_cell() { let _ = made; } +/// An image field with the insertion point in a table cell is refused with a message about image +/// fields, and nothing is inserted; with role text its marker goes into the cell. +#[test] +fn an_image_field_in_a_cell_is_refused_unless_its_role_is_text() { + let mut s = Session::new(); + table_with_caret_in_cell(&mut s, "Name,@Photo\nAda,pics/a.png\n"); + for params in [json!({"field": "Photo"}), json!({"field": "Photo", "role": "image"})] { + let e = s.execute("data.placeholder.add", ¶ms).expect_err("refused").to_string(); + assert!(e.contains("an image field can't go in a table cell or a note"), "{e}"); + assert!(!e.contains("hyperlink"), "{e}"); + assert_eq!(cell_texts(&s), ["Who", "Where"], "nothing inserted"); + } + let r = exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "text"})); + assert_eq!(r["marker"], "<>", "{r}"); + assert_eq!(cell_texts(&s), ["Who", "<>Where"]); + exec(&mut s, "data.preview", json!({"record": 1})); + assert_eq!(cell_texts(&s), ["Who", "pics/a.pngWhere"], "the text role merges the path"); +} + /// Endnote text is filled too: it is a text inside its story, like a footnote's. #[test] fn a_field_in_an_endnote_is_filled() { diff --git a/docs/agents.md b/docs/agents.md index 13977d2af..b2ec4c156 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -90,7 +90,9 @@ external PDF/X certification. `data.source.remove` drops it); `data.fields` lists its fields. `data.placeholder.add {field, role?, story?, at?, end?, item?}` marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the -frame. A QR field (a `#` column) inserted at a text insertion point is refused; bind it to a frame instead. An image +frame. The merge writes only text into a table cell or a note: an image field inserted there is refused unless `role` +is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) inserted at a +text insertion point is refused; bind it to a frame instead. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. From 767c0a542b23118c2ebdbf3a0363a544005be950 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:51:33 -0800 Subject: [PATCH 193/328] Canvas: an idle frame paints and looks up only the spreads in view Every frame, the canvas painted the page shadow, paper, edges, guides, margins and frame edges of every spread in the document, and looked up the composed story of every text frame that ends a story to place its overset mark. Each lookup walks the document, so an idle frame cost more with every page added, and faster than the page count grew. Those shapes are now painted only where they reach into the canvas view: spreads by their bounds, bleed and slug outlines, page grids and guides by their own rectangles, and frames by a rectangle around their anchors, handles and nested objects. A story is looked up only for a frame in view. What shows in the view is the same. In a 400-page document with two frames a page, an idle canvas frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. Part of #1343. Refs #1411, #2298. --- ROADMAP.md | 1 + crates/ui-egui/src/canvas.rs | 20 ++++-- crates/ui-egui/src/canvas/frames.rs | 51 +++++++++++--- crates/ui-egui/src/canvas/page_decor.rs | 40 ++++++++--- crates/ui-egui/src/canvas/tests.rs | 93 +++++++++++++++++++++---- 5 files changed, 170 insertions(+), 35 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..16b009a80 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -413,6 +413,7 @@ Newest first. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). +- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-10-30** · Spreads show a line at each edge where two of their pages meet, on the canvas only (it isn't printed or exported), so the page boundaries inside a spread are visible while laying out across them, in the spread edge's colour. Right-to-left spreads and pages of different sizes put it on the edge the pages share; pages that don't touch, as an imported spread can keep them, get none (#1838). No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4ce86d083..50652ffe6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -133,6 +133,13 @@ impl Xf { } } +/// Whether the canvas rectangle `r`, grown by `margin` screen points, reaches into `clip`. A +/// rectangle with a coordinate that is not finite counts as in view. +fn in_view(xf: &Xf, clip: Rect, r: DRect, margin: f32) -> bool { + let s = xf.rect(r); + !s.is_finite() || s.expand(margin).intersects(clip) +} + /// A guide being dragged out or moved: its line, what caught it, and where it is beside the pointer (#1282). fn draw_guide_drag(app: &DesignApp, painter: &egui::Painter, xf: &Xf, g: &GuideDrag, p: Pos2, rect: Rect, t: &Tokens) { let col = Color32::from_rgb(74, 227, 255); @@ -188,7 +195,9 @@ fn paint_render(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Documen // Preview: only the shown area of each spread keeps its content. for slot in &layout.slots { let r = shown_area(app, doc, xf, slot); - painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone())); + if r.intersects(screen) { + painter.with_clip_rect(r.intersect(screen)).add(egui::Shape::mesh(mesh.clone())); + } } } else { painter.add(egui::Shape::mesh(mesh)); @@ -252,8 +261,11 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let preview = app.ui.screen_mode != ScreenMode::Normal; let bg = if app.ui.screen_mode == ScreenMode::Presentation { Color32::BLACK } else { t.pasteboard }; painter.rect_filled(screen, 0.0, bg); + // The spreads whose pages, shadow or edge reach into the view: the others paint none of them. + let clip = painter.clip_rect(); + let in_sight: Vec<&SpreadSlot> = layout.slots.iter().filter(|slot| in_view(&xf, clip, slot.bounds, 2.0)).collect(); // Page shadow: a hard 1.5 pt black offset on the right and bottom (InDesign 2026). - for slot in &layout.slots { + for slot in &in_sight { let r = xf.rect(slot.bounds); painter.rect_filled(r.translate(vec2(1.5, 1.5)), 0.0, Color32::BLACK); } @@ -261,7 +273,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { // not the shadow's black, until its render arrives. let [r, g, b, _] = doc.resolve_color(designcraft_color::swatch::PAPER, 1.0).unwrap_or(designcraft_color::Color::WHITE).to_rgba8(1.0); let paper = Color32::from_rgb(r, g, b); - for slot in &layout.slots { + for slot in &in_sight { for page in doc.spread(slot.spread).map(|sp| sp.pages.as_slice()).unwrap_or_default() { painter.rect_filled(xf.rect(slot.xf.transform_rect_bbox(page.bounds())), 0.0, paper); } @@ -271,7 +283,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { paint_render(app, &painter, &xf, &doc, &layout, screen, preview); crate::separations::paint(app, ui.ctx(), &painter, &xf, &layout, screen); let hair = 1.0 / ui.ctx().pixels_per_point(); - for slot in &layout.slots { + for slot in &in_sight { painter.rect_stroke(xf.rect(slot.bounds), 0.0, Stroke::new(hair, page_decor::PAGE_EDGE), StrokeKind::Outside); } if !preview { diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 0c92c3c6c..e557c9b1d 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -3,8 +3,8 @@ use super::render::c32; use super::rulers::hair; use super::text_overlay::draw_text_selection; use super::{ - Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, pos2, - vec2, + Affine, CanvasLayout, Color32, Content, DRect, DesignApp, Document, Item, Point, Pos2, Rect, Selection, Stroke, StrokeKind, Xf, compose, in_view, + pos2, vec2, }; /// Spread-space → canvas transform for an item at `loc`. @@ -51,22 +51,31 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc return; } let ported = ported_frames(app, doc); + // Only the objects that reach into the view are drawn, and only their stories are looked up: + // an object out of view adds no shapes and no work on its story. + let clip = painter.clip_rect(); + let parent_items = doc.parents.iter().any(|p| !p.items.is_empty()); for slot in &layout.slots { let Some(sp) = doc.spread(slot.spread) else { continue }; let a = slot.xf; // Parent items on document pages, and base parents' items on a parent spread: dotted edges. - for (pi, page) in sp.pages.iter().enumerate() { - let overridden = doc.overridden_parent_items(slot.spread, pi); + for (pi, page) in sp.pages.iter().enumerate().filter(|_| parent_items) { + let mut overridden = None; for (ppi, ppg) in doc.shown_parent_pages(slot.spread, pi) { let Some(parent) = doc.parents.get(ppi) else { continue }; let Some(ppage) = parent.pages.get(ppg) else { continue }; let dx = page.x - ppage.x; + let shifted = a * Affine::translate((dx, 0.0)); for it in &parent.items { - if (parent.pages.len() > 1 && parent.page_at_x(it.bounds().center().x) != Some(ppg)) || overridden.contains(&it.id) { + let bounds = it.bounds(); + if (parent.pages.len() > 1 && parent.page_at_x(bounds.center().x) != Some(ppg)) + || !in_view(xf, clip, shifted.transform_rect_bbox(bounds), EDGE_MARGIN) + || overridden.get_or_insert_with(|| doc.overridden_parent_items(slot.spread, pi)).contains(&it.id) + { continue; } let col = doc.layer(it.layer).map(|l| c32(l.color)).unwrap_or(Color32::LIGHT_BLUE); - for poly in path_screen(it, xf, a * Affine::translate((dx, 0.0))) { + for poly in path_screen(it, xf, shifted) { for w in poly.windows(2) { dashed(painter, w[0], w[1], Stroke::new(hair(painter), col.gamma_multiply(0.8)), 2.0, 2.0); } @@ -74,13 +83,15 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc } } } - for it in &sp.items { + let seen: Vec<&std::sync::Arc> = + sp.items.iter().filter(|it| reach(it, 0).is_none_or(|r| in_view(xf, clip, a.transform_rect_bbox(r), EDGE_MARGIN))).collect(); + for it in &seen { draw_item_edges(painter, xf, doc, it, a); } // Every overset frame, selected or not and inside groups too, shows its red mark at the // out port (InDesign shows it only on the selected frame; a report in Preflight is easy // to miss while laying out). - for (it, c) in overset_marks(app, doc, layout, &sp.items, xf.zoom, &ported) { + for (it, c) in seen.iter().flat_map(|it| overset_marks(app, doc, layout, std::slice::from_ref(*it), xf.zoom, &ported)) { let c = xf.to_screen(c); let s = designcraft_tools::thread::PORT_SIZE_PX as f32; painter.rect_filled(Rect::from_center_size(c, vec2(s, s)), 0.0, Color32::WHITE); @@ -93,7 +104,7 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc if app.ui.tagged_frames { for top in &sp.items { top.walk(&mut |it: &Item| { - if it.xml_tag.is_empty() { + if it.xml_tag.is_empty() || !in_view(xf, clip, (a * it.xf).transform_rect_bbox(it.inner_bounds()), EDGE_MARGIN) { return; } let Some(t) = doc.xml.tags.iter().find(|t| t.name == it.xml_tag) else { return }; @@ -109,6 +120,28 @@ pub(super) fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc } } +/// How far, in screen points, an object's edges and port marks paint past its bounds: the 8.5 pt +/// port square is centred on the frame's edge. +const EDGE_MARGIN: f32 = 8.0; + +/// A rectangle around `it` and everything nested in it, in its parent's space: every anchor and +/// handle of its path, and those of the objects grouped or pasted into it, which can lie outside +/// its own outline. None when the nesting is deeper than [`PORT_GROUP_DEPTH`]. +fn reach(it: &Item, depth: usize) -> Option { + if depth > PORT_GROUP_DEPTH { + return None; + } + let mut all: Option = None; + let mut add = |r: DRect| all = Some(all.map_or(r, |a| a.union(r))); + for p in it.path.subpaths.iter().flat_map(|sp| &sp.anchors).flat_map(|a| [a.p, a.h_in, a.h_out]) { + add(DRect::from_points(p, p)); + } + for c in it.children() { + add(reach(c, depth + 1)?); + } + Some(it.xf.transform_rect_bbox(all.unwrap_or(DRect::ZERO))) +} + fn draw_item_edges(painter: &egui::Painter, xf: &Xf, doc: &Document, it: &Item, a: Affine) { if it.hidden || doc.layer(it.layer).is_some_and(|l| !l.visible) { return; diff --git a/crates/ui-egui/src/canvas/page_decor.rs b/crates/ui-egui/src/canvas/page_decor.rs index 39df15a78..a42cb6386 100644 --- a/crates/ui-egui/src/canvas/page_decor.rs +++ b/crates/ui-egui/src/canvas/page_decor.rs @@ -3,7 +3,7 @@ use super::render::c32; use super::rulers::hair; use super::{ CanvasLayout, Color32, DRect, DesignApp, Document, GuideSel, Item, Point, Pos2, Rect, ScreenMode, SpreadRef, SpreadSlot, Stroke, StrokeKind, - Tokens, Xf, + Tokens, Xf, in_view, }; pub(super) fn dashed(painter: &egui::Painter, a: Pos2, b: Pos2, stroke: Stroke, dash: f32, gap: f32) { @@ -52,11 +52,16 @@ pub(super) fn draw_guides( ) { let selection: std::collections::HashSet = app.session.active().map(|st| st.selection.guides.iter().copied().collect()).unwrap_or_default(); + // Only what reaches into the view is painted: a spread or a page out of view adds no shapes. + let clip = painter.clip_rect(); for slot in &layout.slots { let Some(sp) = doc.spread(slot.spread) else { continue }; + let shows = |r: DRect| in_view(xf, clip, slot.xf.transform_rect_bbox(r), GUIDE_MARGIN); if app.ui.guides { - draw_bleed_and_slug(painter, xf, doc, slot, sp); - draw_spine(painter, xf, slot, sp); + draw_bleed_and_slug(painter, xf, doc, slot, sp, clip); + if shows(sp.bounds()) { + draw_spine(painter, xf, slot, sp); + } } let pasteboard = slot.xf.inverse().transform_rect_bbox(layout.pasteboard); for (pi, p) in sp.pages.iter().enumerate() { @@ -65,22 +70,28 @@ pub(super) fn draw_guides( if !app.ui.guides { continue; } - draw_page_grids(painter, xf, doc, slot, p, pr, app.ui.baseline_grid); - let cx = GuideCtx { painter, xf, doc, slot, sp, pasteboard }; + if shows(pr.union(p.margin_rect())) { + draw_page_grids(painter, xf, doc, slot, p, pr, app.ui.baseline_grid); + } + let cx = GuideCtx { painter, xf, doc, slot, sp, pasteboard, clip }; draw_page_guides(&cx, (pi, p, pr), moving, &selection); } } let _ = t; } +/// How far, in screen points, a guide, margin or outline paints past its own rectangle: half of +/// a selected guide's 2 pt line, rounded up. +const GUIDE_MARGIN: f32 = 2.0; + /// The bleed and slug outlines of a spread, in their own colours. -fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &SpreadSlot, sp: &designcraft_doc::Spread) { +fn draw_bleed_and_slug(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: &SpreadSlot, sp: &designcraft_doc::Spread, clip: Rect) { let s = &doc.settings; let rect = |r: DRect| xf.rect(slot.xf.transform_rect_bbox(r)); // Bleed, then slug: one rectangle each around the spread (the inside offset only applies // at the spread's outer edges). for (r, color) in [(sp.bleed_rect(s.bleed), s.bleed_color), (sp.slug_rect(s.slug), s.slug_color)] { - if let Some(r) = r { + if let Some(r) = r.filter(|r| in_view(xf, clip, slot.xf.transform_rect_bbox(*r), GUIDE_MARGIN)) { painter.rect_stroke(rect(r), 0.0, Stroke::new(hair(painter), c32(color)), StrokeKind::Middle); } } @@ -105,6 +116,9 @@ fn draw_parent_overlay(painter: &egui::Painter, xf: &Xf, doc: &Document, slot: & && let Some(pp) = doc.parents.get(ppi).and_then(|ps| ps.pages.get(ppg)) { let r = rect(DRect::new(pr.x0, pr.y0, pr.x0 + pp.width, pr.y0 + pp.height)); + if r.is_finite() && !r.expand(GUIDE_MARGIN).intersects(painter.clip_rect()) { + return; + } painter.rect_filled(r, 0.0, Color32::from_rgba_unmultiplied(110, 110, 230, 28)); painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_rgb(110, 110, 230)), StrokeKind::Middle); } @@ -150,6 +164,8 @@ struct GuideCtx<'a> { slot: &'a SpreadSlot, sp: &'a designcraft_doc::Spread, pasteboard: DRect, + /// The painter's clip rectangle: a guide outside it is not painted. + clip: Rect, } /// The page's own guides, then those it shows from its parent page. `moving` draws dragged @@ -182,7 +198,7 @@ fn draw_page_guides( /// One guide as a line: across the pasteboard for a spread guide, across its page otherwise. fn draw_guide(cx: &GuideCtx, pr: DRect, g: &designcraft_doc::Guide, selected: bool) { - let GuideCtx { painter, xf, doc, slot, sp, pasteboard } = *cx; + let GuideCtx { painter, xf, doc, slot, sp, pasteboard, clip } = *cx; let pt = |q: Point| xf.to_screen(slot.xf * q); // Spread guides cross the pasteboard; page guides their page. let span = if g.spread { pasteboard } else { pr }; @@ -193,6 +209,9 @@ fn draw_guide(cx: &GuideCtx, pr: DRect, g: &designcraft_doc::Guide, selected: bo (Point::new(g.position, span.y0), Point::new(g.position, span.y1)) } }; + if !in_view(xf, clip, slot.xf.transform_rect_bbox(DRect::from_points(a, bb)), GUIDE_MARGIN) { + return; + } let stroke = if selected { let color = g.layer.and_then(|l| doc.layer(l)).map_or(Color32::from_rgb(79, 153, 255), |l| c32(l.color)); Stroke::new(2.0, color) @@ -218,7 +237,10 @@ pub(super) fn draw_flattener_preview(painter: &egui::Painter, xf: &Xf, doc: &Doc let Some(sp) = doc.spread(slot.spread) else { continue }; for it in sp.items.iter().filter(|it| !it.hidden && transparent(it)) { let r = it.bounds().inflate(designcraft_render::effect_outset(it), designcraft_render::effect_outset(it)); - painter.rect_filled(xf.rect(slot.xf.transform_rect_bbox(r)), 0.0, red); + let r = slot.xf.transform_rect_bbox(r); + if in_view(xf, painter.clip_rect(), r, 0.0) { + painter.rect_filled(xf.rect(r), 0.0, red); + } } } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 62064ea79..069dce96d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -71,19 +71,28 @@ fn a_press_after_a_drag_is_not_a_double_click() { assert_eq!(press(Some(up), 0.0, 1.0), 1); } -/// The shapes the canvas paints for a new document, after two frames (the first lays out). +/// The shapes the canvas paints for a new document with every spread in view, after two frames +/// (the first lays out). fn canvas_shapes(app: &mut DesignApp) -> Vec { let ctx = egui::Context::default(); let mut shapes = Vec::new(); for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; + shapes = canvas_frame_shapes(app, &ctx); + if let Some(rect) = app.canvas_rect { + fit(app, rect, "all"); + } } shapes } +/// One frame of the canvas alone in a 1440 by 900 window: the shapes it paints. +fn canvas_frame_shapes(app: &mut DesignApp, ctx: &egui::Context) -> Vec { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes +} + /// The spine-coloured vertical hairlines at screen x `x` that run the full height of `page` /// (the spine of one spread shares its x with the pages of the spreads above and below it). fn vertical_lines_at(shapes: &[egui::epaint::ClippedShape], x: f32, page: Rect) -> usize { @@ -172,14 +181,7 @@ fn the_spine_line_hides_with_the_other_guides() { fn pages_show_paper_under_their_render() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.run("file.new", serde_json::json!({"pages": 3, "facingPages": true})).unwrap(); - let ctx = egui::Context::default(); - let mut shapes = Vec::new(); - for _ in 0..2 { - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); - out.textures_delta.clear(); - shapes = out.shapes; - } + let shapes = canvas_shapes(&mut app); let st = app.session.active().unwrap(); let layout = CanvasLayout::new(&st.doc, false); let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); @@ -1272,6 +1274,71 @@ fn overset_mark_sits_on_the_out_port_once() { assert!(marks.is_empty()); } +/// An idle frame of the canvas paints the spreads in view and looks up their stories: a document +/// ten times as long adds no shape and no story lookup, and the view shows the same shapes. +#[test] +fn an_idle_canvas_frame_does_the_same_work_for_a_longer_document() { + // Every page holds an empty frame and an overset text frame with a story of its own. + let work = |pages: usize| { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": pages, "facingPages": false})).unwrap(); + let text = "far too much text for a frame this small, over and over again ".repeat(8); + for page in 0..pages { + app.run("frame.create", json!({"spread": page, "rect": [36, 36, 300, 200]})).unwrap(); + app.run("frame.create", json!({"spread": page, "rect": [36, 300, 200, 340], "content": "text", "text": text})).unwrap(); + } + app.run("edit.deselectAll", json!({})).unwrap(); + let ctx = egui::Context::default(); + canvas_frame_shapes(&mut app, &ctx); + go_to_page(&mut app, 0); + canvas_frame_shapes(&mut app, &ctx); + assert_eq!(current_page(&app), Some(0)); + // With nothing composed, the stories composed after one more frame are the ones it looked up. + app.session.cache.clear(); + let shapes = canvas_frame_shapes(&mut app, &ctx); + let showing = shapes.iter().filter(|s| s.clip_rect.intersects(s.shape.visual_bounding_rect())).count(); + let doc = &app.session.active().unwrap().doc; + let composed = doc.stories.keys().filter(|id| app.session.cache.composed_for(doc, **id).is_some()).count(); + (shapes.len(), showing, composed) + }; + let (short, long) = (work(4), work(40)); + assert_eq!(long.1, short.1, "shapes in view"); + assert_eq!(long.0, short.0, "shapes painted"); + assert_eq!(long.2, short.2, "stories looked up"); + assert!((1..4).contains(&long.2), "the stories in view, not all 40: {}", long.2); +} + +/// A frame on the pasteboard keeps its edges while its page is out of view, in a rotated view +/// too, and a view that shows none of it paints none of them. +#[test] +fn frame_edges_are_painted_for_the_frames_in_view() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [-300, 100, -200, 200], "content": "text", "text": "a"})).unwrap()["id"].as_u64().unwrap(); + app.run("edit.deselectAll", json!({})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let layout = CanvasLayout::new(&doc, false); + let it = out_frame(&doc, id); + let (a, _) = item_canvas_xf(&doc, &layout, it.id).unwrap(); + let frame = a.transform_rect_bbox(it.bounds()); + assert!(frame.x1 < layout.slots[0].bounds.x0 - 150.0, "the frame is on the pasteboard, left of the page"); + let window = Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)); + let edges = |xf: Xf| { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(window), ..Default::default() }, |ui| { + draw_frames(&app, &ui.painter_at(window), &xf, &doc, &layout); + }); + out.textures_delta.clear(); + out.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::Path(_))).count() + }; + // The frame 20 points inside a window too small to reach the page. + let near = Xf { min: Pos2::ZERO, origin: Point::new(frame.x0 - 20.0, frame.y0 - 20.0), zoom: 1.0, rot: 0, pivot: window.center() }; + assert_eq!(edges(near), 1); + assert_eq!(edges(Xf { rot: 1, ..near }), 1); + // The same window over the page: the frame is out of view. + assert_eq!(edges(Xf { origin: Point::new(layout.slots[0].bounds.x0, frame.y0 - 20.0), ..near }), 0); +} + #[test] fn right_clicking_a_ruler_sets_that_rulers_units() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From ba81cb05e91fa01e242c43836661275e0c12d387 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:21:26 -0800 Subject: [PATCH 194/328] Compose: an edit composes only the paragraphs it can change Every edit of a story composed it from its first paragraph, so a typed character in a long threaded story cost as much as laying out the whole story: 456 ms in a story threaded over 300 pages. A composition that lays every paragraph once keeps its state before each paragraph. After an edit, composing starts one paragraph above the first changed one, in the kept state and with the lines above copied. It stops at the first unchanged paragraph it reaches in the state kept for that paragraph, and copies the lines from there on with their story offsets moved by the length of the edit. - The cache does this when only the story differs from its entry. - Composed whole as before: stories with footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced columns, vertical justification other than Top, column rules, type on a path, spanning or split paragraphs, paragraph borders or shading, and a layout that goes back over a paragraph (keep options). - An edit that moves lines into other frames is composed to the end of the story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). Docs: docs/architecture.md, docs/gaps.md (gap 20), ROADMAP. Refs #2298 --- ROADMAP.md | 1 + crates/compose/src/cache.rs | 49 ++- crates/compose/src/lib.rs | 87 ++++- crates/compose/src/reuse.rs | 713 ++++++++++++++++++++++++++++++++++++ crates/compose/src/wrap.rs | 24 +- docs/architecture.md | 10 +- docs/gaps.md | 9 +- 7 files changed, 861 insertions(+), 32 deletions(-) create mode 100644 crates/compose/src/reuse.rs diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..87daec8b7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,6 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames is composed to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole (#2298). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5e4cb0911..ba55e0d86 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -6,12 +6,17 @@ //! its text ([`crate::wrap::neighbours`]). An anchored frame's entry also records where its host //! story's composition places it. Entries hold clones of those `Arc`s, so the pointers //! can't be reused by other allocations while the entry lives. +//! +//! When only the story itself differs from an entry's (an edit of its text or formatting), the +//! new composition starts from the entry's and composes the paragraphs the edit can change +//! ([`crate::reuse`]). use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, PoisonError}; use designcraft_doc::{Document, Item, Story, StoryId, Styles}; +use crate::reuse::{Reuse, Trace}; use crate::vars::RunningIndex; use crate::{ComposeOptions, ComposedStory}; @@ -50,6 +55,25 @@ struct Entry { _keep: (Arc, Arc, Vec>, Vec>), out: Arc, stamp: u64, + /// For composing the story again after an edit ([`crate::reuse`]). + trace: Option>, +} + +/// The story an entry was composed from, its composition and that composition's trace. +type Before = (Arc, Arc, Arc); + +/// How many leading values of a [`signature`] identify the story's own allocation and revision; +/// the rest is everything else the composition was made from. +const STORY_SIG: usize = 2; + +impl Entry { + /// What composing for `sig` can take from this entry: set when only the story itself differs + /// (an edit of its text or formatting) and the entry's composition left a trace. + fn before(&self, sig: &[usize]) -> Option { + let trace = self.trace.as_ref()?; + (self.sig.len() == sig.len() && self.sig.get(STORY_SIG..) == sig.get(STORY_SIG..)) + .then(|| (self._keep.0.clone(), self.out.clone(), trace.clone())) + } } #[derive(Default)] @@ -244,33 +268,38 @@ impl Cache { std::hash::Hash::hash(&doc.list_start(sid, &l.name), &mut h); sig.push(std::hash::Hasher::finish(&h) as usize); } - { + let before = { let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); g.1 += 1; let stamp = g.1; - if let Some(e) = g.0.get_mut(&key) - && e.sig == sig - { - e.stamp = stamp; - return e.out.clone(); + match g.0.get_mut(&key) { + Some(e) if e.sig == sig => { + e.stamp = stamp; + return e.out.clone(); + } + Some(e) => e.before(&sig), + None => None, } - } + }; // Parent-page items are composed per page: markers show its name, variables need its index. let page = page.filter(|_| with_vars); let running = running.then(|| self.running_index(doc)); let others: Vec> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth, resolved)).collect(); - let out = Arc::new(crate::wrap::compose_among( + let (out, trace) = crate::wrap::compose_among_traced( doc, sid, &ComposeOptions { page_name, section_marker, page, running, label: None, xrefs: with_xrefs.then(|| self.xref_index(doc)), placed }, &others.iter().map(|o| &**o).collect::>(), - )); + before.as_ref().map(|(story, composed, trace)| Reuse { story, composed, trace }), + ); + let (out, trace) = (Arc::new(out), trace.map(Arc::new)); let mut g = self.map.lock().unwrap_or_else(PoisonError::into_inner); let stamp = g.1; if g.0.len() > 4096 { g.0.retain(|_, e| stamp - e.stamp < 64); } - let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp }); + let replaced = + g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp, trace }); drop(g); // Only the composition that is shown (not one made for another story's wrap). if key.1 == ShownOn::Own diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..8a86b87c0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -24,6 +24,7 @@ mod outline; mod overlay; mod parabox; mod placed; +mod reuse; mod ruby; pub mod shape; pub mod shatai; @@ -1028,6 +1029,9 @@ fn frame_columns_and_text(frames: &[FrameSpec], direction: designcraft_doc::Text } struct ParagraphProgressInput<'a> { + /// Nothing is left to lay: the rest of the story is in place, or the pass is abandoned + /// ([`reuse::Pass::step`]). + done: bool, paragraph: usize, count: usize, balance_frames: usize, @@ -1047,7 +1051,10 @@ enum ParagraphProgress { } fn paragraph_progress(input: ParagraphProgressInput<'_>) -> ParagraphProgress { - let ParagraphProgressInput { paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + let ParagraphProgressInput { done, paragraph, count, balance_frames, trial, limits, cursor, columns, frames, out, may_retry } = input; + if done { + return ParagraphProgress::Complete; + } if paragraph < count { return ParagraphProgress::Continue; } @@ -2671,6 +2678,40 @@ fn finish_paragraph(input: ParagraphFinishInput<'_>) -> ParagraphFinish { } fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, db: &FontDb) -> ComposedStory { + compose_run(doc, story, frames, opts, db, None, false).map(|(out, _)| out).unwrap_or_default() +} + +/// [`compose`], leaving a trace for composing the story again after an edit when it can +/// ([`reuse`]). With `before` (the story before an edit, its composition and trace), only the +/// paragraphs the edit can change are composed, when the trace covers the edit. +pub(crate) fn compose_traced( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + before: Option>, +) -> (ComposedStory, Option) { + let db = FontDb::global(); + if before.is_some() + && let Some(done) = compose_run(doc, story, frames, opts, db, before.as_ref(), true) + { + return done; + } + compose_run(doc, story, frames, opts, db, None, true).unwrap_or_default() +} + +/// Compose `story` into `frames`, from its start or from what `before` holds for it; with +/// `traced`, also give the trace when the composition can leave one. `None` only with `before`: +/// its trace does not cover the edit, so the story has to be composed from its start. +fn compose_run( + doc: &Document, + story: &Story, + frames: &[FrameSpec], + opts: &ComposeOptions, + db: &FontDb, + before: Option<&reuse::Reuse<'_>>, + traced: bool, +) -> Option<(ComposedStory, Option)> { let db = &db.scoped(doc.font_scope); let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() }; let mut styles_tab: Vec = Vec::new(); @@ -2737,6 +2778,14 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C // and in split columns. let mut span_paras = vec![false; np]; let mut split_paras = vec![false; np]; + // Composing again after an edit starts at the paragraph above it ([`reuse`]). The entries + // for the paragraphs before that one are never read: going back over a paragraph abandons the + // pass. + let plain = traced && reuse::plain(story, frames, opts, &named_labels, &deleted); + let (mut pass, start) = reuse::Pass::new(before, story, plain, reuse::Start { pi, cur, list_counter, info }, &mut out, &mut styles_tab); + (pi, cur, list_counter, info) = (start.pi, start.cur, start.list_counter, start.info); + snaps.extend((0..pi).map(|_| Snapshot::take(&out, &cur, &list_counter))); + note_snaps.resize(pi, (notes.num, notes.key, 0)); 'paras: while pi <= np { cur.pi = pi; cur.limits = Rc::clone(&limits); @@ -2747,8 +2796,12 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C note_snaps.truncate(pi); note_snaps.push((notes.num, notes.key, notes.placed.len())); info.truncate(pi); + // Whether nothing is left to lay: the rest of the story is in place, copied from its + // composition before an edit, or that composition turned out not to hold for this one. + let done = pass.step((pi, np), snaps.last(), &mut out, &mut styles_tab, &mut info); // A balancing trial whose band ran past its frame: re-lay the band with more room. - if trial.as_ref().is_some_and(|t| cur.fi > t.key.0) + if !done + && trial.as_ref().is_some_and(|t| cur.fi > t.key.0) && let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) { balance_runs += 1; @@ -2757,6 +2810,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C continue 'paras; } match paragraph_progress(ParagraphProgressInput { + done, paragraph: pi, count: np, balance_frames, @@ -2843,6 +2897,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C var_cache: &mut var_cache, notes: &mut notes, }); + #[cfg(test)] + reuse::SHAPED.with(|n| n.set(n.get() + 1)); let shaped = shape_paragraph(ParagraphShapeInput { db, doc, @@ -3114,17 +3170,20 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C cur.pending += if spans_in_current_frame || ends_split { pp.space_after.max(pp.span_space_after) } else { pp.space_after }; pi += 1; } - finish_composition(FinishInput { - doc, - story, - frames, - cols: &cols, - notes: &mut notes, - out: &mut out, - boxes: &boxes, - span_paras: &span_paras, - split_paras: &split_paras, - styles_tab, + pass.trace(reuse::plain_end(&span_paras, &split_paras, &boxes), &snaps, info).map(|trace| { + let out = finish_composition(FinishInput { + doc, + story, + frames, + cols: &cols, + notes: &mut notes, + out: &mut out, + boxes: &boxes, + span_paras: &span_paras, + split_paras: &split_paras, + styles_tab, + }); + (out, trace) }) } @@ -3568,7 +3627,7 @@ pub fn deleted_paras(story: &Story, ranges: &[Range]) -> Vec { } /// Where a placed paragraph sits (for keep resolution). -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct ParaInfo { start: (usize, usize), /// Started at the top of a column (moving it can't help). diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs new file mode 100644 index 000000000..67a7d6314 --- /dev/null +++ b/crates/compose/src/reuse.rs @@ -0,0 +1,713 @@ +//! Composing an edited story from the composition it had before the edit. +//! +//! A composition that laid every paragraph once leaves a [`Trace`]: the state it had before each +//! paragraph. Composing the story again after an edit starts at the paragraph before the first +//! changed one, in the state the trace holds for it and with the lines above it copied. It stops +//! at the first paragraph after the edit that it reaches in the state the trace holds for that +//! paragraph, and copies the lines from there on with their story offsets moved by the length of +//! the edit. The result is the composition a full pass over the edited story gives. +//! +//! Only plain stories are traced ([`plain`]): the features left out carry state between +//! paragraphs that the trace does not hold, or move lines after they are set. A composition that +//! goes back over a paragraph (keep options, column balancing, hyphenation across columns) +//! leaves no trace, and one that does so while it reuses a trace is abandoned for a full pass. + +use std::rc::Rc; + +use designcraft_doc::{CharRun, ListCounter, Story, VerticalJustification}; + +use crate::{Above, Band, ComposeOptions, ComposedStory, Cursor, FrameSpec, Line, ParaInfo, RunStyle, Snapshot}; + +#[cfg(test)] +thread_local! { + /// Paragraphs shaped on this thread (tests count the work an edit causes). + pub(crate) static SHAPED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The composition's state before a paragraph: the cursor, the list numbering, and how much of +/// the cursor's frame and of the run style table is filled. +#[derive(Clone, Debug)] +struct Mark { + fi: usize, + col: usize, + last_baseline: Option, + last_descent: f64, + last_reference: f64, + aki_below: Option, + pending: f64, + band: Band, + grid_next: Option<(f64, f64)>, + list_counter: ListCounter, + lines: usize, + decos: usize, + styles: usize, +} + +fn bits(v: Option) -> Option { + v.map(f64::to_bits) +} + +fn above_bits(a: Option) -> Option<[Option; 6]> { + a.map(|a| { + [ + Some(a.top.to_bits()), + Some(a.baseline.to_bits()), + Some(a.descent.to_bits()), + Some(a.reference.to_bits()), + bits(a.aki_below), + Some(a.pending.to_bits()), + ] + }) +} + +impl Mark { + /// The state `snap` holds with `styles` run styles in the table, or `None` when it has state + /// a mark does not hold (a split-column block, balanced column bottoms, tables). + fn of(snap: &Snapshot, styles: usize) -> Option { + let c = &snap.cur; + if c.split.is_some() || !c.limits.is_empty() || !c.split_limits.is_empty() || snap.tables != 0 { + return None; + } + Some(Mark { + fi: c.fi, + col: c.col, + last_baseline: c.last_baseline, + last_descent: c.last_descent, + last_reference: c.last_reference, + aki_below: c.aki_below, + pending: c.pending, + band: c.band, + grid_next: c.grid_next, + list_counter: snap.list_counter.clone(), + lines: snap.lines, + decos: snap.decos, + styles, + }) + } + + fn cursor(&self, pi: usize) -> Cursor { + Cursor { + fi: self.fi, + col: self.col, + last_baseline: self.last_baseline, + last_descent: self.last_descent, + last_reference: self.last_reference, + aki_below: self.aki_below, + pending: self.pending, + pi, + band: self.band, + limits: Rc::default(), + split: None, + split_limits: Rc::default(), + grid_next: self.grid_next, + } + } + + /// The mark with its paragraph numbers after the edit. + fn moved(&self, plan: &Plan) -> Mark { + let band = Band { para: plan.moved(self.band.para), tail: self.band.tail.map(|(p, c)| (plan.moved(p), c)), ..self.band }; + Mark { band, ..self.clone() } + } + + /// Whether composing on from `self` and from `other` sets the same lines. Numbers are + /// compared by their bits: a difference too small to show still changes what follows. + fn same(&self, other: &Mark) -> bool { + let (a, b) = (&self.band, &other.band); + self.fi == other.fi + && self.col == other.col + && bits(self.last_baseline) == bits(other.last_baseline) + && self.last_descent.to_bits() == other.last_descent.to_bits() + && self.last_reference.to_bits() == other.last_reference.to_bits() + && bits(self.aki_below) == bits(other.aki_below) + && self.pending.to_bits() == other.pending.to_bits() + && a.para == b.para + && a.line0 == b.line0 + && above_bits(a.above) == above_bits(b.above) + && a.tail == b.tail + && self.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) == other.grid_next.map(|(x, y)| (x.to_bits(), y.to_bits())) + && self.list_counter == other.list_counter + && self.lines == other.lines + && self.decos == other.decos + && self.styles == other.styles + } +} + +/// What a composition leaves for composing the story again after an edit: its state before each +/// paragraph it laid (and after the last one), and where each paragraph sits. +#[derive(Debug)] +pub(crate) struct Trace { + marks: Vec, + info: Vec, +} + +/// A story as it was before an edit, its composition and that composition's trace. +#[derive(Clone, Copy)] +pub(crate) struct Reuse<'a> { + pub story: &'a Story, + pub composed: &'a ComposedStory, + pub trace: &'a Trace, +} + +/// How much of the composition before an edit holds for the edited story. +pub(crate) struct Plan { + /// The paragraph composing starts at. + pub resume: usize, + /// The first paragraph (numbered as in the edited story) that may take the lines it had + /// before the edit: the one before it is unchanged too. + pub rejoin: usize, + /// Paragraphs and bytes the edit added. + paras: isize, + bytes: isize, + /// The first paragraph the edit left as it was, numbered as before the edit. + old_tail: usize, +} + +impl Plan { + /// The number after the edit of paragraph `p` of the story before it. + fn moved(&self, p: usize) -> usize { + if p >= self.old_tail { p.wrapping_add_signed(self.paras) } else { p } + } + + /// The number before the edit of paragraph `pi` of the edited story's unchanged end. + fn before(&self, pi: usize) -> Option { + pi.checked_add_signed(self.paras.checked_neg()?) + } +} + +/// Whether a composition of `story` in `frames` can leave a trace, or use one. Footnotes, +/// endnotes, tables and anchored objects carry state of their own; named lists and tracked +/// deletions reach across paragraphs; vertical justification and column rules change a frame +/// after its lines are set; type on a path sizes its frame from the story; balanced columns are +/// laid more than once. +pub(crate) fn plain(story: &Story, frames: &[FrameSpec], opts: &ComposeOptions, labels: &[Option], deleted: &[bool]) -> bool { + story.notes.is_empty() + && story.endnotes.is_empty() + && story.objects.is_empty() + && story.tables.is_empty() + && opts.label.is_none() + && labels.iter().all(Option::is_none) + && !deleted.contains(&true) + && frames.iter().all(|f| { + let o = &f.opts; + o.vertical_justification == VerticalJustification::Top && !o.column_rule && o.path.is_none() && !(o.balance_columns && o.columns > 1) + }) +} + +/// Whether the paragraphs a composition laid are ones a trace covers: none spans or splits +/// columns (`span`, `split`, by paragraph) or has a border or shading (`boxes`), which are drawn +/// once every line is set. +pub(crate) fn plain_end(span: &[bool], split: &[bool], boxes: &[Option]) -> bool { + !span.contains(&true) && !split.contains(&true) && boxes.iter().all(Option::is_none) +} + +/// Bytes of text from the start of both run lists (in the order given) that have the same +/// character formats. +fn same_formats<'a>(mut old: impl Iterator, mut new: impl Iterator) -> usize { + let mut same = 0usize; + let (mut a, mut b): (Option<(&CharRun, usize)>, Option<(&CharRun, usize)>) = (None, None); + loop { + if a.is_none_or(|(_, left)| left == 0) { + a = old.find(|r| r.len > 0).map(|r| (r, r.len)); + } + if b.is_none_or(|(_, left)| left == 0) { + b = new.find(|r| r.len > 0).map(|r| (r, r.len)); + } + let (Some((ra, la)), Some((rb, lb))) = (a, b) else { return same }; + if ra.format != rb.format { + return same; + } + let step = la.min(lb); + same += step; + (a, b) = (Some((ra, la - step)), Some((rb, lb - step))); + } +} + +fn returns(text: &str) -> usize { + text.bytes().filter(|b| *b == b'\n').count() +} + +impl Reuse<'_> { + /// Where composing `new` (the story after the edit) starts and may stop, or `None` when the + /// edit changed something a trace does not cover. + pub(crate) fn plan(&self, new: &Story) -> Option { + let old = self.story; + if old.frames != new.frames + || old.direction != new.direction + || old.vertical != new.vertical + || old.optical_margin != new.optical_margin + || old.anchors != new.anchors + || old.xrefs != new.xrefs + || old.index_refs != new.index_refs + || old.editorial != new.editorial + { + return None; + } + let (o, n) = (old.text.as_bytes(), new.text.as_bytes()); + if old.paras.len() != returns(&old.text) + 1 || new.paras.len() != returns(&new.text) + 1 { + return None; + } + // The unchanged start: the same text in the same character formats, then whole paragraphs + // with the same paragraph formats. + let mut head = o.iter().zip(n).take_while(|(a, b)| a == b).count().min(same_formats(old.chars.iter(), new.chars.iter())); + while !new.text.is_char_boundary(head) { + head -= 1; + } + let whole = returns(new.text.get(..head)?); + let first = old.paras.iter().zip(&new.paras).take(whole).take_while(|(a, b)| a == b).count(); + if first < whole { + // A paragraph format changed above the first changed character. + head = match first.checked_sub(1) { + Some(k) => n.iter().enumerate().filter(|(_, b)| **b == b'\n').nth(k).map(|(i, _)| i + 1)?, + None => 0, + }; + } + // The unchanged end, which the unchanged start does not overlap. + let room = o.len().min(n.len()).checked_sub(head)?; + let mut tail = o + .iter() + .rev() + .zip(n.iter().rev()) + .take_while(|(a, b)| a == b) + .count() + .min(same_formats(old.chars.iter().rev(), new.chars.iter().rev())) + .min(room); + while !new.text.is_char_boundary(n.len() - tail) { + tail -= 1; + } + let after = returns(new.text.get(n.len() - tail..)?); + let after = old.paras.iter().rev().zip(new.paras.iter().rev()).take(after).take_while(|(a, b)| a == b).count(); + let (old_paras, new_paras) = (old.paras.len(), new.paras.len()); + Some(Plan { + // One paragraph above the first changed one: setting a paragraph reads the one after it. + resume: first.saturating_sub(1).min(self.trace.marks.len().checked_sub(1)?), + rejoin: new_paras.checked_sub(after)? + 1, + paras: isize::try_from(new_paras).ok()?.checked_sub(isize::try_from(old_paras).ok()?)?, + bytes: isize::try_from(n.len()).ok()?.checked_sub(isize::try_from(o.len()).ok()?)?, + old_tail: old_paras.checked_sub(after)?, + }) + } + + /// Put `out` and `styles` back as they were before paragraph `plan.resume`, and give the + /// cursor, list numbering and paragraph positions of that moment. `None` when the composition + /// before the edit does not match `out`'s frames. + pub(crate) fn restore(&self, plan: &Plan, out: &mut ComposedStory, styles: &mut Vec) -> Option<(Cursor, ListCounter, Vec)> { + let mark = self.trace.marks.get(plan.resume)?; + let before = self.composed; + if before.frames.len() != out.frames.len() || before.frames.iter().zip(&out.frames).any(|(a, b)| a.frame != b.frame) { + return None; + } + let info = self.trace.info.get(..plan.resume)?.to_vec(); + *styles = before.styles.get(..mark.styles)?.to_vec(); + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().take(mark.fi.saturating_add(1)) { + let (lines, decos) = if i < mark.fi { (from.lines.len(), from.decos.len()) } else { (mark.lines, mark.decos) }; + to.lines = from.lines.get(..lines)?.iter().map(|l| moved_line(l, 0, 0)).collect(); + to.decos = from.decos.get(..decos)?.to_vec(); + } + Some((mark.cursor(plan.resume), mark.list_counter.clone(), info)) + } + + /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as + /// they are: when the composition before the edit was in that state before the same + /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + pub(crate) fn rejoin( + &self, + plan: &Plan, + pi: usize, + snap: &Snapshot, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + let before = self.composed; + let Some(k) = plan.before(pi) else { return false }; + let (Some(old), Some(new)) = (self.trace.marks.get(k), Mark::of(snap, styles.len())) else { return false }; + // The paragraph above is where it was, and no chain of keep-with-next paragraphs reaches + // back through it into the changed text. + let last = |v: &[ParaInfo], i: usize| i.checked_sub(1).and_then(|i| v.get(i).cloned()); + let same_above = matches!((last(&self.trace.info, k), last(info, pi)), (Some(a), Some(b)) if a == b && a.keep_with_next == 0); + if !same_above || info.len() != pi || !old.moved(plan).same(&new) || before.styles.get(..old.styles) != Some(styles.as_slice()) { + return false; + } + for (i, (to, from)) in out.frames.iter_mut().zip(&before.frames).enumerate().skip(old.fi) { + let (lines, decos) = if i == old.fi { (old.lines, old.decos) } else { (0, 0) }; + to.lines.extend(from.lines.get(lines..).unwrap_or_default().iter().map(|l| moved_line(l, plan.bytes, plan.paras))); + to.decos.extend(from.decos.get(decos..).unwrap_or_default().iter().cloned()); + } + out.overset_at = before.overset_at.map(|b| b.wrapping_add_signed(plan.bytes)); + styles.clone_from(&before.styles); + info.extend(self.trace.info.get(k..).unwrap_or_default().iter().cloned()); + true + } +} + +/// `line` with its story offsets and paragraph number moved, and without the keep-violation +/// flag, which is set again for the whole story once it is composed. +fn moved_line(line: &Line, bytes: isize, paras: isize) -> Line { + let at = |b: usize| b.wrapping_add_signed(bytes); + let mut l = Line { keep_violation: false, ..line.clone() }; + l.range = at(l.range.start)..at(l.range.end); + l.para = l.para.wrapping_add_signed(paras); + if bytes != 0 { + for g in &mut l.glyphs { + g.byte = at(g.byte); + } + } + if let Some(cap) = &mut l.drop_cap { + cap.end = at(cap.end); + } + l +} + +/// What one composition keeps for its trace, and what it reuses of the composition before an +/// edit. +pub(crate) struct Pass<'a> { + before: Option<(&'a Reuse<'a>, Plan)>, + /// The composition was to reuse the one before an edit and cannot: its result is not used. + abandoned: bool, + /// A trace is wanted and nothing rules one out so far. + traced: bool, + /// Run styles in the table before each paragraph. + styles: Vec, + /// The paragraph the next step should be at: another one means the layout went back over a + /// paragraph. + next: usize, + /// The paragraph the lines copied from before the edit start at. + rejoined: Option, +} + +/// Where a composition starts: the paragraph, the cursor, the list numbering and the positions +/// of the paragraphs above. +pub(crate) struct Start { + pub pi: usize, + pub cur: Cursor, + pub list_counter: ListCounter, + pub info: Vec, +} + +impl<'a> Pass<'a> { + /// The bookkeeping for composing `story`, and where to start. `traced`: a trace is wanted and + /// the story is [`plain`]. `fresh` is the start of the story. With `before`, `out` and + /// `styles` are filled with what holds from before the edit and the start is the paragraph + /// above the edit; when `before` cannot be used the pass is abandoned at its first step. + pub(crate) fn new( + before: Option<&'a Reuse<'a>>, + story: &Story, + traced: bool, + fresh: Start, + out: &mut ComposedStory, + styles: &mut Vec, + ) -> (Pass<'a>, Start) { + let mut pass = Pass { before: None, abandoned: false, traced, styles: Vec::with_capacity(story.paras.len() + 1), next: 0, rejoined: None }; + let Some(b) = before else { return (pass, fresh) }; + let resumed = traced.then(|| b.plan(story)).flatten().and_then(|plan| Some((b.restore(&plan, out, styles)?, plan))); + let Some(((cur, list_counter, info), plan)) = resumed else { + pass.abandoned = true; + return (pass, fresh); + }; + let pi = plan.resume; + // The counts for the paragraphs above are never read: their marks are kept as they are. + pass.styles.resize(pi, 0); + pass.next = pi; + pass.before = Some((b, plan)); + (pass, Start { pi, cur, list_counter, info }) + } + + /// Before paragraph `pi` of `count` is laid, in the state `snap`: whether nothing is left to + /// lay, because the rest of the story is in place (copied from the composition before the + /// edit into `out`, `styles` and `info`) or because the pass is abandoned. + pub(crate) fn step( + &mut self, + (pi, count): (usize, usize), + snap: Option<&Snapshot>, + out: &mut ComposedStory, + styles: &mut Vec, + info: &mut Vec, + ) -> bool { + self.styles.truncate(pi); + self.styles.push(styles.len()); + if pi != self.next { + // The layout went back over a paragraph. + self.traced = false; + self.abandoned |= self.before.is_some(); + } + self.next = pi + 1; + if self.abandoned { + return true; + } + if pi < count + && let (Some((before, plan)), Some(snap)) = (&self.before, snap) + && pi >= plan.rejoin + && before.rejoin(plan, pi, snap, out, styles, info) + { + self.rejoined = Some(pi); + return true; + } + false + } + + /// The trace of the finished composition, when it laid every paragraph once and `plain_end` + /// (no paragraph it laid uses something a trace does not cover): `snaps` holds the state + /// before each paragraph it laid itself, `info` every paragraph's position. The paragraphs + /// above the one a reusing composition started at keep the marks they had, and those after + /// the one it rejoined at the marks that followed before the edit. The outer `None` is for an + /// abandoned pass and for a reusing one that leaves no trace: the story has to be composed + /// from its start. + pub(crate) fn trace(self, plain_end: bool, snaps: &[Snapshot], info: Vec) -> Option> { + if self.abandoned { + return None; + } + let trace = if self.traced && plain_end { self.marks(snaps).map(|marks| Trace { marks, info }) } else { None }; + if self.before.is_some() && trace.is_none() { + return None; + } + Some(trace) + } + + fn marks(&self, snaps: &[Snapshot]) -> Option> { + let reused = self.before.as_ref(); + let start = reused.map_or(0, |(_, plan)| plan.resume); + let mut marks = Vec::with_capacity(snaps.len()); + if let Some((before, _)) = reused { + marks.extend(before.trace.marks.get(..start)?.iter().cloned()); + } + for (snap, styles) in snaps.iter().zip(&self.styles).skip(start) { + marks.push(Mark::of(snap, *styles)?); + } + if let (Some((before, plan)), Some(pi)) = (reused, self.rejoined) { + let k = plan.before(pi)?; + marks.extend(before.trace.marks.get(k + 1..)?.iter().map(|m| m.moved(plan))); + } + // Lines are only ever added to the cursor's frame, so the frames above it are complete. + marks.windows(2).all(|w| w[0].fi <= w[1].fi).then_some(marks) + } +} + +#[cfg(test)] +mod tests { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Align, Document, ItemId, ListType, ParaFormat, SpreadRef, StartParagraph, Story, StoryId, VerticalJustification}; + use designcraft_geom::Rect; + + use super::SHAPED; + use crate::Cache; + + const SENTENCE: &str = "The quick brown fox jumps over the lazy dog while the workbook keeps growing page by page."; + + /// A story of `paras` paragraphs of two to five lines, threaded through `frames` frames of 31 + /// lines each. + fn threaded(paras: usize, frames: usize) -> (Document, StoryId, Vec) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let text = (0..paras).map(|i| vec![SENTENCE; 2 + i % 4].join(" ")).collect::>().join("\n"); + let rect = |i: usize| Rect::new(i as f64 * 600.0, 0.0, i as f64 * 600.0 + 540.0, 456.0); + let (first, sid) = d.add_text_frame(SpreadRef::Doc(0), rect(0), lid, &text, ParaFormat::default()).unwrap(); + let mut ids = vec![first]; + for i in 1..frames { + let (next, _) = d.add_text_frame(SpreadRef::Doc(0), rect(i), lid, "", ParaFormat::default()).unwrap(); + d.thread(ids[i - 1], next).unwrap(); + ids.push(next); + } + (d, sid, ids) + } + + /// What `f` returns and the paragraphs it shaped. + fn shaped(f: impl FnOnce() -> T) -> (T, usize) { + SHAPED.with(|n| n.set(0)); + let out = f(); + (out, SHAPED.with(|n| n.get())) + } + + /// Compose the edited story through `cache`, which holds its composition before the edit, and + /// check the result against composing it whole. Gives the paragraphs the cache shaped. + fn check(cache: &Cache, d: &Document, sid: StoryId, what: &str) -> usize { + let (cached, n) = shaped(|| cache.get(d, sid, None)); + let whole = Cache::new().get(d, sid, None); + assert_eq!(cached.frames.len(), whole.frames.len(), "{what}"); + for (fi, (a, b)) in cached.frames.iter().zip(&whole.frames).enumerate() { + assert_eq!(a.lines.len(), b.lines.len(), "{what}: lines in frame {fi}"); + for (li, (x, y)) in a.lines.iter().zip(&b.lines).enumerate() { + assert_eq!(format!("{x:?}"), format!("{y:?}"), "{what}: frame {fi} line {li}"); + } + } + assert!(format!("{cached:?}") == format!("{whole:?}"), "{what}: the composition differs from composing the story whole"); + n + } + + #[test] + fn a_typed_character_composes_the_paragraphs_around_it() { + for paras in [60, 240] { + let (mut d, sid, _) = threaded(paras, paras / 4); + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert!(first.frames.iter().filter(|f| !f.lines.is_empty()).count() > paras / 12); + assert_eq!(whole, paras); + let len = d.story(sid).unwrap().len(); + for at in [10, len / 2, len - 1] { + d.story_mut(sid).unwrap().insert(at, "x"); + let n = check(&cache, &d, sid, "a typed character"); + assert!(n <= 3, "{n} of {paras} paragraphs composed for a character typed at {at}"); + } + } + } + + #[test] + fn characters_typed_one_after_another_each_compose_the_paragraphs_around_them() { + let (mut d, sid, _) = threaded(80, 20); + let cache = Cache::new(); + cache.get(&d, sid, None); + let at = d.story(sid).unwrap().len() / 2; + for (i, c) in "one two\nthree".chars().enumerate() { + d.story_mut(sid).unwrap().insert(at + i, &c.to_string()); + let n = check(&cache, &d, sid, "typing"); + // A return adds a line, which moves the paragraphs below it in their frame: they are + // composed up to the end of the story. + assert!(c == '\n' || n <= 4, "{n} of 80 paragraphs composed for {c:?}"); + } + } + + #[test] + fn an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in() { + let (mut d, sid, _) = threaded(100, 24); + // Chapters of five paragraphs, each starting in the next frame. + let starts: Vec = + d.story(sid).unwrap().para_ranges().iter().enumerate().filter(|(i, _)| *i > 0 && i % 5 == 0).map(|(_, r)| r.start).collect(); + for at in starts { + d.story_mut(sid).unwrap().format_paras(at..at, |p| p.para.start_paragraph = Some(StartParagraph::NextFrame)); + } + let cache = Cache::new(); + let (first, whole) = shaped(|| cache.get(&d, sid, None)); + assert!(!first.is_overset()); + assert_eq!(whole, 100); + let at = d.story(sid).unwrap().para_ranges()[52].start + 20; + d.story_mut(sid).unwrap().insert(at, &format!(" {SENTENCE} {SENTENCE}")); + let n = check(&cache, &d, sid, "two more lines in a chapter"); + assert!(n <= 6, "{n} of 100 paragraphs composed for lines added to one chapter"); + } + + #[test] + fn edits_give_the_composition_of_the_edited_story() { + let (mut d, sid, _) = threaded(40, 12); + let original = d.clone(); + let cache = Cache::new(); + cache.get(&d, sid, None); + let edits: [(&str, fn(&mut Story)); 15] = [ + ("a character", |s| s.insert(s.len() / 2, "x")), + ("a return", |s| s.insert(s.len() / 2, "\n")), + ("a long insertion", |s| s.insert(s.len() / 3, &format!(" {SENTENCE} {SENTENCE} {SENTENCE}"))), + ("several paragraphs", |s| s.insert(s.len() / 3, &format!("\n{SENTENCE}\n{SENTENCE}\n"))), + ("a deleted character", |s| s.delete(s.len() / 2..s.len() / 2 + 1)), + ("a deleted return", |s| { + let at = s.text[..s.len() / 2].rfind('\n').unwrap(); + s.delete(at..at + 1); + }), + ("a deletion across paragraphs", |s| s.delete(s.len() / 4..s.len() / 4 + 900)), + ("a replacement", |s| s.replace(s.len() / 2..s.len() / 2 + 40, "replaced")), + ("larger type", |s| s.format_chars(s.len() / 2..s.len() / 2 + 60, |f| f.over.size = Some(18.0))), + ("a centered paragraph", |s| s.format_paras(s.len() / 2..s.len() / 2, |p| p.para.align = Some(Align::Center))), + ("text at the start", |s| s.insert(0, "Start. ")), + ("text at the end", |s| s.insert(s.len(), " End.")), + ("a two-byte character", |s| s.insert(s.len() / 2, "\u{e9}")), + ("everything deleted", |s| s.delete(0..s.len())), + ("text in an empty story", |s| s.insert(0, "Again.")), + ]; + for (what, edit) in edits { + edit(d.story_mut(sid).unwrap()); + check(&cache, &d, sid, what); + } + // Undo puts an earlier story back. + check(&cache, &original, sid, "the story before the edits"); + } + + #[test] + fn edits_in_and_above_overset_text_compose_right() { + let (mut d, sid, _) = threaded(60, 3); + let cache = Cache::new(); + assert!(cache.get(&d, sid, None).is_overset()); + let len = d.story(sid).unwrap().len(); + d.story_mut(sid).unwrap().insert(len - 10, "x"); + let n = check(&cache, &d, sid, "a character in overset text"); + assert!(n <= 1, "{n} paragraphs composed for a character typed in overset text"); + d.story_mut(sid).unwrap().insert(200, &format!(" {SENTENCE}")); + check(&cache, &d, sid, "a line added above overset text"); + d.story_mut(sid).unwrap().delete(100..len / 2); + check(&cache, &d, sid, "a deletion that brings overset text into the frames"); + } + + /// Stories with features a trace does not cover are composed whole after an edit. + #[test] + fn edits_of_stories_a_trace_does_not_cover_compose_right() { + let setups: [(&str, fn(&mut Document, StoryId, &[ItemId])); 6] = [ + ("keep options", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| { + p.para.keep_with_next = Some(1); + p.para.keep_lines_together = Some(true); + }); + }), + ("balanced columns", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.balance_columns) = (2, true); + } + }), + ("vertical justification", |d, _, frames| { + for f in frames { + d.item_mut(*f).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Center; + } + }), + ("a numbered list", |d, sid, _| { + let s = d.story_mut(sid).unwrap(); + s.format_paras(0..s.len(), |p| p.para.list_type = Some(ListType::Numbers)); + }), + ("a footnote", |d, sid, _| { + d.story_mut(sid).unwrap().insert_note(300, "A synthetic footnote.", ParaFormat::default()); + }), + ("a column rule", |d, _, frames| { + for f in frames { + let o = &mut d.item_mut(*f).unwrap().text_frame_mut().unwrap().options; + (o.columns, o.column_rule) = (2, true); + } + }), + ]; + for (what, setup) in setups { + let (mut d, sid, frames) = threaded(30, 10); + setup(&mut d, sid, &frames); + let cache = Cache::new(); + cache.get(&d, sid, None); + let mid = d.story(sid).unwrap().len() / 2; + d.story_mut(sid).unwrap().insert(mid, "x"); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().insert(mid, &format!("\n{SENTENCE} {SENTENCE}\n")); + check(&cache, &d, sid, what); + d.story_mut(sid).unwrap().delete(mid / 2..mid); + check(&cache, &d, sid, what); + } + } + + #[test] + fn a_run_of_mixed_edits_composes_right_after_each() { + let (mut d, sid, _) = threaded(40, 14); + let cache = Cache::new(); + cache.get(&d, sid, None); + let texts = ["x", " word", "\n", " several words in a row here", "\n\n", "A sentence. "]; + let mut seed = 0x2545_f491_u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize % below.max(1) + }; + for step in 0..60 { + let s = d.story_mut(sid).unwrap(); + let at = next(s.len() + 1); + match next(4) { + 0 | 1 => s.insert(at, texts[next(texts.len())]), + 2 => s.delete(at..(at + next(120)).min(s.len())), + _ => { + let size = 9.0 + next(10) as f64; + s.format_chars(at..(at + next(60)).min(s.len()), |f| f.over.size = Some(size)); + } + } + check(&cache, &d, sid, &format!("step {step}")); + } + } +} diff --git a/crates/compose/src/wrap.rs b/crates/compose/src/wrap.rs index f28bba424..70675eab5 100644 --- a/crates/compose/src/wrap.rs +++ b/crates/compose/src/wrap.rs @@ -21,6 +21,7 @@ use designcraft_doc::{AnchorPosition, AnchoredObject, Document, Item, OBJECT_MARK, PageSide, SpreadRef, Story, StoryId, WrapMode}; use designcraft_geom::Affine; +use crate::reuse::{Reuse, Trace}; use crate::{ComposeOptions, ComposedStory, Exclusion, FrameSpec}; /// Most extra compositions of a story with its own anchored objects' wrap, however many objects @@ -192,7 +193,22 @@ fn settled(a: &[Vec], b: &[Vec]) -> bool { /// Compose story `sid` with the wrapping anchored objects of `others` (compositions of its /// [`neighbours`]) and of its own. pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, others: &[&ComposedStory]) -> ComposedStory { - let Some(st) = doc.story(sid) else { return ComposedStory { story: sid, ..Default::default() } }; + compose_among_traced(doc, sid, opts, others, None).0 +} + +/// [`compose_among`], also giving the trace for composing the story again after an edit, when +/// the composition leaves one ([`crate::reuse`]). `before` is the story before an edit with its +/// composition among the same `others` and that composition's trace: the paragraphs the edit +/// cannot change are taken from it. A story with wrapping anchored objects of its own is +/// composed whole and leaves no trace. +pub(crate) fn compose_among_traced( + doc: &Document, + sid: StoryId, + opts: &ComposeOptions, + others: &[&ComposedStory], + before: Option>, +) -> (ComposedStory, Option) { + let Some(st) = doc.story(sid) else { return (ComposedStory { story: sid, ..Default::default() }, None) }; let mut specs = crate::frame_specs_placed(doc, sid, &opts.placed); if !others.is_empty() { let mut obs = Vec::new(); @@ -206,10 +222,10 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, specs = with_exclusions(&specs, &added); } } - let mut out = crate::compose(doc, st, &specs, opts); if !has_wrapping_objects(st) { - return out; + return crate::compose_traced(doc, st, &specs, opts, before); } + let mut out = crate::compose(doc, st, &specs, opts); let own = st.objects.iter().filter(|o| wraps(o) && !matches!(o.position, AnchorPosition::Inline { .. })).count(); let mut prev = vec![Vec::new(); specs.len()]; for _ in 0..(own + 1).clamp(MIN_PASSES, MAX_PASSES) { @@ -220,5 +236,5 @@ pub(crate) fn compose_among(doc: &Document, sid: StoryId, opts: &ComposeOptions, out = crate::compose(doc, st, &with_exclusions(&specs, &added), opts); prev = added; } - out + (out, None) } diff --git a/docs/architecture.md b/docs/architecture.md index 7b86388a9..4fede8ca4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,15 @@ AppKit callback never runs the confirmation dialogs inside a modal termination l ## Composition and rendering The compose cache is keyed by story revision, frame geometry, style revision and font database -revision; stories compose in parallel (rayon) on native targets. Composition produces per-frame +revision; stories compose in parallel (rayon) on native targets. After an edit of a story's text +or formatting, composing starts at the paragraph before the first changed one and stops at the +first unchanged paragraph it reaches in the state it had before the edit; the lines above and +below are copied from the composition before the edit (`crates/compose/src/reuse.rs`). An edit +that moves lines into other frames is composed to the story's end. A story is composed whole +when it has footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, +balanced columns, vertical justification other than Top, column rules, type on a path, spanning +or split paragraphs, or paragraph borders or shading, and when its layout goes back over a +paragraph (keep options). Composition produces per-frame lines with positioned glyph runs, decorations, anchors and overset. The canvas renders on a background worker with vello_cpu into tiles; after an edit only frames whose composition changed are re-rendered and patched (damage regions, pixel-identical to a full render). The GPU (wgpu: diff --git a/docs/gaps.md b/docs/gaps.md index addb0b679..df396e9f6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -231,10 +231,13 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · - **Estimate:** 30–60 h (PostScript interpreter is a large separate project: +80–150 h). ### 20. Performance on large documents (P) -- **Missing:** incremental composition (recompose from the edited paragraph; 8 ms keystroke - budget), benchmarks against InDesign on long books and image-heavy catalogues. +- **Missing:** the 8 ms keystroke budget in long stories: an edit that moves lines into other + frames composes the story to its end, the lines an edit keeps are copied, and stories with + footnotes, tables, anchored objects or keep options that move lines compose whole; benchmarks + against InDesign on long books and image-heavy catalogues. - **Have:** compose 300k characters ~38 ms warm, damage-region repaint (< 1 ms while typing), - parallel story composition. + parallel story composition, and an edit composes only the paragraphs it can change in a plain + story (240 paragraphs: 3 composed for a typed character). - **Estimate:** 40–80 h. ### 26. Autoflow flows into the primary text frame of the pages that follow (F) From 5858ccfec1e467459c7498d1190315bd135bf825 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:28:18 -0800 Subject: [PATCH 195/328] ROADMAP: the idle canvas frame entry moves to the top of the progress log The progress log is newest first, and the 2026-11-12 entry sat among the 2026-10-30 entries. --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 16b009a80..b029e87bf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -400,6 +400,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-11-06** · Preflight warns about white or [Paper] set to overprint (#2401): a fill, stroke or stroke gap, or ruby and kenten, in [Paper] or a colour that lays down no ink (C=0 M=0 Y=0 K=0, a 0% tint; a spot ink, such as a white ink or a varnish, prints whatever colour stands in for it), is reported as `whiteOverprint`, since it disappears on press. Text itself has no overprint, so white text in a frame set to Overprint Fill still knocks out and prints, and is not reported. Preflight no longer says PDF export drops ruby and kenten overprint, which it writes. No readiness percentage change. - **2026-11-04** · Interface Language › Português (Brasil) translates the whole interface: 996 strings the catalog lacked (tool names, window and guide commands, Keyboard Shortcuts sets, panel docking, Edit › Menus paths, the Japanese typesetting dialogs, special characters, Load Styles, Data Merge, Preflight, font replacement, the Package summary, OpenType features, page presets, About) and File › New's unit names, and a path is "demarcador" throughout. `cargo xtask i18n-report` counts 2,936 of 2,939 strings for pt-BR (1,933 before); only the Control panel's `IT`, `VA` and `Y:` captions stay English, as in every language. No readiness percentage change. - **2026-11-03** · `type.char` says when the font it applies isn't available (#2189): it returns `{"warnings": ["Missing font: Courier Prime (using Source Sans 3)"]}`, or `Missing font style: …` for a style the family doesn't have, in preflight's words. The font is still applied, as before, so Find Font and preflight list it. A script that asked for a font the machine doesn't have exported in the substitute with no word about it. No readiness percentage change. @@ -413,7 +414,6 @@ Newest first. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). -- **2026-11-12** · An idle canvas frame no longer does work for the spreads out of view (part of #1343): page shadows, paper, guides, margins, frame edges and overset marks are painted for the spreads and objects in view, and only their stories are looked up. In a 400-page document with two frames a page, an idle frame painted 5,099 shapes and looked up 400 stories; it now paints 311 and looks up 1, the same as in a 4-page document. No readiness percentage change. - **2026-10-30** · Spreads show a line at each edge where two of their pages meet, on the canvas only (it isn't printed or exported), so the page boundaries inside a spread are visible while laying out across them, in the spread edge's colour. Right-to-left spreads and pages of different sizes put it on the edge the pages share; pages that don't touch, as an imported spread can keep them, get none (#1838). No readiness percentage change. - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. - **2026-10-28** · A placed image whose pixels would decode past 1 GiB of RGBA (256 Mpx) is refused from its header, before decoding (#1586). A 288 KB 23,000 px gray PNG used to hang the first draw for 9 s and take the app to 4.5 GB; it now draws as an empty frame, and PDF export skips it with a warning. A 300 ppi A0 scan still fits. No readiness percentage change. From e22a6362ccab4088e1b9be2ca7d9c577aea99d3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:53:12 -0800 Subject: [PATCH 196/328] Compose: list every case that composes a story whole in gap 20 docs/gaps.md now lists the same cases as docs/architecture.md and reuse::plain. A doc comment on rejoin says that a run style an edit uses for the first time stops the reuse until the old composition reaches the same style at the same index. --- crates/compose/src/reuse.rs | 5 +++++ docs/gaps.md | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/reuse.rs b/crates/compose/src/reuse.rs index 67a7d6314..d3f570ebe 100644 --- a/crates/compose/src/reuse.rs +++ b/crates/compose/src/reuse.rs @@ -309,6 +309,11 @@ impl Reuse<'_> { /// At paragraph `pi` of the edited story, in the state `snap` with `styles` and `info` as /// they are: when the composition before the edit was in that state before the same /// paragraph, copy what it set from there on into `out`, `styles` and `info`, and say so. + /// + /// The copied lines keep their run-style indexes, so this needs `styles` to equal the old + /// table up to that point. A run style that the edit uses for the first time takes a new + /// index, and the story then composes on until the old composition added the same style at + /// the same index, or to its end. The result is the same; only the time differs. pub(crate) fn rejoin( &self, plan: &Plan, diff --git a/docs/gaps.md b/docs/gaps.md index df396e9f6..02f02a33b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -233,7 +233,10 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format · ### 20. Performance on large documents (P) - **Missing:** the 8 ms keystroke budget in long stories: an edit that moves lines into other frames composes the story to its end, the lines an edit keeps are copied, and stories with - footnotes, tables, anchored objects or keep options that move lines compose whole; benchmarks + footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced + columns, vertical justification other than Top, column rules, type on a path, spanning or + split paragraphs, paragraph borders or shading, or keep options that move lines compose + whole; benchmarks against InDesign on long books and image-heavy catalogues. - **Have:** compose 300k characters ~38 ms warm, damage-region repaint (< 1 ms while typing), parallel story composition, and an edit composes only the paragraphs it can change in a plain From 92043b4c4892224a14d1441160ad25bf4508e523 Mon Sep 17 00:00:00 2001 From: Adithya Shankaran <72570811+adikshan11@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:39:39 +0530 Subject: [PATCH 197/328] =?UTF-8?q?Automation=20roots:=20refuse=20COM?= =?UTF-8?q?=C2=B9=20to=20LPT=C2=B3=20and=20a=20device=20name=20before=20a?= =?UTF-8?q?=20colon=20(#2383)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Automation roots: refuse COM¹ to LPT³ and a device name before a colon is_device_name missed COM¹, COM², COM³ and LPT¹, LPT², LPT³, which Windows reserves as it does COM1. It also cut the name only at a period, so COM1: and NUL:x were not seen as device names. * Credit my name in the About window * Automation roots: document the device-name tests CodeRabbit's docstring check counts the touched tests. same_component stays without a doc comment, because #2205 deletes that function and a doc line above it conflicts. * Automation roots: record the device-name refusal The MCP roots description and the roadmap now name COM¹ to LPT³ and a device name before a colon. --- ROADMAP.md | 3 ++- contributors/people.toml | 4 ++++ crates/engine/src/cmd/export_batch.rs | 6 +++++- crates/engine/src/file_access.rs | 17 ++++++++++++----- docs/mcp.md | 2 +- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 006396b1d..3a5feac4b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md). - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-06 · **Change:** minor (Pages panel parents and alternate layouts; File ▸ Export Layouts and Versions; placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text; automation roots refuse superscript COM/LPT names and a device name before a colon) · **Target:** Adobe InDesign 2026 - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it. - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md. @@ -12,6 +12,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web. +- **2026-11-06** · Automation roots refuse `COM¹` to `LPT³` and a device name before a colon (`COM1:`, `NUL:x`). A batch-export layout of that name is written with a leading `_` on every platform. No readiness percentage change. - **2026-10-30** · Document Fonts lookup treats a bare document filename's empty parent as the current directory (#2014), preserving case-insensitive discovery and automation read-root checks. No readiness percentage change. - **2026-10-28** · Inline table rows leave room for column and spanning footnotes, continuing in the next column or frame when needed (#1901). Cell-local footnotes contribute to row height diff --git a/contributors/people.toml b/contributors/people.toml index 5049c9493..617091888 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -87,3 +87,7 @@ sync_github_name = true [people.JonRC] real_name = "Jonathan Cardoso" display_name = "Jonathan Cardoso" + +[people.adikshan11] +real_name = "Adithya Shankaran" +sync_github_name = true diff --git a/crates/engine/src/cmd/export_batch.rs b/crates/engine/src/cmd/export_batch.rs index 8e685475b..3b24f60c9 100644 --- a/crates/engine/src/cmd/export_batch.rs +++ b/crates/engine/src/cmd/export_batch.rs @@ -557,13 +557,17 @@ mod tests { assert!(pdf.starts_with(b"%PDF-")); } + /// An export name drops reserved characters, and a Windows device name (`CON`, `COM¹`, `LPT³`) + /// is written with a leading `_`. Two files built from one name stay distinct. #[test] fn names_are_made_safe_and_unique() { assert_eq!(safe_name("../a/b:c*?"), "a b c"); assert_eq!(safe_name(" ... "), "Untitled"); assert_eq!(safe_name(&"x".repeat(500)).chars().count(), MAX_NAME); // Windows device names name no file. - for (name, safe) in [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("Console", "Console")] { + for (name, safe) in + [("CON", "_CON"), ("nul", "_nul"), ("com1.x", "_com1.x"), ("COM¹", "_COM¹"), ("lpt³.x", "_lpt³.x"), ("Console", "Console")] + { assert_eq!(safe_name(name), safe); } let mut s = two_layouts(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 69edeaca1..e1127dd5f 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -265,10 +265,11 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next() == Some(r)) } -/// A Windows device name (`CON`, `NUL`, `COM1`… also with an extension), which names no file. +/// A Windows device name (`CON`, `NUL`, `COM1`, `COM¹`… also with an extension or a colon), which names no file. pub(crate) fn is_device_name(component: &str) -> bool { - let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); - let numbered = |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")); + let stem = component.split(['.', ':']).next().unwrap_or(component).trim_end_matches(' ').to_ascii_uppercase(); + let numbered = + |prefix: &str| stem.strip_prefix(prefix).is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")); matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT") } @@ -526,6 +527,8 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// On Windows an existing file spelled in another case is still inside its root, and `NUL`, + /// `COM1` and `COM¹` are refused. #[cfg(windows)] #[test] fn windows_ignores_case_and_refuses_devices() { @@ -536,6 +539,8 @@ mod tests { let e = roots.check(s(base.join("out/NUL")), Access::Write).unwrap_err(); assert!(e.contains("reserved device names"), "{e}"); assert!(roots.check(s(base.join("out/com1.txt")), Access::Write).is_err()); + let e = roots.check(s(base.join("out/COM¹.txt")), Access::Write).unwrap_err(); + assert!(e.contains("reserved device names"), "{e}"); assert_eq!(roots.check(s(base.join("out/console.txt")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } @@ -561,6 +566,8 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// `COM¹` to `LPT³`, and a device name before a colon, are reserved. `COM⁴`, `com¹0`, `lpt¹x` + /// and `console:x` are file names. #[test] fn inside_compares_components_exactly() { assert!(inside(Path::new("/work/in/a"), Path::new("/work/in"))); @@ -571,10 +578,10 @@ mod tests { #[test] fn device_names() { - for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL "] { + for d in ["CON", "nul", "Com1", "LPT9.txt", "aux.designcraft", "NUL ", "COM¹", "Lpt²", "lpt³.txt", "COM1:", "nul:x", "COM¹:"] { assert!(is_device_name(d), "{d}"); } - for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x"] { + for f in ["console", "com10", "COM0", "lpt", "a.designcraft", "nul-x", "COM⁴", "com¹0", "lpt¹x", "console:x"] { assert!(!is_device_name(f), "{f}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index f7e0b8187..3c190317d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -143,7 +143,7 @@ config works across the suite) keep the agent to the folders you give it: folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would create its target). The result is compared with each root by whole folder names: `/work2/x` is not inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like - drive-letter ones, and device names (`CON`, `NUL`, `COM1`...) are refused. + drive-letter ones, and device names (`CON`, `NUL`, `COM1`, `COM¹`, including before a colon) are refused. - A refused path is an ordinary tool error the agent can read and correct, for example `automation path rejected: outside the write root /work/project/out: /etc/x.designcraft` (with several, `outside the write roots /work/project/out, /tmp/scratch: ...`) or From 092c46c1487203f3711fab335d7ba4b0aaaf1f09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:39:06 -0800 Subject: [PATCH 198/328] Render: list layers among the kept shadow image's dependencies The doc comment on with_kept_filters now names the document's layers next to its colors, styles and images, as Deps holds them. --- crates/render/src/fx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index c6cbd532e..0cfe63661 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -491,7 +491,7 @@ impl Renderer { /// [`Renderer::with_filters`] for a drop shadow or an outer glow of `it`, keeping its image /// between renders. While the object, its effect, the view's scale and rotation, the render - /// options and the document's colours, styles and images stay the same, a move of the object + /// options and the document's colors, styles, layers and images stay the same, a move of the object /// or of the view by whole device pixels places the kept image again instead of drawing and /// blurring it. Only multithreaded contexts (the canvas) keep images, and only of objects /// without text or nested items. From c2a15435285a1c6d02a2293529a3949a3ccced4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:40:29 -0800 Subject: [PATCH 199/328] Copy: mark the renumber results as must-use renumber and its helpers return false when a copy nests deeper than MAX_COPY_DEPTH and must not be inserted. They now carry #[must_use], so a caller that drops the result fails to build under -D warnings. --- crates/engine/src/cmd/object.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 149a4eab1..a9da97458 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1112,12 +1112,14 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { /// the stories of `src` copied so far to their copies. False when its groups, or the tables and notes in the table cells /// of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below that keep their ids, and the copy /// must not be used. +#[must_use = "false means the copy is incomplete and must not be inserted"] pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { renumber_in(dst, src, it, stories, 0, true) } /// [`renumber`] for an item `depth` groups deep. `adopt` is false inside a story copy, whose asset references the copy /// has already adopted. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap, depth: usize, adopt: bool) -> bool { it.id = ItemId(dst.alloc()); let my_id = it.id; @@ -1190,6 +1192,7 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut /// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their /// destinations where those are copied, and the copy's paragraphs follow its tables. False when tables or notes in /// table cells nest deeper than [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) -> bool { let base = st.id.0 << 24; let mut anchors = HashMap::new(); @@ -1243,6 +1246,7 @@ fn retarget_copies(dst: &mut Document, src: &Document, stories: &HashMap bool { let mut tables = HashMap::new(); for (old, mut table) in std::mem::take(&mut st.tables) { @@ -1320,6 +1324,7 @@ fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth /// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522), each `depth` /// levels deep. False when one of them nests groups deeper than [`MAX_COPY_DEPTH`]. +#[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap, depth: usize) -> bool { let mut complete = true; let mut fresh = |t: &mut Story| { From 3ff65a381a308267eecc14a8f7ba36c476f2c522 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:42:44 -0800 Subject: [PATCH 200/328] Layers: compare frame paths in the duplicate thread-order test Both text frames in the test start with an identity transform, so comparing transforms passed even when the copied thread was reversed. The assertion now compares the frames' paths, which differ. --- crates/engine/src/cmd/layout/layers.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index a527df660..b696653b4 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -538,8 +538,8 @@ mod layer_tests { assert_eq!(st.text, orig.text, "the copy holds the whole text"); // Thread order as in the original (a's copy first, though b's copy was made first), without c. let pos = |id: designcraft_doc::ItemId| d.find(id).map(|l| l.path.clone()); - let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().xf).collect(); - let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().xf).collect(); + let order: Vec<_> = st.frames.iter().map(|f| d.item(*f).unwrap().path.clone()).collect(); + let want: Vec<_> = [a, b].iter().map(|f| d.item(designcraft_doc::ItemId(*f)).unwrap().path.clone()).collect(); assert_eq!(order, want); assert!(st.frames.iter().all(|f| pos(*f).is_some())); } From 329806477e0bd05f7bf05f16e44d06fdb9cfb5f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:45:10 -0800 Subject: [PATCH 201/328] Data merge: an explicit QR role in text is refused, and the caret follows each field data.placeholder.add with role qr and the insertion point in text bound the QR code to the first selected frame, which the caret was not in. It now returns "qr placeholders bind to a frame", as a QR field there does. A field inserted at the insertion point left the caret before its marker, so a second field went in front of the first. The caret now moves past the marker, as after typing. Docs: docs/agents.md. --- crates/engine/src/cmd/datamerge.rs | 9 +++++- crates/engine/src/cmd/datamerge/tests.rs | 38 ++++++++++++++++++++++++ docs/agents.md | 5 ++-- 3 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/datamerge.rs b/crates/engine/src/cmd/datamerge.rs index e03da2d05..c57d507fb 100644 --- a/crates/engine/src/cmd/datamerge.rs +++ b/crates/engine/src/cmd/datamerge.rs @@ -485,7 +485,9 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) } else if explicit_story || role_param == Some("text") { false } else if role_param == Some("qr") { - true + // A QR role with the insertion point in text is refused below rather than bound to a + // selected frame the caret is not in. + sel.text.is_none() } else if role_param == Some("image") { // An image role with the insertion point in text places an inline image there. sel.text.is_none() @@ -585,6 +587,11 @@ fn add_placeholder(d: &mut Document, sel: &mut Selection, p: &Value, name: &str) st.replace(at..at, &marker); } d.adjust_text_ranges(story, at..at, marker.len()); + // The caret moves past the field, as after typing, so the next field goes after it. + if let Some(t) = sel.text.as_mut().filter(|t| t.story == story && t.cell.is_none()) { + let shift = |pos: usize| if pos >= at { pos + marker.len() } else { pos }; + (t.anchor, t.focus) = (shift(t.anchor), shift(t.focus)); + } PlaceholderAnchor::Text { story, start: at, end: at.saturating_add(marker.len()) } } else { let text = d.story(story).map(|st| st.text.clone()).unwrap_or_default(); diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 5f5c4a118..9180964c2 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -831,6 +831,44 @@ fn a_qr_field_at_the_insertion_point_is_refused() { assert!(s.documents()[0].doc.data_merge.placeholders.is_empty()); } +/// An explicit QR role at a text insertion point is refused too, rather than binding the QR code +/// to a selected frame the caret is not in. +#[test] +fn an_explicit_qr_role_at_the_insertion_point_is_refused() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,#Code\nAda,hello\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + let other = text_frame(&mut s, [36.0, 400.0, 300.0, 600.0], "", None); + let other_id = designcraft_doc::ItemId(other["id"].as_u64().unwrap()); + let sid = StoryId(made["story"].as_u64().unwrap()); + let doc = s.doc_mut().unwrap(); + doc.selection = Selection::text(TextSel { story: sid, anchor: 3, focus: 3, frame: None, cell: None }); + doc.selection.items = vec![other_id]; + let msg = err(&mut s, "data.placeholder.add", json!({"field": "Code", "role": "qr"})); + assert!(msg.contains("bind to a frame"), "{msg}"); + let doc = &s.documents()[0].doc; + assert!(doc.data_merge.placeholders.is_empty()); + assert_eq!(doc.item(other_id).unwrap().label, "", "the other frame is not bound"); +} + +/// Fields inserted one after another at the insertion point keep their order: the caret moves +/// past each marker, as after typing. +#[test] +fn fields_inserted_at_the_insertion_point_keep_their_order() { + let mut s = Session::new(); + new_doc(&mut s, 1); + select_csv(&mut s, "Name,City,@Photo\nAda,Paris,/x.png\n"); + let made = text_frame(&mut s, [36.0, 36.0, 300.0, 300.0], "Hi ", None); + exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 3, "focus": 3})); + exec(&mut s, "data.placeholder.add", json!({"field": "Name", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "City", "role": "text"})); + exec(&mut s, "data.placeholder.add", json!({"field": "Photo"})); + assert_eq!(texts(&s), vec!["Hi <><><>".to_string()]); + let t = s.documents()[0].selection.text.unwrap(); + assert_eq!((t.anchor, t.focus), (28, 28)); +} + /// A typed `<>` marker for an image column places the image too, from an absolute path; /// an explicit text role still writes the path as text. #[test] diff --git a/docs/agents.md b/docs/agents.md index b2ec4c156..8058510e6 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -91,8 +91,9 @@ external PDF/X certification. marks text or a frame as a field (`role`: text, image, qr, hyperlink). An image field (a `@` column) inserted at a text insertion point, or typed there as `<>`, merges as an inline image at its natural size, scaled down to fit the frame. The merge writes only text into a table cell or a note: an image field inserted there is refused unless `role` -is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) inserted at a -text insertion point is refused; bind it to a frame instead. An image +is `text`, and its `<>` marker, inserted or typed, merges as the path. A QR field (a `#` column) or `role: "qr"` +at a text insertion point is refused; bind it to a frame with `item` instead. A field inserted at the insertion point +puts the caret after its marker. An image path is absolute or relative to the data file's folder, then the document's; a path that starts with one separator (`\Photos\a.jpg`) is tried from the drive's root first. `data.options` sets records, tiling and image fitting; `data.preview {record}` / `data.preview.stop` show one record without saving it. From 72475633c20751b433a705268d4c9a6e87f3c6fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:49:45 -0800 Subject: [PATCH 202/328] Layers: point copied live captions at copied anchored objects Duplicate Layer pointed copied live captions at the copied objects before anchored objects in the copied stories had their ids, so a caption whose source is anchored kept the original object as its source. Anchored objects in copied stories also kept their captions and parent-item overrides unchanged. The copies now take their links after every anchored object has its id, and anchored objects get the same remapping as the other copies. --- crates/engine/src/cmd/layout/layers.rs | 53 +++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index b696653b4..26e3545d1 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -91,11 +91,6 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { copies.push((r, copy)); } } - // Every copy has its id before overrides are pointed at the copied parent items. - for (r, mut copy) in copies { - move_copy(&mut copy, new_id, &ids); - d.insert_item(r, copy, None)?; - } // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of // anchored text frames get copies in turn. The story copies are taken in story order. let mut pending: Vec = stories.values().copied().collect(); @@ -106,6 +101,17 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); d.stories.insert(new, Arc::new(st)); } + // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and + // live captions at the copied objects. + for (r, mut copy) in copies { + move_copy(&mut copy, new_id, &ids); + d.insert_item(r, copy, None)?; + } + for new in stories.values() { + if let Some(st) = d.story_mut(*new) { + move_anchored(st, new_id, &ids); + } + } // Each story copy gets its frames in the original order, text anchors of its own, which its cross-references // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. @@ -375,6 +381,22 @@ fn move_copy(it: &mut Item, to: LayerId, ids: &HashMap) { } } +/// Run [`move_copy`] on the anchored objects of `st` and of the stories of its table cells and notes. [`too_deep`] bounds +/// the nesting. +fn move_anchored(st: &mut Story, to: LayerId, ids: &HashMap) { + for o in &mut st.objects { + move_copy(&mut Arc::make_mut(o).item, to, ids); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + move_anchored(&mut c.text, to, ids); + } + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + move_anchored(&mut Arc::make_mut(n).text, to, ids); + } +} + #[cfg(test)] mod layer_tests { use serde_json::json; @@ -695,6 +717,27 @@ mod layer_tests { assert_ne!(frame.id.0, a); } + #[test] + fn duplicate_layer_points_copied_live_captions_at_copied_anchored_objects() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let text = json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after."}); + let f = s.execute("frame.create", &text).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + // The caption's source moves into the story and keeps its id. + s.execute("anchored.insert", &json!({"ids": [a], "story": sid.0, "pos": 7})).unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let anchored = d.anchored_items().into_iter().map(|(_, i)| i).find(|i| i.layer.0 == copy).unwrap(); + assert_ne!(anchored.id.0, a); + let copies = on_layer(d, copy); + let caption = copies.iter().find_map(|i| i.live_caption.as_ref()).unwrap(); + assert_eq!(caption.source, anchored.id, "the caption's copy follows the anchored object's copy"); + } + #[test] fn duplicate_layer_copies_the_hyperlinks_of_its_objects_and_text() { use designcraft_doc::{HyperlinkDest, HyperlinkSource}; From 5c484618ca37c1fa3b923d529d8c4b3269e387e0 Mon Sep 17 00:00:00 2001 From: jayzed80 <121670721+jayzed80@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:53:23 +0000 Subject: [PATCH 203/328] Save: a TIFF, BMP or PSD too big for opening to inflate is stored as is, so the document reopens (#2283) (#2701) save deflated every asset that isn't PNG, JPEG, GIF or WebP, with no size cap, while opening refuses a deflated asset over 1 GiB or deflated entries over 4 GiB together. An asset past either cap is now stored as is, which opening reads at any size. Smaller assets are deflated as before, and the zip bomb guard on load is unchanged. --- crates/format/src/lib.rs | 25 +++++++++++++++++++++---- crates/format/src/tests.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a03667209..52ce74860 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -86,6 +86,11 @@ fn required_version(doc: &Document) -> u32 { } fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_entry: usize) -> Result, FormatError> { + save_within(doc, preview, large_entry, Limits::DEFAULT) +} + +/// [`save_with_large_entries_from`], deflating only what a reader with `limits` inflates. +fn save_within(doc: &Document, preview: Option<&[u8]>, large_entry: usize, limits: Limits) -> Result, FormatError> { // JSON writes infinity and NaN as null, which no load accepts: the file would not open. if let Some(id) = doc.non_finite_item() { return Err(FormatError::Unsaveable(format!("object {} has a position or size that is not a finite number", id.0))); @@ -103,8 +108,8 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en z.write_all(MIME.as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; z.start_file("meta.json", deflate).map_err(io)?; let version = required_version(doc); - let meta = json!({"format": "designcraft", "version": version, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))}); - z.write_all(meta.to_string().as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; + let meta = json!({"format": "designcraft", "version": version, "generator": concat!("DesignCraft ", env!("CARGO_PKG_VERSION"))}).to_string(); + z.write_all(meta.as_bytes()).map_err(|e| FormatError::Io(e.to_string()))?; if let Some(png) = preview { z.start_file(PREVIEW, stored).map_err(io)?; z.write_all(png).map_err(|e| FormatError::Io(e.to_string()))?; @@ -112,12 +117,23 @@ fn save_with_large_entries_from(doc: &Document, preview: Option<&[u8]>, large_en z.start_file("document.json", deflate).map_err(io)?; let json = serde_json::to_vec_pretty(doc).map_err(|e| FormatError::Io(e.to_string()))?; z.write_all(&json).map_err(|e| FormatError::Io(e.to_string()))?; + // Opening caps what deflated entries expand to, one asset and all of them together, while a + // stored entry opens at any size. An asset deflated past those caps would save but never + // open again (#2283), so it is stored as is instead. + let mut deflate_left = limits.total.saturating_sub(meta.len() as u64).saturating_sub(json.len() as u64); for (id, a) in &doc.assets { if a.data.is_empty() { continue; } + let len = a.data.len() as u64; // Already-compressed images are stored as-is. - let opts = if matches!(a.mime.as_str(), "image/png" | "image/jpeg" | "image/gif" | "image/webp") { stored } else { deflate }; + let compressed = matches!(a.mime.as_str(), "image/png" | "image/jpeg" | "image/gif" | "image/webp"); + let opts = if compressed || len > limits.asset || len > deflate_left { + stored + } else { + deflate_left = deflate_left.saturating_sub(len); + deflate + }; let opts = opts.large_file(a.data.len() >= large_entry); z.start_file(format!("assets/{}.{}", id.0, ext_for(&a.mime)), opts).map_err(io)?; z.write_all(&a.data).map_err(|e| FormatError::Io(e.to_string()))?; @@ -183,7 +199,8 @@ const MAX_ENTRIES: usize = 100_000; /// bytes in the archive, which is already in memory, and all stored entries read together are /// held to the archive's own size), so a placed image — stored as is by [`save`] — opens whatever /// its size and doesn't count against the budget. Saving has no cap, and this keeps every saved -/// document openable (#2166). +/// document openable (#2166): [`save`] deflates an asset only while it stays within these limits, +/// and stores the rest as is (#2283). #[derive(Clone, Copy, Debug)] struct Limits { /// Most bytes `meta.json` or `document.json` may expand to. diff --git a/crates/format/src/tests.rs b/crates/format/src/tests.rs index 0e6f613cd..5b73801ea 100644 --- a/crates/format/src/tests.rs +++ b/crates/format/src/tests.rs @@ -152,6 +152,44 @@ fn stored_assets_open_at_any_size_while_deflated_ones_stay_capped() { assert!(!doc.assets.is_empty() && doc.assets.values().all(|x| x.data.len() == 50_000), "every saved image is back"); } +fn tiff_asset(d: &mut Document, data: Vec) -> AssetId { + let aid = AssetId(d.alloc()); + let a = Asset { id: aid, name: "x.tif".into(), mime: "image/tiff".into(), data: Arc::new(data), pixels: Some((1, 1)), ..Default::default() }; + d.assets.insert(aid, Arc::new(a)); + place(d, aid, 0.0); + aid +} + +fn is_deflated(bytes: &[u8], aid: AssetId) -> bool { + let mut z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + z.by_name(&format!("assets/{}.tif", aid.0)).unwrap().compression() == zip::CompressionMethod::Deflated +} + +/// #2283: `save` deflates a TIFF, BMP or PSD, and opening caps what a deflated asset (and all of +/// them together) may expand to. One past either cap is stored as is, so the document opens again. +#[test] +fn assets_too_big_to_inflate_are_stored_so_the_document_reopens() { + let mut d = Document::new(&NewDocument::default()); + let big = tiff_asset(&mut d, noise(5_000)); + let b = tiff_asset(&mut d, noise(3_000)); + let c = tiff_asset(&mut d, noise(3_000).into_iter().rev().collect()); + let small = tiff_asset(&mut d, vec![0; 500]); + // Room for the JSON, the small asset and one 3 000-byte asset, not two. + let json_len = serde_json::to_vec_pretty(&d).unwrap().len() as u64; + let tight = Limits { json: 256 << 20, asset: 4_000, total: json_len + 500 + 500 + 4_000 }; + + let saved = save_within(&d, None, LARGE_ENTRY, tight).unwrap(); + let back = load_zip_within(&saved, tight).expect("a saved document opens under the limits it was saved for"); + for aid in [big, b, c, small] { + assert_eq!(back.assets[&aid].data, d.assets[&aid].data, "asset {} round-trips", aid.0); + } + assert!(!is_deflated(&saved, big), "an asset over the per-asset cap is stored"); + assert!(!(is_deflated(&saved, b) && is_deflated(&saved, c)), "the two together would pass the total budget"); + // Within the limits nothing changes: everything still deflates under the defaults. + let normal = save(&d).unwrap(); + assert!([big, b, c, small].iter().all(|a| is_deflated(&normal, *a))); +} + #[test] fn explicit_all_on_pdf_layers_require_a_capable_reader_only_when_needed() { let mut d = Document::new(&NewDocument::default()); From 7604db695f5fd9b8c238986d27ca8f63df0f2bad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 07:57:27 -0800 Subject: [PATCH 204/328] Copy: point copied cross-references at copied anchors in one pass Each copied story with text anchors walked every story copied before it to retarget their cross-references, so copying many such frames took time quadratic in their number. The copies' cross-references are now pointed at the copied anchors once, after the last item is copied. --- crates/engine/src/cmd/edit.rs | 1 + crates/engine/src/cmd/object.rs | 75 ++++++++------------------------- 2 files changed, 18 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00e197514..958c7c511 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -117,6 +117,7 @@ fn paste_text(s: &mut Session, text: Option, formatted: bool) -> Result< Ok(i) }) .collect::>()?; + super::object::retarget_copied_xrefs(d, &items, &stories); let end = super::anchored::anchor_items(d, t.story, r.start, fresh, &Default::default())?; sel.text = Some(designcraft_doc::TextSel { anchor: end, focus: end, ..t }); Ok(json!({"pos": end, "anchored": list.len()})) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a9da97458..481385952 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1095,6 +1095,7 @@ pub fn duplicate_from(dst: &mut Document, src: &Document, ids: &[ItemId], to: Sp dst.insert_item(to, copy, None)?; out.push(nid); } + retarget_copied_xrefs(dst, src, &story_map); Ok(out) } @@ -1109,9 +1110,10 @@ fn adopt_or_dangle(dst: &mut Document, src: &Document, id: AssetId) -> AssetId { } /// Give `it` (an item of `src`) fresh ids from `dst`, with copies of its stories and the assets it uses. `stories` maps -/// the stories of `src` copied so far to their copies. False when its groups, or the tables and notes in the table cells -/// of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below that keep their ids, and the copy -/// must not be used. +/// the stories of `src` copied so far to their copies. After the last call with the same `stories`, +/// [`retarget_copied_xrefs`] points the copies' cross-references at the copied anchors. False when its groups, or the +/// tables and notes in the table cells of its stories, nest deeper than [`MAX_COPY_DEPTH`]: the items and tables below +/// that keep their ids, and the copy must not be used. #[must_use = "false means the copy is incomplete and must not be inserted"] pub(crate) fn renumber(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut HashMap) -> bool { renumber_in(dst, src, it, stories, 0, true) @@ -1138,7 +1140,7 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut let n = StoryId(dst.alloc()); let mut st = src.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); st.id = n; - let marked = renumber_marks(dst, src, stories, &mut st); + let marked = renumber_marks(dst, &mut st); let mut assets = HashMap::new(); for a in designcraft_doc::story_asset_refs(&st) { let na = adopt_or_dangle(dst, src, a); @@ -1150,14 +1152,8 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. stories.insert(tf.story, n); - let copied = stories.len(); complete = renumber_anchored(dst, src, &mut st, stories, depth + 1) && marked; dst.stories.insert(n, Arc::new(st)); - // The stories anchored in this one were copied while it was not yet in `dst`. - if stories.len() > copied { - let anchors = copied_anchors(dst, src, stories); - retarget_copies(dst, src, stories, &anchors); - } n } }; @@ -1187,39 +1183,26 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut true } -/// Give the text anchors and tables of `st`, a new copy of a story of `src`, ids of their own (anchors from the story's -/// id, tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] -/// levels. Cross-references in `st` and in the copies `stories` already lists point at the copies of their -/// destinations where those are copied, and the copy's paragraphs follow its tables. False when tables or notes in -/// table cells nest deeper than [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. +/// Give the text anchors and tables of `st`, a new copy of a story, ids of their own (anchors from the story's id, +/// tables from `dst`), as do the tables in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] levels. +/// The copy's paragraphs follow its tables. False when tables or notes in table cells nest deeper than +/// [`MAX_COPY_DEPTH`]: the tables below that keep their ids, and the copy must not be used. #[must_use = "false means the copy is incomplete and must not be inserted"] -fn renumber_marks(dst: &mut Document, src: &Document, stories: &HashMap, st: &mut Story) -> bool { +fn renumber_marks(dst: &mut Document, st: &mut Story) -> bool { let base = st.id.0 << 24; - let mut anchors = HashMap::new(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { - anchors.insert(a.id, base + k); Arc::make_mut(a).id = base + k; } - // Earlier copies change only when this story brings anchors, and this story only when it holds cross-references. - let own = !anchors.is_empty(); - if own || has_xrefs(st, 0) { - anchors.extend(copied_anchors(dst, src, stories)); - if own { - retarget_copies(dst, src, stories, &anchors); - } - remap_xrefs(st, &anchors, 0); - } renumber_tables(dst, st, 0) } -/// Whether `st`, or a story of its table cells and notes down to [`MAX_COPY_DEPTH`] levels, holds a cross-reference. -fn has_xrefs(st: &Story, depth: usize) -> bool { - if !st.xrefs.is_empty() { - return true; +/// Point the cross-references in the story copies in `dst` that `stories` maps at the copies of their destinations +/// where [`renumber`] copied those, in one pass after the last copy. Other cross-references keep their destination. +pub(crate) fn retarget_copied_xrefs(dst: &mut Document, src: &Document, stories: &HashMap) { + let anchors = copied_anchors(dst, src, stories); + if !anchors.is_empty() { + retarget_copies(dst, src, stories, &anchors); } - depth < MAX_COPY_DEPTH - && (st.tables.values().any(|t| t.cells.iter().any(|c| has_xrefs(&c.text, depth + 1))) - || st.notes.iter().chain(&st.endnotes).any(|n| has_xrefs(&n.text, depth + 1))) } /// The anchor ids of the stories of `src` that `stories` maps, each to the id of its copy's anchor in `dst`. @@ -1275,30 +1258,6 @@ fn renumber_tables(dst: &mut Document, st: &mut Story, depth: usize) -> bool { complete } -/// Point the cross-references in `st`, and in the stories of its table cells and notes down to [`MAX_COPY_DEPTH`] -/// levels, at the anchors `map` gives for their targets. -fn remap_xrefs(st: &mut Story, map: &HashMap, depth: usize) { - if map.is_empty() { - return; - } - for x in &mut st.xrefs { - if let Some(n) = map.get(&x.target) { - Arc::make_mut(x).target = *n; - } - } - if depth >= MAX_COPY_DEPTH { - return; - } - for t in st.tables.values_mut() { - for c in &mut Arc::make_mut(t).cells { - remap_xrefs(&mut c.text, map, depth + 1); - } - } - for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - remap_xrefs(&mut Arc::make_mut(n).text, map, depth + 1); - } -} - /// Point the cross-references in `copy`, a copy of `orig`, and in the stories of its table cells and notes down to /// [`MAX_COPY_DEPTH`] levels, at the anchors `map` gives for the targets of the matching references in `orig`. fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth: usize) { From 812c7c4fd8319203906b8c6d5f2fe30e95127c21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:01:00 -0800 Subject: [PATCH 205/328] Layers: give copied text anchors ids no other anchor has Duplicate Layer gave each copied text anchor the id story id << 24 | n without checking it, so a document holding an anchor with that id, such as one loaded from a file, got two anchors with one id, and cross-references could find the wrong one. A copied anchor now takes a new id when another anchor has that one or when the story id does not fit in the high bits. --- crates/engine/src/cmd/layout/layers.rs | 42 +++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index 26e3545d1..2f423e676 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -129,7 +129,18 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { } st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); for (k, a) in (1..).zip(st.anchors.iter_mut()) { - let id = (new.0 << 24) + k; + // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id + // does not fit. + let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); + let id = match made { + Some(id) => id, + None => loop { + let id = d.alloc(); + if !used.contains(&id) { + break id; + } + }, + }; anchors.insert(a.id, id); used.insert(id); Arc::make_mut(a).id = id; @@ -800,6 +811,35 @@ mod layer_tests { assert_eq!(d.find_anchor(st.anchors[0].id).map(|a| a.0), Some(copied)); } + #[test] + fn duplicate_layer_gives_copied_text_anchors_ids_no_other_anchor_has() { + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Head"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + let g = s.execute("frame.create", &json!({"rect": [72, 450, 400, 600], "content": "text", "text": "Other"})).unwrap()["id"].as_u64().unwrap(); + let other = s.doc().unwrap().doc.item(designcraft_doc::ItemId(g)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.story_mut(sid).unwrap().insert_anchor(0, "Heading"); + // A story on another layer holds the ids the copy's first anchor would take, as anchors loaded from a file can. + let next = d.next_id; + let st = d.story_mut(other).unwrap(); + for k in 1..=64 { + st.insert_anchor(0, "Taken"); + Arc::make_mut(&mut st.anchors[0]).id = ((next + k) << 24) + 1; + } + s.execute("layer.duplicate", &json!({"id": base})).unwrap(); + let d = &s.doc().unwrap().doc; + let all: Vec = d.stories.values().flat_map(|st| st.anchors.iter().map(|a| a.id)).collect(); + assert_eq!(all.len(), 66); + let unique: std::collections::HashSet<_> = all.iter().collect(); + assert_eq!(unique.len(), all.len(), "the copied anchor has an id no other anchor has"); + } + #[test] fn duplicate_layer_remaps_anchors_in_cells_and_notes() { use designcraft_doc::Story; From 20319e991e049862f15da16632dffa3ff3fc265e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:07:12 -0800 Subject: [PATCH 206/328] Text Frame Options: link the insets only when every selected frame has even sides The dialog turned the inset link on when the first selected frame had the same inset on all four sides. With a second frame whose sides differ, typing one side then set all four sides of every selected frame, so the second frame lost its other insets. The link is now on only when every frame the dialog changes has even sides: the selected items, else the caret's frame, else every frame of the caret's story. --- crates/ui-egui/src/dialogs.rs | 21 +++++++++++- crates/ui-egui/src/dialogs/tests.rs | 51 +++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..1499b37e5 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1005,6 +1005,24 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { + let Some(st) = app.session.active() else { + return true; + }; + let mut ids = st.selection.items.clone(); + if ids.is_empty() + && let Some(t) = st.selection.text + { + ids = match t.frame { + Some(f) => vec![f], + None => st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(), + }; + } + ids.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|t| t.options.inset.iter().all(|v| (v - t.options.inset[0]).abs() < 1e-9)) +} + /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, /// so OK sends only the fields the user changed. Fields given when the dialog opened count as /// changed. @@ -1056,7 +1074,8 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); } } - d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(o.inset.iter().all(|v| (v - o.inset[0]).abs() < 1e-9))); + // Linked only when no selected frame has uneven sides, so a typed side cannot overwrite them. + d.fields.entry("insetLinked".to_string()).or_insert_with(|| json!(selected_frames_have_even_insets(app))); // The frame's width: Fixed Number shows each column's width from it as the fields change. if let Some(w) = selected_frame_width(app) { d.fields.insert("_frameWidth".into(), json!(w)); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..5c2cf749e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1485,6 +1485,57 @@ fn text_frame_options_change_only_what_was_edited() { assert_eq!(opts(&app), before); } +#[test] +fn text_frame_options_link_the_insets_only_when_every_selected_frame_has_even_sides() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = |app: &mut DesignApp, rect: [u32; 4], inset: Value| { + let r = app.run("frame.create", json!({"rect": rect, "content": "text", "text": "Hello"})).unwrap(); + let id = r["id"].as_u64().unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "inset": inset})).unwrap(); + (designcraft_doc::ItemId(id), r["story"].clone()) + }; + let (even, _) = frame(&mut app, [36, 36, 236, 236], json!(6)); + let (uneven, uneven_story) = frame(&mut app, [300, 36, 500, 236], json!([1, 2, 3, 4])); + let (other_even, other_even_story) = frame(&mut app, [36, 300, 236, 500], json!(9)); + let inset = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.inset; + let seeded = |app: &DesignApp| { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d + }; + // The frame with even sides is selected first: the uneven one still turns the link off. + app.run("selection.set", json!({"ids": [even.0, uneven.0]})).unwrap(); + let mut d = seeded(&app); + assert_eq!(d.s("insetTop"), "0p6"); + assert!(!d.b("insetLinked"), "a selected frame with uneven sides leaves the link off"); + // Top edited while unlinked: only Top changes, and each frame keeps its other sides. + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(inset(&app, even), [12.0, 6.0, 6.0, 6.0]); + assert_eq!(inset(&app, uneven), [12.0, 2.0, 3.0, 4.0]); + // A frame with even sides alone keeps the link on; selected with the uneven one, the link is off. + app.run("selection.set", json!({"ids": [other_even.0]})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + app.run("selection.set", json!({"ids": [other_even.0, uneven.0]})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); + // A caret: the frames the dialog changes decide. + app.run("text.select", json!({"story": uneven_story, "anchor": 0, "focus": 0})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); + app.run("text.select", json!({"story": other_even_story, "anchor": 0, "focus": 0})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + // A story threaded on into the uneven frame: a caret placed in the first frame changes only + // that frame, and a caret with no frame changes every frame of the story. + let (first, story) = frame(&mut app, [300, 300, 500, 500], json!(6)); + let (last, _) = frame(&mut app, [300, 520, 500, 700], json!([1, 2, 3, 4])); + app.run("text.thread", json!({"from": first.0, "to": last.0})).unwrap(); + app.run("text.placeCaret", json!({"frame": first.0, "point": [310, 310]})).unwrap(); + assert!(seeded(&app).b("insetLinked")); + app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); + assert!(!seeded(&app).b("insetLinked")); +} + #[test] fn toc_dialog_adds_a_style_and_ok_makes_the_table_of_contents() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5e60c4d8fe56a8265123bac2eef45aec161b9c0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:54:29 -0800 Subject: [PATCH 207/328] Compose: vertical justification stays finite with an extreme grid increment A grid increment so small that the room holds more steps than an f64 can count made the grid step count infinite, and Bottom, Center and Justify then moved the grid-aligned lines to an infinite baseline. Such an increment now leaves the lines placed as they are without a grid. A Center step so large that doubling it overflows no longer turns a zero step count into a NaN shift; the lines stay where they are. --- crates/compose/src/lib.rs | 6 +++++- crates/compose/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f43caad84..84da4a148 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5604,6 +5604,9 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de }); let shift = match step { None => shifts(most_room(space)), + // A step so small that the room holds more steps than an f64 can count: the lines take + // the room as they do without a grid, and stay within one step of a grid line. + Some(inc) if !(space / inc).is_finite() => shifts(most_room(space)), Some(inc) => { // The room one grid step takes: Center moves the lines by half the room. let unit = if center { 2.0 * inc } else { inc }; @@ -5615,7 +5618,8 @@ fn vertical_justify(ft: &mut FrameText, f: &FrameSpec, spanned: bool, notes: &de if steps > 0.0 && !fits(&shifts(steps * unit)) { steps -= 1.0; } - shifts(steps * unit) + // With no step taken the lines stay put, even when Center's doubled step overflows. + shifts(if steps > 0.0 { steps * unit } else { 0.0 }) } }; let before: Vec = idx.iter().map(|&i| ft.lines[i].baseline).collect(); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0f7b54da2..aca4ab07c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2435,6 +2435,43 @@ fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); } +/// A grid increment too small for the room to be counted in steps, or too large to double, leaves +/// a grid-aligned line at a finite place inside the text area with Bottom, Center and Justify. +#[test] +fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Justify, Top}; + // The grid starts at the line's natural baseline, so the line sits on it before it moves. + let (natural, grid) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::None), ..Default::default() }, |_, _| {}); + let natural = natural[0].baseline; + let start = natural - grid.0; + let compose_with = |mode: VerticalJustification, inc: f64| { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start, inc)); + opts.vertical_justification = mode; + }); + (area, lines[0].baseline) + }; + for inc in [1e-310, 1e308] { + let (_, top) = compose_with(Top, inc); + assert!((top - natural).abs() < 1e-6, "Top with increment {inc:e}: baseline {top}, natural {natural}"); + for mode in [Bottom, Center, Justify] { + let (area, b) = compose_with(mode, inc); + assert!(b.is_finite() && b >= top - 1e-6 && b <= area.y1 + 1e-6, "{mode:?} with increment {inc:e}: baseline {b}, text area {area:?}"); + } + } + // A step far smaller than the room: Bottom takes the room as it does without a grid. + let (area, b) = compose_with(Bottom, 1e-310); + assert!((b - area.y1).abs() < 1e-6, "Bottom with a tiny increment: baseline {b}, text area {area:?}"); + // A step far larger than the room: the line does not move. + let (_, b) = compose_with(Center, 1e308); + assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); +} + /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top /// and with Center: a line's band above the text area isn't held to the frame's outline (#1999). /// Center puts the last baseline halfway between where Top sets it and the bottom inset, also in From f0f609a3ba9c1e5b8ed14dacf634e96500036e7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 08:55:00 -0800 Subject: [PATCH 208/328] Canvas: a scaled object's hardened shadow or glow stays in its damage The spread of a drop shadow or outer glow is stroked through the item's transform, so on a scaled item it reaches that much farther. Damage now grows the effect outset by the item's largest scale factor, and the multithreaded renderer crops the effect's offscreen image to the scaled reach, so the outer part of the glow is no longer cut off. --- crates/render/src/damage.rs | 42 +++++++++++++++-------- crates/render/src/fx.rs | 68 ++++++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 18 deletions(-) diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index bacd3864c..aa1780014 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -11,6 +11,8 @@ use std::sync::Arc; use designcraft_doc::{Document, Item, ItemId, SpreadRef, Story, StoryId}; use designcraft_geom::Rect; +use crate::fx::max_scale; + /// Changed regions in spread coordinates, or `None` when the whole view must be repainted. pub fn damage(old: &Document, new: &Document) -> Option> { damage_with(old, new, None) @@ -167,23 +169,18 @@ fn item_area(it: &Item) -> Option { if !ok { return None; } - // The stroke is drawn through the item's transform. The item's own drop shadow and outer glow - // reach `fx::outset` past what it paints; its inner effects and feathers stay inside the shape. - let stroke = it.stroke.extent().max(0.0) * max_scale(it.xf)?; - let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset(it); + // The stroke and the effects' spread are drawn through the item's transform. The item's own + // drop shadow and outer glow reach `fx::outset_scaled` past what it paints; its inner effects + // and feathers stay inside the shape. + let scale = max_scale(it.xf)?; + let stroke = it.stroke.extent().max(0.0) * scale; + let pad = stroke + 2.0 + if it.is_text_frame() { 24.0 } else { 0.0 } + crate::fx::outset_scaled(it, scale); + if !pad.is_finite() { + return None; + } Some(painted_bounds(it)?.inflate(pad, pad)) } -/// The largest factor `m` stretches a length by (its linear part's largest singular value), or -/// None when that is not finite. -fn max_scale(m: designcraft_geom::Affine) -> Option { - let [a, b, c, d, _, _] = m.as_coeffs(); - let s = a * a + b * b + c * c + d * d; - let det = a * d - b * c; - let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); - v.is_finite().then_some(v) -} - /// An item's bounds, grown to its text: text is composed in the box around the frame's path in /// the frame's own coordinates, which a sheared then rotated frame turns past its path's bounds. /// Its children's bounds include their strokes. None when a child's transform is not finite. @@ -427,6 +424,23 @@ mod tests { let changed = changed_pixels_in_damage(&old, &d); assert!(changed.iter().any(|p| !Rect::new(98.0, 98.0, 312.0, 242.0).contains(*p)), "glow {glow}: the effect paints outside the object"); } + // A hardened glow on a scaled object: its growth is stroked through the transform, so it + // reaches three times as far on the spread as the glow's size says. + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let id = ItemId(d.alloc()); + let mut it = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0))); + it.xf = designcraft_geom::Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let old = d.clone(); + let it = d.item_mut(id).unwrap(); + it.xf = designcraft_geom::Affine::translate((60.0, 40.0)) * it.xf; + // The square covers 150..270 before the move; its glow reaches 60 pt past that. + let changed = changed_pixels_in_damage(&old, &d); + assert!(changed.iter().any(|p| p.x < 110.0), "the hard glow grows with the object's scale"); // An effect on an object inside a group is drawn through the group's transform: unbounded. let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); let lid = d.default_layer(); diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 7c7c91fe1..26a87dacd 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -35,17 +35,37 @@ pub(crate) fn offset(angle: f64, distance: f64) -> Vec2 { /// How far (points) the effects of `it` reach outside its geometry. pub(crate) fn outset(it: &Item) -> f64 { + outset_scaled(it, 1.0) +} + +/// [`outset`] for an item whose transform stretches lengths by up to `scale`: the blur and the +/// shadow's distance are spread lengths, but the spread's growth is stroked through the item's +/// transform and grows with it. +pub(crate) fn outset_scaled(it: &Item, scale: f64) -> f64 { let e = &it.effects; + let extra = |size: f64, pct: f64| split(size, pct).1 * (scale - 1.0).max(0.0); let mut o: f64 = 0.0; if e.drop_shadow.on { - o = o.max(bound(e.drop_shadow.distance).abs() + bound(e.drop_shadow.size).abs() * 1.6 + 1.0); + let s = &e.drop_shadow; + o = o.max(bound(s.distance).abs() + bound(s.size).abs() * 1.6 + 1.0 + extra(s.size, s.spread)); } if e.outer_glow.on { - o = o.max(bound(e.outer_glow.size).abs() * 1.6 + 1.0); + let g = &e.outer_glow; + o = o.max(bound(g.size).abs() * 1.6 + 1.0 + extra(g.size, g.spread)); } o } +/// The largest factor `m` stretches a length by (its linear part's largest singular value), or +/// None when that is not finite. +pub(crate) fn max_scale(m: Affine) -> Option { + let [a, b, c, d, _, _] = m.as_coeffs(); + let s = a * a + b * b + c * c + d * d; + let det = a * d - b * c; + let v = ((s + (s * s - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + v.is_finite().then_some(v) +} + /// (blur σ, growth) in points for an effect `size` with `pct` percent hardened. fn split(size: f64, pct: f64) -> (f64, f64) { let size = bound(size).max(0.0); @@ -104,7 +124,9 @@ impl Renderer { pub(crate) fn draw_item_fx(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: ShownOn) { let doc = f.doc; let e = &it.effects; - let sw = if it.stroke.is_none() { 0.0 } else { it.stroke.extent() }; + // The stroke and the effects' growth are drawn through `xf`, which stretches them. + let scale = max_scale(xf).unwrap_or(1.0); + let sw = if it.stroke.is_none() { 0.0 } else { it.stroke.extent() * scale }; // Spread-space reach of what the object paints. let reach = xf.transform_rect_bbox(bp.bounding_box()).inflate(sw + 1.0, sw + 1.0); // The silhouette is the shape when the object paints its area (fill / image); text frames @@ -125,7 +147,7 @@ impl Renderer { let filter = shadow(sigma, color_of(&c, opacity.clamp(0.0, 1.0))); // The offset moves the geometry, not the filter: vello drops layer content that lies // entirely outside the viewport before filtering. - let r = (reach + off).inflate(grow, grow); + let r = (reach + off).inflate(grow * scale, grow * scale); // The effect's blend sees what's behind the object: a layer around the filtered one. let mix = crate::blend_mode(mode).mix; if mix != Mix::Normal { @@ -607,4 +629,42 @@ mod tests { // The transparent half shows the page: no shadow painted there. assert!(lum(150) > 700, "nothing over the transparent part: {}", lum(150)); } + + /// A hardened outer glow is stroked through the item's transform, so a scaled item's glow + /// grows with it. The multithreaded renderer draws the glow offscreen, cropped to its reach, + /// and that reach scales too. + #[test] + fn a_scaled_items_hard_glow_is_not_cropped() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0)), + ); + it.xf = Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + // max_scale's own cases: a plain scale, a rotation and a shear. + assert_eq!(max_scale(it.xf), Some(3.0)); + assert!((max_scale(Affine::rotate(0.7)).unwrap() - 1.0).abs() < 1e-12); + assert!((max_scale(Affine::skew(1.0, 0.0)).unwrap() - (1.0 + 5f64.sqrt()) / 2.0).abs() < 1e-12); + assert_eq!(max_scale(Affine::scale(f64::INFINITY)), None); + // The 20 pt growth is 60 pt on the spread: the glow covers 90..330. + assert_eq!(outset_scaled(&it, 3.0), outset(&it) + 40.0); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cache = crate::Cache::new(); + for threads in [0, 2] { + let mut r = Renderer::new(); + r.threads = threads; + let page = r.render_page(&d, &cache, 0, 1.0, false, &crate::RenderOptions::default()).unwrap(); + let p = page.pixel(100, 210); + let lum = u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + assert!(lum < 200, "{threads} threads: the glow 50 pt left of the scaled square is drawn, luminance {lum}"); + } + } } From 49792c9ad5d25d499b5c34f63a64294f3ade8f28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:04:11 -0800 Subject: [PATCH 209/328] Text wrap: look up Alpha Channel outlines by binary search The document keeps its outlines sorted by image and threshold, and the lookup uses a binary search. The data merge test now checks that the merged document has the image's outline, and that a bounding box wrap leaves the same caption overset. --- crates/doc/src/lib.rs | 6 +++-- crates/engine/src/cmd/alpha_wrap.rs | 30 ++++++++++++++++++++++++ crates/engine/src/cmd/datamerge/tests.rs | 24 +++++++++++++++---- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5e18186da..f4c8a25b6 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -803,7 +803,8 @@ pub struct Document { pub sections: Vec
, #[serde(default)] pub assets: BTreeMap>, - /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]). Not saved. + /// Alpha Channel contour outlines of placed images (see [`AlphaOutline`]), sorted by asset + /// and then threshold, at most one for each pair. Not saved. #[serde(skip)] pub alpha_outlines: Vec>, /// Hyperlinks (Window → Interactive → Hyperlinks). @@ -1118,7 +1119,8 @@ impl Document { /// The Alpha Channel outline of `asset` at `threshold`, once the engine has traced it. pub fn alpha_outline(&self, asset: AssetId, threshold: u8) -> Option<&AlphaOutline> { - self.alpha_outlines.iter().map(|o| &**o).find(|o| o.asset == asset && o.threshold == threshold) + let i = self.alpha_outlines.binary_search_by_key(&(asset, threshold), |o| (o.asset, o.threshold)).ok()?; + self.alpha_outlines.get(i).map(|o| &**o) } pub fn layer(&self, id: LayerId) -> Option<&Layer> { diff --git a/crates/engine/src/cmd/alpha_wrap.rs b/crates/engine/src/cmd/alpha_wrap.rs index 86b864a61..ea9801f79 100644 --- a/crates/engine/src/cmd/alpha_wrap.rs +++ b/crates/engine/src/cmd/alpha_wrap.rs @@ -49,6 +49,7 @@ pub(crate) fn sync(doc: &mut Document) { let assets = &doc.assets; doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data))); let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect(); + let kept = doc.alpha_outlines.len(); for (asset, threshold) in wanted { if traced.contains(&(asset, threshold)) { continue; @@ -59,6 +60,10 @@ pub(crate) fn sync(doc: &mut Document) { let o = trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold)); doc.alpha_outlines.push(Arc::new(o)); } + // `Document::alpha_outline` finds an outline by binary search. + if doc.alpha_outlines.len() > kept { + doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold)); + } } /// The empty outline standing for an image `trace` found none in: zero-size, which composition @@ -443,6 +448,31 @@ mod tests { assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline"); } + /// An outline traced after others is still found: a threshold lower than a kept outline's + /// is traced later and must not hide either outline from the lookup. + #[test] + fn outlines_traced_later_are_found_by_image_and_threshold() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let data = png(|x, _| (16..48).contains(&x)); + let image = s + .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200})) + .unwrap(); + s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold"); + let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") }; + for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] { + let o = d.alpha_outline(g.asset, threshold); + assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found"); + } + assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses"); + } + /// A wrap with the default threshold saves as it did before thresholds were stored; another /// threshold is saved. #[test] diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index 055f7e5d6..963cb4fd7 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1339,10 +1339,22 @@ fn a_previewed_image_gets_its_alpha_channel_outline() { } /// The overset count data merge reports is composed with the merged images' Alpha Channel -/// outlines: a caption over the image's transparent part is set, not counted as overset. +/// outlines: a caption over the image's transparent part is set, not counted as overset. With a +/// bounding box wrap the same caption is overset, so the count depends on the outline. #[test] fn a_merge_counts_overset_text_with_the_merged_images_outlines() { - let dir = scratch("alpha-merge"); + let (r, outlines) = merge_with_wrap("alpha-merge", json!({"mode": "contour", "contour": "alphaChannel", "offset": 0})); + assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + assert_eq!(outlines, 1, "the merged document has the image's outline"); + let (r, _) = merge_with_wrap("alpha-merge-box", json!({"mode": "boundingBox", "offset": 0})); + assert_eq!(r["oversetStories"], 1, "the image's frame covers the caption: {r}"); +} + +/// Merges one record whose image is visible only in its left quarter into a graphic placeholder +/// with the text wrap `wrap`, beside a caption over the image's transparent part. Returns the +/// merge's answer and the number of nonempty Alpha Channel outlines in the merged document. +fn merge_with_wrap(name: &str, wrap: Value) -> (Value, usize) { + let dir = scratch(name); // Visible only in the left quarter. let mut pixels = vec![0u8; 64 * 64 * 4]; for y in 0..64 { @@ -1358,11 +1370,15 @@ fn a_merge_counts_overset_text_with_the_merged_images_outlines() { let frame = exec(&mut s, "frame.create", json!({"rect": [100.0, 100.0, 300.0, 300.0], "content": "graphic"})); exec(&mut s, "data.placeholder.add", json!({"field": "Photo", "role": "image", "item": frame["id"]})); exec(&mut s, "data.options", json!({"fitting": "fitContentToFrame"})); - exec(&mut s, "object.textWrap", json!({"ids": [frame["id"]], "mode": "contour", "contour": "alphaChannel", "offset": 0})); + let mut params = wrap; + params["ids"] = json!([frame["id"]]); + exec(&mut s, "object.textWrap", params); text_frame(&mut s, [220.0, 180.0, 290.0, 220.0], "Hi", None); let r = exec(&mut s, "data.merge", json!({})); - assert_eq!(r["oversetStories"], 0, "the caption sits beside the image's visible pixels: {r}"); + let doc = &s.documents()[s.active_index().unwrap()].doc; + let outlines = doc.alpha_outlines.iter().filter(|o| o.width > 0 && !o.outer.subpaths.is_empty()).count(); let _ = std::fs::remove_dir_all(&dir); + (r, outlines) } /// The cell texts of the first table in the active document's first story that has one. From 58cf0ba28afa3f6c8df55ed148bd6f5fee706d17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:08:51 -0800 Subject: [PATCH 210/328] Place: WebP EXIF stops at the declared RIFF end The RIFF size counts the bytes after its own field, so the container ends at offset 8 plus the size, not 12. An EXIF chunk that ran up to four bytes past the declared container was read when trailing bytes followed it. A new test covers an exact size with and without trailing bytes, a size declared four bytes short, and a file cut inside the EXIF chunk. --- crates/images/src/resolution.rs | 3 ++- crates/images/src/tests.rs | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/images/src/resolution.rs b/crates/images/src/resolution.rs index ea0a55eaa..3b04d8e73 100644 --- a/crates/images/src/resolution.rs +++ b/crates/images/src/resolution.rs @@ -203,8 +203,9 @@ fn png_resolution(bytes: &[u8]) -> Option<(f64, f64)> { /// A WebP EXIF chunk carries a TIFF header: reuse the TIFF resolution tags. fn webp_resolution(bytes: &[u8]) -> Option<(f64, f64)> { + // The RIFF size counts the bytes after the size field itself (offset 8). let riff = u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?) as usize; - let end = 12usize.checked_add(riff)?.min(bytes.len()); + let end = 8usize.checked_add(riff)?.min(bytes.len()); let mut pos = 12; loop { let kind = bytes.get(pos..pos + 4)?; diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 1803b310a..d7d46e4a4 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -676,6 +676,40 @@ fn webp_exif_after_many_frames_is_read() { assert_eq!(raster_resolution(&webp), Some((300.0, 300.0))); } +/// The RIFF size counts the bytes after its own field (offset 8): an EXIF chunk that runs past +/// the declared container is not read, even when trailing bytes follow the container. +#[test] +fn webp_exif_past_the_declared_riff_end_is_not_read() { + let mut body = b"WEBP".to_vec(); + body.extend_from_slice(b"VP8X"); + body.extend_from_slice(&10u32.to_le_bytes()); + body.extend_from_slice(&[0; 10]); + let exif = tiff_bytes((300, 1), (300, 1), Some(2)); + body.extend_from_slice(b"EXIF"); + body.extend_from_slice(&(exif.len() as u32).to_le_bytes()); + body.extend_from_slice(&exif); + if exif.len() % 2 == 1 { + body.push(0); + } + let riff = |size: usize, trailing: usize| { + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&(size as u32).to_le_bytes()); + webp.extend_from_slice(&body); + webp.extend_from_slice(&vec![0xAA; trailing]); + webp + }; + // The exact size, with or without trailing data, reads the chunk. + assert_eq!(raster_resolution(&riff(body.len(), 0)), Some((300.0, 300.0))); + assert_eq!(raster_resolution(&riff(body.len(), 4)), Some((300.0, 300.0))); + // A size declared 4 bytes short ends the container inside the EXIF chunk. + assert_eq!(raster_resolution(&riff(body.len() - 4, 4)), None); + assert_eq!(raster_resolution(&riff(body.len() - 4, 0)), None); + // A file cut inside the EXIF chunk is not read either. + let mut cut = riff(body.len(), 0); + cut.truncate(cut.len() - 6); + assert_eq!(raster_resolution(&cut), None); +} + /// A real encoder-written BMP with the header pixels-per-meter patched (compression and image /// size stay zero, as the encoder writes them). fn bmp_with_ppm(ppm: i32) -> Vec { From 970e98fcc53c09552d2907a451df4eb6b192885c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:12:05 -0800 Subject: [PATCH 211/328] Compose: say where reuse resumes after an edit that moves lines An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, as an_edit_that_moves_lines_composes_up_to_the_next_frame_the_text_starts_in shows. The ROADMAP line no longer cites an issue about selection lag. --- ROADMAP.md | 2 +- docs/architecture.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 87daec8b7..8bc497cbf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -387,7 +387,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log -- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames is composed to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole (#2298). No readiness percentage change. +- **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/docs/architecture.md b/docs/architecture.md index 4fede8ca4..29e9757ad 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,8 @@ revision; stories compose in parallel (rayon) on native targets. After an edit o or formatting, composing starts at the paragraph before the first changed one and stops at the first unchanged paragraph it reaches in the state it had before the edit; the lines above and below are copied from the composition before the edit (`crates/compose/src/reuse.rs`). An edit -that moves lines into other frames is composed to the story's end. A story is composed whole +that moves lines into other frames composes on until a paragraph starts in the same frame and +place as before, or to the story's end. A story is composed whole when it has footnotes, endnotes, tables, anchored objects, named lists, tracked deletions, balanced columns, vertical justification other than Top, column rules, type on a path, spanning or split paragraphs, or paragraph borders or shading, and when its layout goes back over a From 2c0121aebb098ccaab6473c8d8eddcc84f81dd5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:14:42 -0800 Subject: [PATCH 212/328] Text: Text Frame Options from the Type tool stay with their document The dialog stores the frames it took from the caret or selection with the document state they came from. OK and Preview are refused when another document became active after the dialog opened, or when Revert replaced the document, since the stored frame ids can name a different frame there. --- crates/ui-egui/src/dialogs.rs | 19 +++++++++-- crates/ui-egui/src/dialogs/tests.rs | 53 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f2689c927..b6141a75f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1102,6 +1102,9 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { // text into another frame does not change which frames the options apply to. if let Some(ids) = typing_frame_ids(app) { d.fields.insert("_targets".into(), ids); + // The document state those frames are in: another document, or the document after + // Revert, can reuse their ids. + d.fields.insert("_targetsDoc".into(), json!(app.session.active().map(|doc| doc.identity_epoch))); } d.fields.insert("_shown".into(), shown); } @@ -1605,14 +1608,24 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, json!(d.m("paragraphSpacingLimit").filter(|v| *v >= 0.0).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?), ); } - // Typing in a frame: the options apply to the frame that showed the caret, or to every frame - // that held part of the selected text, when the dialog opened. - if let Some(ids) = d.fields.get("_targets").cloned().or_else(|| typing_frame_ids(app)) { + if let Some(ids) = text_frame_targets(app, d).map_err(bad)? { p.insert("ids".into(), ids); } Ok(p) } +/// Typing in a frame: the frame that showed the caret, or every frame that held part of the +/// selected text, when the dialog opened. Those ids are refused once another document is active, +/// or once Revert has replaced the document. +fn text_frame_targets(app: &DesignApp, d: &Dialog) -> Result, &'static str> { + let Some(ids) = d.fields.get("_targets").cloned() else { return Ok(typing_frame_ids(app)) }; + let active = app.session.active().map(|doc| doc.identity_epoch); + if d.fields.get("_targetsDoc").and_then(Value::as_u64) != active { + return Err("the document the dialog opened on is no longer the active one"); + } + Ok(Some(ids)) +} + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..1d2bcd4a1 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1389,6 +1389,59 @@ fn text_frame_options_set_columns_baseline_and_wrap_as_indesign_does() { assert_eq!((opts(&app).columns_kind, opts(&app).column_width), (designcraft_doc::ColumnsKind::FixedNumber, 120.0)); } +/// The frames Text Frame Options took while typing belong to the document it opened on: when +/// another document becomes active before OK, OK changes nothing there. +#[test] +fn text_frame_options_from_the_type_tool_stay_with_their_document() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let make = |app: &mut crate::DesignApp| { + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + let (id, story) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap()); + app.run("text.select", json!({"story": story, "anchor": 2})).unwrap(); + id + }; + let a = make(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert_eq!(d.fields.get("_targets"), Some(&json!([a]))); + d.fields.insert("columns".into(), json!(3)); + // A second document, with a caret in a frame that has the same id, becomes active. + let b = make(&mut app); + assert_eq!(a, b); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + let columns = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(b)).and_then(|i| i.text_frame().map(|t| t.options.columns)); + assert_eq!(columns, Some(1), "the other document's frame is unchanged"); +} + +/// Revert replaces the document while Text Frame Options taken while typing stay open: OK is +/// refused, since the saved frame ids can name another frame in the reverted document. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn text_frame_options_from_the_type_tool_are_refused_after_revert() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "Unsaved"})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 1})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("columns".into(), json!(3)); + app.run("file.revert", json!({})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 300], "content": "text", "text": "After"})).unwrap(); + assert_eq!(a["id"], b["id"], "the reverted document gives a new frame the same id"); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let b = designcraft_doc::ItemId(b["id"].as_u64().unwrap()); + let columns = app.session.active().unwrap().doc.item(b).and_then(|i| i.text_frame().map(|t| t.options.columns)); + assert_eq!(columns, Some(1), "the new frame is unchanged"); +} + #[test] fn baseline_grid_increment_error_explains_the_positive_measure_rule() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 8d39765e936f388bc7fa8675ca4fe598acab5088 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:15:31 -0800 Subject: [PATCH 213/328] Layers: use the anchored copies object copying now makes Copying a frame now gives the objects anchored in its story copy ids of their own and copies of the stories of anchored text frames. Duplicate Layer renumbered them a second time, so live captions kept pointing at the originals and shared stories were copied again. It now records the ids of those copies instead. Copying a frame also renumbers objects anchored in endnotes inside table cells and footnotes, which kept their original ids before. --- crates/engine/src/cmd/layout/layers.rs | 113 ++++++++++++------------- crates/engine/src/cmd/object.rs | 19 +++-- 2 files changed, 63 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index b2a2ec8ac..f93a3c09c 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -1,7 +1,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use designcraft_doc::{Content, Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; +use designcraft_doc::{Guide, Hyperlink, HyperlinkSource, Item, ItemId, SpreadRef, Story, StoryId}; use super::{LAYER_COLORS, Layer, LayerId, Result, Session, Value, bad, json, ok}; @@ -91,15 +91,12 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { copies.push((r, copy)); } } - // A story copy holds the same anchored objects as the original: they get ids of their own, and the stories of - // anchored text frames get copies in turn. The story copies are taken in story order. - let mut pending: Vec = stories.values().copied().collect(); - pending.sort_unstable(); - pending.reverse(); - while let Some(new) = pending.pop() { - let Some(mut st) = d.story(new).cloned() else { continue }; - renumber_anchored(d, &mut st, new_id, &mut stories, &mut ids, &mut pending); - d.stories.insert(new, Arc::new(st)); + // The story copies hold copies of the original's anchored objects with ids of their own (and copies of the + // stories of anchored text frames): record each copy's id against the original's. + for (old, new) in &stories { + if let (Some(orig), Some(copy)) = (src.story(*old), d.story(*new)) { + map_anchored(orig, copy, &mut ids); + } } // Every copy, anchored objects included, has its id before overrides are pointed at the copied parent items and // live captions at the copied objects. @@ -242,27 +239,21 @@ fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collection false } -/// Give the items anchored in `st`, and in the stories of its table cells and notes, new ids from `d` (recorded in `ids`) -/// and layer `to`. An anchored text frame's story gets one copy, recorded in `stories`, that every copied frame of the -/// story shares; a new copy goes on `pending`, and its frame list is filled in afterwards. [`too_deep`] bounds the nesting. -fn renumber_anchored( - d: &mut designcraft_doc::Document, - st: &mut Story, - to: LayerId, - stories: &mut HashMap, - ids: &mut HashMap, - pending: &mut Vec, -) { - for o in &mut st.objects { - renumber_anchored_item(d, &mut Arc::make_mut(o).item, to, stories, ids, pending); +/// Run [`map_ids`] on the items anchored in story `orig` and in its copy `copy`, and in the stories of their table cells +/// and notes. [`too_deep`] bounds the nesting. +fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { + for (o, c) in orig.objects.iter().zip(©.objects) { + map_ids(&o.item, &c.item, ids); } - for t in st.tables.values_mut() { - for c in &mut Arc::make_mut(t).cells { - renumber_anchored(d, &mut c.text, to, stories, ids, pending); + for (k, t) in &orig.tables { + if let Some(ct) = copy.tables.get(k) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); + } } } - for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - renumber_anchored(d, &mut Arc::make_mut(n).text, to, stories, ids, pending); + for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { + map_anchored(&o.text, &c.text, ids); } } @@ -343,39 +334,6 @@ fn remap_xrefs(st: &mut Story, map: &HashMap) { } } -/// [`renumber_anchored`] for one anchored item and its descendants. -fn renumber_anchored_item( - d: &mut designcraft_doc::Document, - it: &mut Item, - to: LayerId, - stories: &mut HashMap, - ids: &mut HashMap, - pending: &mut Vec, -) { - let id = ItemId(d.alloc()); - ids.insert(it.id, id); - it.id = id; - it.layer = to; - if let Content::Text(tf) = &mut it.content { - tf.story = match stories.get(&tf.story) { - Some(n) => *n, - None => { - let n = StoryId(d.alloc()); - let mut copy = d.story(tf.story).cloned().unwrap_or_else(|| Story::new(n)); - copy.id = n; - copy.frames.clear(); - d.stories.insert(n, Arc::new(copy)); - stories.insert(tf.story, n); - pending.push(n); - n - } - }; - } - for c in it.children_mut().into_iter().flatten() { - renumber_anchored_item(d, Arc::make_mut(c), to, stories, ids, pending); - } -} - /// Put `it` and its descendants on layer `to`, and point overrides at the copied parent items and live captions at the /// copied objects. A copy whose parent item was not copied is detached from it, so the original override stays the only /// one of that item. @@ -908,6 +866,39 @@ mod layer_tests { assert_eq!(redone, after); } + #[test] + fn duplicate_layer_gives_objects_anchored_in_endnotes_of_cells_their_own_ids() { + use designcraft_doc::AnchoredObject; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let a = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.caption", &json!({"ids": [a], "text": "{name}", "live": true})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Rows"})).unwrap()["id"].as_u64().unwrap(); + let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().text_frame().unwrap().story; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + // The caption's source moves into an endnote of a table cell and keeps its id. + let it = d.item(designcraft_doc::ItemId(a)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != a); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + let cell = &mut table.cells[0].text; + cell.insert_endnote(cell.len(), "Endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, AnchoredObject::new(it, Default::default())); + d.story_mut(sid).unwrap().insert_table(0, table); + d.check().unwrap(); + let copy = s.execute("layer.duplicate", &json!({"id": base})).unwrap()["id"].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + d.check().unwrap(); + let anchored: Vec<_> = d.anchored_items().into_iter().map(|(_, i)| (i.id, i.layer.0)).collect(); + assert_eq!(anchored.len(), 2); + let copied = anchored.iter().find(|i| i.1 == copy).unwrap().0; + assert_ne!(copied.0, a, "the copy has an id of its own"); + let caption = on_layer(d, copy).iter().find_map(|i| i.live_caption.clone()).unwrap(); + assert_eq!(caption.source, copied, "the caption's copy follows the anchored object's copy"); + } + #[test] fn duplicate_layer_gives_copied_cell_anchors_ids_no_other_anchor_has() { use std::sync::Arc; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..a6526e93b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1161,16 +1161,19 @@ fn renumber_in(dst: &mut Document, src: &Document, it: &mut Item, stories: &mut } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes (#1522). +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, at every depth +/// (#1522). fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap) { - let mut fresh = |t: &mut Story| { - for o in &mut t.objects { - renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, false); + for o in &mut st.objects { + renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, false); + } + for t in st.tables.values_mut() { + for c in &mut Arc::make_mut(t).cells { + renumber_anchored(dst, src, &mut c.text, stories); } - }; - st.for_each_text_mut(&mut fresh); - for n in &mut st.endnotes { - Arc::make_mut(n).text.for_each_text_mut(&mut fresh); + } + for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { + renumber_anchored(dst, src, &mut Arc::make_mut(n).text, stories); } } From f7df4052d68bbd23a9ec6d957aba5a1f0d0aaab5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:23:07 -0800 Subject: [PATCH 214/328] Layers: count Duplicate Layer's nesting limit across anchored stories Copying an object recurses from its groups into the stories of anchored text frames and on into theirs. The limit on how deeply a layer's objects may nest now counts that depth in all, from the object on the spread, instead of starting again at each story. --- crates/engine/src/cmd/layout/layers.rs | 67 +++++++++++++++++++++----- 1 file changed, 54 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index f93a3c09c..cd6e72ee2 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -68,7 +68,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?); let r = s.edit(|d, _| { let i = d.layers.iter().position(|l| l.id == id).ok_or_else(|| bad(ID, "no such layer"))?; - let mut seen = std::collections::HashSet::new(); + let mut seen = HashMap::new(); if d.spreads.iter().chain(&d.parents).flat_map(|sp| sp.items.iter()).any(|it| it.layer == id && too_deep(it, d, &mut seen)) { return Err(bad(ID, "the layer's objects are nested too deeply to copy")); } @@ -205,20 +205,22 @@ fn map_ids(orig: &Item, copy: &Item, ids: &mut HashMap) { } } -/// A layer whose groups, anchored objects, table cells and notes nest deeper than this within one story or object is -/// not duplicated. +/// A layer whose groups, anchored objects, table cells and notes nest deeper than this, counted from an object on a +/// spread through the stories its anchored text frames show, is not duplicated. const MAX_COPY_DEPTH: usize = 64; -/// Whether `it`, or a story its text frames reach directly or through anchored text frames, nests groups, anchored -/// objects, table cells and notes deeper than [`MAX_COPY_DEPTH`]. Stories in `seen` were checked already and are skipped. -fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collections::HashSet) -> bool { - fn item(it: &Item, depth: usize, next: &mut Vec) -> bool { +/// Whether `it`, with the stories its text frames reach directly or through anchored text frames, nests groups, +/// anchored objects, table cells and notes deeper than [`MAX_COPY_DEPTH`] in all: a story counts from the depth of the +/// frame that shows it, as copying it recurses on from there. `seen` holds the deepest level each story was checked at; +/// a story reached again no deeper is skipped. +fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut HashMap) -> bool { + fn item(it: &Item, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { if let Some(t) = it.text_frame() { - next.push(t.story); + next.push((t.story, depth)); } depth > MAX_COPY_DEPTH || it.children().iter().any(|c| item(c, depth + 1, next)) } - fn story(st: &Story, depth: usize, next: &mut Vec) -> bool { + fn story(st: &Story, depth: usize, next: &mut Vec<(StoryId, usize)>) -> bool { depth > MAX_COPY_DEPTH || st.objects.iter().any(|o| item(&o.item, depth + 1, next)) || st.tables.values().flat_map(|t| &t.cells).any(|c| story(&c.text, depth + 1, next)) @@ -228,10 +230,13 @@ fn too_deep(it: &Item, d: &designcraft_doc::Document, seen: &mut std::collection if item(it, 0, &mut next) { return true; } - while let Some(sid) = next.pop() { - if seen.insert(sid) - && let Some(st) = d.story(sid) - && story(st, 0, &mut next) + while let Some((sid, depth)) = next.pop() { + if seen.get(&sid).is_some_and(|&checked| checked >= depth) { + continue; + } + seen.insert(sid, depth); + if let Some(st) = d.story(sid) + && story(st, depth, &mut next) { return true; } @@ -1088,6 +1093,42 @@ mod layer_tests { assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); } + /// Two stories, each anchoring groups nested 40 deep, the innermost group of the first holding a text frame that + /// shows the second: within the limit in each story, past it in all. + #[test] + fn duplicate_layer_refuses_nesting_too_deep_across_stories() { + use designcraft_doc::{AnchoredObject, Content, Item, ItemId}; + use std::sync::Arc; + + fn nest(d: &mut designcraft_doc::Document, mut it: Item, levels: usize) -> Item { + for _ in 0..levels { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + it + } + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Top"})).unwrap()["id"].as_u64().unwrap(); + let g = s.execute("frame.create", &json!({"rect": [0, 0, 60, 30], "content": "text", "text": "Inner"})).unwrap()["id"].as_u64().unwrap(); + let h = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let top = d.item(ItemId(f)).unwrap().text_frame().unwrap().story; + let (inner_frame, leaf) = (d.item(ItemId(g)).cloned().unwrap(), d.item(ItemId(h)).cloned().unwrap()); + let inner = inner_frame.text_frame().unwrap().story; + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != g && i.id.0 != h); + let deep_leaf = nest(d, leaf, 40); + d.story_mut(inner).unwrap().insert_object(0, AnchoredObject::new(deep_leaf, Default::default())); + let deep_frame = nest(d, inner_frame, 40); + d.story_mut(top).unwrap().insert_object(0, AnchoredObject::new(deep_frame, Default::default())); + let before = s.doc().unwrap().doc.layers.clone(); + assert!(s.execute("layer.duplicate", &json!({"id": base})).is_err()); + assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); + } + #[test] fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { let mut s = crate::Session::new(); From a8656662e9ec091ee1e4ac4c7d85f10ebffab19b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:29:14 -0800 Subject: [PATCH 215/328] Compose: vertical justification looks up each wrap's anchored object once The object anchored at each story byte is indexed once per column, and each wrap's object is found once, not once for every line. --- crates/compose/src/lib.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9c38b29a5..4891b41a1 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5691,14 +5691,20 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u }; let in_col = |k: u32| spanned || k == c; let justify = f.opts.vertical_justification == VerticalJustification::Justify; + // The object whose mark is at each story byte, placed on one of these lines (the first one + // listed). + let mut by_anchor = HashMap::new(); + for o in ft.objects.iter().filter(|o| ft.lines.get(o.line).is_some_and(|l| in_col(l.column))) { + if let Some(&a) = anchors.get(o.index) { + by_anchor.entry(a).or_insert(o); + } + } // An own-story anchored object whose anchor is on one of these lines and whose position // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how // much lower that line was when the wrap was taken (an earlier pass placed the object after // moving the lines). let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { - let a = e.after?; - // The object whose mark is the anchor, placed on one of these lines. - let o = ft.objects.iter().find(|o| anchors.get(o.index) == Some(&a) && ft.lines.get(o.line).is_some_and(|l| in_col(l.column)))?; + let o = *by_anchor.get(&e.after?)?; let follows = match &o.object.position { designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, // Kept within the column, it can stop at the column's edge instead of following. @@ -5709,6 +5715,8 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) }; + // Each wrap's object is looked up once, not for every line. + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); @@ -5734,8 +5742,7 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = ft.columns.get(k as usize).copied().unwrap_or(f.area); let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; - for e in f.exclusions.iter().filter(|e| e.wraps_line(start)) { - let anchor = moves_with_text(e); + for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { if anchor.is_some() && !justify { continue; } From b0f282f607e5cae22116cb85adb0c63bc155a282 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:40:38 -0800 Subject: [PATCH 216/328] Object styles: the dialog changes only the document it opened for New Object Style and Object Style Options record the document they open on, with the epoch that File > Revert changes. OK is refused, and the dialog stays open with the reason, when another document is active, the document was closed, or it was reverted. Apply Style to Selection applies the new style to the objects selected when the dialog opened that still exist, not to a selection made while it was open. --- crates/ui-egui/src/object_style_dialog.rs | 121 +++++++++++++++++++++- 1 file changed, 118 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index bdac19645..4200732a9 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -42,10 +42,26 @@ fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, nex } } +/// The active document as the dialog records it: its uid and the epoch that File › Revert +/// changes. +fn document_key(app: &DesignApp) -> Value { + app.session.active().map_or(Value::Null, |st| json!([st.uid, st.identity_epoch])) +} + +/// The document the dialog was opened on is still the active one and was not reverted since, so +/// OK never gives its settings to another document's style of the same name. +fn same_document(app: &DesignApp, d: &Dialog) -> Result<(), String> { + let key = document_key(app); + if !key.is_null() && d.fields.get("doc") == Some(&key) { Ok(()) } else { Err(format!("the active document changed after {} opened", title(d))) } +} + /// The dialog for a new style from the selected object (its fill, stroke, corners and effects, /// as InDesign's New Object Style), named "Object Style n". pub fn open_new(app: &mut DesignApp) { + let doc = document_key(app); let Some(st) = app.session.active() else { return }; + // Apply Style to Selection applies the style to the objects selected now. + let targets: Vec = st.selection.items.iter().map(|i| i.0).collect(); let it = st.selection.items.first().and_then(|i| st.doc.item(*i)).cloned(); let taken = |n: &str| st.doc.styles.object_style(n).is_some(); let name = (1..).map(|i| format!("Object Style {i}")).find(|n| !taken(n)).unwrap_or_default(); @@ -54,6 +70,8 @@ pub fn open_new(app: &mut DesignApp) { let frame = it.as_ref().and_then(|i| i.text_frame()).map(|t| t.options.clone()); let mut fields = json!({ "new": true, + "doc": doc, + "targets": targets, "name": name, "basedOn": designcraft_doc::NO_OBJECT_STYLE, "fill": it.as_ref().map(|i| i.fill.clone()).unwrap_or_default(), @@ -81,6 +99,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) -> Result<(), String> { } let mut fields = json!({ "new": false, + "doc": document_key(app), "orig": name, "name": name, "basedOn": os.based_on.as_deref().unwrap_or(designcraft_doc::NO_OBJECT_STYLE), @@ -171,6 +190,7 @@ fn general_json(o: &designcraft_doc::TextFrameOptions) -> Value { /// OK: the new style (applied to the selection when asked), or the edited one. pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { + same_document(app, d)?; let name = d.s("name").trim().to_string(); if name.is_empty() { return Err(crate::i18n::tr(&app.ui.language, "Enter a style name.").to_string()); @@ -183,10 +203,21 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; let made = r["name"].as_str().unwrap_or(&name).to_string(); // The style exists now, so OK again mustn't make a second one: a refused apply (locked - // objects) goes to the status line and the dialog closes. + // objects) goes to the status line and the dialog closes. The style goes to the objects + // selected when the dialog opened that still exist, not to a selection made since. + let targets: Vec = app.session.active().map_or_else(Vec::new, |st| { + d.fields + .get("targets") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_u64) + .filter(|id| st.doc.item(designcraft_doc::ItemId(*id)).is_some()) + .collect() + }); if d.b("apply") - && app.session.active().is_some_and(|st| !st.selection.items.is_empty()) - && let Err(e) = app.run("style.object.apply", json!({"name": made})) + && !targets.is_empty() + && let Err(e) = app.run("style.object.apply", json!({"name": made, "ids": targets})) { app.status(e.to_string()); } @@ -771,4 +802,88 @@ mod tests { assert!(e.contains("already named"), "{e}"); assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); } + + /// Object Style Options and New Object Style act only on the document they opened for. With + /// another document active, after their document closed, or after it was reverted, OK keeps + /// the dialog open with the reason and changes no style. + #[test] + fn the_dialog_acts_only_on_the_document_it_opened_for() { + let name = designcraft_doc::BASIC_GRAPHICS_FRAME; + let weights = |app: &DesignApp| -> Vec { + app.session + .documents() + .iter() + .map(|st| st.doc.styles.object_style(name).and_then(|s| s.stroke.as_ref()).map_or(-1.0, |s| s.weight)) + .collect() + }; + let edit = |app: &mut DesignApp| { + open_edit(app, name).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + set(d, &["stroke", "weight"], json!(9.0)); + } + }; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"title": "A"})).unwrap(); + app.run("file.new", json!({"title": "B"})).unwrap(); + app.session.set_active(0); + let before = weights(&app); + assert_eq!(before.len(), 2); + + // Options opened on A, OK with B active: B has a style of the same name. + edit(&mut app); + app.session.set_active(1); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("active document changed"), "{e}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e), "the dialog stays open with the reason"); + assert_eq!(weights(&app), before, "neither document's style changed"); + + // New Object Style opened on A makes nothing in B, and OK works once A is active again. + app.ui.dialog = None; + app.session.set_active(0); + open_new(&mut app); + app.session.set_active(1); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert!(app.session.documents().iter().all(|st| st.doc.styles.object_style("Object Style 1").is_none())); + app.session.set_active(0); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.documents()[0].doc.styles.object_style("Object Style 1").is_some()); + assert!(app.session.documents()[1].doc.styles.object_style("Object Style 1").is_none()); + + // Options opened on A, A closed: B is active and keeps its style. + edit(&mut app); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(weights(&app), vec![before[1]]); + app.ui.dialog = None; + + // Options opened on B, B reverted: the reverted document keeps its style. + #[cfg(not(target_arch = "wasm32"))] + { + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 144, 144], "content": "graphic"})).unwrap(); + edit(&mut app); + app.run("file.revert", json!({})).unwrap(); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(weights(&app), vec![before[1]]); + } + } + + /// Apply Style to Selection applies the new style to the objects selected when the dialog + /// opened, not to a selection made while it was open. + #[test] + fn apply_style_to_selection_uses_the_selection_the_dialog_opened_with() { + let (mut app, a) = app_with_frame(); + let b = app.run("frame.create", json!({"rect": [200, 72, 300, 172], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [a]})).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Picked")); + } + app.run("selection.set", json!({"ids": [b]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + let style = |id: u64| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().object_style.clone(); + assert_eq!(style(a), "Picked"); + assert_ne!(style(b), "Picked"); + } } From 737fcfec043afabaa32a6bc41e1c0f1cfda08f57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:53:54 -0800 Subject: [PATCH 217/328] IDML: an item without corners keeps none over its object style Object styles now export their corners, and an import gives an item without corner attributes the corners of its style chain and of [None]. An item with no corners whose style, a style it is based on, or [None] sets corners now writes None for each corner, so it keeps no corners after export and import. The lookup runs once per style. --- crates/idml/src/export.rs | 3 +++ crates/idml/src/export/item.rs | 36 +++++++++++++++++++++++-- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 717bb5d6c..0c85e8f8a 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -106,6 +106,8 @@ struct Ex<'a> { /// Index topic path → first serialized sort key; See / See also cross-references. index_topics: BTreeMap, String>, index_xrefs: Vec<(Vec, &'static str, String)>, + /// Object style name → whether its chain or `[None]` sets corners, found once per style. + style_corners: HashMap, } impl<'a> Ex<'a> { @@ -121,6 +123,7 @@ impl<'a> Ex<'a> { link_text_sources: Vec::new(), index_topics: BTreeMap::new(), index_xrefs: Vec::new(), + style_corners: HashMap::new(), }; ex.assign_swatch_ids(); for s in d.stories.values() { diff --git a/crates/idml/src/export/item.rs b/crates/idml/src/export/item.rs index 469053c2f..3c240deca 100644 --- a/crates/idml/src/export/item.rs +++ b/crates/idml/src/export/item.rs @@ -87,8 +87,10 @@ impl<'a> Ex<'a> { el.set("GradientStrokeAngle", num(a)); } self.stroke_attrs(&mut el, &it.stroke); - // Corner options: map path-order corners to the named corners by geometry. - if !it.corners.is_none() { + // Corner options: map path-order corners to the named corners by geometry. An item without + // corners whose object style chain sets some writes None, so an import does not give it + // the style's corners. + if !it.corners.is_none() || self.style_sets_corners(os) { let names_by_index = corner_names(&it.path); for (i, c) in it.corners.corners.iter().enumerate() { let n = names_by_index[i]; @@ -153,6 +155,36 @@ impl<'a> Ex<'a> { el } + /// Whether object style `name`, a style it is based on, or `[None]` (which an import reads + /// after every item's style chain) sets corners other than None. A built-in style the + /// document lacks counts as its default. + fn style_sets_corners(&mut self, name: &str) -> bool { + if let Some(&known) = self.style_corners.get(name) { + return known; + } + let defaults = designcraft_doc::Styles::default(); + let style = |n: &str| self.d.styles.object_style(n).or_else(|| defaults.object_style(n)); + let rounds = |os: &designcraft_doc::ObjectStyle| os.corners.is_some_and(|c| !c.is_none()); + let mut seen: Vec<&str> = Vec::new(); + let mut cur = Some(name); + let mut found = false; + while let Some(n) = cur.take() { + if seen.contains(&n) { + break; + } + let Some(os) = style(n) else { break }; + if rounds(os) { + found = true; + break; + } + seen.push(n); + cur = os.based_on.as_deref(); + } + let found = found || style(designcraft_doc::NO_OBJECT_STYLE).is_some_and(rounds); + self.style_corners.insert(name.to_string(), found); + found + } + fn append_transparency(&self, el: &mut El, it: &Item, os: &str) { // Transparency. // An item whose style sets effects writes the effects it has turned off too, so that on diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 4ff0fa6bf..6226d4a74 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -232,6 +232,43 @@ fn exported_frames_keep_their_own_values_over_their_object_style() { assert_eq!(got.options, want); } +/// Items without corners keep none after export and import, though their object style, the style +/// it is based on, or `[None]` (read after every style chain) sets rounded corners. +#[test] +fn exported_frames_keep_no_corners_over_their_object_style() { + let mut d = small_doc(); + let lid = d.default_layer(); + let id = designcraft_doc::ItemId(d.alloc()); + let rect = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 420.0, 200.0, 500.0))); + d.insert_item(SpreadRef::Doc(0), rect, None).unwrap(); + let rounded = Some(designcraft_geom::corners::CornerOptions { + corners: [designcraft_geom::corners::Corner { shape: CornerShape::Rounded, size: 12.0 }; 4], + }); + let styles = std::sync::Arc::make_mut(&mut d.styles); + styles.object.push(designcraft_doc::ObjectStyle { name: "Round".into(), corners: rounded, ..Default::default() }); + styles.object.push(designcraft_doc::ObjectStyle { name: "Child".into(), based_on: Some("Round".into()), ..Default::default() }); + match styles.object.iter_mut().find(|o| o.name == designcraft_doc::NO_OBJECT_STYLE) { + Some(none) => none.corners = rounded, + None => { + styles.object.push(designcraft_doc::ObjectStyle { name: designcraft_doc::NO_OBJECT_STYLE.into(), corners: rounded, ..Default::default() }) + } + } + styles.object.push(designcraft_doc::ObjectStyle { name: "Plain".into(), ..Default::default() }); + let names = ["Round", "Child", designcraft_doc::NO_OBJECT_STYLE, "Plain"]; + let ids: Vec<_> = d.spreads.iter().flat_map(|s| s.items.iter().map(|i| i.id)).take(4).collect(); + assert_eq!(ids.len(), 4); + for (id, style) in ids.iter().zip(names) { + let it = d.item_mut(*id).unwrap(); + it.object_style = style.into(); + assert!(it.corners.is_none()); + } + let back = import_idml(&export_idml(&d)).unwrap(); + for style in names { + let it = back.spreads.iter().flat_map(|s| s.items.iter()).find(|i| i.object_style == style).unwrap(); + assert!(it.corners.is_none(), "{style}: {:?}", it.corners); + } +} + #[test] fn text_wrap_side_and_contour_come_from_the_style_for_frames_and_placed_graphics() { let styles = r#" From f0e63b333dd0ff85f6c498d5fa1c31e127cb223e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:01:16 -0800 Subject: [PATCH 218/328] IDML: a style without a category flag takes it from its based-on style An object style that gives neither EnableStrokeAndCornerOptions nor corners of its own takes the category from the style it is based on, and one without EnableTextFrameGeneralOptions does the same for its text frame options. A style based on [None] still sets neither, and [None] keeps the corners it sets itself. --- crates/idml/src/import/styles.rs | 40 +++++++++++++++++--------- crates/idml/src/tests/object_styles.rs | 37 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index e2e11e979..023ab2d40 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -199,8 +199,9 @@ impl<'r> Importer<'r> { .flatten(); let levels = based_on_levels(e, &objects_by_self); // Text Frame General Options: each attribute from the nearest style whose - // `TextFramePreference` sets it, among the styles that don't turn the category off. - let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") { + // `TextFramePreference` sets it, among the styles that don't turn the category off. A + // style without the category flag takes it from the style it is based on. + let text_frame = if category_on(&levels, "EnableTextFrameGeneralOptions", |_| false) { let prefs: Vec<&El> = levels .iter() .filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false")) @@ -211,7 +212,7 @@ impl<'r> Importer<'r> { None }; let effects = self.style_effects(e); - let corners = style_corners(e, &levels); + let corners = style_corners(&levels); let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, apply_next_style, text_frame, effects, corners }; match self.styles.object.iter_mut().find(|o| o.name == name) { @@ -412,21 +413,34 @@ impl<'r> Importer<'r> { } } -/// Object style `e`'s corner options (Stroke & Corner Options), by name, when it sets them. A style -/// that sets some corners, or turns the category on, takes the others from the styles in `levels` -/// (`e` and the styles it is based on) that don't turn the category off. -fn style_corners(e: &El, levels: &[&El]) -> Option { - match e.get("EnableStrokeAndCornerOptions") { - Some("false") => return None, - Some("true") => {} - _ => { - corners(e, "")?; - } +/// The corner options (Stroke & Corner Options) of the object style that starts `levels` (the +/// style, then the styles it is based on), by name, when it sets them. A style that sets some +/// corners, or turns the category on (itself or through the style it is based on), takes the +/// others from the styles in `levels` that don't turn the category off. +fn style_corners(levels: &[&El]) -> Option { + if !category_on(levels, "EnableStrokeAndCornerOptions", |l| corners(l, "").is_some()) { + return None; } let on: Vec<&El> = levels.iter().copied().filter(|l| l.get("EnableStrokeAndCornerOptions") != Some("false")).collect(); corners_in(&on, "").map(|c| CornerOptions { corners: c }) } +/// Whether the style chain `levels` (a style, then the styles it is based on) turns the category +/// whose flag is `flag` on. The nearest style that gives the flag decides; a style without it +/// turns the category on when `own` finds settings of its own. A `[None]` after the first style +/// ends the chain, as a `BasedOn` of `[None]` names no style. +fn category_on(levels: &[&El], flag: &str, own: impl Fn(&El) -> bool) -> bool { + let none = |l: &&El| l.get("Self") == Some("ObjectStyle/$ID/[None]"); + for l in levels.iter().take(1).chain(levels.iter().skip(1).take_while(|l| !none(l))) { + match l.get(flag) { + Some(v) => return v == "true", + None if own(l) => return true, + None => {} + } + } + false +} + /// Object style `e`, then the styles it is based on, nearest first (cycle-safe, at most 16). A /// `BasedOn` may name a style by its `Self` id or by its bare name. fn based_on_levels<'e>(e: &'e El, objects_by_self: &HashMap<&str, &'e El>) -> Vec<&'e El> { diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 6226d4a74..52cfd3e20 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -363,6 +363,43 @@ fn a_style_turning_corners_on_inherits_all_four() { assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); } +/// A style with no Stroke & Corner Options or Text Frame General Options flag and no settings of +/// its own takes each category from the style it is based on: on, off, or (for a style based on +/// `[None]`) not set. +#[test] +fn a_style_without_category_flags_takes_them_from_its_based_on_style() { + let styles = r#" + $ID/[None] + + + + ObjectStyle/Round + + + + ObjectStyle/Round + + + ObjectStyle/Framed + + + ObjectStyle/Off + + + $ID/[None] + "#; + let d = fixture(&format!("{ROUND}{styles}"), &[]); + let style = |n: &str| d.styles.object_style(n).cloned().unwrap(); + let c = style("RoundKid").corners.expect("RoundKid inherits Round's corners").corners; + assert_eq!((c.map(|c| c.shape), c.map(|c| c.size)), ([CornerShape::Rounded; 4], [17.0; 4])); + assert_eq!(style("FramedKid").text_frame.map(|t| t.columns), Some(3), "FramedKid inherits Framed's text frame options"); + for n in ["OffKid", "Bare"] { + assert!(style(n).corners.is_none() && style(n).text_frame.is_none(), "{n}: {:?}", style(n)); + } + assert!(style(designcraft_doc::NO_OBJECT_STYLE).corners.is_some(), "[None] keeps the corners it sets itself"); +} + /// An object style giving its corners only with the legacy all-corners `CornerOption` and /// `CornerRadius` keeps them, so applying it to another frame rounds it. #[test] From d3a073470cef09eb58856ca442b83a79cf87db10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:18:07 -0800 Subject: [PATCH 219/328] Images: decode JPEG screen proxies at a reduced size A placed JPEG drawn at a fraction of its pixel size was decoded at full size first and then halved down to the level the screen needs. For a 24 MP photo that is a 96 MB decode per image, and with several such images on a page the decoded pixels outgrow the image cache. A YCbCr or grayscale JPEG whose wanted level is a half, a quarter or an eighth of its size (or smaller) is now decoded at that size straight from its compressed blocks with jpeg-decoder's scaled IDCT, cut to the size the halving path gives the same level, and halved from there for smaller levels. The embedded ICC profile is applied as in a full decode. CMYK and YCCK JPEGs, other formats and the full size still decode in full. --- Cargo.lock | 7 ++ ROADMAP.md | 1 + crates/images/Cargo.toml | 2 + crates/images/src/colour/tests.rs | 22 ++++++ crates/images/src/jpeg.rs | 38 +++++++++ crates/images/src/lib.rs | 18 +++++ crates/images/src/tests.rs | 50 ++++++++++++ crates/render/src/decode.rs | 12 ++- crates/render/src/images.rs | 125 ++++++++++++++++++++++++++++++ 9 files changed, 274 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 9760f61ff..4c4887099 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1504,6 +1504,7 @@ dependencies = [ "designcraft-fonts", "flate2", "image", + "jpeg-decoder", "log", "quick-xml 0.41.0", "resvg", @@ -3305,6 +3306,12 @@ dependencies = [ "libc", ] +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" + [[package]] name = "js-sys" version = "0.3.106" diff --git a/ROADMAP.md b/ROADMAP.md index 402c81438..559fed4e1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/images/Cargo.toml b/crates/images/Cargo.toml index 685c7d947..658047784 100644 --- a/crates/images/Cargo.toml +++ b/crates/images/Cargo.toml @@ -21,6 +21,8 @@ log = { workspace = true } craft-cms = { workspace = true } zune-core = { version = "0.5", default-features = false } zune-jpeg = "0.5" +# Reduced-size JPEG decoding (1/2, 1/4, 1/8 through the DCT) for screen proxies. +jpeg-decoder = { version = "0.3", default-features = false } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/images/src/colour/tests.rs b/crates/images/src/colour/tests.rs index ca1607965..28bd99c99 100644 --- a/crates/images/src/colour/tests.rs +++ b/crates/images/src/colour/tests.rs @@ -241,3 +241,25 @@ fn unusable_profiles_leave_the_pixels_alone() { let png = png_with_icc(1, 1, &px, Some(vec![0xAB; 300])); assert_eq!(decode_rgba(&png).unwrap().as_raw(), &px); } + +#[test] +fn reduced_jpegs_get_the_colour_handling_of_full_decodes() { + // An Adobe RGB JPEG: the reduced decode applies the profile as the full decode does. + let img = image::RgbImage::from_pixel(64, 48, image::Rgb([64, 192, 64])); + let mut jpeg = Vec::new(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 95); + enc.set_icc_profile(adobe_rgb_icc()).unwrap(); + enc.write_image(img.as_raw(), 64, 48, image::ExtendedColorType::Rgb8).unwrap(); + let full = decode_rgba(&jpeg).unwrap().get_pixel(3, 3).0; + let reduced = crate::decode_rgba_reduced(&jpeg, 3).unwrap(); + assert_eq!(reduced.dimensions(), (8, 6)); + let p = reduced.get_pixel(1, 1).0; + for c in 0..4 { + assert!(p[c].abs_diff(full[c]) <= 2, "{p:?} vs {full:?}"); + } + let want = adobe_to_srgb([64, 192, 64]); + assert!((f32::from(p[0]) - want[0]).abs() <= 3.0, "{p:?} vs {want:?}"); + // CMYK and YCCK JPEGs stay with the full decode, which converts their inks. + assert!(crate::decode_rgba_reduced(&solid_jpeg([0, 255, 255, 255], Some(0)), 1).is_none()); + assert!(crate::decode_rgba_reduced(&solid_jpeg([76, 85, 255, 255], Some(2)), 1).is_none()); +} diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 8b44d0c9a..fea0a1e64 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -62,6 +62,44 @@ pub(crate) fn decode_cmyk(bytes: &[u8]) -> Option<(CmykRaster, Option>)> Some((raster, icc)) } +/// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. +pub(crate) const MAX_SHRINK: u8 = 3; + +/// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for +/// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, +/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. +pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaImage, bool)> { + use jpeg_decoder::PixelFormat; + if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { + return None; + } + let mut d = jpeg_decoder::Decoder::new(bytes); + d.set_max_decoding_buffer_size(MAX_BYTES); + d.read_info().ok()?; + let info = d.info()?; + let colour = match info.pixel_format { + PixelFormat::RGB24 => true, + PixelFormat::L8 => false, + PixelFormat::L16 | PixelFormat::CMYK32 => return None, + }; + let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); + let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; + let px = d.decode().ok()?; + let pixels = usize::from(w).checked_mul(usize::from(h))?; + let rgba: Vec = if colour { + if px.len() != pixels.checked_mul(3)? { + return None; + } + px.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect() + } else { + if px.len() != pixels { + return None; + } + px.iter().flat_map(|&v| [v, v, v, 255]).collect() + }; + Some((image::RgbaImage::from_raw(u32::from(w), u32::from(h), rgba)?, colour)) +} + /// Whether an APP14 "Adobe" segment comes before the image data. fn adobe_marker(bytes: &[u8]) -> bool { let mut i = 2; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 081af6c2b..530ca8097 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -442,6 +442,24 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// The largest `shrink` [`decode_rgba_reduced`] takes: 3, an eighth of each side. +pub const MAX_REDUCED_SHRINK: u8 = jpeg::MAX_SHRINK; + +/// [`decode_rgba`] of a JPEG at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each +/// side rounded up), read from its compressed blocks without a full-size decode. The embedded ICC +/// profile is applied as [`decode_rgba`] applies it. `None` where only a full decode applies: other +/// formats, CMYK, 12-bit and lossless JPEGs, and files [`decode_rgba`] refuses as too large. +pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option { + use colour::{DisplayColour, Pixels, to_display_rgba}; + if too_large_to_decode(bytes) { + return None; + } + let (rgba, has_colour) = jpeg::decode_reduced(bytes, shrink)?; + let Some(icc) = embedded_icc(bytes) else { return Some(rgba) }; + let px = if has_colour { Pixels::Rgb(rgba) } else { Pixels::Gray(rgba) }; + to_display_rgba(px, Some(&icc), &DisplayColour::active()) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index cd577f09a..ae5435a62 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -561,3 +561,53 @@ fn a_webp_icc_chunk_that_declares_more_than_it_holds_is_refused_before_decoding( assert!(webp_icc_is_sane(b"\x89PNG not a webp")); assert!(webp_icc_is_sane(&webp_with(&[(b"VP8L", 6, &[0; 6])]))); } + +/// A JPEG of a smooth gradient, `w` × `h`. +fn gradient_jpeg(w: u32, h: u32, gray: bool) -> Vec { + let rgb = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 255 / w) as u8, (y * 255 / h) as u8, 128])); + let img = if gray { image::DynamicImage::ImageRgb8(rgb).into_luma8().into() } else { image::DynamicImage::ImageRgb8(rgb) }; + let mut out = Vec::new(); + img.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)).unwrap(); + out +} + +#[test] +fn reduced_jpegs_decode_at_a_half_quarter_or_eighth_rounded_up() { + let jpeg = gradient_jpeg(1001, 77, false); + let full = decode_rgba(&jpeg).unwrap(); + for (shrink, size) in [(1, (501, 39)), (2, (251, 20)), (3, (126, 10))] { + let img = decode_rgba_reduced(&jpeg, shrink).unwrap(); + assert_eq!(img.dimensions(), size, "shrink {shrink}"); + // The same picture as the full decode sampled at the block centres, give or take rounding. + let step = 1u32 << shrink; + let (mut total, mut n) = (0u64, 0u64); + for y in 0..size.1 - 1 { + for x in 0..size.0 - 1 { + let (p, q) = (img.get_pixel(x, y).0, full.get_pixel(x * step + step / 2, y * step + step / 2).0); + total += (0..3).map(|c| u64::from(p[c].abs_diff(q[c]))).sum::(); + n += 3; + assert_eq!(p[3], 255); + } + } + assert!(total / n <= 3, "shrink {shrink}: mean difference {}", total / n); + } + // Only 1/2, 1/4 and 1/8 are read from the blocks. + assert!(decode_rgba_reduced(&jpeg, 0).is_none()); + assert!(decode_rgba_reduced(&jpeg, 4).is_none()); +} + +#[test] +fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { + let gray = decode_rgba_reduced(&gradient_jpeg(64, 64, true), 2).unwrap(); + assert_eq!(gray.dimensions(), (16, 16)); + assert!(gray.pixels().all(|p| p[0] == p[1] && p[1] == p[2] && p[3] == 255)); + let png = png_from_rgba(16, 16, vec![255; 16 * 16 * 4]).unwrap(); + assert!(decode_rgba_reduced(&png, 1).is_none()); + assert!(decode_rgba_reduced(&[0xFF, 0xD8], 1).is_none()); + let jpeg = gradient_jpeg(200, 150, false); + for n in (0..jpeg.len()).step_by(37) { + if let Some(img) = decode_rgba_reduced(&jpeg[..n], 1) { + assert_eq!(img.dimensions(), (100, 75)); + } + } +} diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..8c703701e 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -19,7 +19,17 @@ pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } - let img = designcraft_images::decode_rgba(bytes)?; + premultiplied(&designcraft_images::decode_rgba(bytes)?) +} + +/// [`decode_pixmap`] of a JPEG at 1/2^`shrink` of its size, `shrink` 1 to +/// [`designcraft_images::MAX_REDUCED_SHRINK`], without a full-size decode. `None` where only a +/// full decode applies (other formats, CMYK JPEGs). +pub(crate) fn decode_pixmap_reduced(bytes: &[u8], shrink: u8) -> Option { + premultiplied(&designcraft_images::decode_rgba_reduced(bytes, shrink)?) +} + +fn premultiplied(img: &image::RgbaImage) -> Option { let (w, h) = img.dimensions(); if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 { return None; diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 37606097d..69691135e 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -10,6 +10,7 @@ use std::sync::{Arc, Mutex}; use vello_cpu::Pixmap; +use crate::decode::decode_pixmap_reduced; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -130,6 +131,11 @@ pub fn decoded(bytes: &Arc>, page: u32) -> Option> { /// The mip level of `bytes` closest above `on_screen` device pixels per point for a graphic /// `width_pt` points wide. pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if lookup((Arc::as_ptr(bytes) as usize, page, 0)).is_none() + && let Some(pm) = reduced(bytes, page, width_pt, on_screen) + { + return Some(pm); + } let full = decoded(bytes, page)?; let ppt = full.width() as f64 / width_pt.max(1e-6); let id = Arc::as_ptr(bytes) as usize; @@ -149,6 +155,71 @@ pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Op Some(pm) } +/// [`mip`]'s level for a JPEG, decoded at 1/2, 1/4 or 1/8 of its size straight from its blocks +/// and halved from there, so a screen-sized level needs no full-size decode. `None` when the +/// full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). +fn reduced(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let id = Arc::as_ptr(bytes) as usize; + if with(|c| c.bad.contains_key(&(id, page))) { + return None; + } + // The level `mip` picks from a full decode, with each level's size as `halve` gives it. + let (mut w, mut h) = crate::image_size(bytes)?; + let ppt = w as f64 / width_pt.max(1e-6); + let mut sizes = vec![(w, h)]; + while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { + (w, h) = ((w / 2).max(1), (h / 2).max(1)); + sizes.push((w, h)); + } + let level = u8::try_from(sizes.len() - 1).ok()?; + if level == 0 { + return None; + } + if let Some(pm) = lookup((id, page, level)) { + return Some(pm); + } + let shrink = level.min(designcraft_images::MAX_REDUCED_SHRINK); + let mut pm = match lookup((id, page, shrink)) { + Some(p) => p, + None => { + // Cut to `halve`'s size (it rounds down, the decoder up), as the level a full + // decode makes. + let (sw, sh) = sizes[usize::from(shrink)]; + let p = Arc::new(crop(decode_pixmap_reduced(bytes, shrink)?, sw, sh)?); + store(bytes, page, shrink, p.clone()); + p + } + }; + for l in shrink + 1..=level { + pm = match lookup((id, page, l)) { + Some(p) => p, + None => { + let half = Arc::new(halve(&pm)); + store(bytes, page, l, half.clone()); + half + } + }; + } + Some(pm) +} + +/// The top-left `w` × `h` of `pm`; `None` when `pm` is smaller. +fn crop(pm: Pixmap, w: u32, h: u32) -> Option { + let (pw, ph) = (u32::from(pm.width()), u32::from(pm.height())); + if (pw, ph) == (w, h) { + return Some(pm); + } + if w > pw || h > ph || w == 0 || h == 0 { + return None; + } + let (pw, w, h) = (pw as usize, w as usize, h as usize); + let data: Vec<_> = pm.data().chunks_exact(pw).take(h).flat_map(|row| &row[..w]).copied().collect(); + Some(Pixmap::from_parts(data, u16::try_from(w).ok()?, u16::try_from(h).ok()?)) +} + /// Drop every decoded image. pub fn clear() { with(|c| { @@ -176,4 +247,58 @@ mod tests { let last = &buffers[MAX_BAD + 9]; assert!(c.bad.contains_key(&(Arc::as_ptr(last) as usize, 0))); } + + fn jpeg(w: u32, h: u32) -> Arc> { + let img = image::RgbImage::from_fn(w, h, |x, y| image::Rgb([(x * 255 / w) as u8, (y * 255 / h) as u8, 128])); + let mut out = Vec::new(); + img.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)).unwrap(); + Arc::new(out) + } + + #[test] + fn screen_levels_of_a_jpeg_need_no_full_size_decode() { + let bytes = jpeg(1024, 768); + let id = Arc::as_ptr(&bytes) as usize; + // 1 px per point drawn at 0.1: level 3, an eighth, read straight from the blocks. + let pm = mip(&bytes, 0, 1024.0, 0.1).unwrap(); + assert_eq!((pm.width(), pm.height()), (128, 96)); + assert!(lookup((id, 0, 0)).is_none(), "no full-size decode is kept"); + // Close to the full decode halved three times. + let mut want = decode_pixmap_page(&bytes, 0).unwrap(); + for _ in 0..3 { + want = halve(&want); + } + let diff: u64 = pm.data().iter().zip(want.data()).map(|(p, q)| u64::from(p.r.abs_diff(q.r)) + u64::from(p.g.abs_diff(q.g))).sum(); + assert!(diff / (2 * 128 * 96) <= 3, "mean difference {}", diff / (2 * 128 * 96)); + // Smaller levels are halved from that eighth, down to 64 px as before. + let small = mip(&bytes, 0, 1024.0, 0.02).unwrap(); + assert_eq!((small.width(), small.height()), (64, 48)); + assert!(lookup((id, 0, 0)).is_none(), "no full-size decode is kept"); + // The full size is still a full decode. + let full = mip(&bytes, 0, 1024.0, 1.0).unwrap(); + assert_eq!((full.width(), full.height()), (1024, 768)); + } + + #[test] + fn reduced_levels_of_odd_sized_jpegs_have_the_halved_size() { + let bytes = jpeg(1001, 771); + let mut want = decode_pixmap_page(&bytes, 0).unwrap(); + for _ in 0..3 { + want = halve(&want); + } + let pm = mip(&bytes, 0, 1001.0, 0.1).unwrap(); + assert!(lookup((Arc::as_ptr(&bytes) as usize, 0, 0)).is_none()); + assert_eq!((pm.width(), pm.height()), (want.width(), want.height())); + assert_eq!((pm.width(), pm.height()), (125, 96)); + } + + #[test] + fn a_jpeg_that_does_not_decode_is_remembered_as_failed() { + let mut broken = jpeg(256, 256).to_vec(); + broken.truncate(40); + let bytes = Arc::new(broken); + assert!(mip(&bytes, 0, 256.0, 0.1).is_none()); + assert!(with(|c| c.bad.contains_key(&(Arc::as_ptr(&bytes) as usize, 0)))); + assert!(mip(&bytes, 0, 256.0, 0.1).is_none()); + } } From 4e363e1bfacc4a2c3b36f4b7f5c56afcef94833c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:29:50 -0800 Subject: [PATCH 220/328] Render: placed images are premultiplied in their decoded buffer Decoding a placed raster built a second full-size pixel vector from the RGBA image and premultiplied every pixel into it. The pixels are now premultiplied in place, opaque pixels are skipped, and the buffer becomes the pixmap's pixels without a copy (bytemuck's cast_vec, with a copy when the capacity is not a whole number of pixels). The rendered SVG path reuses its buffer the same way. For a 6000 x 4000 opaque image the step takes 7 ms instead of 120 ms, with identical pixels. --- Cargo.lock | 1 + Cargo.toml | 2 ++ ROADMAP.md | 1 + crates/render/Cargo.toml | 1 + crates/render/src/decode.rs | 38 ++++++++++++++++++++++++++----------- crates/render/src/tests.rs | 30 +++++++++++++++++++++++++++++ 6 files changed, 62 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9760f61ff..09e504a80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1574,6 +1574,7 @@ dependencies = [ name = "designcraft-render" version = "0.20.1" dependencies = [ + "bytemuck", "craft-pdf", "designcraft-color", "designcraft-compose", diff --git a/Cargo.toml b/Cargo.toml index dcf2c7235..d90986f91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,8 @@ skrifa = "0.47" harfrust = "0.13" vello_cpu = "0.2" vello_common = { version = "0.2", default-features = false } +# Decoded image buffers become pixmap pixels without a copy; the version vello_common uses. +bytemuck = { version = "1.25", features = ["extern_crate_alloc"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] } # CMYK TIFF samples for PDF export (`image` decodes them to RGB); the version `image` uses. tiff = "0.11" diff --git a/ROADMAP.md b/ROADMAP.md index 402c81438..f7f8aff00 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 8cd446af1..ac5d8a0f1 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -16,6 +16,7 @@ designcraft-fonts = { workspace = true } designcraft-compose = { workspace = true } vello_cpu = { workspace = true } vello_common = { workspace = true } +bytemuck = { workspace = true } image = { workspace = true } craft-pdf = { workspace = true, features = ["raster"] } designcraft-images = { workspace = true } diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..d720362c7 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -16,23 +16,39 @@ pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { } if designcraft_images::is_svg(bytes) { let (px, w, h) = designcraft_images::render_svg(bytes, 3000)?; - let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); - return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); + return Some(Pixmap::from_parts(premul_pixels(px), w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } let img = designcraft_images::decode_rgba(bytes)?; let (w, h) = img.dimensions(); if w == 0 || h == 0 || w > u16::MAX as u32 || h > u16::MAX as u32 { return None; } - let data: Vec = img - .pixels() - .map(|p| { - let a = p[3] as u16; - let m = |c: u8| ((c as u16 * a + 127) / 255) as u8; - vello_cpu::color::PremulRgba8 { r: m(p[0]), g: m(p[1]), b: m(p[2]), a: p[3] } - }) - .collect(); - Some(Pixmap::from_parts(data, w as u16, h as u16)) + let mut px = img.into_raw(); + px.truncate(w as usize * h as usize * 4); + Some(Pixmap::from_parts(premultiply(px), w as u16, h as u16)) +} + +/// Premultiply straight-alpha RGBA bytes in place and return them as pixmap pixels. Opaque pixels +/// are left as they are. +pub(crate) fn premultiply(mut px: Vec) -> Vec { + for p in px.as_chunks_mut::<4>().0 { + let a = p[3]; + if a != 255 { + let m = |c: u8| ((c as u16 * a as u16 + 127) / 255) as u8; + p[0] = m(p[0]); + p[1] = m(p[1]); + p[2] = m(p[2]); + } + } + premul_pixels(px) +} + +/// Premultiplied RGBA bytes as pixmap pixels, in the same allocation when its capacity is a whole +/// number of pixels and in a copy otherwise. +fn premul_pixels(px: Vec) -> Vec { + bytemuck::allocation::try_cast_vec(px).unwrap_or_else(|(_, px)| { + px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect() + }) } /// Box-filter downsample by 2. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9e3d74e8b..8309667b2 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -30,6 +30,36 @@ fn eps_source_decodes_like_its_preview() { assert!(image_size(corrupt).is_none()); } +#[test] +fn decoded_images_are_premultiplied_for_every_alpha() { + // Column x holds colour value x, row y holds alpha y. + let img = image::RgbaImage::from_fn(256, 256, |x, y| image::Rgba([x as u8, 255 - x as u8, (x / 2) as u8, y as u8])); + let mut png = Vec::new(); + image::DynamicImage::ImageRgba8(img.clone()).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pm = decode_pixmap(&png).unwrap(); + assert_eq!((pm.width(), pm.height()), (256, 256)); + for (p, q) in img.pixels().zip(pm.data()) { + let m = |c: u8| ((c as u16 * p[3] as u16 + 127) / 255) as u8; + assert_eq!([q.r, q.g, q.b, q.a], [m(p[0]), m(p[1]), m(p[2]), p[3]], "{p:?}"); + } +} + +#[test] +fn premultiplied_pixels_reuse_the_decoded_buffer() { + use vello_cpu::color::PremulRgba8; + let expected = + [PremulRgba8 { r: 10, g: 20, b: 30, a: 255 }, PremulRgba8 { r: 100, g: 50, b: 25, a: 128 }, PremulRgba8 { r: 0, g: 0, b: 0, a: 0 }]; + let px = vec![10, 20, 30, 255, 200, 100, 50, 128, 1, 2, 3, 0]; + let ptr = px.as_ptr() as usize; + let out = decode::premultiply(px); + assert_eq!(out.as_ptr() as usize, ptr); + assert_eq!(out, expected); + // A capacity that is not a whole number of pixels is copied. + let mut px = Vec::with_capacity(13); + px.extend([10, 20, 30, 255, 200, 100, 50, 128, 1, 2, 3, 0]); + assert_eq!(decode::premultiply(px), expected); +} + #[test] fn footnote_vector_objects_are_painted() { use designcraft_doc::{AnchorPosition, AnchoredObject, ItemId, Shape, SpreadRef}; From 855d017d5b56b61bdf5a46c974a280f0eace7398 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:34:02 -0800 Subject: [PATCH 221/328] Images: limit reduced JPEG decodes by the full image size A reduced decode now applies the full decode's size limits before it reads any image data: - A file whose size pixel_size cannot read is refused, so the 256 Mpx check always has a size to compare. The JPEG decoder's own reading of the frame size is checked against the same limit. - A progressive JPEG keeps the coefficients of the full-size image until its last scan, whatever the output size. When those take more than 512 MiB (each component counted at full size, each side rounded up to 32 pixels), the reduced decode is refused and the full decode, with its own limits, applies. --- crates/images/src/jpeg.rs | 21 ++++++++++++-- crates/images/src/lib.rs | 12 ++++++-- crates/images/src/tests.rs | 58 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index fea0a1e64..6188a53fc 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,21 +67,38 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for /// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, -/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. +/// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. `None` as well for a +/// JPEG whose full size is over the full decode's limit, and for a progressive JPEG whose +/// full-size coefficients take more than [`MAX_BYTES`]; the full decode applies its own limits to +/// those. pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaImage, bool)> { - use jpeg_decoder::PixelFormat; + use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; } let mut d = jpeg_decoder::Decoder::new(bytes); + // This limits the output only, which is the reduced size. d.set_max_decoding_buffer_size(MAX_BYTES); d.read_info().ok()?; let info = d.info()?; + if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { + return None; + } let colour = match info.pixel_format { PixelFormat::RGB24 => true, PixelFormat::L8 => false, PixelFormat::L16 | PixelFormat::CMYK32 => return None, }; + if info.coding_process == CodingProcess::DctProgressive { + // A progressive JPEG holds every coefficient of the full-size image (two bytes each) until + // its last scan, whatever the output size. Each component is counted at the full size and + // each side is rounded up to the largest MCU (32 pixels): an upper bound. + let side = |n: u16| u64::from(n).next_multiple_of(32); + let components: u64 = if colour { 3 } else { 1 }; + if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + return None; + } + } let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; let px = d.decode().ok()?; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 530ca8097..5754e8788 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -407,7 +407,12 @@ const MAX_RGBA_BYTES: u64 = 1 << 30; /// Whether a raster's header gives it more pixels than [`decode_rgba`] decodes. pub fn too_large_to_decode(bytes: &[u8]) -> bool { // `image` limits only its own output, which can be a quarter of the RGBA copy or less. - pixel_size(bytes).is_some_and(|(w, h)| u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES) + pixel_size(bytes).is_some_and(|(w, h)| over_rgba_budget(w, h)) +} + +/// Whether a `w` × `h` raster takes more than [`MAX_RGBA_BYTES`] as RGBA. +fn over_rgba_budget(w: u32, h: u32) -> bool { + u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4) > MAX_RGBA_BYTES } /// Straight (non-premultiplied) RGBA8 of a raster in display sRGB: an embedded ICC profile is @@ -448,9 +453,12 @@ pub const MAX_REDUCED_SHRINK: u8 = jpeg::MAX_SHRINK; /// [`decode_rgba`] of a JPEG at 1/2^`shrink` of its size (`shrink` 1 to [`MAX_REDUCED_SHRINK`], each /// side rounded up), read from its compressed blocks without a full-size decode. The embedded ICC /// profile is applied as [`decode_rgba`] applies it. `None` where only a full decode applies: other -/// formats, CMYK, 12-bit and lossless JPEGs, and files [`decode_rgba`] refuses as too large. +/// formats, CMYK, 12-bit and lossless JPEGs, files whose size [`pixel_size`] cannot read, and files +/// [`decode_rgba`] refuses as too large. pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option { use colour::{DisplayColour, Pixels, to_display_rgba}; + // The size check must have a size to check: a header only the JPEG decoder reads is refused. + pixel_size(bytes)?; if too_large_to_decode(bytes) { return None; } diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index ae5435a62..184e3c9c9 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -611,3 +611,61 @@ fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { } } } + +#[test] +fn reduced_decoding_refuses_a_jpeg_whose_size_the_size_check_cannot_read() { + let jpeg = gradient_jpeg(64, 48, false); + assert_eq!(decode_rgba_reduced(&jpeg, 1).unwrap().dimensions(), (32, 24)); + // A stray byte after the start marker: the JPEG decoder skips it, but `pixel_size` doesn't + // recognize the file, so `too_large_to_decode` has no size to check. + let mut stray = jpeg.clone(); + stray.insert(2, 0); + assert_eq!(pixel_size(&stray), None); + assert!(decode_rgba_reduced(&stray, 1).is_none()); + assert!(decode_rgba(&stray).is_none()); +} + +/// A progressive JPEG with only its DC scan, `w` × `h` with `components` 1×1-sampled components: +/// every coefficient is zero (a flat mid-gray image). +fn progressive_jpeg(w: u16, h: u16, components: u8) -> Vec { + let mut out = vec![0xFF, 0xD8]; + // One quantization table of ones. + out.extend([0xFF, 0xDB, 0, 67, 0]); + out.extend([1; 64]); + // Start of frame, progressive DCT. + out.extend([0xFF, 0xC2, 0, 8 + 3 * components, 8]); + out.extend(h.to_be_bytes()); + out.extend(w.to_be_bytes()); + out.push(components); + for id in 1..=components { + out.extend([id, 0x11, 0]); + } + // A DC table with one code, "0", for a difference of 0. + out.extend([0xFF, 0xC4, 0, 20, 0x00, 1]); + out.extend([0; 15]); + out.push(0); + // The DC scan of every component (Ss, Se, Ah/Al all 0), then zero bits. + out.extend([0xFF, 0xDA, 0, 6 + 2 * components, components]); + for id in 1..=components { + out.extend([id, 0x00]); + } + out.extend([0, 0, 0]); + out.extend([0; 16]); + out.extend([0xFF, 0xD9]); + out +} + +#[test] +fn reduced_decoding_refuses_progressive_jpegs_whose_full_size_coefficients_are_over_the_limit() { + let small = decode_rgba_reduced(&progressive_jpeg(64, 48, 3), 3).unwrap(); + assert_eq!(small.dimensions(), (8, 6)); + // 10,240 × 8,800 is within the RGBA limit, but its three components' coefficients take + // 10,240 × 8,800 × 3 × 2 bytes, over 512 MiB, whatever the output size. + let large = progressive_jpeg(10_240, 8_800, 3); + assert_eq!(pixel_size(&large), Some((10_240, 8_800))); + assert!(!too_large_to_decode(&large)); + assert!(decode_rgba_reduced(&large, 3).is_none()); + // One component of the same size stays under the limit. + let gray = decode_rgba_reduced(&progressive_jpeg(10_240, 8_800, 1), 3).unwrap(); + assert_eq!(gray.dimensions(), (1_280, 1_100)); +} From b5fad8e858447d8251ce90962cc8c0840547d4a7 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 12 Nov 2026 19:45:08 +0100 Subject: [PATCH 222/328] Use mutable subpath iteration for current Clippy --- crates/engine/src/cmd/paths.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 946da4215..6a2dca01c 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -92,8 +92,8 @@ fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> let boxes: Vec<_> = beziers.iter().map(BezPath::bounding_box).collect(); let n = path.subpaths.len(); let mut tests = 0usize; - for i in 0..n { - let Some(p) = path.subpaths[i].anchors.first().map(|a| a.p) else { continue }; + for (i, sp) in path.subpaths.iter_mut().enumerate() { + let Some(p) = sp.anchors.first().map(|a| a.p) else { continue }; let mut depth = 0; for j in (0..n).filter(|&j| j != i && boxes[j].inflate(1e-6, 1e-6).contains(p)) { tests += 1; @@ -102,7 +102,6 @@ fn orient_holes_within(path: &mut PathData, command: &str, max_tests: usize) -> } depth += usize::from(designcraft_geom::hit::fill_contains(&beziers[j], designcraft_geom::FillRule::NonZero, p)); } - let sp = &mut path.subpaths[i]; let cw = sp.area() > 0.0; if cw == (depth % 2 == 1) { sp.reverse(); From fe631061dba453dfd5ad500da01d8fd55c087364 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 12 Nov 2026 19:49:14 +0100 Subject: [PATCH 223/328] Use mutable row iteration in render fixture --- crates/render/src/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 9e3d74e8b..3287ab836 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -529,9 +529,9 @@ fn degenerate_dash_patterns_draw_solid_and_fill_types_close_table_corners() { let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap(); d.item_mut(fid).unwrap().stroke = designcraft_doc::Stroke { weight: 2.0, kind: fine.clone(), ..Default::default() }; let mut t = designcraft_doc::Table::new(1, 2, 2, 0, 0, 200.0); - for r in 0..2 { - t.rows[r].height = 60.0; - t.rows[r].mode = designcraft_doc::RowHeightMode::Exactly; + for row in t.rows.iter_mut().take(2) { + row.height = 60.0; + row.mode = designcraft_doc::RowHeightMode::Exactly; } let stroke = |kind| designcraft_doc::CellStroke { weight: 8.0, kind, gap_color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() }; for cell in &mut t.cells { From 75d1119def2c22979c4113cbbc99cb3cd02f8a99 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 10:59:49 -0800 Subject: [PATCH 224/328] Text: Text Frame Options previews go from their document, and Undo refuses stored frames A preview remembers the document it is shown in. When OK is refused or Cancel is chosen after another document became active, that document goes back as it was instead of keeping the previewed options. The frames taken from the caret or selected text are also refused once the document has changed after the dialog opened. Undo puts back the document's id counter, so a frame made after Undo can take a stored id. --- crates/ui-egui/src/dialogs.rs | 116 +++++++++++++++++++++++++++++----- 1 file changed, 101 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 927ed1968..ab53948f9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -589,6 +589,68 @@ mod color_theme_tests { assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); } + /// A preview shown in one document goes when OK is refused, or Cancel is chosen, after another + /// document became active. + #[test] + fn text_frame_options_preview_goes_from_its_document_after_another_becomes_active() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let make = |app: &mut crate::DesignApp| { + app.run("file.new", json!({})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap(); + app.run("text.select", json!({"story": r["story"], "anchor": 2})).unwrap(); + designcraft_doc::ItemId(r["id"].as_u64().unwrap()) + }; + let a = make(&mut app); + let first = |app: &DesignApp| { + let st = &app.session.documents()[0]; + (st.doc.item(a).unwrap().text_frame().unwrap().options.columns, st.interaction.is_some()) + }; + let preview = |app: &mut DesignApp| { + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(app, &mut d); + d.fields.insert("columns".into(), json!("3")); + d.fields.insert("preview".into(), json!(true)); + text_frame_preview(app, &mut d); + assert_eq!(first(app), (3, true), "previewed in the first document"); + d + }; + let d = preview(&mut app); + make(&mut app); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("no longer the active one"), "{err}"); + assert_eq!(first(&app), (1, false), "OK refused: the first document is as it was"); + app.ui.dialog = None; + app.session.set_active(0); + let d = preview(&mut app); + app.session.set_active(1); + app.ui.dialog = Some(d); + cancel(&mut app); + assert_eq!(first(&app), (1, false), "Cancel: the first document is as it was"); + } + + /// Undo puts back the document's id counter, so a frame made after Undo can take the id of a + /// frame the dialog stored; OK is refused instead of changing the new frame. + #[test] + fn text_frame_options_from_the_type_tool_are_refused_after_undo_reuses_the_frame_id() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": "First"})).unwrap(); + app.run("text.select", json!({"story": a["story"], "anchor": 1})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + d.fields.insert("columns".into(), json!("3")); + app.run("edit.undo", json!({})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 300], "content": "text", "text": "Second"})).unwrap(); + assert_eq!(a["id"], b["id"], "the new frame takes the undone frame's id"); + app.run("text.select", json!({"story": b["story"], "anchor": 1})).unwrap(); + app.ui.dialog = Some(d); + let err = confirm(&mut app).unwrap_err().to_string(); + assert!(err.contains("changed after the dialog opened"), "{err}"); + let b = designcraft_doc::ItemId(b["id"].as_u64().unwrap()); + assert_eq!(app.session.doc().unwrap().doc.item(b).unwrap().text_frame().unwrap().options.columns, 1, "the new frame is unchanged"); + } + #[test] fn toc_right_indent_separator_survives_the_dialog_and_update() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); @@ -1152,10 +1214,17 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { // The document state those frames are in: another document, or the document after // Revert, can reuse their ids. d.fields.insert("_targetsDoc".into(), json!(app.session.active().map(|doc| doc.identity_epoch))); + // Undo puts back the document's id counter, so a frame made after it can take a stored id. + d.fields.insert("_targetsRevision".into(), json!(app.session.active().map(base_revision))); } d.fields.insert("_shown".into(), shown); } +/// The document's revision without a preview on top: the one the open gesture began at. +fn base_revision(st: &designcraft_engine::DocState) -> u64 { + st.interaction.as_ref().map_or(st.revision, |it| it.revision) +} + /// With the Type tool and no frame selected: the frame that shows the caret, or every frame that /// holds part of the selected text. fn typing_frame_ids(app: &DesignApp) -> Option { @@ -1280,8 +1349,7 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { let shown = d.fields.get(PREVIEWED).cloned(); if !d.b("preview") { if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); d.fields.remove("status"); } return; @@ -1291,8 +1359,7 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { Err(e) => { // Values OK would refuse don't stay on the page: it goes back to how it was. if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); } d.fields.insert("status".into(), json!(e)); return; @@ -1304,16 +1371,16 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { // Nothing edited (yet, or any more): the page as it was. if params.as_object().is_some_and(|m| m.keys().all(|k| k == "ids")) { if shown.is_some() { - app.session.cancel_interaction(); - d.fields.remove(PREVIEWED); + end_text_frame_preview(app, d); } return; } - if shown.is_none() - && let Err(e) = app.session.begin_interaction("Text Frame Options") - { - d.fields.insert("status".into(), json!(e.to_string())); - return; + if shown.is_none() { + if let Err(e) = app.session.begin_interaction("Text Frame Options") { + d.fields.insert("status".into(), json!(e.to_string())); + return; + } + d.fields.insert(PREVIEW_DOC.into(), json!(app.session.active().map(|doc| doc.uid))); } match app.session.preview("object.textFrameOptions", params.clone()) { Ok(()) => d.fields.remove("status"), @@ -1322,6 +1389,15 @@ fn text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { d.fields.insert(PREVIEWED.into(), params); } +/// The preview goes from the document it was shown in, also when another document is active now. +fn end_text_frame_preview(app: &mut DesignApp, d: &mut Dialog) { + d.fields.remove(PREVIEWED); + match d.fields.remove(PREVIEW_DOC).as_ref().and_then(Value::as_u64) { + Some(uid) => app.session.cancel_interaction_of(uid), + None => app.session.cancel_interaction(), + } +} + /// Text Frame Options › General, as InDesign's: Columns (kind, number and width, gutter and /// maximum, Balance Columns), Inset Spacing (top and bottom, the link, left and right; one Inset /// for a non-rectangular frame), Vertical Justification (align, paragraph spacing limit) and @@ -1568,8 +1644,8 @@ fn text_frame_baseline_grid(d: &Dialog, bad: &dyn Fn(&str) -> String) -> Result< fn confirm_text_frame_options(app: &mut DesignApp, d: &mut Dialog) -> Result { seed_text_frame_options(app, d); // The preview goes; the options are set once, as one undo step. - if d.fields.remove(PREVIEWED).is_some() { - app.session.cancel_interaction(); + if d.fields.contains_key(PREVIEWED) { + end_text_frame_preview(app, d); } let p = text_frame_params(app, d)?; if p.keys().all(|k| k == "ids") { @@ -1679,13 +1755,17 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, /// Typing in a frame: the frame that showed the caret, or every frame that held part of the /// selected text, when the dialog opened. Those ids are refused once another document is active, -/// or once Revert has replaced the document. +/// once Revert has replaced the document, or once the document has changed (Undo can give a new +/// frame a stored id). fn text_frame_targets(app: &DesignApp, d: &Dialog) -> Result, &'static str> { let Some(ids) = d.fields.get("_targets").cloned() else { return Ok(typing_frame_ids(app)) }; let active = app.session.active().map(|doc| doc.identity_epoch); if d.fields.get("_targetsDoc").and_then(Value::as_u64) != active { return Err("the document the dialog opened on is no longer the active one"); } + if d.fields.get("_targetsRevision").and_then(Value::as_u64) != app.session.active().map(base_revision) { + return Err("the document changed after the dialog opened"); + } Ok(Some(ids)) } @@ -4258,7 +4338,11 @@ pub fn cancel(app: &mut DesignApp) { } crate::new_document::end_preview(app); if d.as_ref().is_some_and(|d| d.fields.contains_key(PREVIEWED)) { - app.session.cancel_interaction(); + // Text Frame Options names the document its preview is in. + match d.as_ref().and_then(|d| d.fields.get(PREVIEW_DOC)).and_then(Value::as_u64) { + Some(uid) => app.session.cancel_interaction_of(uid), + None => app.session.cancel_interaction(), + } } app.cancel_pdf_import(); if let Some(d) = d @@ -8978,6 +9062,8 @@ fn toc_dialog(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { } /// The params a previewing dialog shows on the page (its interaction is open while it is set). const PREVIEWED: &str = "_previewed"; +/// The uid of the document a Text Frame Options preview is shown in. +const PREVIEW_DOC: &str = "_previewDoc"; /// Edit › Step and Repeat, as in InDesign: Repeat (Count, or Rows and Columns with Create as a /// grid), Offset (Vertical, Horizontal, in the document's ruler units) and Preview, which shows From 2aa93ea807aa7b0da2c95c342d6270ee4981c4e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:10:13 -0800 Subject: [PATCH 225/328] Text: Text Frame Options from the Type tool show the inset of the frames they change The one Inset field of a non-rectangular frame and the inset link now follow the frames the dialog changes: the frame that shows the caret, or every frame holding selected text. Before, a caret with no stored frame showed four sides for an oval frame, and the link checked every frame of the story. --- crates/ui-egui/src/dialogs.rs | 47 ++++++++++++++++++----------- crates/ui-egui/src/dialogs/tests.rs | 6 ++-- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index ab53948f9..7b5ff93ca 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -589,6 +589,30 @@ mod color_theme_tests { assert_eq!((inset(&app, a), inset(&app, b)), (24.0, 0.0)); } + /// With the caret in the oval second frame of a thread whose first frame has uneven insets, the + /// dialog shows the one Inset of the oval and keeps the link on: both follow the frame it changes. + #[test] + fn text_frame_options_from_the_type_tool_show_the_inset_of_the_caret_frame() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = + app.run("frame.create", json!({"rect": [36, 200, 300, 700], "shape": "ellipse", "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = + (designcraft_doc::ItemId(a["id"].as_u64().unwrap()), designcraft_doc::ItemId(b["id"].as_u64().unwrap()), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a.0, "to": b.0})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [a.0], "inset": [1, 2, 3, 4]})).unwrap(); + let cs = designcraft_compose::compose_story(&app.session.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default()); + let caret = cs.frame(b).unwrap().range.start + 2; + app.run("text.select", json!({"story": sid, "anchor": caret})).unwrap(); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert_eq!(d.fields.get("_targets"), Some(&json!([b.0]))); + assert!(d.b("_shaped"), "the oval shows one Inset"); + assert!(d.b("insetLinked"), "the first frame's uneven sides do not turn the link off"); + } + /// A preview shown in one document goes when OK is refused, or Cancel is chosen, after another /// document became active. #[test] @@ -1105,25 +1129,17 @@ fn selected_frame_options(app: &DesignApp) -> Option bool { let Some(st) = app.session.active() else { return true; }; - let mut ids = st.selection.items.clone(); - if ids.is_empty() - && let Some(t) = st.selection.text - { - ids = match t.frame { - Some(f) => vec![f], - None => st.doc.story(t.story).map(|s| s.frames.clone()).unwrap_or_default(), - }; - } + let ids = designcraft_engine::cmd::text_frame_options_frames(&app.session); ids.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|t| t.options.inset.iter().all(|v| (v - t.options.inset[0]).abs() < 1e-9)) } -/// Whether every selected text frame (the selected items, or the frame of the caret) has an -/// outline that is not its own axis-aligned rectangle: an oval, a polygon, rounded or other corner +/// Whether every text frame the dialog changes (the selected items, else the frame that shows the +/// caret or every frame holding selected text) has an outline that is not its own axis-aligned rectangle: an oval, a polygon, rounded or other corner /// options. Its text keeps one inset from the outline, as compose sets it; type on a path doesn't. /// A selection that mixes them with rectangular frames shows the four sides, so each frame keeps /// the sides left as shown. @@ -1137,11 +1153,8 @@ fn selected_frame_is_shaped(app: &DesignApp) -> bool { let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; Some(designcraft_compose::FrameOutline::new(&bp, 0.0).is_some()) }; - if st.selection.items.is_empty() { - let Some(fid) = st.selection.text.and_then(|t| t.frame) else { return false }; - return shaped(fid).unwrap_or(false); - } - st.selection.items.iter().all(|&fid| shaped(fid).unwrap_or(false)) + let ids = designcraft_engine::cmd::text_frame_options_frames(&app.session); + !ids.is_empty() && ids.iter().all(|&fid| shaped(fid).unwrap_or(false)) } /// Object › Text Frame Options shows the selected frame's options. `_shown` keeps what it showed, diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9f66fb4f8..0bad3ce0e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1831,15 +1831,15 @@ fn text_frame_options_link_the_insets_only_when_every_selected_frame_has_even_si assert!(!seeded(&app).b("insetLinked")); app.run("text.select", json!({"story": other_even_story, "anchor": 0, "focus": 0})).unwrap(); assert!(seeded(&app).b("insetLinked")); - // A story threaded on into the uneven frame: a caret placed in the first frame changes only - // that frame, and a caret with no frame changes every frame of the story. + // A story threaded on into the uneven frame: a caret placed in the first frame, or a caret + // with no stored frame drawn in the first frame, changes only that frame. let (first, story) = frame(&mut app, [300, 300, 500, 500], json!(6)); let (last, _) = frame(&mut app, [300, 520, 500, 700], json!([1, 2, 3, 4])); app.run("text.thread", json!({"from": first.0, "to": last.0})).unwrap(); app.run("text.placeCaret", json!({"frame": first.0, "point": [310, 310]})).unwrap(); assert!(seeded(&app).b("insetLinked")); app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap(); - assert!(!seeded(&app).b("insetLinked")); + assert!(seeded(&app).b("insetLinked")); } #[test] From b9894b47c5131ab47c996e507fe2083f62525acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:14:54 -0800 Subject: [PATCH 226/328] Images: decode the images in view together before drawing A render decoded each placed image that was not cached yet while drawing it, one after another, so page thumbnails, image exports and the first canvas frame of a page with several large photos took the sum of their decodes. Before drawing, the renderer now lists the images in view (with the same culling as drawing: hidden items and layers, nonprinting items, items out of view, PDF layer choices) and decodes the uncached ones on up to eight threads, with the mip levels they are drawn at. It leaves the work to the render when fewer than two images need decoding, on the web, and in Fast display. The images it decodes stay within what the cache keeps, sized by their pixels (PDF pages and SVGs at the size they are rasterized at), and decodes in flight together stay within half the cache budget. --- ROADMAP.md | 1 + crates/render/src/decode.rs | 34 ++++- crates/render/src/draw.rs | 151 +++++++++++++++------- crates/render/src/driver.rs | 33 +++-- crates/render/src/images.rs | 248 +++++++++++++++++++++++++++++++++++- crates/render/src/stroke.rs | 45 ++++--- crates/render/src/tests.rs | 86 +++++++++++++ 7 files changed, 517 insertions(+), 81 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1ed2064a0..00836637e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A render decodes the placed images in view that are not cached yet on several threads before it draws, instead of one after another while drawing. Page thumbnails, image exports and the first canvas frame of a page with six 24 MP photos take about 1.2 s instead of 2.8 s. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..5668a205f 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -6,16 +6,46 @@ pub fn decode_pixmap(bytes: &[u8]) -> Option { decode_pixmap_page(bytes, 0) } +/// Longer side (pixels) PDF pages and SVGs are drawn at by [`decode_pixmap_page`]. +const VECTOR_SIDE: u32 = 3000; + +/// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third +/// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a +/// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is +/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + let drawn = |(w, h): (f64, f64), side: f64, most: f64| { + let k = (side / w.max(h).max(1e-3)).min(most); + ((w * k).round().max(1.0), (h * k).round().max(1.0)) + }; + let size = if designcraft_images::is_eps(bytes) { + image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { + // Without a preview, the pixel size is the 2 pixels per point placeholder's. + let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); + let px = (pw as f64, ph as f64); + if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + }) + } else if is_pdf(bytes) { + // As render_pdf_page scales: at most 8 times the page size. + pdf_page_size(bytes, page as usize).map(|s| drawn(s, VECTOR_SIDE as f64, 8.0)) + } else if designcraft_images::is_svg(bytes) { + designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) + } else { + image_size(bytes).map(|(w, h)| (w as f64, h as f64)) + }; + size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) +} + /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { // Documents retain the EPS source; only display its TIFF preview or placeholder. let proxy = if designcraft_images::is_eps(bytes) { Some(designcraft_images::eps_proxy(bytes)?.0) } else { None }; let bytes = proxy.as_deref().unwrap_or(bytes); if is_pdf(bytes) { - return render_pdf_page(bytes, page as usize, 3000); + return render_pdf_page(bytes, page as usize, VECTOR_SIDE); } if designcraft_images::is_svg(bytes) { - let (px, w, h) = designcraft_images::render_svg(bytes, 3000)?; + let (px, w, h) = designcraft_images::render_svg(bytes, VECTOR_SIDE)?; let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 625338eb0..add9daa87 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -1,8 +1,9 @@ use super::color::{HIDDEN_LAYERS, blend_mode, color_of, overprints, rect_overlaps, screen_color, set_fill_paint, spread_blends}; -use super::types::{DisplayQuality, Frame}; +use super::stroke::image_want; +use super::types::{DisplayQuality, Frame, RenderOptions}; use super::{ - Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Item, Mix, RenderContext, Renderer, Shape, ShownOn, SpreadRef, - StoryId, Vec2, blendspace, corners, fx, grid, kurbo, peniko, + Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Document, Item, Mix, RenderContext, Renderer, Shape, ShownOn, + SpreadRef, StoryId, Vec2, blendspace, corners, fx, grid, images, kurbo, peniko, }; /// An item's fill under its content; an overprinting fill multiplies into what is beneath. @@ -25,6 +26,104 @@ fn draw_body_fill(ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, x } } +/// Each item spread `sr` draws at the top level, in drawing order (layers back to front; within +/// each layer parent items first), with its transform to the spread and where it shows. +fn each_top_item(doc: &Document, sr: SpreadRef, opts: &RenderOptions, mut visit: impl FnMut(&Item, Affine, ShownOn)) { + let Some(sp) = doc.spread(sr) else { return }; + for layer in doc.layers.iter().rev() { + if !layer.visible || opts.printing_only && !layer.printable { + continue; + } + // Document pages show their parent and its bases; a parent spread shows its bases. + let first = match sr { + SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), + SpreadRef::Parent(_) => None, + }; + // Base items compose for where they show: the document page, or this parent spread. + let shown_on = |pi: usize| match (sr, first) { + (SpreadRef::Parent(p), _) => ShownOn::Parent(p), + (_, Some(a)) => ShownOn::Page(a + pi), + (_, None) => ShownOn::Own, + }; + for (pi, page) in sp.pages.iter().enumerate() { + if !page.show_parent_items { + continue; + } + let chain = doc.shown_parent_pages(sr, pi); + // This page's overrides and those of every parent page behind it (#1469). + let overridden = doc.overridden_parent_items(sr, pi); + for (ppi, ppage) in chain { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppg) = parent.pages.get(ppage) else { continue }; + let dx = page.x - ppg.x; + for it in &parent.items { + if it.layer != layer.id || overridden.contains(&it.id) { + continue; + } + // Parent items belong to the parent page they sit on. + if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { + continue; + } + visit(it, Affine::translate((dx, 0.0)), shown_on(pi)); + } + } + } + for it in &sp.items { + if it.layer == layer.id { + visit(it, Affine::IDENTITY, ShownOn::Own); + } + } + } +} + +/// The placed images drawing spread `sr` in frame `f` takes from the image cache (see +/// [`images::warm`]), with the culling [`Renderer::draw_item`] applies. Images inside text (inline +/// and anchored objects) are left to the render. +pub(crate) fn wanted_images(f: &Frame, sr: SpreadRef, out: &mut Vec) { + // Fast display draws grey boxes for images. + if f.opts.quality == DisplayQuality::Fast { + return; + } + each_top_item(f.doc, sr, f.opts, |it, parent, _| wanted_in(f, it, parent, 0, out)); +} + +fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec) { + // As deep as draw_item draws. + if depth >= 64 || it.hidden || f.opts.hidden.contains(&it.id) || f.opts.printing_only && it.nonprinting { + return; + } + let xf = parent * it.xf; + if !it.children().is_empty() && !it.has_nested_items() { + for c in it.shown_children() { + wanted_in(f, c, xf, depth + 1, out); + } + return; + } + let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(it.stroke.extent() + 2.0, it.stroke.extent() + 2.0); + let fx_outset = if it.effects.any() && f.opts.quality != DisplayQuality::Fast { fx::outset(it) } else { 0.0 }; + if !rect_overlaps(vb.inflate(fx_outset, fx_outset), f.visible) { + return; + } + match &it.content { + Content::Graphic(g) => { + let g = &if it.media.is_some() { it.drawn_graphic(&f.doc.assets).unwrap_or_else(|| g.clone()) } else { g.clone() }; + let Some(asset) = f.doc.assets.get(&g.asset) else { return }; + let hidden = it.has_pdf_layer_override().then(|| it.pdf_hidden_layers.clone()); + let previous = HIDDEN_LAYERS.with(|h| h.replace(hidden)); + if let Some((want, ..)) = image_want(f, asset, g, xf) { + out.push(want); + } + HIDDEN_LAYERS.with(|h| h.replace(previous)); + } + Content::Group { items } if it.has_nested_items() => { + for c in items { + wanted_in(f, c, xf, depth + 1, out); + } + } + _ => {} + } +} + impl Renderer { pub(crate) fn draw_spread(&mut self, ctx: &mut RenderContext, f: &Frame, sr: SpreadRef) { let doc = f.doc; @@ -70,51 +169,7 @@ impl Renderer { if isolate { ctx.push_layer(None, None, None, None, None); } - // Layers back to front; within each layer parent items first. - for layer in doc.layers.iter().rev() { - if !layer.visible || f.opts.printing_only && !layer.printable { - continue; - } - // Document pages show their parent and its bases; a parent spread shows its bases. - let first = match sr { - SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), - SpreadRef::Parent(_) => None, - }; - // Base items compose for where they show: the document page, or this parent spread. - let shown_on = |pi: usize| match (sr, first) { - (SpreadRef::Parent(p), _) => ShownOn::Parent(p), - (_, Some(a)) => ShownOn::Page(a + pi), - (_, None) => ShownOn::Own, - }; - for (pi, page) in sp.pages.iter().enumerate() { - if !page.show_parent_items { - continue; - } - let chain = doc.shown_parent_pages(sr, pi); - // This page's overrides and those of every parent page behind it (#1469). - let overridden = doc.overridden_parent_items(sr, pi); - for (ppi, ppage) in chain { - let Some(parent) = doc.parents.get(ppi) else { continue }; - let Some(ppg) = parent.pages.get(ppage) else { continue }; - let dx = page.x - ppg.x; - for it in &parent.items { - if it.layer != layer.id || overridden.contains(&it.id) { - continue; - } - // Parent items belong to the parent page they sit on. - if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { - continue; - } - self.draw_item(ctx, f, it, Affine::translate((dx, 0.0)), shown_on(pi)); - } - } - } - for it in &sp.items { - if it.layer == layer.id { - self.draw_item(ctx, f, it, Affine::IDENTITY, ShownOn::Own); - } - } - } + each_top_item(doc, sr, f.opts, |it, parent, page| self.draw_item(ctx, f, it, parent, page)); if isolate { ctx.pop_layer(); } diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index c837e3686..e217def45 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -1,8 +1,10 @@ use super::color::{PLATE, RICH_BLACK, blend_space_view, rect_overlaps}; use super::decode::now; +use super::draw::wanted_images; use super::types::{Frame, FrameStats, MAX_PAGE_PIXELS, MAX_SIDE, Placed, RenderOptions, Rendered, default_threads}; use super::{ - Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, kurbo, peniko, text, vello_cpu, + Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, images, kurbo, peniko, text, + vello_cpu, }; impl Renderer { @@ -100,17 +102,26 @@ impl Renderer { } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let canvas_visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); - for pl in spreads { - let Some(sp) = doc.spread(pl.spread) else { continue }; - let sview = view * pl.xf; - let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); - let bounds = sp.bounds(); - // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). - if !rect_overlaps(bounds.inflate(2000.0, 2000.0), visible) { - continue; + let frames: Vec<(Frame, SpreadRef)> = spreads + .iter() + .filter_map(|pl| { + let sp = doc.spread(pl.spread)?; + let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); + // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). + rect_overlaps(sp.bounds().inflate(2000.0, 2000.0), visible) + .then_some((Frame { doc, cache, view: view * pl.xf, visible, px, opts, mt }, pl.spread)) + }) + .collect(); + // Decode the images in view that aren't cached yet together, before drawing them. + if images::can_warm() { + let mut wanted = Vec::new(); + for (f, sr) in &frames { + wanted_images(f, *sr, &mut wanted); } - let f = Frame { doc, cache, view: sview, visible, px, opts, mt }; - self.draw_spread(&mut ctx, &f, pl.spread); + images::warm(wanted); + } + for (f, sr) in &frames { + self.draw_spread(&mut ctx, f, *sr); } ctx.flush(); // Render straight into the returned buffer (no extra copy of the frame). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 37606097d..ee0d917ba 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -6,10 +6,12 @@ //! are evicted beyond a memory budget; at most `MAX_BAD` failed assets are remembered. use std::collections::HashMap; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; +use crate::decode::decoded_bytes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -114,7 +116,10 @@ pub fn decoded(bytes: &Arc>, page: u32) -> Option> { return None; } // Decode outside the lock: other threads keep drawing cached images meanwhile. - match decode_pixmap_page(bytes, page) { + let pm = decode_pixmap_page(bytes, page); + #[cfg(test)] + DECODED_ON.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, std::thread::current().id())); + match pm { Some(pm) => { let pm = Arc::new(pm); store(bytes, page, 0, pm.clone()); @@ -149,6 +154,160 @@ pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Op Some(pm) } +/// The decodes [`decoded`] ran: the address of the encoded bytes and the thread. +#[cfg(test)] +pub(crate) static DECODED_ON: Mutex> = Mutex::new(Vec::new()); + +/// A placed image a render draws, as [`mip`] takes it: the encoded bytes, the PDF page, the +/// width (points) and the device pixels per point. +pub(crate) struct Want { + pub bytes: Arc>, + pub page: u32, + pub width_pt: f64, + pub on_screen: f64, +} + +/// Threads [`warm`] decodes on (1 on the web, which has none). +fn workers() -> usize { + #[cfg(target_arch = "wasm32")] + { + 1 + } + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::available_parallelism().map_or(2, std::num::NonZero::get).clamp(2, 8) + } +} + +/// Whether [`warm`] can decode on several threads here. +pub(crate) fn can_warm() -> bool { + workers() >= 2 +} + +/// Whether a decode of about `size` bytes may start while decodes of `in_flight` bytes run: when +/// none run, or when together they take at most half the budget. +fn admits(in_flight: usize, size: usize) -> bool { + in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 +} + +/// Bytes decoding at once and the most there were, with the signal that some finished. +type Gate = (Mutex<(usize, usize)>, Condvar); + +/// Takes a finished decode's bytes off its [`Gate`] when dropped. +struct Release<'a>(&'a Gate, usize); + +impl Drop for Release<'_> { + fn drop(&mut self) { + let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + g.0 = g.0.saturating_sub(self.1); + drop(g); + self.0.1.notify_all(); + } +} + +/// Decode the images in `wants` that are not cached yet on several threads at once, with the +/// mip levels they are drawn at, so the render that draws them next finds them cached instead +/// of decoding them one after another. Does nothing when fewer than two images need decoding. +/// The images in view that are cached count against the cache budget first; a new image that +/// would take the total past what the cache keeps (by its pixel size) is left to the render. +/// Decodes wait while those in flight together would take more than half the budget. Returns +/// the most bytes (estimated) that were decoding at once. +pub(crate) fn warm(wants: Vec) -> usize { + let workers = workers(); + if workers < 2 { + return 0; + } + // What is drawn of each asset and page, in drawing order. + let mut assets: Vec<((usize, u32), Vec)> = Vec::new(); + let mut index: HashMap<(usize, u32), usize> = HashMap::new(); + for w in wants { + let key = (Arc::as_ptr(&w.bytes) as usize, w.page); + match index.get(&key).and_then(|&i| assets.get_mut(i)) { + Some(a) => a.1.push(w), + None => { + index.insert(key, assets.len()); + assets.push((key, vec![w])); + } + } + } + // The bytes each asset in view holds in the cache, when it is cached or failed, and the bytes + // of everything else cached. Its levels become the most recently used, so the stores below + // evict other images first. + let (held, others) = with(|c| { + c.clock += 1; + let clock = c.clock; + let mut held: HashMap<(usize, u32), usize> = HashMap::new(); + for (k, e) in c.map.iter_mut() { + if index.contains_key(&(k.0, k.1)) { + e.stamp = clock; + *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); + } + } + let in_view = held.values().sum::(); + // Smaller levels alone don't make an asset cached. + held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + for k in index.keys() { + if c.bad.contains_key(k) { + held.entry(*k).or_default(); + } + } + (held, c.bytes.saturating_sub(in_view)) + }); + // One image to decode gains nothing from threads (and is not worth sizing). + if assets.iter().filter(|(key, _)| !held.contains_key(key)).count() < 2 { + return 0; + } + let mut pixels = held.values().fold(0usize, |n, b| n.saturating_add(*b)); + let mut jobs: Vec<(usize, Vec)> = Vec::new(); + for (key, wanted) in assets { + if held.contains_key(&key) { + continue; + } + let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + // A store past the budget evicts down to three quarters of it: the images in view must + // fit in that, unless they and the rest fit in the budget. + let total = pixels.saturating_add(size); + if total > BUDGET * 3 / 4 && others.saturating_add(total) > BUDGET { + continue; + } + pixels = total; + jobs.push((size, wanted)); + } + if jobs.len() < 2 { + return 0; + } + // While it converts the pixels, a decode holds buffers of about its size besides the cache: + // a decode waits while those in flight would take it past half the budget (one always runs). + let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); + let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..workers.min(jobs.len()) { + let work = || { + while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let mut g = lock(); + while !admits(g.0, *size) { + g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + } + g.0 += size; + g.1 = g.1.max(g.0); + drop(g); + // Released even if the decode panics, so no other decode waits forever. + let _release = Release(&gate, *size); + for w in job { + let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); + } + } + }; + // A thread that can't start leaves its share to the others, or to the render. + if std::thread::Builder::new().name("image decode".into()).spawn_scoped(s, work).is_err() { + break; + } + } + }); + gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 +} + /// Drop every decoded image. pub fn clear() { with(|c| { @@ -176,4 +335,89 @@ mod tests { let last = &buffers[MAX_BAD + 9]; assert!(c.bad.contains_key(&(Arc::as_ptr(last) as usize, 0))); } + + fn png(side: u32, value: u8) -> Arc> { + let mut out = Vec::new(); + let img = image::RgbaImage::from_pixel(side, side, image::Rgba([value, 0, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + Arc::new(out) + } + + fn want(bytes: &Arc>) -> Want { + Want { bytes: bytes.clone(), page: 0, width_pt: 100.0, on_screen: 1.0 } + } + + /// A PSD header claiming `side` pixels square (its pixels don't decode). + fn psd(side: u32) -> Arc> { + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + psd[14..18].copy_from_slice(&side.to_be_bytes()); + psd[18..22].copy_from_slice(&side.to_be_bytes()); + Arc::new(psd) + } + + /// Where the decode log ends now. Taken after the test's images are made: while they live, + /// no other buffer has their address, so later entries with it are theirs. + fn mark() -> usize { + DECODED_ON.lock().unwrap().len() + } + + /// The threads that decoded `bytes` after `since`. + fn decoders(bytes: &Arc>, since: usize) -> Vec { + let id = Arc::as_ptr(bytes) as usize; + DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + } + + #[test] + fn warm_decodes_several_images_off_the_calling_thread() { + let images: Vec<_> = (0..3u8).map(|i| png(8, 40 + i)).collect(); + let since = mark(); + // The same image drawn at two sizes is one decode. + let mut wants: Vec = images.iter().map(want).collect(); + wants.push(Want { on_screen: 0.1, ..want(&images[0]) }); + warm(wants); + let me = std::thread::current().id(); + for img in &images { + let on = decoders(img, since); + assert_eq!(on.len(), 1, "decoded once"); + assert_ne!(on[0], me, "decoded on a worker"); + } + } + + #[test] + fn warm_leaves_one_image_or_an_over_budget_one_to_the_render() { + // A header claiming 100,000 pixels square is far past the budget. + let (one, huge, a, b, c) = (png(8, 7), psd(100_000), png(8, 9), png(8, 11), png(8, 13)); + let since = mark(); + warm(vec![want(&one)]); + assert!(decoders(&one, since).is_empty(), "one image: no threads"); + // The huge one, first or not, is left to the render; the small images beside it are + // decoded ahead. + warm(vec![want(&huge), want(&a), want(&b)]); + assert!(decoders(&huge, since).is_empty(), "over budget: not decoded ahead"); + assert_eq!((decoders(&a, since).len(), decoders(&b, since).len()), (1, 1)); + // With the huge one and a single small image, nothing is left to do together. + warm(vec![want(&c), want(&huge)]); + assert!(decoders(&c, since).is_empty() && decoders(&huge, since).is_empty()); + } + + #[test] + fn warm_decodes_large_images_one_at_a_time() { + // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // take more than half of it; the small image still decodes beside them. + let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let since = mark(); + let large = decoded_bytes(&d, 0); + assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); + let peak = warm(vec![want(&d), want(&e), want(&small)]); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= large, "the large images were decoded ahead"); + let me = std::thread::current().id(); + for img in [&d, &e, &small] { + let on = decoders(img, since); + assert!(on.len() == 1 && on[0] != me); + } + } } diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index a63dd44a3..a10df2da2 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -6,6 +6,30 @@ use super::{ pdf_layers, peniko, vello_cpu, }; +/// The pixels drawing placed graphic `g` takes from the image cache, the page rectangle they +/// cover in graphic space and that page's height (points). `None` for video and sound, Fast +/// display and a PDF whose hidden layers can't be applied (none of these draw image pixels). +pub(crate) fn image_want(f: &Frame, asset: &designcraft_doc::Asset, g: &designcraft_doc::Graphic, xf: Affine) -> Option<(images::Want, Rect, f64)> { + if designcraft_doc::media_kind(&asset.mime).is_some() || f.opts.quality == DisplayQuality::Fast { + return None; + } + // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). + let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); + let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; + let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); + let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { + // An explicit choice (including all-on) that cannot be rewritten fails closed: + // stale persisted/relinked choices must not reveal hidden source content. + Some(hidden) => pdf_layers::layered(&asset.data, hidden)?, + None => asset.data.clone(), + }; + // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. + let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); + let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); + let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); + Some((images::Want { bytes: data, page: asset.page, width_pt: page_w, on_screen }, page, page_h)) +} + /// `stroke` as round dots `weight` wide, one every `2 × weight`. Kurbo's stroker drops /// zero-length dashes, so each dot is a dash a hair long, centred where the zero-length dash /// would be (so the path's ends get dots too). @@ -170,24 +194,9 @@ impl Renderer { ctx.fill_rect(&Rect::new(0.0, 0.0, g.size.0, g.size.1)); return; } - // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). - let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); - let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; - let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); - let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { - // An explicit choice (including all-on) that cannot be rewritten fails closed: - // stale persisted/relinked choices must not reveal hidden source content. - Some(hidden) => { - let Some(variant) = pdf_layers::layered(&asset.data, hidden) else { return }; - variant - } - None => asset.data.clone(), - }; - // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. - let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); - let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); - let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); - let Some(pm) = images::mip(&data, asset.page, page_w, on_screen) else { return }; + let Some((want, page, page_h)) = image_want(f, asset, g, xf) else { return }; + let page_w = want.width_pt; + let Some(pm) = images::mip(&want.bytes, want.page, page_w, want.on_screen) else { return }; // A coloured image is already in the plate's inks (its colours come from `color_of`). let pm = match (colorize::colorized(f.doc, &g.fill, &asset.data, &pm), PLATE.with(std::cell::Cell::get)) { (Some(coloured), _) => coloured, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 3287ab836..5d4f6a048 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -773,3 +773,89 @@ fn dotted_strokes_draw_every_dot() { let dots = outline.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); assert_eq!(dots, 13); } + +/// The size the image cache budgets for a decode is the size the decode has: a PDF page by the +/// pixels it is rasterized at, not by its size in points. +#[test] +fn decode_size_estimates_match_the_decodes() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(30, 20, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pdf = one_page_pdf("0 0 1 rg 0 0 100 100 re f"); + for bytes in [&png, &pdf] { + let pm = decode_pixmap_page(bytes, 0).unwrap(); + assert_eq!(decode::decoded_bytes(bytes, 0), pm.width() as usize * pm.height() as usize * 16 / 3); + } + assert_eq!(decode::decoded_bytes(b"not an image", 0), 0); + // An EPS drawn from its PostScript is budgeted at no less than it takes. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor 0 0 100 50 rectfill\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; + assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); + assert!(decode::decoded_bytes(eps, 0) >= drawn); +} + +#[test] +fn images_in_view_are_decoded_together_before_drawing() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + // Place a 4×4 PNG of one red value in `r`; returns its encoded bytes. + let place = |d: &mut Document, r: Rect, red: u8, hidden: bool| { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([red, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let data = Arc::new(png); + let aid = designcraft_doc::AssetId(d.alloc()); + let asset = designcraft_doc::Asset { + id: aid, + name: "red.png".into(), + mime: "image/png".into(), + data: data.clone(), + pixels: Some((4, 4)), + ..Default::default() + }; + d.assets.insert(aid, Arc::new(asset)); + let mut it = Item::new(designcraft_doc::ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r)); + it.hidden = hidden; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (r.width(), r.height()), + xf: Affine::translate((r.x0, r.y0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + data + }; + let shown: Vec<_> = + (0..3).map(|i| place(&mut d, Rect::new(20.0 + 90.0 * i as f64, 20.0, 100.0 + 90.0 * i as f64, 100.0), 200 + i as u8, false)).collect(); + let hidden = place(&mut d, Rect::new(20.0, 150.0, 100.0, 230.0), 10, true); + let outside = place(&mut d, Rect::new(400.0, 600.0, 500.0, 700.0), 20, false); + // Decodes logged from here on with these buffers' addresses are theirs (they live on). + let since = images::DECODED_ON.lock().unwrap().len(); + let cache = Cache::new(); + let mut r = Renderer::new(); + r.threads = 0; + let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let img = r.render(&d, &cache, &placed, (300, 300), Affine::IDENTITY, &RenderOptions { background: Some([255; 4]), ..Default::default() }); + for i in 0..3u8 { + assert_eq!(img.pixel(60 + 90 * u32::from(i), 60)[..3], [200 + i, 0, 0], "image {i} drawn"); + } + let me = std::thread::current().id(); + let decoded_on = |data: &Arc>| -> Vec { + let id = Arc::as_ptr(data) as usize; + images::DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + }; + for (i, data) in shown.iter().enumerate() { + let on = decoded_on(data); + assert_eq!(on.len(), 1, "image {i} decoded once"); + assert_ne!(on[0], me, "image {i} decoded ahead, off the render thread"); + } + assert!(decoded_on(&hidden).is_empty(), "a hidden image is not decoded"); + assert!(decoded_on(&outside).is_empty(), "an image out of view is not decoded"); +} From 213f3b75a309b0ad45e087f975800011ee5b494f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 15:43:43 -0500 Subject: [PATCH 227/328] Report recovery writes owned by another session --- crates/engine/src/recovery.rs | 37 ++++++++++++++++++++--------- crates/engine/src/recovery/tests.rs | 26 ++++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs index d045b2415..16b1e0ee2 100644 --- a/crates/engine/src/recovery.rs +++ b/crates/engine/src/recovery.rs @@ -886,8 +886,14 @@ pub(crate) fn start_tracked(s: &mut Session, dir: &Path) -> Result { // A write still running for this document already holds a snapshot of it; the next // timer tick catches up with the edits made since. match worker::submit(entry) { - Some(true) => queued += 1, - Some(false) => {} + Some(worker::Submit::Queued) => queued += 1, + Some(worker::Submit::AlreadyQueued) => {} + Some(worker::Submit::Conflict) => { + return Err(crate::EngineError::Other(format!( + "recovery data for document {} is already being written by another session", + document.uid + ))); + } None => { // No thread: write this one here rather than lose the recovery data. let written = write_snapshot(&Snapshot::of(&access, dir, document), || false); @@ -1326,24 +1332,33 @@ mod worker { }) } - /// Queue a document's write. `None`: no writer thread (the caller writes it itself); - /// `Some(false)`: one for this document is still queued or running. - pub(super) fn submit(entry: Snapshot) -> Option { + pub(super) enum Submit { + Queued, + AlreadyQueued, + Conflict, + } + + /// Queue a document's write. `None`: no writer thread (the caller writes it itself). + pub(super) fn submit(entry: Snapshot) -> Option { let w = writer()?; let mut running = w.running.lock().ok()?; let key = (entry.key.clone(), entry.uid); - // A session is writing this document now: this write waits for a later turn. - if w.writing_now.lock().is_ok_and(|now| now.contains_key(&key)) { - return Some(false); + // Another session's save or recovery write owns this destination. Check ownership while + // holding the same reservation locks used to queue or publish writes. + if let Some(owner) = w.writing_now.lock().ok().and_then(|now| now.get(&key).copied()) { + return Some(if owner == entry.owner { Submit::AlreadyQueued } else { Submit::Conflict }); } if let Some(q) = running.get_mut(&key) { // The write in flight was cancelled (the document was saved since), so it holds // nothing to recover: this one follows it, in place of any that was waiting. if w.cancelled.lock().is_ok_and(|cancelled| cancelled.contains(&key)) { + if q.next.as_ref().is_some_and(|next| next.owner != entry.owner) { + return Some(Submit::Conflict); + } q.next = Some(entry); - return Some(true); + return Some(Submit::Queued); } - return Some(false); + return Some(if q.owner == entry.owner { Submit::AlreadyQueued } else { Submit::Conflict }); } running.insert(key.clone(), Queued { owner: entry.owner, dir: entry.dir.clone(), next: None }); // A write is wanted again: whatever cancelled the last one does not apply to this one. @@ -1354,7 +1369,7 @@ mod worker { running.remove(&key); return None; } - Some(true) + Some(Submit::Queued) } } diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index f66d28879..8d28dc8a9 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -705,6 +705,32 @@ fn a_clean_document_leaves_another_sessions_write_queued_behind_its_own() { discard(dir.path(), uid); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_background_recovery_write_reports_another_sessions_held_write() { + let _turn = background(); + let dir = tempfile::tempdir().unwrap(); + let mut first = dirty_session(); + first.recovery_dir = Some(dir.path().to_path_buf()); + let uid = first.docs[0].uid; + let mut second = dirty_session(); + second.recovery_dir = Some(dir.path().to_path_buf()); + second.docs[0].uid = uid; + second.execute("frame.create", &json!({"rect": [20, 20, 60, 60]})).unwrap(); + + let held = testing::hold_next_write(dir.path()); + first.execute("file.recovery.save", &json!({"background": true})).unwrap(); + held.wait_until_held(); + + let err = second.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("another session"), "{err}"); + + held.release(); + assert_eq!(finished_writes(&mut first), 1); + assert!(files(dir.path(), uid).0.exists(), "the first session's recovery file remains intact"); + discard(dir.path(), uid); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_clean_document_in_another_session_leaves_this_sessions_write_alone() { From b30d39fdec19ade8a1aabcf47237f8c995e3869a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:48:41 -0800 Subject: [PATCH 228/328] Layers: Duplicate Layer maps copies by the original's anchors and tables object::renumber now gives a story copy's anchors and tables new ids. Duplicate Layer keys each copied anchor by the original anchor's id, so copied cross-references point at the copied paragraph, and pairs copied tables with the originals in order, so objects anchored in table cells keep their live captions. A copy that renumber reports incomplete is refused with the nested-too-deeply error. --- crates/engine/src/cmd/layout/layers.rs | 53 +++++++++++++++++++++----- 1 file changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layout/layers.rs b/crates/engine/src/cmd/layout/layers.rs index cd6e72ee2..6601e11e0 100644 --- a/crates/engine/src/cmd/layout/layers.rs +++ b/crates/engine/src/cmd/layout/layers.rs @@ -86,7 +86,9 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { let Some(sp) = src.spread(r) else { continue }; for it in sp.items.iter().filter(|it| it.layer == id) { let mut copy = Item::clone(it); - super::super::object::renumber(d, &src, &mut copy, &mut stories); + if !super::super::object::renumber(d, &src, &mut copy, &mut stories) { + return Err(bad(ID, "the layer's objects are nested too deeply to copy")); + } map_ids(it, ©, &mut ids); copies.push((r, copy)); } @@ -113,8 +115,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { // and those of the other copies point at, and tables with ids of their own, the tables in its cells and notes // included, allocated in story order. let mut anchors = HashMap::new(); + // The copies' own anchors are given ids below, so only the other stories' anchors count as taken. + let copied: HashSet = stories.values().copied().collect(); let mut used = HashSet::new(); - for st in d.stories.values() { + for st in d.stories.values().filter(|st| !copied.contains(&st.id)) { anchor_ids(st, &mut used); } let mut order: Vec<(StoryId, StoryId)> = stories.iter().map(|(old, new)| (*old, *new)).collect(); @@ -125,7 +129,10 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { st.link = Some((stories.get(&parent).copied().unwrap_or(parent), revision)); } st.frames = src.story(*old).map(|o| o.frames.iter().filter_map(|f| ids.get(f).copied()).collect()).unwrap_or_default(); - for (k, a) in (1..).zip(st.anchors.iter_mut()) { + // The copy's anchors may already have new ids: each is keyed by the id of the original's anchor, which the + // copied cross-references still point at. + let originals: Vec = src.story(*old).map(|o| o.anchors.iter().map(|a| a.id).collect()).unwrap_or_default(); + for ((k, a), orig_id) in (1..).zip(st.anchors.iter_mut()).zip(originals) { // `story id << 24 | n`, as anchors are made, or a new id when another anchor has that one or the story id // does not fit. let made = new.0.checked_mul(1 << 24).and_then(|base| base.checked_add(k)).filter(|id| !used.contains(id)); @@ -138,7 +145,7 @@ pub(super) fn duplicate_layer(s: &mut Session, p: &Value) -> Result { } }, }; - anchors.insert(a.id, id); + anchors.insert(orig_id, id); used.insert(id); Arc::make_mut(a).id = id; } @@ -250,11 +257,10 @@ fn map_anchored(orig: &Story, copy: &Story, ids: &mut HashMap) { for (o, c) in orig.objects.iter().zip(©.objects) { map_ids(&o.item, &c.item, ids); } - for (k, t) in &orig.tables { - if let Some(ct) = copy.tables.get(k) { - for (o, c) in t.cells.iter().zip(&ct.cells) { - map_anchored(&o.text, &c.text, ids); - } + // Copied tables have new ids, given in the order of the old ones, so the two maps list them in the same order. + for (t, ct) in orig.tables.values().zip(copy.tables.values()) { + for (o, c) in t.cells.iter().zip(&ct.cells) { + map_anchored(&o.text, &c.text, ids); } } for (o, c) in orig.notes.iter().chain(&orig.endnotes).zip(copy.notes.iter().chain(©.endnotes)) { @@ -1129,6 +1135,35 @@ mod layer_tests { assert_eq!(s.doc().unwrap().doc.layers, before, "nothing changes"); } + /// An empty group inside 64 others: within the layer's depth check, which counts the objects below a group, but + /// past the limit of the copy, which counts the group itself. + #[test] + fn duplicate_layer_refuses_an_empty_group_at_the_copy_limit() { + use designcraft_doc::{Content, ItemId}; + use std::sync::Arc; + + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let base = s.doc().unwrap().doc.layers[0].id.0; + let f = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let mut it = d.item(ItemId(f)).cloned().unwrap(); + it.content = Content::Group { items: Vec::new() }; + for _ in 0..super::MAX_COPY_DEPTH { + let mut group = it.clone(); + group.id = ItemId(d.alloc()); + group.content = Content::Group { items: vec![Arc::new(it)] }; + it = group; + } + let items = &mut Arc::make_mut(&mut d.spreads[0]).items; + items.retain(|i| i.id.0 != f); + items.push(Arc::new(it)); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("layer.duplicate", &json!({"id": base})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changes"); + } + #[test] fn duplicate_layer_detaches_overrides_of_parent_items_on_other_layers() { let mut s = crate::Session::new(); From 6d8f26a6beff4c0c5e63e5acf5b5678baefdd69d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:48:49 -0800 Subject: [PATCH 229/328] Render: cull a scaled object by its scaled stroke and glow Culling grew an object's box by its unscaled stroke and effect outset, so a view or repaint patch that showed only the outer part of a scaled object's stroke or hardened glow skipped the object. Culling now scales both by the object's largest scale factor, as drawing does. The CMYK ink-pass area grows each object, and each nested child, by its stroke and effect outset under its full transform. --- crates/render/src/blendspace.rs | 45 +++++++++++++++++++++++++++++++-- crates/render/src/draw.rs | 7 +++-- crates/render/src/fx.rs | 44 ++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 4 deletions(-) diff --git a/crates/render/src/blendspace.rs b/crates/render/src/blendspace.rs index 6096b3419..5dd8232a5 100644 --- a/crates/render/src/blendspace.rs +++ b/crates/render/src/blendspace.rs @@ -371,10 +371,18 @@ impl Renderer { } } // What an object can paint on the spread: its bounds with its (and its children's) - // strokes and effects. + // strokes and effects, which are drawn through each one's transform and grow with it. + fn outset(it: &Item, outer: Affine, o: &mut f64) { + let xf = outer * it.xf; + let scale = crate::fx::max_scale(xf).unwrap_or(1.0); + *o = o.max(crate::fx::outset_scaled(it, scale) + it.stroke.extent() * scale); + for c in it.children() { + outset(c, xf, o); + } + } let reach = |it: &Item| { let mut o: f64 = 0.0; - it.walk(&mut |c| o = o.max(crate::fx::outset(c) + c.stroke.extent())); + outset(it, Affine::IDENTITY, &mut o); it.bounds().inflate(o + 2.0, o + 2.0) }; let items: Vec<(Rect, bool)> = sp.items.iter().filter(|it| visible(it)).map(|it| (reach(it), transparent(it))).collect(); @@ -601,6 +609,39 @@ mod tests { assert_eq!(draw(&doc, &mut renderer).pixels, rgb.pixels); } + /// A hardened outer glow is stroked through the object's transform, and through its group's, + /// so the ink-pass area grows by the scaled growth: the square at 30..60 glows out to -30. + #[test] + fn cmyk_area_holds_a_scaled_objects_glow() { + for nested in [false, true] { + let mut doc = document(); + let mut item = Item::new( + ItemId(doc.alloc()), + doc.default_layer(), + Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), + ); + item.fill = Fill::swatch("C=100 M=0 Y=0 K=0"); + let g = &mut item.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + if nested { + let mut group = Item::new(ItemId(doc.alloc()), doc.default_layer(), Shape::Group, Default::default()); + group.xf = Affine::scale(3.0); + group.content = Content::Group { items: vec![Arc::new(item)] }; + doc.insert_item(SpreadRef::Doc(0), group, None).unwrap(); + } else { + item.xf = Affine::scale(3.0); + doc.insert_item(SpreadRef::Doc(0), item, None).unwrap(); + } + let cache = Cache::new(); + let opts = RenderOptions::default(); + let f = + Frame { doc: &doc, cache: &cache, view: Affine::IDENTITY, visible: Rect::new(-1e4, -1e4, 1e4, 1e4), px: 1.0, opts: &opts, mt: false }; + let area = Renderer::new().transparent_area(&f, SpreadRef::Doc(0)).unwrap(); + assert!(area.x0 <= -30.0, "nested {nested}: the area {area:?} holds the glow out to -30"); + } + } + #[test] fn cmyk_pass_count_is_constant_and_unchanged_views_are_cached() { let mut doc = document(); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 625338eb0..dbaa1d1b3 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -179,7 +179,10 @@ impl Renderer { return; } let xf = parent * it.xf; - let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(it.stroke.extent() + 2.0, it.stroke.extent() + 2.0); + // The stroke and the effects' growth are drawn through `xf`, which stretches them. + let scale = fx::max_scale(xf).unwrap_or(1.0); + let stroke = it.stroke.extent() * scale; + let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(stroke + 2.0, stroke + 2.0); // A frame with items pasted into it draws like any other object (draw_body: fill, the items // clipped to the frame, stroke), so its effects apply to all of it. if !it.children().is_empty() && !it.has_nested_items() { @@ -193,7 +196,7 @@ impl Renderer { _ => 0.0, }; let effects = it.effects.any() && f.opts.quality != DisplayQuality::Fast; - let fx_outset = if effects { fx::outset(it) } else { 0.0 }; + let fx_outset = if effects { fx::outset_scaled(it, scale) } else { 0.0 }; if !rect_overlaps(vb.inflate(margin + fx_outset, margin + fx_outset), f.visible) { return; } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 0fc1ba048..89f193d06 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -1576,4 +1576,48 @@ mod tests { assert!(lum < 200, "{threads} threads: the glow 50 pt left of the scaled square is drawn, luminance {lum}"); } } + + /// Culling measures a scaled item's stroke and hardened glow as they are drawn, through its + /// transform, so a view (or a repaint patch) that shows only that part still draws it. + #[test] + fn a_scaled_items_hard_glow_and_stroke_are_not_culled() { + use designcraft_doc::build::NewDocument; + use designcraft_doc::{Document, SpreadRef}; + let square = |glow: bool| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut it = Item::new( + designcraft_doc::ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 90.0, 90.0)), + ); + it.xf = Affine::scale(3.0); + it.fill = designcraft_doc::Fill::swatch(designcraft_color::swatch::BLACK); + if glow { + let g = &mut it.effects.outer_glow; + (g.on, g.color, g.opacity, g.size, g.spread) = (true, designcraft_color::swatch::BLACK.into(), 1.0, 20.0, 100.0); + } else { + (it.stroke.swatch, it.stroke.weight) = (designcraft_color::swatch::BLACK.into(), 20.0); + } + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + d + }; + let cache = crate::Cache::new(); + let opts = crate::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + // The square covers 150..270 on the spread. Its glow grows 60 pt (to 90), past the + // unscaled 33 pt reach; its 20 pt stroke is 60 pt wide (to 120), past the unscaled 22 pt. + for (glow, x) in [(true, 95.0), (false, 123.0)] { + let d = square(glow); + for threads in [0, 2] { + let mut r = Renderer::new(); + r.threads = threads; + let place = [crate::Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let image = r.render(&d, &cache, &place, (4, 20), Affine::translate((-x, -200.0)), &opts); + let p = image.pixel(1, 10); + let lum = u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2]); + assert!(lum < 200, "glow {glow}, {threads} threads: the view at x {x} shows the scaled square's edge, luminance {lum}"); + } + } + } } From 55963c491872cec854735278c7d80b60da2bc6cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:57:16 -0800 Subject: [PATCH 230/328] Images: pick a reduced JPEG's scale by its long side The JPEG decoder takes the smallest scale that meets either requested side. A short side rounds up to the same size at several scales, so a 100 x 2 JPEG asked for at a half decoded at an eighth (13 x 1). The long side alone now picks the scale, and a decode whose size differs from the requested reduction is refused, which falls back to the full decode. --- crates/images/src/jpeg.rs | 9 ++++++++- crates/images/src/tests.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 6188a53fc..a4a2a0971 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -100,7 +100,14 @@ pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaIma } } let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok(); - let (w, h) = d.scale(reduced(info.width)?, reduced(info.height)?).ok()?; + let expected = (reduced(info.width)?, reduced(info.height)?); + // The decoder takes the smallest scale that meets either requested side, and a short side + // rounds up to the same size at several scales, so only the long side is requested. + let request = if info.width >= info.height { (expected.0, u16::MAX) } else { (u16::MAX, expected.1) }; + let (w, h) = d.scale(request.0, request.1).ok()?; + if (w, h) != expected { + return None; + } let px = d.decode().ok()?; let pixels = usize::from(w).checked_mul(usize::from(h))?; let rgba: Vec = if colour { diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index 184e3c9c9..3edfa89b9 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -596,6 +596,19 @@ fn reduced_jpegs_decode_at_a_half_quarter_or_eighth_rounded_up() { assert!(decode_rgba_reduced(&jpeg, 4).is_none()); } +#[test] +fn a_thin_reduced_jpeg_keeps_its_long_side_at_the_requested_reduction() { + // The short side rounds up to 1 at every reduction, so it cannot pick the scale. + for (w, h) in [(100, 2), (2, 100)] { + let jpeg = gradient_jpeg(w, h, false); + for (shrink, long) in [(1, 50), (2, 25), (3, 13)] { + let img = decode_rgba_reduced(&jpeg, shrink).unwrap(); + let size = if w > h { (long, 1) } else { (1, long) }; + assert_eq!(img.dimensions(), size, "{w} × {h}, shrink {shrink}"); + } + } +} + #[test] fn reduced_decoding_is_for_jpegs_and_survives_damaged_ones() { let gray = decode_rgba_reduced(&gradient_jpeg(64, 64, true), 2).unwrap(); From 07d264fd238013bae6ac85e2f976f96a294a884f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:57:17 -0800 Subject: [PATCH 231/328] Copy: bound the anchored-object walk through cells and notes Copying a story gives the objects anchored in its table cells and notes fresh ids down to 64 levels, as the table copy does. A copy whose stories below that level hold anchored objects, tables or notes is refused with the nested-too-deeply error instead of recursing without limit. --- crates/engine/src/cmd/object.rs | 70 +++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 8b0e1cd51..b7a6d780b 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1281,21 +1281,41 @@ fn retarget_xrefs(copy: &mut Story, orig: &Story, map: &HashMap, depth } } -/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes, at every depth -/// (#1522), each `depth` levels deep. False when one of them nests groups deeper than [`MAX_COPY_DEPTH`]. +/// Fresh ids for the objects anchored in story copy `st`, its table cells, footnotes and endnotes down to +/// [`MAX_COPY_DEPTH`] levels (#1522), each `depth` levels deep. False when one of them nests groups deeper than +/// [`MAX_COPY_DEPTH`], or when the stories below that level hold anchored objects, tables or notes. #[must_use = "false means the copy is incomplete and must not be inserted"] fn renumber_anchored(dst: &mut Document, src: &Document, st: &mut Story, stories: &mut HashMap, depth: usize) -> bool { + renumber_anchored_in(dst, src, st, stories, depth, 0) +} + +/// [`renumber_anchored`] for a story `level` table cells and notes below the story copy. +#[must_use = "false means the copy is incomplete and must not be inserted"] +fn renumber_anchored_in( + dst: &mut Document, + src: &Document, + st: &mut Story, + stories: &mut HashMap, + depth: usize, + level: usize, +) -> bool { let mut complete = true; for o in &mut st.objects { complete &= renumber_in(dst, src, &mut Arc::make_mut(o).item, stories, depth, false); } + if level >= MAX_COPY_DEPTH { + let leaf = |s: &Story| s.objects.is_empty() && s.tables.is_empty() && s.notes.is_empty() && s.endnotes.is_empty(); + return complete + && st.tables.values().all(|t| t.cells.iter().all(|c| leaf(&c.text))) + && st.notes.iter().chain(&st.endnotes).all(|n| leaf(&n.text)); + } for t in st.tables.values_mut() { for c in &mut Arc::make_mut(t).cells { - complete &= renumber_anchored(dst, src, &mut c.text, stories, depth); + complete &= renumber_anchored_in(dst, src, &mut c.text, stories, depth, level + 1); } } for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) { - complete &= renumber_anchored(dst, src, &mut Arc::make_mut(n).text, stories, depth); + complete &= renumber_anchored_in(dst, src, &mut Arc::make_mut(n).text, stories, depth, level + 1); } complete } @@ -5744,6 +5764,48 @@ mod copy_ids_tests { assert_eq!(s.doc().unwrap().doc, before, "nothing is pasted"); } + #[test] + fn objects_anchored_in_cells_nested_too_deeply_are_not_copied() { + use std::sync::Arc; + + // The first cell of the story's table holds `n` tables, each in the first cell of the one before, and the cell + // of the innermost one holds an anchored object. + fn nested(n: usize) -> crate::Session { + let mut s = crate::Session::new(); + let (f, sid) = marked_frame(&mut s); + let leaf = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let item = d.item(designcraft_doc::ItemId(leaf)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != leaf); + let mut chain: Option = None; + for _ in 0..n { + let mut t = designcraft_doc::Table::new(d.alloc(), 1, 1, 0, 0, 40.0); + match chain.take() { + Some(inner) => { + t.cells[0].text.insert_table(0, inner); + } + None => { + t.cells[0].text.insert_object(0, designcraft_doc::AnchoredObject::new(item.clone(), Default::default())); + } + } + chain = Some(t); + } + let st = d.story_mut(sid).unwrap(); + let text = &mut Arc::make_mut(st.tables.values_mut().next().unwrap()).cells[0].text; + text.insert_table(text.len(), chain.unwrap()); + s.execute("selection.set", &json!({"ids": [f]})).unwrap(); + s + } + let mut s = nested(super::MAX_COPY_DEPTH - 1); + s.execute("edit.duplicate", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.anchored_items().len(), 2, "the anchored object is copied"); + let mut s = nested(super::MAX_COPY_DEPTH); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("edit.duplicate", &json!({})).unwrap_err().to_string(); + assert!(e.contains("too deeply to copy"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing is copied"); + } + #[test] fn pasted_cross_references_follow_the_pasted_anchors_of_other_stories() { let mut s = crate::Session::new(); From fc5221060c38df2573f4f6a5c150c9bf9f9a5d1f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 15:59:29 -0500 Subject: [PATCH 232/328] Fix vertical justification test arguments --- crates/compose/src/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index d2f92f2ee..41a734f4c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2660,7 +2660,7 @@ fn vertical_justification_counts_table_fragment_bottoms() { let mut spec = frame_specs(&d, sid).remove(0); spec.opts.vertical_justification = mode; - vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[]); + vertical_justify(&mut ft, &spec, false, &d.footnote_options, &[], &[]); let moved = ft.lines[anchor].baseline - baseline; let limit = ft.notes[0].rect.y0 - d.footnote_options.space_before; From 946e3ea4c19e18693c4fb144ef7b3a5ed02496c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 12:50:29 -0800 Subject: [PATCH 233/328] Compose: grid-aligned vertical justification takes only grid steps that fit a shaped frame In a frame that narrows and widens again, Bottom, Center and Justify now try lower grid steps until the lines fit the outline, and leave the lines in place when none does, instead of taking the next lower step unchecked. A grid whose step is too small to count across the column is now treated as no grid when a line is placed, so the line keeps a finite baseline. Tests cover a waist-shaped frame on a 40 pt grid, a tiny-step grid that starts away from the line, and Justify with a wrapped paragraph under All Lines and First Line Only. --- crates/compose/src/lib.rs | 20 ++++++++--- crates/compose/src/tests.rs | 70 +++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b83f479fe..9a11229c4 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1858,8 +1858,14 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { if cur.last_baseline.is_some() { baseline += cur.last_reference - reference; } - let grid = f.grid.filter(|&(_, inc)| { - inc > 0.0 && inc.is_finite() && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) + // A step so small that the column holds more steps than an f64 can count is no grid: the + // line is placed as it is without one. + let countable = |g_start: f64, inc: f64| [baseline, col.y0, col.y1].iter().all(|y| ((y - g_start) / inc).is_finite()); + let grid = f.grid.filter(|&(g_start, inc)| { + inc > 0.0 + && inc.is_finite() + && countable(g_start, inc) + && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0)) }); if let Some((g_start, inc)) = grid { let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI); @@ -6152,8 +6158,14 @@ fn vertical_justify( let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); // Bottom and Justify take the lowest grid line, Center the one nearest the middle. let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; - if steps > 0.0 && !fits(&shifts(steps * unit)) { - steps -= 1.0; + // A shaped frame can narrow and widen again, so a lower step may not fit either: take + // the nearest step that fits, and leave the lines in place when none of the next + // `MAX_GRID_TRIES` does. + const MAX_GRID_TRIES: usize = 512; + let mut tries = 0; + while steps > 0.0 && !fits(&shifts(steps * unit)) { + tries += 1; + steps = if tries < MAX_GRID_TRIES { steps - 1.0 } else { 0.0 }; } // With no step taken the lines stay put, even when Center's doubled step overflows. shifts(if steps > 0.0 { steps * unit } else { 0.0 }) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 41a734f4c..ab8f56837 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2799,6 +2799,25 @@ fn vertical_justification_keeps_grid_aligned_lines_on_the_grid() { let (_, first_only, _) = compose_with(Bottom, GridAlign::FirstLineOnly); assert!(first_only.iter().all(|&b| on_grid(b, grid)), "Bottom, first lines only: {first_only:?}"); + // Justify with a paragraph that wraps: with all lines aligned the last line lands on the grid; + // with first lines only it is not a first line, so it goes down to the bottom inset. + let wrapped = "The first line of this paragraph sits on the baseline grid, and the lines after it keep the leading they have."; + let justify_wrapped = |align: GridAlign| { + let (lines, _) = grid_doc(wrapped, ParaAttrs { grid_align: Some(align), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options.vertical_justification = Justify; + }); + lines.iter().map(|l| l.baseline).collect::>() + }; + let all = justify_wrapped(GridAlign::AllLines); + assert!(all.len() >= 2, "the paragraph wraps: {all:?}"); + let last = all[all.len() - 1]; + assert!(on_grid(last, grid) && last <= area.y1 + 1e-6 && last > area.y1 - inc, "Justify, all lines: last baseline {last}"); + let first_lines = justify_wrapped(GridAlign::FirstLineOnly); + assert!(first_lines.len() >= 2, "the paragraph wraps: {first_lines:?}"); + let last = first_lines[first_lines.len() - 1]; + assert!((last - area.y1).abs() < 1e-6 && !on_grid(last, grid), "Justify, first lines only: last baseline {last}, inset at {}", area.y1); + // Without grid alignment the last baseline goes down to the bottom inset. let (_, free, _) = compose_with(Bottom, GridAlign::None); assert!((free[2] - area.y1).abs() < 1e-6, "Bottom without the grid: {free:?}"); @@ -2839,6 +2858,57 @@ fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { // A step far larger than the room: the line does not move. let (_, b) = compose_with(Center, 1e308); assert!((b - natural).abs() < 1e-6, "Center with a huge increment: baseline {b}, natural {natural}"); + + // A grid that starts away from the line, with a step too small to count the distance: the line + // is placed as it is without a grid. + for mode in [Top, Bottom, Center, Justify] { + let mut area = Rect::ZERO; + let (lines, _) = grid_doc("One", ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }, |d, sid| { + let spec = frame_specs(d, sid).remove(0); + area = spec.area; + let opts = &mut d.item_mut(spec.id).unwrap().text_frame_mut().unwrap().options; + opts.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(start - 5.0, 1e-310)); + opts.vertical_justification = mode; + }); + let b = lines[0].baseline; + assert!(b.is_finite() && b >= natural - 1e-6 && b <= area.y1 + 1e-6, "{mode:?}, grid away from the line: baseline {b}, text area {area:?}"); + if mode == Top { + assert!((b - natural).abs() < 1e-6, "Top, grid away from the line: baseline {b}, natural {natural}"); + } + } +} + +/// In a shaped frame that narrows and widens again, Bottom with Align to Baseline Grid takes the +/// lowest grid step at which the line's slot fits the outline, even when the grid steps next to +/// the lowest room all fall in the narrow part. +#[test] +fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { + use designcraft_doc::GridAlign; + use designcraft_doc::VerticalJustification::Bottom; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a + // point at 300 pt. + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; + let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 40.0)); + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let top = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[0].baseline; + assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = Bottom; + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + let (b, band_top) = (l.baseline, l.baseline - l.ascent); + assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); + let upper = b <= 100.0 + 1e-6; + let lower = band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + assert!(upper || lower, "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); } /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top From fb77a73d93bcd7cdabd1ac78f306b8e9ae21f257 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 13:04:14 -0800 Subject: [PATCH 234/328] Compose: Center on the grid takes the fitting step nearest the middle in a shaped frame When the grid step nearest the centered place puts the lines outside a frame that narrows and widens again, Center now tries the steps on both sides of it, nearest first, instead of only the steps above it. --- crates/compose/src/lib.rs | 27 +++++++++++++------ crates/compose/src/tests.rs | 52 +++++++++++++++++++++++-------------- 2 files changed, 51 insertions(+), 28 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9a11229c4..9c423cec0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6157,15 +6157,26 @@ fn vertical_justify( // The last baseline stays above the bottom of the text, and the rows above it fit. let most = (space / inc + 1e-9).floor().min((room / unit + 1e-9).floor()).max(0.0); // Bottom and Justify take the lowest grid line, Center the one nearest the middle. - let mut steps = if center { (space / 2.0 / inc).round().min(most) } else { most }; - // A shaped frame can narrow and widen again, so a lower step may not fit either: take - // the nearest step that fits, and leave the lines in place when none of the next - // `MAX_GRID_TRIES` does. + let target = if center { (space / 2.0 / inc).round().min(most) } else { most }; + // A shaped frame can narrow and widen again, so the target step may not fit: take + // the fitting step nearest it, up to `most` (the lower one on a tie, and no step + // when that is as near), and leave the lines in place when none within + // `MAX_GRID_TRIES` steps of it fits. const MAX_GRID_TRIES: usize = 512; - let mut tries = 0; - while steps > 0.0 && !fits(&shifts(steps * unit)) { - tries += 1; - steps = if tries < MAX_GRID_TRIES { steps - 1.0 } else { 0.0 }; + let mut steps = 0.0; + for d in 0..MAX_GRID_TRIES { + let (below, above) = (target - d as f64, target + d as f64); + if below <= 0.0 { + break; + } + if fits(&shifts(below * unit)) { + steps = below; + break; + } + if d > 0 && above <= most && fits(&shifts(above * unit)) { + steps = above; + break; + } } // With no step taken the lines stay put, even when Center's doubled step overflows. shifts(if steps > 0.0 { steps * unit } else { 0.0 }) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ab8f56837..59777d657 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -2878,37 +2878,49 @@ fn vertical_justification_with_an_extreme_grid_increment_stays_finite() { } } -/// In a shaped frame that narrows and widens again, Bottom with Align to Baseline Grid takes the -/// lowest grid step at which the line's slot fits the outline, even when the grid steps next to -/// the lowest room all fall in the narrow part. +/// In a shaped frame that narrows and widens again, Align to Baseline Grid takes the grid step +/// nearest the place Bottom or Center would choose at which the line's slot fits the outline: +/// Bottom goes up past steps in the narrow part, and Center goes down a step when the step nearest +/// the middle is in the narrow part and the next one fits. #[test] fn vertical_justification_on_the_grid_skips_steps_that_leave_a_shaped_frame() { use designcraft_doc::GridAlign; - use designcraft_doc::VerticalJustification::Bottom; + use designcraft_doc::VerticalJustification::{self, Bottom, Center, Top}; use designcraft_geom::{Anchor, PathData, Point, SubPath}; // Full width down to 100 pt, a waist at 150 pt, full width again from 200 to 230 pt, then a // point at 300 pt. let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 100.0), (200.0, 150.0), (300.0, 200.0), (300.0, 230.0), (150.0, 300.0)]; let pts: Vec<(f64, f64)> = pts.iter().copied().chain([(0.0, 230.0), (0.0, 200.0), (100.0, 150.0), (0.0, 100.0)]).collect(); - let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; - let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); - let it = d.item_mut(fid).unwrap(); - it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); - let o = &mut it.text_frame_mut().unwrap().options; - o.inset = [0.0; 4]; - o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, 40.0)); - let grid = frame_specs(&d, sid)[0].grid.unwrap(); - let top = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[0].baseline; + let compose_with = |mode: VerticalJustification, inc: f64| { + let para = ParaAttrs { grid_align: Some(GridAlign::AllLines), ..Default::default() }; + let (mut d, sid, fid) = doc_with("Typography", Rect::new(0.0, 0.0, 300.0, 300.0), para); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.inset = [0.0; 4]; + o.baseline_grid = Some(designcraft_doc::FrameBaselineGrid::new(0.0, inc)); + o.vertical_justification = mode; + let grid = frame_specs(&d, sid)[0].grid.unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let l = all_lines(&cs)[0]; + (grid, l.baseline, l.baseline - l.ascent) + }; + let lower = |b: f64, band_top: f64| band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; + + // A 40 pt grid: the lowest room ends between 160 and 200 pt, and the steps above it down to + // 120 pt put the line in the waist. + let (grid, top, _) = compose_with(Top, 40.0); assert!(on_grid(top, grid), "Top: baseline {top} on the grid {grid:?}"); - d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = Bottom; - let cs = compose_story(&d, sid, &ComposeOptions::default()); - let l = all_lines(&cs)[0]; - let (b, band_top) = (l.baseline, l.baseline - l.ascent); + let (_, b, band_top) = compose_with(Bottom, 40.0); assert!(on_grid(b, grid), "Bottom: baseline {b} on the grid {grid:?}"); - let upper = b <= 100.0 + 1e-6; - let lower = band_top >= 200.0 - 1e-6 && b <= 230.0 + 1e-6; - assert!(upper || lower, "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); + assert!(b <= 100.0 + 1e-6 || lower(b, band_top), "Bottom: the line's band {band_top}..{b} reaches into the narrow part"); assert!(b > top, "Bottom moves the line down a grid step that fits: {b}, Top at {top}"); + + // A 45 pt grid: the step nearest the middle puts the baseline at 180 pt, in the waist; the + // step below it fits in the lower full-width part. + let (grid, b, band_top) = compose_with(Center, 45.0); + assert!(on_grid(b, grid), "Center: baseline {b} on the grid {grid:?}"); + assert!(lower(b, band_top), "Center: the line's band {band_top}..{b} is not in the lower full-width part"); } /// A corner radius leaves a Cap Height first line where it sits in a rectangular frame, with Top From 5931b17bb6e78c2fd8e47e7569a6366ee35a2663 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:22:26 -0500 Subject: [PATCH 235/328] Translate duplicate layer in remaining locales --- crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/hu.rs | 1 + crates/ui-egui/src/i18n/sv.rs | 1 + 3 files changed, 3 insertions(+) diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 685591a96..91ad54dd1 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -212,6 +212,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("New Hyperlink", "Nouvel hyperlien"), ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"), ("New Layer", "Nouveau calque"), + ("Duplicate Layer \"{name}\"", "Dupliquer le calque « {name} »"), ("New Page Reference", "Nouvelle référence de page"), ("New Parent", "Nouveau gabarit"), ("Export Layouts and Versions…", "Exporter les mises en page et versions…"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index fd9057213..f0e1e28c0 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -865,6 +865,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Last Page", "Utolsó oldal"), ("Last Spread", "Utolsó oldalpár"), ("Layer Options…", "Réteg beállításai…"), + ("Duplicate Layer \"{name}\"", "„{name}” réteg duplikálása"), ("Layers", "Rétegek"), ("Layout", "Elrendezés"), ("Layout/Index", "Elrendezés/Tárgymutató"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index bc826031d..f835146cc 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -2177,6 +2177,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Color Group Options…", "Alternativ för färggrupp…"), ("Layer Options", "Lageralternativ"), ("Layer Options for \"{name}\"…", "Lageralternativ för \"{name}\"…"), + ("Duplicate Layer \"{name}\"", "Duplicera lagret ”{name}”"), ("Swatch Name:", "Färgrutenamn:"), ("Name with Color Value", "Namn med färgvärde"), ("Color Type:", "Färgtyp:"), From 9847f972da194e4c7ab05ad0ec42e6577e9a17dc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:27:52 -0500 Subject: [PATCH 236/328] Update recovery test for explicit write conflict --- crates/engine/src/recovery/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/recovery/tests.rs b/crates/engine/src/recovery/tests.rs index 8d28dc8a9..ab967f4ff 100644 --- a/crates/engine/src/recovery/tests.rs +++ b/crates/engine/src/recovery/tests.rs @@ -394,8 +394,8 @@ fn no_other_sessions_write_of_the_uid_is_queued_during_a_write_now() { other.recovery_dir = Some(dir.path().to_path_buf()); other.docs[0].uid = uid; let now = worker::write_now(dir.path(), uid, writing.recovery_owner.0).expect("nothing else is in flight"); - let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); - assert_eq!(queued["queued"], 0, "another session's write was queued during the write now: {queued}"); + let err = other.execute("file.recovery.save", &json!({"background": true})).unwrap_err(); + assert!(err.to_string().contains("another session"), "{err}"); assert!(worker::write_now(dir.path(), uid, other.recovery_owner.0).is_none(), "a second write now of the uid started"); drop(now); let queued = other.execute("file.recovery.save", &json!({"background": true})).unwrap(); From 2b6fb6fa061d9b954f87a07bc14d83d0c324917b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:56:44 -0800 Subject: [PATCH 237/328] Images: count a decode's buffers at their peak before decoding in parallel The gate that limits parallel decodes counted each image at its cached size (4 bytes a pixel and a third more for the smaller levels). A decode holds more than that while it converts the pixels: an 8-bit image keeps its RGBA copy beside the decoded or the premultiplied pixels, 8 bytes a pixel. Two 5,500 pixel square images passed the gate together and could hold more than half the cache budget at once. - decode_sizes returns the cached size and the peak size from one size read. The peak counts the samples as stored beside their converted copy (designcraft_images::decode_bytes_per_pixel): 8 bytes a pixel for 8-bit color, 10 for 16-bit RGB, 12 for 16-bit CMYK TIFFs and 16-bit RGBA, 10 for 8-bit CMYKA TIFFs, 15 for 16-bit CMYKA TIFFs, 9 for PSDs. An EPS counts as its TIFF preview. PDF pages, SVGs and EPS files without a preview count 8. - warm budgets the cache with the cached size and gates decodes with the peak size. - Every warm call in the process shares one gate, so the canvas worker, thumbnails and exports together stay within half the budget while they decode. warm returns the most its own call had decoding. - An EPS without a preview is sized at the larger of its drawn PostScript and its placeholder. The placeholder is clamped to 4000 pixels on each side, so a 10,000 by 4,000 point EPS that is not drawn takes 4000 by 4000 pixels, not the 4000 by 1600 counted before. --- crates/images/src/eps.rs | 2 +- crates/images/src/lib.rs | 33 +++++++++ crates/images/src/tests.rs | 26 ++++++++ crates/render/src/decode.rs | 32 +++++++-- crates/render/src/images.rs | 129 ++++++++++++++++++++++++++++-------- crates/render/src/tests.rs | 8 +++ 6 files changed, 197 insertions(+), 33 deletions(-) diff --git a/crates/images/src/eps.rs b/crates/images/src/eps.rs index bd2498f1a..1f209ccf0 100644 --- a/crates/images/src/eps.rs +++ b/crates/images/src/eps.rs @@ -98,7 +98,7 @@ pub fn eps_size(bytes: &[u8]) -> Option<(f64, f64)> { ((0.001..=20_000.0).contains(&w) && (0.001..=20_000.0).contains(&h)).then_some((w, h)) } -fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { +pub(crate) fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { let (_, tiff) = sections(bytes); let tiff = tiff?; let (w, h) = crate::pixel_size(tiff)?; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 081af6c2b..820f9a8b4 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -442,6 +442,39 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied +/// copy of its result: the samples as stored beside the copy they are converted to, and at least +/// 8 (the RGBA result and its premultiplied copy). 16-bit CMYK TIFF samples are narrowed into an +/// 8-bit copy and CMYK alpha is split off into one, so a 16-bit CMYKA TIFF counts 15. An EPS +/// counts as its TIFF preview, or 8 for its placeholder or drawn PostScript. +pub fn decode_bytes_per_pixel(bytes: &[u8]) -> usize { + if is_eps(bytes) { + return eps::preview(bytes).map_or(8, |(tiff, _)| if is_eps(tiff) { 8 } else { decode_bytes_per_pixel(tiff) }); + } + if is_psd(bytes) { + // RGBA-sized channels, an alpha plane, and the RGBA copy of CMYK inks. + return 9; + } + if let Some(mut d) = tiff_decoder(bytes) { + let cmyk = match d.colortype() { + Ok(tiff::ColorType::CMYK(bits)) => Some((4, bits)), + Ok(tiff::ColorType::CMYKA(bits)) => Some((5, bits)), + _ => None, + }; + if let Some((samples, bits)) = cmyk { + let stored = samples * usize::from(bits).div_ceil(8); + let copy = if bits > 8 || samples == 5 { samples } else { 0 }; + return (stored + copy).max(samples + 4).max(8); + } + } + let sample = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .map_or(4, |d| usize::from(image::ImageDecoder::color_type(&d).bytes_per_pixel())); + (sample + 4).max(8) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index cd577f09a..0d8e65ab2 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -372,6 +372,32 @@ fn cmyk_tiff_keeps_inks() { assert_eq!(decode_cmyk_tiff(&b[..b.len() / 2]), None, "truncated"); } +/// A decode holds the samples as stored beside the copy they are converted to. +#[test] +fn decode_bytes_per_pixel_counts_the_stored_samples_and_their_copy() { + use tiff::encoder::colortype::{CMYK8, CMYK16, CMYKA8, RGB16}; + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 8); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 5], true)), 10); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 12); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 3], false)), 10); + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + assert_eq!(decode_bytes_per_pixel(&psd), 9); + assert_eq!(decode_bytes_per_pixel(b"not an image"), 8); + // An EPS counts as its TIFF preview, or 8 without one. + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\nnewpath\n%%EOF\n"; + assert_eq!(decode_bytes_per_pixel(ps), 8); + let preview = tiff_of::(1, 1, &[0; 4], false); + let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; + for v in [30, ps.len(), 0, 0, 30 + ps.len(), preview.len()] { + dos.extend((v as u32).to_le_bytes()); + } + dos.extend([0xFF, 0xFF]); + dos.extend_from_slice(ps); + dos.extend_from_slice(&preview); + assert_eq!(decode_bytes_per_pixel(&dos), 12); +} + /// Indexed colour (PhotometricInterpretation 3), which the `tiff` encoder has no type for. struct Palette; impl tiff::encoder::colortype::ColorType for Palette { diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 5668a205f..dfaed5c55 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -12,18 +12,39 @@ const VECTOR_SIDE: u32 = 3000; /// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third /// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a /// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is -/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +/// drawn) or at its placeholder's size when that is larger, other images and previews at their +/// pixel size. 0 when the size can't be read. +#[cfg(test)] pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).0 +} + +/// [`decoded_bytes`] of `bytes`, and about how many bytes [`decode_pixmap_page`] of it holds at +/// once while it runs: a raster as decoded and its RGBA copy, or that copy and the premultiplied +/// pixels, whichever is more ([`designcraft_images::decode_bytes_per_pixel`]: 8 bytes a pixel +/// for 8-bit color, 12 for 16-bit RGBA, an EPS as its TIFF preview). PDF pages, SVGs and EPS +/// files without a preview count 8 bytes a pixel. Both are 0 when the size can't be read. +pub(crate) fn decode_sizes(bytes: &[u8], page: u32) -> (usize, usize) { + let Some((w, h)) = drawn_size(bytes, page) else { return (0, 0) }; + let raster = !is_pdf(bytes) && !designcraft_images::is_svg(bytes); + let per_pixel = if raster { designcraft_images::decode_bytes_per_pixel(bytes) } else { 8 } as f64; + ((w * h * 16.0 / 3.0) as usize, (w * h * per_pixel) as usize) +} + +/// The pixel size [`decode_pixmap_page`] of `bytes` draws at, as [`decoded_bytes`] describes it. +fn drawn_size(bytes: &[u8], page: u32) -> Option<(f64, f64)> { let drawn = |(w, h): (f64, f64), side: f64, most: f64| { let k = (side / w.max(h).max(1e-3)).min(most); ((w * k).round().max(1.0), (h * k).round().max(1.0)) }; - let size = if designcraft_images::is_eps(bytes) { + if designcraft_images::is_eps(bytes) { image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { - // Without a preview, the pixel size is the 2 pixels per point placeholder's. + // Without a preview, the pixel size is the 2 pixels per point placeholder's. The + // PostScript may be drawn instead, at another size: count the larger of the two. let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); let px = (pw as f64, ph as f64); - if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + let rendered = drawn((w, h), 4000.0, 8.0); + if px == placeholder && rendered.0 * rendered.1 > px.0 * px.1 { rendered } else { px } }) } else if is_pdf(bytes) { // As render_pdf_page scales: at most 8 times the page size. @@ -32,8 +53,7 @@ pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) } else { image_size(bytes).map(|(w, h)| (w as f64, h as f64)) - }; - size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) + } } /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index ee0d917ba..dca7bcead 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -11,7 +11,7 @@ use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; -use crate::decode::decoded_bytes; +use crate::decode::decode_sizes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -190,18 +190,20 @@ fn admits(in_flight: usize, size: usize) -> bool { in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 } -/// Bytes decoding at once and the most there were, with the signal that some finished. -type Gate = (Mutex<(usize, usize)>, Condvar); +/// Bytes [`warm`] is decoding at once in every render in the process (canvas worker, thumbnails, +/// exports), with the signal that some finished. +static GATE: (Mutex, Condvar) = (Mutex::new(0), Condvar::new()); -/// Takes a finished decode's bytes off its [`Gate`] when dropped. -struct Release<'a>(&'a Gate, usize); +/// Takes a finished decode's bytes off [`GATE`] and off its own call's count when dropped. +struct Release<'a>(&'a AtomicUsize, usize); impl Drop for Release<'_> { fn drop(&mut self) { - let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - g.0 = g.0.saturating_sub(self.1); + self.0.fetch_sub(self.1, Ordering::Relaxed); + let mut g = GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + *g = g.saturating_sub(self.1); drop(g); - self.0.1.notify_all(); + GATE.1.notify_all(); } } @@ -210,8 +212,8 @@ impl Drop for Release<'_> { /// of decoding them one after another. Does nothing when fewer than two images need decoding. /// The images in view that are cached count against the cache budget first; a new image that /// would take the total past what the cache keeps (by its pixel size) is left to the render. -/// Decodes wait while those in flight together would take more than half the budget. Returns -/// the most bytes (estimated) that were decoding at once. +/// Decodes wait while those in flight in every render together would take more than half the +/// budget. Returns the most bytes (estimated) this call had decoding at once. pub(crate) fn warm(wants: Vec) -> usize { let workers = workers(); if workers < 2 { @@ -263,7 +265,7 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -271,29 +273,34 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((size, wanted)); + jobs.push((decoding, wanted)); } if jobs.len() < 2 { return 0; } - // While it converts the pixels, a decode holds buffers of about its size besides the cache: - // a decode waits while those in flight would take it past half the budget (one always runs). - let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); - let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // While it converts the pixels, a decode holds the buffers `decode_sizes` counts: a + // decode waits while those in flight in any render would take it past half the budget (one + // always runs). + let lock = || GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let next = AtomicUsize::new(0); + // This call's bytes decoding, and the most there were. + let (mine, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); std::thread::scope(|s| { for _ in 0..workers.min(jobs.len()) { let work = || { while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { let mut g = lock(); - while !admits(g.0, *size) { - g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + while !admits(*g, *size) { + #[cfg(test)] + waited(job); + g = GATE.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); } - g.0 += size; - g.1 = g.1.max(g.0); + *g = g.saturating_add(*size); + let now = mine.fetch_add(*size, Ordering::Relaxed).saturating_add(*size); + peak.fetch_max(now, Ordering::Relaxed); drop(g); // Released even if the decode panics, so no other decode waits forever. - let _release = Release(&gate, *size); + let _release = Release(&mine, *size); for w in job { let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); } @@ -305,7 +312,19 @@ pub(crate) fn warm(wants: Vec) -> usize { } } }); - gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 + peak.into_inner() +} + +/// The images whose decode waited at [`GATE`] (the address of the encoded bytes), with the +/// signal that one did. +#[cfg(test)] +static WAITED: (Mutex>, Condvar) = (Mutex::new(Vec::new()), Condvar::new()); + +#[cfg(test)] +fn waited(job: &[Want]) { + let id = job.first().map_or(0, |w| Arc::as_ptr(&w.bytes) as usize); + WAITED.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(id); + WAITED.1.notify_all(); } /// Drop every decoded image. @@ -320,6 +339,11 @@ pub fn clear() { #[cfg(test)] mod tests { use super::*; + use crate::decode::decoded_bytes; + + fn decode_peak_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).1 + } #[test] fn failed_assets_are_capped_and_oldest_is_dropped() { @@ -403,21 +427,74 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // Two 6,500 pixel square images fit the budget together, but decoding both at once would // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); - assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + let decoding = decode_peak_bytes(&d, 0); + assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); - assert!(peak >= large, "the large images were decoded ahead"); + assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); assert!(on.len() == 1 && on[0] != me); } } + + #[test] + fn warm_counts_a_decode_at_its_peak() { + // A decode holds the RGBA copy beside the decoded or the premultiplied pixels: two 5,500 + // pixel square images would take less than half the budget cached, but more than half of + // it while both decode, so they decode one at a time. + let (f, g) = (psd(5500), psd(5500)); + let decoding = decode_peak_bytes(&f, 0); + assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); + assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. + let mut deep = Vec::new(); + let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); + img.write_to(&mut std::io::Cursor::new(&mut deep), image::ImageFormat::Png).unwrap(); + assert_eq!(decode_peak_bytes(&deep, 0), 16 * 12); + assert_eq!(decode_peak_bytes(&png(8, 1), 0), 64 * 8); + } + + #[test] + fn warm_waits_for_decodes_in_other_renders() { + // Another render's decodes take half the budget: this render's decodes wait for them. + let (a, b) = (png(8, 17), png(8, 19)); + let ids = [Arc::as_ptr(&a) as usize, Arc::as_ptr(&b) as usize]; + let (since, decoded_since) = (WAITED.0.lock().unwrap().len(), mark()); + let other = BUDGET / 2; + *GATE.0.lock().unwrap() += other; + let done = std::sync::atomic::AtomicBool::new(false); + let (waited, peak) = std::thread::scope(|s| { + let render = s.spawn(|| { + let peak = warm(vec![want(&a), want(&b)]); + let w = WAITED.0.lock().unwrap(); + done.store(true, Ordering::SeqCst); + drop(w); + WAITED.1.notify_all(); + peak + }); + let seen = |w: &Vec| w.iter().skip(since).any(|id| ids.contains(id)); + let mut w = WAITED.0.lock().unwrap(); + while !seen(&w) && !done.load(Ordering::SeqCst) { + w = WAITED.1.wait(w).unwrap(); + } + let waited = seen(&w); + drop(w); + *GATE.0.lock().unwrap() -= other; + GATE.1.notify_all(); + (waited, render.join().unwrap()) + }); + assert!(waited, "decoded beside the other render's decodes"); + assert_eq!((decoders(&a, decoded_since).len(), decoders(&b, decoded_since).len()), (1, 1)); + assert!(peak > 0 && peak <= BUDGET / 2, "{peak} bytes decoding at once"); + } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 5d4f6a048..82e8fc77f 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -792,6 +792,14 @@ fn decode_size_estimates_match_the_decodes() { let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); assert!(decode::decoded_bytes(eps, 0) >= drawn); + // A wide EPS whose PostScript isn't drawn keeps its placeholder, clamped to 4000 pixels on + // each side: it is budgeted at no less than that. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10000 4000\n%%EndComments\n0 0 moveto 10 10 lineto stroke\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + assert_eq!((pm.width(), pm.height()), (4000, 4000)); + let px = pm.width() as usize * pm.height() as usize; + assert!(decode::decoded_bytes(eps, 0) >= px * 16 / 3); + assert!(decode::decode_sizes(eps, 0).1 >= px * 8); } #[test] From 6bb9907de5df77d3532dfbfeb639084bf75f7aef Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 16:54:46 -0500 Subject: [PATCH 238/328] Use shared French duplicate layer translation --- crates/ui-egui/src/i18n/fr.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index bbe23824f..8a7c537ce 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -212,7 +212,6 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("New Hyperlink", "Nouvel hyperlien"), ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"), ("New Layer", "Nouveau calque"), - ("Duplicate Layer \"{name}\"", "Dupliquer le calque « {name} »"), ("New Page Reference", "Nouvelle référence de page"), ("New Parent", "Nouveau gabarit"), ("Export Layouts and Versions…", "Exporter les mises en page et versions…"), From 2794a60bf079b15f7285101f3fcce423d0876af4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:21:20 -0500 Subject: [PATCH 239/328] Account for image decode buffers in warm gate --- crates/render/src/images.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index f9f82ac31..8ae0691c7 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -250,9 +250,9 @@ pub(crate) fn warm(wants: Vec) -> usize { *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); } } - let in_view = held.values().sum::(); // Smaller levels alone don't make an asset cached. held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + let in_view = held.values().sum::(); for k in index.keys() { if c.bad.contains_key(k) { held.entry(*k).or_default(); @@ -278,7 +278,9 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((decoding, wanted)); + // The estimate covers the decoded image and its converted pixels; leave headroom for + // temporary buffers inside individual format decoders. + jobs.push((decoding.saturating_mul(3) / 2, wanted)); } if jobs.len() < 2 { return 0; From 9595f3d62e62963df4e3118b24c3b0df8a523601 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:23:50 -0800 Subject: [PATCH 240/328] Anchored text frames: test nested hosts in groups, footnotes and table cells (#2722) Adds three tests for a text frame anchored inside another anchored text frame: the outer frame as a member of an anchored group with a rotation and a scale, the inner frame in a footnote of the outer frame, and the inner frame in a table cell of the outer frame. Each checks the inner frame's spread, transform and page. --- crates/compose/src/tests.rs | 120 ++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 59777d657..3c182f871 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -9622,6 +9622,126 @@ fn a_frame_anchored_in_an_anchored_frame_is_placed_through_both_hosts() { assert_eq!(Cache::new().get(&d, isid, None).frames.len(), 1); } +/// An unplaced `w` × `h` text frame showing a new story of `text`, ready to anchor. +fn anchored_text_frame(d: &mut Document, text: &str, w: f64, h: f64) -> (designcraft_doc::Item, StoryId) { + let lid = d.default_layer(); + let (fid, fsid) = (ItemId(d.alloc()), StoryId(d.alloc())); + let mut story = Story::with_text(fsid, text, ParaFormat::default()); + story.frames.push(fid); + d.stories.insert(fsid, Arc::new(story)); + let mut it = + designcraft_doc::Item::new(fid, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, w, h))); + it.content = Content::Text(designcraft_doc::TextFrame { story: fsid, options: Default::default() }); + (it, fsid) +} + +/// A one-page document whose body frame holds `outer` anchored before its second line. Returns +/// the body frame and the body story's composition. +fn body_holding(d: &mut Document, outer: designcraft_doc::Item) -> (ItemId, ComposedStory) { + let lid = d.default_layer(); + let body = "One.\nTwo.\nThree."; + let (bf, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap(); + d.story_mut(sid).unwrap().insert_object(body.find("Two").unwrap(), designcraft_doc::AnchoredObject::new(outer, Default::default())); + (bf, compose_story(d, sid, &ComposeOptions::default())) +} + +/// `isid`'s one frame, `inner`, is placed on page 1 with parent space `want`, and the cache +/// composes it there. +fn assert_placed_on_page_one(d: &Document, isid: StoryId, inner: ItemId, want: Affine) { + let placed = placed::placements(d, isid, &mut |h| Arc::new(compose_story(d, h, &ComposeOptions::default()))); + assert_eq!(placed.len(), 1, "{placed:?}"); + let (id, p) = placed[0]; + assert_eq!((id, p.spread), (inner, SpreadRef::Doc(0))); + let (got, want) = (p.xf.as_coeffs(), want.as_coeffs()); + assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} != {want:?}"); + assert_eq!(frame_specs_placed(d, isid, &placed)[0].page, Some(0)); + assert_eq!(Cache::new().get(d, isid, None).frames.len(), 1); +} + +/// A text frame anchored in an anchored text frame that is a member of an anchored group with a +/// rotation and a scale is placed through the group's transform and the member's own. +#[test] +fn a_frame_anchored_in_a_grouped_anchored_frame_is_placed_through_the_group() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (mut outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 100.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + outer.xf = Affine::translate((12.0, 7.0)); + d.story_mut(osid).unwrap().insert_object("Outer ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let mut g = + designcraft_doc::Item::new(ItemId(d.alloc()), d.default_layer(), designcraft_doc::Shape::Group, designcraft_geom::PathData::default()); + g.content = Content::Group { items: vec![Arc::new(outer)] }; + g.xf = Affine::rotate(0.25) * Affine::scale(1.25); + let (gid, gxf) = (g.id, g.xf); + let (bf, host) = body_holding(&mut d, g); + + let o1 = &host.frame(bf).unwrap().objects[0]; + // The composed group keeps its rotation and scale; its offset puts its box at the object's origin. + let gxf_placed = o1.object.item.xf; + assert_eq!((o1.object.item.id, gxf_placed.as_coeffs()[..4].to_vec()), (gid, gxf.as_coeffs()[..4].to_vec())); + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let o2 = &mid.frame(outer_id).unwrap().objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * gxf_placed + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a footnote of an anchored text frame is placed through the footnote's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_footnote_of_an_anchored_frame_is_placed_through_the_footnote() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 120.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let st = d.story_mut(osid).unwrap(); + st.insert_note("Outer".len(), "Note text", ParaFormat::default()); + Arc::make_mut(&mut st.notes[0]).text.insert_object("Note ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let note = &mid.frame(outer_id).unwrap().notes[0]; + let o2 = ¬e.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(note.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + +/// A text frame anchored in a table cell of an anchored text frame is placed through the cell's +/// spot in that frame as well as both hosts. +#[test] +fn a_frame_anchored_in_a_table_cell_of_an_anchored_frame_is_placed_through_the_cell() { + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let (outer, osid) = anchored_text_frame(&mut d, "Outer text", 200.0, 150.0); + let (inner, isid) = anchored_text_frame(&mut d, "Inner", 80.0, 30.0); + let (outer_id, inner_id) = (outer.id, inner.id); + let mut table = designcraft_doc::Table::new(77, 1, 1, 0, 0, 180.0); + table.cells[0].text.insert(0, "Cell "); + table.cells[0].text.insert_object("Cell ".len(), designcraft_doc::AnchoredObject::new(inner, Default::default())); + let st = d.story_mut(osid).unwrap(); + let end = st.len(); + st.insert_table(end, table); + let (bf, host) = body_holding(&mut d, outer); + + let o1 = &host.frame(bf).unwrap().objects[0]; + let mid = compose_story(&d, osid, &ComposeOptions::default()); + let cell = &mid.frame(outer_id).unwrap().tables[0].cells[0]; + let o2 = &cell.text.frames[0].objects[0]; + let want = d.text_xf(d.item(bf).unwrap()) + * Affine::translate(o1.origin.to_vec2()) + * d.text_xf(d.anchored_item(outer_id).unwrap()) + * Affine::translate(cell.origin.to_vec2()) + * Affine::translate(o2.origin.to_vec2()); + assert_placed_on_page_one(&d, isid, inner_id, want); +} + /// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt /// above its anchor's baseline on a right-hand page. It composes against the document grid where /// it is placed: its first line moves down onto the grid line, the second follows 10 pt below, From c803ea80b10429204dba64baede4be5c2846a0aa Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:24:34 -0800 Subject: [PATCH 241/328] Compose: vertical justification in a shaped frame tests lines to their baselines (#2708) Center, Bottom and Justify tested every moved line except the last against the frame's outline down to its descent, so an outline that narrows under an earlier line held the text higher by that line's descent. Each moved line is now tested from its top down to its baseline, and its descenders may cross the outline, as the last line's already did. Above footnotes and in vertical frames the descenders still stay inside. --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 12 +++++++----- crates/compose/src/tests.rs | 33 ++++++++++++++++++++++++++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index afecef5d3..9e83d73ae 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -395,6 +395,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. +- **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9c423cec0..e2665720e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6066,12 +6066,14 @@ fn vertical_justify( }; // Only the last row's descenders hang below the bottom of the text: an earlier line whose // ink reaches below the last baseline (tight leading) isn't moved past the text area. - // In a shaped frame each moved line's slot stays inside the outline over its new band, as - // when the line was fitted: a frame that narrows towards the bottom holds the text higher. - let in_outline = |l: &Line, last: bool, dy: f64| match &f.outline { + // In a shaped frame each moved line's slot stays inside the outline from its top down to + // its baseline: a frame that narrows towards the bottom holds the text higher. Every moved + // line's descenders may cross the outline, as the last line's do below the bottom of the + // text; above footnotes, and in vertical frames, they stay inside. + let in_outline = |l: &Line, dy: f64| match &f.outline { Some(o) => { let b = l.baseline + dy; - let desc = if last && !inside { 0.0 } else { l.descent.max(0.0) }; + let desc = if inside { l.descent.max(0.0) } else { 0.0 }; let tol = 1e-6; o.intervals(l.x0, l.x1, (b - l.ascent).max(f.area.y0).min(b), b + desc).iter().any(|&(a, z)| a <= l.x0 + tol && z >= l.x1 - tol) } @@ -6095,7 +6097,7 @@ fn vertical_justify( let fits = |shift: &[f64]| { idx.iter().zip(&rows).rev().all(|(&i, &k)| { let l = &ft.lines[i]; - shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, k == n, shift[k])) + shift[k] <= 0.0 || ((k == n || l.baseline + l.descent + shift[k] <= limit + 1e-9) && in_outline(l, shift[k])) }) && clear(shift) }; // In a rectangular frame fit decreases monotonically as the shift grows. A shaped diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 3c182f871..38dad232c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3019,13 +3019,13 @@ fn vertical_justification_keeps_lines_inside_a_shaped_frame() { assert!(lines.len() >= 2, "{mode:?}: {lines:?}"); (spec.area, lines) }; - // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, the last line's - // descenders left out. + // Narrowing downward: |x - 150| <= (300 - y) / 2 over each slot's band, from the line's top to + // its baseline. let down = [Point::new(0.0, 0.0), Point::new(300.0, 0.0), Point::new(150.0, 300.0)]; for mode in [Center, Bottom, Justify] { let (area, lines) = compose_with(down, mode); for (k, l) in lines.iter().enumerate() { - let bottom = if k + 1 == lines.len() { l.baseline } else { l.baseline + l.descent }; + let bottom = l.baseline; let top = (l.baseline - l.ascent).max(area.y0); for (x, y) in [(l.x0, top), (l.x1, top), (l.x0, bottom), (l.x1, bottom)] { assert!((x - 150.0).abs() <= (300.0 - y) / 2.0 + 1e-3, "{mode:?}: line {k} corner ({x}, {y}) outside the triangle: {lines:?}"); @@ -3055,6 +3055,33 @@ fn vertical_justification_keeps_lines_inside_a_shaped_frame() { assert!((last.baseline - 260.0).abs() < 1e-3, "Bottom: last baseline at {}", last.baseline); } +/// In a shaped frame, Center and Bottom move every line until its slot reaches the outline at its +/// baseline: an earlier line's descenders may cross the outline, as the last line's do. A frame +/// full width down to 20 pt and half width below it holds the first line's baseline at 20 pt. +#[test] +fn vertical_justification_lets_earlier_descenders_cross_a_shaped_frame() { + use designcraft_doc::VerticalJustification::{Bottom, Center}; + use designcraft_geom::{Anchor, PathData, Point, SubPath}; + let pts = [(0.0, 0.0), (300.0, 0.0), (300.0, 20.0), (150.0, 20.0), (150.0, 300.0), (0.0, 300.0)]; + for mode in [Center, Bottom] { + let (mut d, sid, fid) = doc_with("Typography\ngypsy", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let it = d.item_mut(fid).unwrap(); + it.path = PathData::single(SubPath { anchors: pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), closed: true }); + let o = &mut it.text_frame_mut().unwrap().options; + o.vertical_justification = mode; + o.inset = [0.0; 4]; + assert!(frame_specs(&d, sid)[0].outline.is_some()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2, "{mode:?}: {lines:?}"); + let (first, last) = (lines[0], lines[1]); + assert!((first.x1 - 300.0).abs() < 1e-6 && (last.x1 - 150.0).abs() < 1e-6, "{mode:?}: slots {lines:?}"); + assert!(first.descent > 1.0, "{mode:?}: {first:?}"); + assert!((first.baseline - 20.0).abs() < 1e-3, "{mode:?}: first baseline at {}, step at 20", first.baseline); + assert!(last.baseline <= 300.0 + 1e-6, "{mode:?}: last baseline at {}", last.baseline); + } +} + /// In a shaped frame with a text wrap under the text, Center, Bottom and Justify keep the lines /// inside the outline and out of the wrap together: in a triangle that widens downward, Bottom and /// Justify put the last baseline on the wrap's top and Center moves half as far; in one that From 6923c220ad3920415efe0e12bd3c59e9295e7b95 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:24:40 -0800 Subject: [PATCH 242/328] Text wrap: Bottom and Center move a line down between a contour's arms (#2719) A line set in the open middle of a U-shaped contour now goes down to the contour's base. The clearance check tests the occupied parts of the contour in the line's band, as line setting does, instead of its outer extent across both arms. --- crates/compose/src/lib.rs | 7 ++++--- crates/compose/src/tests.rs | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e2665720e..a367e7ade 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -6309,9 +6309,10 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u { // A contour beside or under this line whose box reaches the line's slot (the // contour stays inside its box). Moved down by `d`, the line's band sweeps from its - // top to its baseline plus `d`; the contour's extent there only grows with `d`, so - // the furthest clear move is found by bisection to 0.01 pt. - let hits = |d: f64| contour.band_extent(top + dy, bottom + d + dy).and_then(|x| sided(e, col, x)).is_some_and(meets); + // top to its baseline plus `d`; the parts of the contour there only grow with `d`, + // so the furthest clear move is found by bisection to 0.01 pt. As when the line is + // set, the gaps between parts of the contour stay open. + let hits = |d: f64| contour.band_spans(top + dy, bottom + d + dy).into_iter().any(|x| sided(e, col, x).is_some_and(meets)); let (mut lo, mut hi) = ((r.y0 - bottom).max(0.0), (r.y1 - top).min(f.area.y1 - bottom).min(cap)); if lo < hi && hits(hi) { if hits(lo) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 38dad232c..ccc71578d 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -723,6 +723,44 @@ fn vertical_justification_stops_where_a_contour_under_the_text_meets_it() { assert!(b > 122.0, "Bottom stopped the line at {b}, short of where the contour meets the column at 122.5"); } +/// A line set in the open middle of a U-shaped contour goes down between its arms: Bottom stops +/// it on the contour's base, not where the line starts because the arms span its slot. +#[test] +fn vertical_justification_moves_a_line_down_between_the_arms_of_a_contour() { + use designcraft_doc::VerticalJustification::{Bottom, Top}; + // Arms 0..15 and 45..60 from y = 0, joined by a base from y = 170 down to y = 190. + let pts = [ + Point::new(0.0, 0.0), + Point::new(15.0, 0.0), + Point::new(15.0, 170.0), + Point::new(45.0, 170.0), + Point::new(45.0, 0.0), + Point::new(60.0, 0.0), + Point::new(60.0, 190.0), + Point::new(0.0, 190.0), + ]; + let run = |vj| { + let (mut d, sid, fid) = doc_with("42", Rect::new(0.0, 0.0, 60.0, 200.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + let l = all_lines(&cs)[0]; + (l.baseline, l.x0, l.x1) + }; + let (top, x0, x1) = run(Top); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Top sets the line between the arms: {x0}..{x1}"); + let (b, x0, x1) = run(Bottom); + assert!(x0 >= 15.0 - 1e-6 && x1 <= 45.0 + 1e-6, "Bottom keeps the line between the arms: {x0}..{x1}"); + assert!(b <= 170.0 + 1e-6, "Bottom moved the baseline to {b}, into the contour's base at 170"); + assert!(b > 169.9, "Bottom stopped the line at {b} (Top at {top}), short of the contour's base at 170"); +} + /// An object anchored in the text and positioned from its anchor moves down with the lines, so /// Center places lines above it as it places them without its wrap. #[test] From 66b8c8ba3e1b66faf8b48b69647e2e982761a437 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:25:39 -0800 Subject: [PATCH 243/328] Object styles: checks and fixes for corners, strokes and the style dialog (#2721) - Corner options use path order for a path with more than one subpath, so a second rectangle no longer takes the first one's corner order. - IDML export writes EnableStrokeAndCornerOptions="false" for a style without corners, so it does not take corners from its based-on style on import. - style.object.create and style.object.edit refuse a stroke gap tint outside 0 to 1 and a stroke type field that its kind does not take, as object.stroke does. An edit that changes nothing returns restyled: 0. - New Object Style and Object Style Options read a bare number in the document's ruler unit, keep a Text Frame General measurement that was not edited at its exact value, and New Object Style refuses a name another style has. - Clear Overrides in the Object Styles panel is enabled when any selected object differs from its style. --- crates/engine/src/cmd/object.rs | 30 +++--- crates/engine/src/cmd/style.rs | 4 +- crates/engine/src/cmd/style/object.rs | 17 +++- crates/engine/src/tests.rs | 19 +++- crates/geom/src/corners.rs | 10 +- crates/idml/src/export/styles.rs | 2 +- crates/idml/src/tests/object_styles.rs | 14 +++ crates/ui-egui/src/object_style_dialog.rs | 114 +++++++++++++++++++--- crates/ui-egui/src/panels/styles.rs | 58 +++++++++-- 9 files changed, 222 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 03e93a35b..c269e4f1d 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -26,6 +26,22 @@ pub(crate) fn known_swatch(doc: &designcraft_doc::Document, name: &str, cmd: &st Err(bad(cmd, format!("{key}: no swatch named `{name}`{hint}; create one with `swatch.create` and use its returned name"))) } +/// The fields of a stroke `type` object must be `kind` and the one its kind takes (`pattern` for +/// dashed, `bands` for stripes, `name` for style). `kind` is the type's own, else `base_kind`. +pub(crate) fn check_stroke_type_fields(v: &Value, base_kind: Option<&str>, cmd: &str) -> Result<()> { + let Some(fields) = v.as_object() else { return Ok(()) }; + let field = match v.get("kind").and_then(Value::as_str).or(base_kind) { + Some("dashed") => Some("pattern"), + Some("stripes") => Some("bands"), + Some("style") => Some("name"), + _ => None, + }; + match fields.keys().find(|key| *key != "kind" && Some(key.as_str()) != field) { + Some(key) => Err(bad(cmd, format!("type: unknown field `{key}`"))), + None => Ok(()), + } +} + pub fn specs() -> Vec { vec![ cmd!( @@ -265,19 +281,7 @@ pub fn specs() -> Vec { let kind: Option = p .get("type") .map(|v| { - if let Some(fields) = v.as_object() { - let field = match v.get("kind").and_then(Value::as_str) { - Some("dashed") => Some("pattern"), - Some("stripes") => Some("bands"), - Some("style") => Some("name"), - _ => None, - }; - for key in fields.keys() { - if key != "kind" && Some(key.as_str()) != field { - return Err(bad("object.stroke", format!("type: unknown field `{key}`"))); - } - } - } + check_stroke_type_fields(v, None, "object.stroke")?; serde_json::from_value(v.clone()).map_err(|e| bad("object.stroke", format!("type: {e}"))) }) .transpose()?; diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 7e55e0529..0b592786c 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -182,7 +182,7 @@ pub fn specs() -> Vec { "New Object Style…", [], None, - "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", + "{name, fromSelection?: true (fill, stroke, corners, effects and text frame options of the first selected item), fill?: swatch | {swatch?, tint?}, stroke?: {swatch?, weight?, tint?, type?, …} (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?, size?} | {corners: [{shape, size}] ×4}, paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?}, dropShadow?: {on?, color?, opacity? (0–1), angle?, globalLight?, distance?, size?, spread?}, feather?: width, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} → {name} (made unique)", has_doc, create_object ), @@ -191,7 +191,7 @@ pub fn specs() -> Vec { "Object Style Options…", [], None, - "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; unknown fill and stroke keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", + "{name, rename?: new name (every use follows), fill?: swatch | {swatch?, tint?} | null, stroke?: {swatch?, weight?, tint?, type?, …} | null (swatches must exist; tint and gapTint 0–1; unknown fill, stroke and stroke type keys are refused), corners?: {shape?: none|rounded|inverseRounded|inset|bevel|fancy, size?} | {corners: [{shape, size}] ×4} | null (null: the style no longer sets it; items keep theirs), paragraphStyle?: a paragraph style (null: none; the text of a frame the style is applied to takes it), applyNextStyle?: bool (each paragraph after the first takes the Next Style of the one before), textFrame?: {columns? (1–40), columnsKind?, gutter?, columnWidth?, balanceColumns?, inset?: [top, left, bottom, right] | one number for all four, verticalJustification?: top|center|bottom|justify, vjParagraphSpacingLimit?, ignoreWrap?} | null (Text Frame General Options, named as `document.inspect` names text frame options; lengths 0–15552 pt; other keys are refused; a frame keeps its baseline, auto-size and column rule settings; null: the style sets none), effects?: {…} | null (the style no longer sets effects), dropShadow?, feather?, innerShadow?, outerGlow?, innerGlow?, bevel?, satin?, gradientFeather?, directionalFeather?} — effect objects merge field by field into the style's effects (fields as in `document.inspect` item effects); values that aren't finite numbers are refused, the others clamped (opacities 0–1, sizes and distances ≥ 0); items using the style whose effects (fill, stroke, corners) match the style's (an item's defaults, when the style set none) take the new ones, items with their own keep them; the text of frames still in the old paragraph styles takes the new ones → {name, updated, restyled}", has_doc, edit_object ), diff --git a/crates/engine/src/cmd/style/object.rs b/crates/engine/src/cmd/style/object.rs index a8572a3fa..630eaf117 100644 --- a/crates/engine/src/cmd/style/object.rs +++ b/crates/engine/src/cmd/style/object.rs @@ -243,11 +243,17 @@ fn bool_param(cmd: &str, p: &Value, key: &str) -> Result> { } } -/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0 -/// or the tint isn't 0–1. +/// `p.stroke` merged over `base` (as [`group_param`]), refused when the weight isn't a number ≥ 0, +/// the tint or gap tint isn't 0–1, or the type has a field its kind doesn't take. fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> Result>> { let optional = ["gapOverprint", "gradientAngle", "gradientVector"]; - let st = group_param(cmd, p, "stroke", base.unwrap_or(&designcraft_doc::Stroke::default()), &optional)?; + let base = base.cloned().unwrap_or_default(); + // A type without `kind` keeps the style's kind, so it takes that kind's fields. + if let Some(t) = p.get("stroke").and_then(|s| s.get("type")) { + let base_kind = serde_json::to_value(&base.kind).ok().and_then(|k| k.get("kind").and_then(Value::as_str).map(str::to_string)); + crate::cmd::object::check_stroke_type_fields(t, base_kind.as_deref(), cmd)?; + } + let st = group_param(cmd, p, "stroke", &base, &optional)?; if let Some(Some(st)) = &st { if !(st.weight.is_finite() && st.weight >= 0.0) { return Err(bad(cmd, "stroke weight must be a number ≥ 0")); @@ -255,6 +261,9 @@ fn stroke_param(cmd: &str, p: &Value, base: Option<&designcraft_doc::Stroke>) -> if !(0.0..=1.0).contains(&st.tint) { return Err(bad(cmd, "stroke tint must be 0..1")); } + if !(0.0..=1.0).contains(&st.gap_tint) { + return Err(bad(cmd, "stroke gap tint must be 0..1")); + } } Ok(st) } @@ -382,7 +391,7 @@ pub(super) fn edit_object(s: &mut Session, p: &Value) -> Result { new.name = r.clone(); } if new == old { - return Ok(json!({"name": name, "updated": 0})); + return Ok(json!({"name": name, "updated": 0, "restyled": 0})); } s.edit(|d, _| { let Some(os) = d.styles_mut().object.iter_mut().find(|o| o.name == name) else { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index afbd25e73..10b42ee68 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -752,8 +752,9 @@ fn object_style_effects_follow_the_style_until_overridden() { assert_eq!(s.doc().unwrap().revision, rev); } -/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting, a word or null -/// for a switch, a rename that isn't a name and a corner size outside 0–10000 pt. +/// `style.object.create` and `edit` refuse an unknown swatch, a misspelled setting (a stroke type's +/// included), a word or null for a switch, a rename that isn't a name, a corner size outside +/// 0–10000 pt and a stroke gap tint outside 0–1. #[test] fn object_style_parameters_are_checked() { let mut s = session(); @@ -768,6 +769,11 @@ fn object_style_parameters_are_checked() { json!({"corners": {"size": -1}}), json!({"corners": {"size": 10_001}}), json!({"applyNextStyle": null}), + json!({"stroke": {"gapTint": -1}}), + json!({"stroke": {"gapTint": 1.5}}), + json!({"stroke": {"type": {"kind": "dashed", "pattern": [2, 2], "patern": [4, 4]}}}), + json!({"stroke": {"type": {"kind": "solid", "pattern": [2, 2]}}}), + json!({"stroke": {"type": {"bands": [[0, 0.5]]}}}), ] { let mut p = bad.clone(); p["name"] = json!("Framed"); @@ -787,6 +793,15 @@ fn object_style_parameters_are_checked() { assert!(!names.iter().any(|n| n == "Other" || n == "Odd"), "{names:?}"); } +/// An edit that leaves the style as it is answers with the same fields as one that changes it. +#[test] +fn an_object_style_edit_that_changes_nothing_reports_no_restyled_frames() { + let mut s = session(); + s.execute("style.object.create", &json!({"name": "Framed", "fromSelection": false})).unwrap(); + let r = s.execute("style.object.edit", &json!({"name": "Framed"})).unwrap(); + assert_eq!((r["name"].as_str(), r["updated"].as_u64(), r["restyled"].as_u64()), (Some("Framed"), Some(0), Some(0)), "{r}"); +} + /// The course's "Rounded Corner Image, White Stroke" style: made from a frame with rounded corners /// and a paper stroke, applied to another frame, then edited (a thicker stroke, bigger corners): /// the frames that follow the style change, one with its own stroke keeps it; a rename follows. diff --git a/crates/geom/src/corners.rs b/crates/geom/src/corners.rs index 9c1bfbb00..10db62fd4 100644 --- a/crates/geom/src/corners.rs +++ b/crates/geom/src/corners.rs @@ -60,7 +60,7 @@ pub struct CornerOptions { /// anchors at four different corners keeps a rectangle's order. pub fn named_slots(path: &PathData) -> [usize; 4] { let rect_order = [0, 1, 2, 3]; - let Some(sp) = path.subpaths.first() else { return rect_order }; + let [sp] = path.subpaths.as_slice() else { return rect_order }; let Some(b) = path.bounds() else { return rect_order }; if sp.anchors.len() != 4 { return rect_order; @@ -317,6 +317,14 @@ mod tests { assert_eq!(named.named_to_path(&rectangle(Rect::new(0.0, 0.0, 10.0, 10.0))), named); let tri = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(5.0, 9.0)], true)); assert_eq!(named.named_to_path(&tri), named); + // A path of two rectangles keeps the order: one subpath's order can't name the other's + // anchors. + let two = PathData::new(vec![ + SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0), Point::new(100.0, 0.0)], true), + SubPath::polyline(&[Point::new(40.0, 40.0), Point::new(60.0, 40.0), Point::new(60.0, 60.0), Point::new(40.0, 60.0)], true), + ]); + assert_eq!(named_slots(&two), [0, 1, 2, 3]); + assert_eq!(named.named_to_path(&two), named); } #[test] diff --git a/crates/idml/src/export/styles.rs b/crates/idml/src/export/styles.rs index d131dc19d..b5dc46cff 100644 --- a/crates/idml/src/export/styles.rs +++ b/crates/idml/src/export/styles.rs @@ -121,8 +121,8 @@ impl<'a> Ex<'a> { el.set("EnableStroke", bool_s(os.stroke.is_some())); el.set("EnableParagraphStyle", bool_s(os.paragraph_style.is_some())); el.set("EnableTextFrameGeneralOptions", bool_s(os.text_frame.is_some())); + el.set("EnableStrokeAndCornerOptions", bool_s(os.corners.is_some())); if let Some(c) = &os.corners { - el.set("EnableStrokeAndCornerOptions", "true"); for (n, c) in ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].iter().zip(c.corners) { el.set(&format!("{n}CornerOption"), names::corner_out(c.shape)); el.set(&format!("{n}CornerRadius"), num(c.size)); diff --git a/crates/idml/src/tests/object_styles.rs b/crates/idml/src/tests/object_styles.rs index 52cfd3e20..719936f40 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -177,6 +177,20 @@ fn object_style_apply_next_style_round_trips() { } } +/// A style that sets no corners keeps none after export and import, though the style it is based +/// on sets rounded corners. +#[test] +fn a_style_without_corners_keeps_none_over_its_based_on_style() { + let mut d = small_doc(); + let rounded = Some(designcraft_geom::corners::CornerOptions::uniform(CornerShape::Rounded, 12.0)); + let styles = std::sync::Arc::make_mut(&mut d.styles); + styles.object.push(designcraft_doc::ObjectStyle { name: "Round".into(), corners: rounded, ..Default::default() }); + styles.object.push(designcraft_doc::ObjectStyle { name: "Square".into(), based_on: Some("Round".into()), ..Default::default() }); + let back = import_idml(&export_idml(&d)).unwrap(); + assert_eq!(back.styles.object_style("Round").and_then(|s| s.corners), rounded); + assert_eq!(back.styles.object_style("Square").and_then(|s| s.corners), None); +} + /// A style's Text Frame General Options take each setting its own `TextFramePreference` leaves out /// from the style it is based on (named by its id or bare name, and only when that style doesn't /// turn the category off), and export and import keep the merged options. diff --git a/crates/ui-egui/src/object_style_dialog.rs b/crates/ui-egui/src/object_style_dialog.rs index 4200732a9..a89ef46d9 100644 --- a/crates/ui-egui/src/object_style_dialog.rs +++ b/crates/ui-egui/src/object_style_dialog.rs @@ -28,20 +28,31 @@ const ATTRIBUTES: [(&str, &str); 6] = [ /// The fields of the Paragraph Styles and Text Frame General Options pages: the style's paragraph /// style (`""`: none), Apply Next Style, and text frame options `tf` as the Text Frame Options -/// dialog shows them (`tfBase` keeps the options the page doesn't show). +/// dialog shows them (`tfBase` keeps the options as they are, `tfShown` the fields as first shown). fn text_fields(app: &DesignApp, fields: &mut Value, paragraph: Option<&str>, next: bool, tf: &designcraft_doc::TextFrameOptions) { - let units = app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units); fields["paragraphStyle"] = json!(paragraph.unwrap_or("")); fields["applyNext"] = json!(next); fields["tfBase"] = serde_json::to_value(tf).unwrap_or_default(); fields["insetLinked"] = json!(tf.inset.iter().all(|v| (v - tf.inset[0]).abs() < 1e-9)); - if let (Value::Object(f), Value::Object(shown)) = - (fields, crate::dialogs::text_frame_fields(tf, units, None, &crate::dialogs::document_grid(app))) - { + let shown = crate::dialogs::text_frame_fields(tf, doc_units(app), None, &crate::dialogs::document_grid(app)); + fields["tfShown"] = shown.clone(); + if let (Value::Object(f), Value::Object(shown)) = (fields, shown) { f.extend(shown); } } +/// The active document's ruler unit, which a bare number in a measurement field is in. +fn doc_units(app: &DesignApp) -> designcraft_geom::Unit { + app.session.active().map_or(designcraft_geom::Unit::Picas, |s| s.doc.settings.horizontal_units) +} + +/// The dialog with `fields`, reading bare numbers in the document's ruler unit. +fn dialog(app: &DesignApp, fields: Value) -> Dialog { + let mut d = Dialog::new(ID, fields); + d.unit = doc_units(app); + d +} + /// The active document as the dialog records it: its uid and the epoch that File › Revert /// changes. fn document_key(app: &DesignApp) -> Value { @@ -85,7 +96,7 @@ pub fn open_new(app: &mut DesignApp) { "apply": from, }); text_fields(app, &mut fields, None, false, &frame.unwrap_or_default()); - app.ui.dialog = Some(Dialog::new(ID, fields)); + app.ui.dialog = Some(dialog(app, fields)); } /// Object Style Options for style `name`; refused for a style the document doesn't have and for @@ -116,7 +127,7 @@ pub fn open_edit(app: &mut DesignApp, name: &str) -> Result<(), String> { "apply": false, }); text_fields(app, &mut fields, os.paragraph_style.as_deref(), os.apply_next_style, &os.text_frame.clone().unwrap_or_default()); - app.ui.dialog = Some(Dialog::new(ID, fields)); + app.ui.dialog = Some(dialog(app, fields)); Ok(()) } @@ -157,23 +168,31 @@ fn frame_options(d: &Dialog) -> Result } let mut o: designcraft_doc::TextFrameOptions = d.fields.get("tfBase").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(); let bad = |what: &str| format!("Text Frame General Options: {what}"); - let measure = |key: &str| d.m(key).filter(|v| v.is_finite() && (0.0..=15552.0).contains(v)); + // A field still as first shown keeps the option's value, which the field shows rounded. + let shown = d.fields.get("tfShown").cloned().unwrap_or(Value::Null); + let measure = |key: &str, was: f64| { + if d.fields.get(key).is_some_and(|v| *v == shown[key]) { + return Some(was); + } + d.m(key).filter(|v| v.is_finite() && (0.0..=15552.0).contains(v)) + }; o.columns = d .n("columns") .filter(|n| (1.0..=40.0).contains(n) && n.fract() == 0.0) .ok_or_else(|| bad("the number of columns is a whole number from 1 to 40"))? as u32; - o.gutter = measure("gutter").ok_or_else(|| bad("the gutter is not a measure"))?; + o.gutter = measure("gutter", o.gutter).ok_or_else(|| bad("the gutter is not a measure"))?; o.columns_kind = serde_json::from_value(json!(d.s("columnsKind"))).unwrap_or(o.columns_kind); if o.columns_kind == designcraft_doc::ColumnsKind::FixedWidth { - o.column_width = measure("columnWidth").ok_or_else(|| bad("the column width is not a measure"))?; + o.column_width = measure("columnWidth", o.column_width).ok_or_else(|| bad("the column width is not a measure"))?; } o.balance_columns = d.b("balanceColumns"); for (side, key) in o.inset.iter_mut().zip(["insetTop", "insetLeft", "insetBottom", "insetRight"]) { - *side = measure(key).ok_or_else(|| bad("an inset is not a measure"))?; + *side = measure(key, *side).ok_or_else(|| bad("an inset is not a measure"))?; } o.vertical_justification = serde_json::from_value(json!(d.s("verticalJustification"))).unwrap_or(o.vertical_justification); if o.vertical_justification == designcraft_doc::VerticalJustification::Justify { - o.vj_paragraph_spacing_limit = measure("paragraphSpacingLimit").ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; + o.vj_paragraph_spacing_limit = + measure("paragraphSpacingLimit", o.vj_paragraph_spacing_limit).ok_or_else(|| bad("the paragraph spacing limit is not a measure"))?; } o.ignore_wrap = d.b("ignoreWrap"); Ok(Some(o)) @@ -198,6 +217,10 @@ pub fn confirm(app: &mut DesignApp, d: &Dialog) -> Result { let mut p = attrs(d); p.insert("textFrame".into(), frame_options(d)?.map_or(Value::Null, |o| general_json(&o))); if d.b("new") { + // A name another style has is refused, as Object Style Options refuses it. + if app.session.active().is_some_and(|st| st.doc.styles.object_style(&name).is_some()) { + return Err(format!("an object style is already named `{name}`")); + } p.insert("name".into(), json!(name)); p.insert("fromSelection".into(), json!(false)); let r = app.run("style.object.create", Value::Object(p)).map_err(|e| e.to_string())?; @@ -775,8 +798,8 @@ mod tests { assert!(app.ui.dialog.as_ref().is_some_and(|d| d.b("new"))); } - /// A refused OK (an empty name, a name another style has) keeps the dialog and its edits, - /// with the reason shown. + /// A refused OK (an empty name, a name another style has, in Object Style Options and in New + /// Object Style) keeps the dialog and its edits, with the reason shown. #[test] fn a_refused_ok_keeps_the_dialog_open_with_the_reason() { let (mut app, _) = app_with_frame(); @@ -801,6 +824,69 @@ mod tests { let e = crate::dialogs::confirm(&mut app).unwrap_err(); assert!(e.contains("already named"), "{e}"); assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); + // New Object Style with a name another style has makes no style under another name. + app.ui.dialog = None; + let count = |app: &DesignApp| app.session.active().unwrap().doc.styles.object.len(); + let before = count(&app); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Taken")); + } + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("already named"), "{e}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.s("status") == e)); + assert_eq!(count(&app), before, "no style was made"); + } + + fn app_with_text_frame(units: &str) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("document.preferences", json!({"horizontalUnits": units, "verticalUnits": units})).unwrap(); + let r = app.run("frame.create", json!({"rect": [36, 36, 336, 336], "content": "text", "caret": false})).unwrap(); + app.run("selection.set", json!({"ids": [r["id"]]})).unwrap(); + app + } + + /// In a document measured in millimeters, a bare number in a Text Frame General Options field + /// is millimeters, in New Object Style and in Object Style Options. + #[test] + fn bare_numbers_are_in_the_documents_ruler_unit() { + let mut app = app_with_text_frame("millimeters"); + let mm = 72.0 / 25.4; + let frame = |app: &DesignApp| app.session.active().unwrap().doc.styles.object_style("Metric").and_then(|s| s.text_frame.clone()).unwrap(); + open_new(&mut app); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Metric")); + for k in ["insetTop", "insetLeft", "insetBottom", "insetRight"] { + d.fields.insert(k.into(), json!("6")); + } + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!(frame(&app).inset.iter().all(|v| (v - 6.0 * mm).abs() < 1e-6), "{:?}", frame(&app).inset); + open_edit(&mut app, "Metric").unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("columns".into(), json!("2")); + d.fields.insert("gutter".into(), json!("5")); + } + crate::dialogs::confirm(&mut app).unwrap(); + assert!((frame(&app).gutter - 5.0 * mm).abs() < 1e-6, "{}", frame(&app).gutter); + } + + /// Object Style Options keeps a General measurement the user did not edit exactly as the style + /// has it, though the field shows it rounded. + #[test] + fn general_measurements_left_alone_keep_their_value() { + let mut app = app_with_text_frame("points"); + let tf = json!({"gutter": 2.123456, "inset": [1.23456, 2.34567, 3.45678, 4.56789]}); + app.run("style.object.create", json!({"name": "Precise", "fromSelection": false, "textFrame": tf})).unwrap(); + open_edit(&mut app, "Precise").unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("name".into(), json!("Precise Too")); + d.fields.insert("insetTop".into(), json!("7 pt")); + } + crate::dialogs::confirm(&mut app).unwrap(); + let o = app.session.active().unwrap().doc.styles.object_style("Precise Too").and_then(|s| s.text_frame.clone()).unwrap(); + assert_eq!((o.gutter, o.inset), (2.123456, [7.0, 2.34567, 3.45678, 4.56789])); } /// Object Style Options and New Object Style act only on the document they opened for. With diff --git a/crates/ui-egui/src/panels/styles.rs b/crates/ui-egui/src/panels/styles.rs index fac694ace..3b2d19e1e 100644 --- a/crates/ui-egui/src/panels/styles.rs +++ b/crates/ui-egui/src/panels/styles.rs @@ -110,15 +110,21 @@ pub fn character(app: &mut DesignApp, ui: &mut egui::Ui) { fn object_style_of_selection(app: &DesignApp) -> Option<(String, bool)> { let st = app.session.active()?; let it = st.selection.items.first().and_then(|i| st.doc.item(*i))?; + Some((it.object_style.clone(), overrides_its_style(&st.doc, it))) +} + +/// Whether `it` differs from its object style: its own attributes, or a text frame's paragraphs +/// in other styles than the object style gives them. +fn overrides_its_style(doc: &designcraft_doc::Document, it: &designcraft_doc::Item) -> bool { + let Some(os) = doc.styles.object_style(&it.object_style) else { return false }; let mut styled = it.clone(); - let mut over = false; - if let Some(os) = st.doc.styles.object_style(&it.object_style) { - os.apply_to(&mut styled); - if let Some(tf) = it.text_frame() { - over = st.doc.story(tf.story).is_some_and(|s| !os.story_follows(&st.doc.styles, s)); - } - } - Some((it.object_style.clone(), over || styled != *it)) + os.apply_to(&mut styled); + styled != *it || it.text_frame().is_some_and(|tf| doc.story(tf.story).is_some_and(|s| !os.story_follows(&doc.styles, s))) +} + +/// Whether any selected object differs from its object style (Clear Overrides clears them all). +fn selection_overrides_styles(app: &DesignApp) -> bool { + app.session.active().is_some_and(|st| st.selection.items.iter().filter_map(|i| st.doc.item(*i)).any(|it| overrides_its_style(&st.doc, it))) } /// Window › Styles › Object Styles, as InDesign's: the selected object's style on top (`+` when @@ -188,7 +194,7 @@ pub fn object(app: &mut DesignApp, ui: &mut egui::Ui) { crate::object_style_dialog::open_new(app); } } - let over = current.as_ref().is_some_and(|c| c.1); + let over = selection_overrides_styles(app); if ui.add_enabled_ui(over, |ui| icons::button(ui, "style-clear", 20.0, false, crate::i18n::tr(&lang, "Clear Overrides"))).inner.clicked() && over { @@ -409,6 +415,40 @@ mod tests { assert!(styles.contains(&"Object Style 1".to_string()), "{styles:?}"); } + /// Clear Overrides is on when any selected frame differs from its style, not only the first; + /// the label on top describes the first. + #[test] + fn clear_overrides_is_on_when_a_later_selected_frame_is_overridden() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let frame = |app: &mut DesignApp, x: f64| { + app.run("frame.create", json!({"rect": [x, 36, x + 100.0, 136], "content": "graphic"})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (frame(&mut app, 36.0), frame(&mut app, 200.0)); + app.run("style.object.create", json!({"name": "Framed", "fromSelection": false, "stroke": {"swatch": "[Paper]", "weight": 3}})).unwrap(); + app.run("style.object.apply", json!({"name": "Framed", "ids": [a, b]})).unwrap(); + app.run("object.stroke", json!({"weight": 1, "ids": [b]})).unwrap(); + app.run("selection.set", json!({"ids": [a, b]})).unwrap(); + let mut h = Harness::builder().with_size(vec2(320.0, 260.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let id = egui::Id::unique("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + object(app, ui); + }, + app, + ); + h.run_steps(4); + assert_eq!(h.get_all_by_label("Framed").count(), 2, "the first frame follows its style"); + h.get_by_label("Clear Overrides").click(); + h.run_steps(3); + let weight = |h: &Harness| h.state().session.active().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().stroke.weight; + assert_eq!(weight(&h), 3.0); + } + #[test] fn paragraph_color_override_is_marked_and_cleared_from_the_row_menu() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 5fb75aaefcf71d57e328c581b8602c08c97ed7ec Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:27:08 -0800 Subject: [PATCH 244/328] Properties: Text Frame section shows inset spacing and vertical justification (#2661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Properties: Text Frame section shows inset spacing and vertical justification Properties › Text Frame now shows the frame's inset spacing under the columns: Top and Bottom, a link that makes all four the same, then Left and Right. A non-rectangular frame shows one Inset, the distance its text keeps from the outline. Four buttons set Vertical Justification to Top, Center, Bottom or Justify. Type on a path shows neither. The section also shows with the Type tool in a frame. There it changes the frame that shows the insertion point, or every frame that holds part of the selected text, as Object › Text Frame Options does. * Properties: one Inset for a non-rectangular frame keeps the other sides The single Inset sets only the top inset, the one kept from the outline. A rectangular frame that holds part of the same selected text keeps its own sides. * Properties: the one Inset field and the composer share the frame outline test FrameOutline::of_item builds an item's outline with its corner options applied. The composer uses it to keep the top inset from the outline, and the Properties panel uses it to decide whether a frame shows one Inset, so the two give the same answer for every frame. * Text Frame Options: frames taken while typing stay with their document OK is refused when another document became active after the dialog opened, so the saved frame ids do not change frames in that document. * Properties: the inset link starts linked again after Revert The link's state is kept per document state instead of per document, so a frame with equal insets in the reverted document starts linked. * Text Frame Options: frames taken while typing are refused after Revert Revert keeps the document's id but replaces its state, so a new frame can reuse a saved frame id. The dialog now ties the frames to the document state, and OK is refused after Revert as it is in another document. * Properties: the one Inset of a non-rectangular frame sets all four sides The composer bounds a shaped frame's text by its rectangle less all four insets as well as by the outline, so a single Inset that changed only the top left hidden sides in place: lowering a uniform 96 pt inset to 0 kept text overset. When every frame the field changes is shaped, it now sets all four sides. With a rectangular frame among them, only the top inset changes and each frame keeps its other sides. * Fix text frame dialog merge resolution * Keep text frame preview targets fixed * Fix target field key inference * Tests: Text Frame Options show four sides for text through an oval and a rectangle With the Type tool and text selected through an oval and a threaded rectangle, with the oval as the caret's stored frame, the dialog shows the four inset sides, a changed Top leaves the rectangle's other sides as they were, and the link stays off while the rectangle's sides are uneven. * Properties: the inset link starts off when another frame has uneven sides With selected text that runs through several frames, the link of Text Frame > Inset Spacing started linked when the frame the section shows had four equal insets, and a changed Top then set all four sides of every frame. The link now starts linked only when every frame the field changes has four equal insets. Its state is kept for that set of frames, so a link turned on for one frame does not carry over to selected text that also runs through a frame with uneven sides. --------- Co-authored-by: Dylan M. Taylor --- ROADMAP.md | 2 + crates/compose/src/lib.rs | 5 +- crates/compose/src/outline.rs | 7 + crates/engine/src/cmd/object.rs | 1 - crates/ui-egui/src/dialogs.rs | 6 + crates/ui-egui/src/dialogs/tests.rs | 55 +++- crates/ui-egui/src/icons.rs | 27 ++ crates/ui-egui/src/panels/properties.rs | 9 +- crates/ui-egui/src/panels/properties/tests.rs | 269 +++++++++++++++++- crates/ui-egui/src/panels/properties/text.rs | 132 ++++++++- docs/target-app-parity.md | 1 + 11 files changed, 496 insertions(+), 18 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 9e83d73ae..ee0f4e022 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -394,12 +394,14 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · Properties › Text Frame shows the frame's inset spacing (Top, Bottom, Left and Right with a link that makes all four the same; one Inset for a non-rectangular frame) and four Vertical Justification buttons (Top, Center, Bottom, Justify), and the section also shows with the Type tool in a frame, where it changes the frame that shows the insertion point. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. + - **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. - **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change. - **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a367e7ade..333959626 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1205,10 +1205,7 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId // area (all four insets) still bounds the lines. let outline = match &tf.options.path { Some(_) => None, - None => { - let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; - FrameOutline::new(&bp, tf.options.inset[0]) - } + None => FrameOutline::of_item(item, tf.options.inset[0]), }; // Vertical type: composed in the turned box; wraps and page rects turned with it. let vertical = doc.frame_vertical(item); diff --git a/crates/compose/src/outline.rs b/crates/compose/src/outline.rs index bfc709710..dd1f59c0e 100644 --- a/crates/compose/src/outline.rs +++ b/crates/compose/src/outline.rs @@ -59,6 +59,13 @@ impl FrameOutline { Some(FrameOutline { edges, inset }) } + /// The outline of `item`'s path with its corner options applied, or None when that is the + /// item's own rectangle. The composer and the Properties panel's one Inset field both use it. + pub fn of_item(item: &designcraft_doc::Item, inset: f64) -> Option { + let bp = if item.corners.is_none() { item.path.to_bezpath() } else { designcraft_geom::corners::apply(&item.path, &item.corners) }; + FrameOutline::new(&bp, inset) + } + /// The outline mapped by `xf` (into a vertical frame's turned box). pub fn transformed(&self, xf: Affine) -> FrameOutline { FrameOutline { edges: self.edges.iter().map(|&(a, b)| (xf * a, xf * b)).collect(), inset: self.inset } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index c269e4f1d..c41564047 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -2732,7 +2732,6 @@ fn content_type(s: &mut Session, p: &Value) -> Result { /// The most columns a text frame takes. const MAX_FRAME_COLUMNS: u64 = 40; - /// The frames `object.textFrameOptions` changes when the call names none: the selected objects, /// or with the Type tool the frame that shows the caret or every frame holding part of the /// selected text. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a5babb120..409943f75 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1173,6 +1173,12 @@ fn seed_text_frame_options(app: &DesignApp, d: &mut Dialog) { m.insert("inset".into(), json!(format_measure(o.inset[0], units))); } d.fields.insert("_shaped".into(), json!(shaped)); + if let Some(targets) = typing_frame_ids(app) { + d.fields.entry("_targets").or_insert(targets); + if let Some(epoch) = app.session.active().map(|doc| doc.identity_epoch) { + d.fields.entry("_targetsDoc").or_insert(json!(epoch)); + } + } if let Value::Object(m) = &shown { for (k, v) in m { d.fields.entry(k.clone()).or_insert_with(|| v.clone()); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 0bad3ce0e..ca057856d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1690,6 +1690,47 @@ fn text_frame_options_show_four_sides_for_a_mixed_selection() { assert!(d.b("_shaped")); } +/// With the Type tool, text selected through an oval and a threaded rectangle shows the four +/// sides even when the caret's frame is the oval, and a changed side leaves the rectangle's other +/// sides as they were. +#[test] +fn text_frame_options_show_four_sides_for_text_through_an_oval_and_a_rectangle() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let oval = app.run("frame.create", json!({"rect": [36, 36, 236, 136], "shape": "ellipse", "content": "text", "text": text})).unwrap(); + let sid = oval["story"].as_u64().unwrap(); + let oval = designcraft_doc::ItemId(oval["id"].as_u64().unwrap()); + let rect = app.run("frame.create", json!({"rect": [36, 200, 336, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let rect = designcraft_doc::ItemId(rect["id"].as_u64().unwrap()); + app.run("text.thread", json!({"from": oval.0, "to": rect.0})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [oval.0, rect.0], "inset": [6, 2, 3, 4]})).unwrap(); + let opts = |app: &DesignApp, id| app.session.doc().unwrap().doc.item(id).unwrap().text_frame().unwrap().options.clone(); + let select_through_both = |app: &mut DesignApp| { + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + // The caret's stored frame is the oval. + if let Some(t) = app.session.active_mut().unwrap().selection.text.as_mut() { + t.frame = Some(oval); + } + assert_eq!(designcraft_engine::cmd::text_frame_options_frames(&app.session), vec![oval, rect], "the selected text runs through both frames"); + }; + select_through_both(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("_shaped") && !d.fields.contains_key("inset"), "text through a rectangle shows the four sides"); + d.fields.insert("insetTop".into(), json!("1p0")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + assert_eq!(opts(&app, rect).inset, [12.0, 2.0, 3.0, 4.0]); + assert_eq!(opts(&app, oval).inset, [12.0, 2.0, 3.0, 4.0]); + // An even oval does not link the sides while the rectangle's sides are uneven. + app.run("object.textFrameOptions", json!({"ids": [oval.0], "inset": [5, 5, 5, 5]})).unwrap(); + select_through_both(&mut app); + let mut d = Dialog::new("textFrameOptions", json!({})); + seed_text_frame_options(&app, &mut d); + assert!(!d.b("insetLinked"), "a frame with uneven sides among the targets leaves the link off"); +} + /// The dialog dims Top, Left, Bottom, Right and the link for a non-rectangular frame and adds an /// Inset field; for a rectangle it shows no Inset field and the sides stay editable. #[test] @@ -4350,12 +4391,20 @@ fn retype_beside(h: &mut egui_kittest::Harness<'static, crate::test_window::Wind h.run_steps(3); } +/// The dialog's "Make all settings the same" links, in reading order: the Properties panel's +/// own links (its Text Frame insets, with a caret in a frame) are to the right of its Quick +/// Actions heading's left edge and are left out. +fn dialog_links(h: &egui_kittest::Harness<'static, crate::test_window::Window>) -> Vec { + use egui_kittest::kittest::Queryable; + let panel_left = h.query_by_label("Quick Actions").map_or(f32::INFINITY, |n| n.rect().left()); + h.get_all_by_label("Make all settings the same").map(|n| n.rect()).filter(|r| r.center().x < panel_left).collect() +} + /// The course's chapter 40: Paragraph Border's four weights are linked as InDesign's, so a /// side typed in sets all four; with the link off ("Make all settings the same") a side is set /// alone, as the lesson gives the border only a thick left side. The corners link the same way. #[test] fn paragraph_border_sides_and_corners_link_as_indesigns() { - use egui_kittest::kittest::Queryable; let (app, _) = ruled_paragraph(); let mut h = crate::test_window::open(app, egui::vec2(1400.0, 900.0)); h.state_mut().app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": "Ruled Child", "section": "border", "p.borderOn": true}))); @@ -4370,7 +4419,7 @@ fn paragraph_border_sides_and_corners_link_as_indesigns() { // The link of the weights (0), corners (1) or offsets (2), where it is now: the dialog // scrolls as fields take focus. let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + let links = dialog_links(h); assert_eq!(links.len(), 3, "weights, corners and offsets each have a link"); links[n].center() }; @@ -4427,7 +4476,7 @@ fn paragraph_shading_page_is_laid_out_as_indesigns() { assert_eq!(field(&h, "shadingOverprint"), json!(true)); // The corners' link (0) and the offsets' (1). let link = |h: &egui_kittest::Harness<'static, crate::test_window::Window>, n: usize| { - let links: Vec = h.get_all_by_label("Make all settings the same").map(|n| n.rect()).collect(); + let links = dialog_links(h); assert_eq!(links.len(), 2, "corners and offsets each have a link"); links[n].center() }; diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c8eeee911..e15c90ec9 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -997,6 +997,19 @@ fn paint_text(pen: &mut Pen, name: &str) -> bool { pen.line(&[(12.0, 3.5), (12.0, 16.5)]); pen.line(&[(9.0, 10.0), (11.0, 10.0)]); } + "vjust-top" | "vjust-center" | "vjust-bottom" | "vjust-justify" => { + // A frame with three lines of text at its top, middle or bottom, or spread over it. + pen.rect(2.5, 2.5, 17.5, 17.5); + let ys = match name { + "vjust-top" => [5.5, 8.0, 10.5], + "vjust-center" => [7.5, 10.0, 12.5], + "vjust-bottom" => [9.5, 12.0, 14.5], + _ => [5.5, 10.0, 14.5], + }; + for y in ys { + pen.line(&[(5.0, y), (15.0, y)]); + } + } "small-caps" => { // Two original T shapes share a baseline; no phonetic small-cap glyph is required. pen.line(&[(3.0, 5.0), (10.0, 5.0)]); @@ -1383,6 +1396,20 @@ mod tests { } } + /// Each Vertical Justification button in Properties › Text Frame has its own glyph. + #[test] + fn vertical_justification_glyphs_are_distinct() { + let names = ["vjust-top", "vjust-center", "vjust-bottom", "vjust-justify"]; + let unknown = drawing("no-such-icon"); + let glyphs: Vec = names.iter().map(|n| drawing(n)).collect(); + for (k, g) in glyphs.iter().enumerate() { + assert_ne!(*g, unknown, "{} falls back to the placeholder", names[k]); + for (j, other) in glyphs.iter().enumerate().skip(k + 1) { + assert_ne!(g, other, "{} and {} draw alike", names[k], names[j]); + } + } + } + #[test] fn distribute_icons_are_distinct_from_align_and_each_other() { // `objalign-*` ship upstream and back the Properties Align row; only the diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 9b949f547..b6dabfe65 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -38,7 +38,8 @@ pub use object_panels::{align_panel, attributes_panel, effects_panel, pathfinder use object_panels::{anchor_point_sections, pathfinder_row}; pub(crate) use text::{LANGUAGES, kerning_control, language_menu}; use text::{ - bullets_section, character_section, paragraph_section, quick_actions_text, text_appearance_section, text_frame_section, text_style_section, + bullets_section, character_section, paragraph_section, quick_actions_text, text_appearance_section, text_frame_section, text_frame_target, + text_style_section, }; pub use typography::{DIGIT_OPTIONS, character_panel, digit_label, paragraph_panel, show_typography_panel}; #[cfg(test)] @@ -137,6 +138,12 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { section(ui, crate::i18n::tr(&app.ui.language, "Bullets and Numbering"), true); bullets_section(app, ui); divider(ui); + // The frame that shows the caret, as with the frame selected. + if text_frame_target(app).is_some() { + section(ui, crate::i18n::tr(&app.ui.language, "Text Frame"), true); + text_frame_section(app, ui); + divider(ui); + } section(ui, crate::i18n::tr(&app.ui.language, "Quick Actions"), true); quick_actions_text(app, ui); return; diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 59e0cbd1e..1792e3b3a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -798,7 +798,9 @@ fn bullets_options_open_the_bullets_and_numbering_dialog() { let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs"})).unwrap(); app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 6})).unwrap(); let mut h = panel(app); - h.get_by_label("Options").click(); + // Bullets and Numbering's Options, above Text Frame's. + let bullets = h.get_all_by_label("Options").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap(); + bullets.click(); h.run_steps(3); let d = h.state().ui.dialog.clone().expect("a dialog"); assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "bullets")); @@ -1278,6 +1280,269 @@ fn transform_flips_and_rotates_from_properties() { assert!(h.query_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("90°")).is_some()); } +/// The vertical extent of Properties › Text Frame: from its heading (the last "Text Frame" label; +/// the selection band above may say "Text Frame" too) to the Quick Actions heading. +fn text_frame_band(h: &Harness<'_, DesignApp>) -> (f32, f32) { + let top = h.get_all_by_label("Text Frame").map(|n| n.rect().bottom()).fold(f32::MIN, f32::max); + (top, h.get_by_label("Quick Actions").rect().top()) +} + +/// The text fields of Properties › Text Frame, in reading order. +fn text_frame_fields(h: &Harness<'_, DesignApp>) -> Vec { + let (top, bottom) = text_frame_band(h); + let mut v: Vec = + h.get_all_by_role(egui::accesskit::Role::TextInput).map(|n| n.rect()).filter(|r| r.center().y > top && r.center().y < bottom).collect(); + v.sort_by(|a, b| (a.top(), a.left()).partial_cmp(&(b.top(), b.left())).unwrap()); + v +} + +/// Clicks the control labeled `label` inside Properties › Text Frame. +fn click_in_text_frame(h: &mut Harness<'_, DesignApp>, label: &str) { + let (top, bottom) = text_frame_band(h); + h.get_all_by_label(label).find(|n| n.rect().center().y > top && n.rect().center().y < bottom).unwrap().click(); + h.run_steps(3); +} + +fn type_in_field(h: &mut Harness<'_, DesignApp>, at: egui::Rect, text: &str) { + h.hover_at(at.center()); + h.drag_at(at.center()); + h.drop_at(at.center()); + h.run_steps(2); + h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }); + h.event(egui::Event::Text(text.into())); + h.key_press(egui::Key::Enter); + h.run_steps(3); +} + +fn frame_options(app: &DesignApp, id: u64) -> designcraft_doc::TextFrameOptions { + app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().text_frame().unwrap().options.clone() +} + +/// Properties › Text Frame shows the frame's inset spacing under the columns, linked while the +/// four insets are the same, and the four vertical justification buttons. Each change is one +/// undo step; the button that is already on adds none. +#[test] +fn properties_text_frame_sets_inset_spacing_and_vertical_justification() { + use designcraft_doc::VerticalJustification; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "content": "text", "text": "Hello"})).unwrap()["id"].as_u64().unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + // Columns and gutter, then Top and Left, then Bottom and Right. + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + let steps = undo_steps(h.state()); + // Linked: the top inset sets all four. + type_in_field(&mut h, f[2], "12pt"); + assert_eq!(frame_options(h.state(), id).inset, [12.0; 4]); + assert_eq!(undo_steps(h.state()), steps + 1); + // Unlinked: the bottom one alone. + click_in_text_frame(&mut h, "Make all settings the same"); + let f = text_frame_fields(&h); + type_in_field(&mut h, f[4], "6pt"); + assert_eq!(frame_options(h.state(), id).inset, [12.0, 12.0, 6.0, 12.0], "[top, left, bottom, right]"); + // Vertical justification. + assert_eq!(frame_options(h.state(), id).vertical_justification, VerticalJustification::Top); + for (label, vj) in + [("Bottom", VerticalJustification::Bottom), ("Center", VerticalJustification::Center), ("Justify", VerticalJustification::Justify)] + { + click_in_text_frame(&mut h, label); + assert_eq!(frame_options(h.state(), id).vertical_justification, vj, "{label}"); + } + let steps = undo_steps(h.state()); + click_in_text_frame(&mut h, "Justify"); + assert_eq!(undo_steps(h.state()), steps, "the button already on adds no undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(frame_options(h.state(), id).vertical_justification, VerticalJustification::Center); +} + +/// Insets unlinked before Revert start linked again in the reverted document, whose frame has the +/// same id and four equal insets. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn properties_text_frame_inset_link_starts_linked_after_revert() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "content": "text", "text": "Hello"})).unwrap()["id"].as_u64().unwrap(); + let dir = tempfile::tempdir().unwrap(); + app.run("file.saveAs", json!({"path": dir.path().join("revert.designcraft")})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + click_in_text_frame(&mut h, "Make all settings the same"); + h.state_mut().run("frame.create", json!({"rect": [320, 72, 400, 150], "content": "text", "text": "unsaved"})).unwrap(); + h.state_mut().run("file.revert", json!({})).unwrap(); + h.state_mut().run("selection.set", json!({"ids": [id]})).unwrap(); + h.run_steps(3); + let f = text_frame_fields(&h); + type_in_field(&mut h, f[4], "6pt"); + assert_eq!(frame_options(h.state(), id).inset, [6.0; 4], "linked: the bottom inset sets all four"); +} + +/// With the Type tool in the second frame of a thread, Properties shows the Text Frame section, +/// and its insets and vertical justification change that frame and not the first. +#[test] +fn properties_text_frame_shows_while_typing_and_changes_the_caret_frame() { + use designcraft_doc::VerticalJustification; + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + // The end of the story is in the second frame. + app.run("text.select", json!({"story": sid, "anchor": text.len()})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets while typing: {f:?}"); + type_in_field(&mut h, f[2], "9pt"); + click_in_text_frame(&mut h, "Bottom"); + let (oa, ob) = (frame_options(h.state(), a), frame_options(h.state(), b)); + assert_eq!((oa.inset, ob.inset), ([0.0; 4], [9.0; 4])); + assert_eq!((oa.vertical_justification, ob.vertical_justification), (VerticalJustification::Top, VerticalJustification::Bottom)); + assert!(h.state().session.active().unwrap().selection.text.is_some(), "the caret stays in the text"); +} + +/// A non-rectangular text frame shows one Inset, which sets the distance its text keeps from +/// the outline. The composer also bounds its text by all four insets, so the field sets all four. +#[test] +fn properties_text_frame_shows_one_inset_for_an_oval() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset: {f:?}"); + h.state_mut().run("object.textFrameOptions", json!({"ids": [id], "inset": [1, 2, 3, 4]})).unwrap(); + h.run_steps(2); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), id).inset, [8.0; 4]); +} + +/// Lowering an oval's uniform inset with the one Inset field lowers every side, so no hidden +/// side keeps the old inset and the text area that goes with it. +#[test] +fn properties_text_frame_one_inset_lowers_a_uniform_inset_on_every_side() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": "Hello"})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("object.textFrameOptions", json!({"ids": [id], "inset": 96})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset: {f:?}"); + type_in_field(&mut h, f[2], "0pt"); + assert_eq!(frame_options(h.state(), id).inset, [0.0; 4]); +} + +/// With selected text that runs from an oval into a rectangular frame, the one Inset field +/// changes the top inset of both, and each frame keeps its other sides. +#[test] +fn properties_text_frame_one_inset_keeps_the_sides_of_a_rectangle_in_the_selection() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [72, 72, 300, 300], "shape": "ellipse", "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [72, 400, 300, 760], "content": "text", "text": "", "caret": false})).unwrap(); + let (oval, rect, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": oval, "to": rect})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [oval, rect], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + assert_eq!( + designcraft_engine::cmd::text_frame_options_frames(&app.session), + [designcraft_doc::ItemId(oval), designcraft_doc::ItemId(rect)], + "the selected text runs through both frames" + ); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 3, "columns, gutter and one inset for the first frame, an oval: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), oval).inset, [8.0, 2.0, 3.0, 4.0]); + assert_eq!(frame_options(h.state(), rect).inset, [8.0, 2.0, 3.0, 4.0]); +} + +/// With selected text that runs through two rectangular frames, the inset link starts off when +/// one of them has uneven sides, even while the frame the section shows has four equal insets, so +/// a changed Top leaves the other sides of each frame as they were. +#[test] +fn properties_text_frame_inset_link_starts_off_when_another_frame_has_uneven_sides() { + for even_first in [true, false] { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + let (even, uneven) = if even_first { (a, b) } else { (b, a) }; + app.run("object.textFrameOptions", json!({"ids": [even], "inset": 5})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [uneven], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("text.select", json!({"story": sid, "anchor": 0, "focus": text.len()})).unwrap(); + assert_eq!( + designcraft_engine::cmd::text_frame_options_frames(&app.session), + [designcraft_doc::ItemId(a), designcraft_doc::ItemId(b)], + "the selected text runs through both frames" + ); + let mut h = panel(app); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), even).inset, [8.0, 5.0, 5.0, 5.0], "even frame first: {even_first}"); + assert_eq!(frame_options(h.state(), uneven).inset, [8.0, 2.0, 3.0, 4.0], "even frame first: {even_first}"); + } +} + +/// A link turned on for one frame does not carry over to selected text that runs from that frame +/// into a frame with uneven sides: the link starts off there, and a changed Top leaves the other +/// sides as they were. +#[test] +fn properties_text_frame_inset_link_of_one_frame_does_not_carry_to_a_text_selection() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let text = (0..40).map(|i| format!("Line {i} of the threaded story.")).collect::>().join(" "); + let a = app.run("frame.create", json!({"rect": [36, 36, 300, 120], "content": "text", "text": text})).unwrap(); + let b = app.run("frame.create", json!({"rect": [36, 200, 300, 700], "content": "text", "text": "", "caret": false})).unwrap(); + let (a, b, sid) = (a["id"].as_u64().unwrap(), b["id"].as_u64().unwrap(), a["story"].as_u64().unwrap()); + app.run("text.thread", json!({"from": a, "to": b})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [a], "inset": 5})).unwrap(); + app.run("object.textFrameOptions", json!({"ids": [b], "inset": [1, 2, 3, 4]})).unwrap(); + app.run("selection.set", json!({"ids": [a]})).unwrap(); + let mut h = panel(app); + // Off, then on again: the link of the first frame alone is now turned on by hand. + click_in_text_frame(&mut h, "Make all settings the same"); + click_in_text_frame(&mut h, "Make all settings the same"); + // The caret at the start of the story is in the first frame; the selection runs into the second. + h.state_mut().run("text.select", json!({"story": sid, "anchor": text.len(), "focus": 0})).unwrap(); + h.run_steps(3); + let f = text_frame_fields(&h); + assert_eq!(f.len(), 6, "columns, gutter and four insets: {f:?}"); + type_in_field(&mut h, f[2], "8pt"); + assert_eq!(frame_options(h.state(), a).inset, [8.0, 5.0, 5.0, 5.0]); + assert_eq!(frame_options(h.state(), b).inset, [8.0, 2.0, 3.0, 4.0]); +} + +/// Type on a path sets one line along the path: Properties › Text Frame shows no insets and no +/// vertical justification buttons for it. +#[test] +fn properties_text_frame_shows_no_insets_for_type_on_a_path() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "ellipse"})).unwrap()["id"].as_u64().unwrap(); + app.run("type.onPath", json!({"id": id, "text": "Around"})).unwrap(); + app.run("selection.set", json!({"ids": [id]})).unwrap(); + assert!(frame_options(&app, id).path.is_some()); + let h = panel(app); + assert_eq!(text_frame_fields(&h).len(), 2, "columns and gutter only"); + let (top, bottom) = text_frame_band(&h); + assert!(h.query_all_by_label("Justify").all(|n| n.rect().center().y < top || n.rect().center().y > bottom)); +} + /// With the Type tool, the Text Frame section shows the frame Text Frame Options change: the frame /// the caret is drawn in, not the caret's stored frame. #[test] @@ -1294,6 +1559,6 @@ fn text_frame_section_shows_the_frame_that_shows_the_caret() { // The end of the story is drawn in the second frame; the caret's stored frame is the first. app.session.doc_mut().unwrap().selection = Selection::text(TextSel { story: StoryId(sid), anchor: text.len(), focus: text.len(), frame: Some(ItemId(a)), cell: None }); - let shown = super::text::text_frame_target(&app).map(|(id, o)| (id, o.columns)); + let shown = super::text::text_frame_target(&app).map(|(id, o, _)| (id, o.columns)); assert_eq!(shown, Some((ItemId(b), 3))); } diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index f444d6ba2..94e3b4ef8 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -517,20 +517,31 @@ pub(super) fn quick_actions_text(app: &mut DesignApp, ui: &mut Ui) { } /// The text frame the Text Frame section shows, as Text Frame Options shows it: the first selected -/// frame, the frame that shows the caret, or the first frame holding selected text. Its id and its -/// options. -pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions)> { +/// frame, the frame that shows the caret, or the first frame holding selected text. Its id, its +/// options, and whether its outline is not its own rectangle (an oval, a polygon or corner +/// options), where the text keeps one inset from the outline. Type on a path is not shaped. +pub(super) fn text_frame_target(app: &DesignApp) -> Option<(designcraft_doc::ItemId, designcraft_doc::TextFrameOptions, bool)> { let st = app.session.active()?; let fid = designcraft_engine::cmd::text_frame_options_frames(&app.session).first().copied()?; - Some((fid, st.doc.item(fid)?.text_frame()?.options.clone())) + let item = st.doc.item(fid)?; + let opts = item.text_frame()?.options.clone(); + Some((fid, opts, is_shaped(item))) } -/// Text Frame section: columns, gutter, [Options]. With the Type tool it changes the frame that -/// shows the caret, or every frame that holds part of the selected text. +/// Whether a text frame's outline is not its own rectangle, where its text keeps one inset from +/// the outline. Type on a path is not shaped. +fn is_shaped(item: &designcraft_doc::Item) -> bool { + item.text_frame().is_some_and(|tf| tf.options.path.is_none()) && designcraft_compose::FrameOutline::of_item(item, 0.0).is_some() +} + +/// Text Frame section: columns, gutter, [Options]; Inset Spacing (Top and Bottom, the link that +/// makes all four the same, Left and Right; one Inset for a non-rectangular frame); the four +/// Vertical Justification buttons (neither for type on a path). With the Type tool it changes the +/// frame that shows the caret, or every frame that holds part of the selected text. pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let u = units(app); - let Some((_, opts)) = text_frame_target(app) else { return }; + let Some((fid, opts, shaped)) = text_frame_target(app) else { return }; let b = block(ui, FIELD_H); icons::paint(ui.painter(), sub(b, 0.0, 1.0, 19.0, 19.0), "text-columns", t.icon); if let Some(v) = place(ui, sub(b, 22.0, 0.0, 54.0, FIELD_H), |ui| { @@ -548,6 +559,113 @@ pub(super) fn text_frame_section(app: &mut DesignApp, ui: &mut Ui) { if place(ui, sub(b, 164.0, 0.5, ow, 20.0), |ui| outline_button(ui, crate::i18n::tr(&app.ui.language, "Options"), ow)).clicked() { app.ui.dialog = Some(crate::dialogs::Dialog::new("textFrameOptions", json!({}))); } + // Type on a path sets one line along the path: insets and vertical justification do not apply. + if opts.path.is_some() { + return; + } + text_frame_insets(app, ui, fid, &opts, shaped); + ui.add_space(4.0); + let cur = opts.vertical_justification; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for (vj, icon, tip) in [ + (designcraft_doc::VerticalJustification::Top, "vjust-top", "Top"), + (designcraft_doc::VerticalJustification::Center, "vjust-center", "Center"), + (designcraft_doc::VerticalJustification::Bottom, "vjust-bottom", "Bottom"), + (designcraft_doc::VerticalJustification::Justify, "vjust-justify", "Justify"), + ] { + if icon_toggle(ui, icon, cur == vj, crate::i18n::tr(&app.ui.language, tip)).clicked() { + let _ = app.run("object.textFrameOptions", json!({"verticalJustification": vj})); + } + } + }); +} + +/// Inset Spacing under the columns: Top and Bottom, the link that makes all four the same, then +/// Left and Right, as the wrap offsets are laid out. A non-rectangular frame shows one Inset, the +/// distance its text keeps from the outline. +fn text_frame_insets(app: &mut DesignApp, ui: &mut Ui, fid: designcraft_doc::ItemId, opts: &designcraft_doc::TextFrameOptions, shaped: bool) { + let t = Tokens::get(ui.ctx()); + let lang = app.ui.language.clone(); + let tr = |s: &str| crate::i18n::tr(&lang, s).to_string(); + let u = units(app); + let inset = opts.inset; + ui.add_space(4.0); + if shaped { + let b = block(ui, FIELD_H); + let ir = sub(b, 0.0, 2.0, 17.0, 17.0); + icons::paint(ui.painter(), ir, "margin-top", t.icon); + ui.interact(ir, ui.scope_id().with("prop_tf_inset"), Sense::hover()).on_hover_ui(|ui| { + crate::rtl::label(ui, tr("Inset")); + }); + if let Some(v) = place(ui, sub(b, 20.0, 0.0, 76.0, FIELD_H), |ui| { + NumField::measure("tfInset", Some(inset[0]), u).width(76.0).spinner().range(0.0, 15552.0).show(ui) + }) { + // The composer also bounds the text by the frame's rectangle less all four insets, so + // when every frame it changes is shaped the one Inset sets all four. With a + // rectangular frame among them (part of the same selected text), only the top inset + // changes and each frame keeps its other sides. + let all_shaped = app.session.active().is_some_and(|st| { + designcraft_engine::cmd::text_frame_options_frames(&app.session) + .iter() + .filter_map(|id| st.doc.item(*id)) + .filter(|it| it.text_frame().is_some_and(|tf| tf.options.path.is_none())) + .all(is_shaped) + }); + let inset = if all_shaped { json!(v) } else { json!([v, null, null, null]) }; + let _ = app.run("object.textFrameOptions", json!({"inset": inset})); + } + return; + } + let b = block(ui, 2.0 * FIELD_H + 5.0); + // The link's state belongs to the frames the field changes in this document state: other + // frames, or frames with the same ids in another document or after Revert, start linked when + // every one of them has four equal insets, so a frame with uneven sides keeps them when one + // side changes. + let doc_epoch = app.session.active().map_or(0, |st| st.identity_epoch); + let targets = designcraft_engine::cmd::text_frame_options_frames(&app.session); + let target_ids: Vec = targets.iter().map(|id| id.0).collect(); + let link_id = egui::Id::unique(("prop_tf_inset_linked", doc_epoch, fid.0, target_ids)); + let even = |i: &[f64; 4]| i.iter().all(|v| (v - i[0]).abs() < 1e-9); + let same = even(&inset) + && app.session.active().is_none_or(|st| targets.iter().filter_map(|id| st.doc.item(*id)?.text_frame()).all(|tf| even(&tf.options.inset))); + let linked = ui.data(|d| d.get_temp::(link_id)).unwrap_or(same); + let mut set = None; + // Insets are [top, left, bottom, right]. + for (k, key, icon, tip, x, y) in [ + (0, "tfInsetTop", "margin-top", "Top", 0.0, 0.0), + (2, "tfInsetBottom", "margin-bottom", "Bottom", 0.0, FIELD_H + 5.0), + (1, "tfInsetLeft", "margin-inside", "Left", 140.0, 0.0), + (3, "tfInsetRight", "margin-outside", "Right", 140.0, FIELD_H + 5.0), + ] { + let ir = sub(b, x, y + 2.0, 17.0, 17.0); + icons::paint(ui.painter(), ir, icon, t.icon); + ui.interact(ir, ui.scope_id().with(("prop_tf_inset", k)), Sense::hover()).on_hover_ui(|ui| { + crate::rtl::label(ui, tr(tip)); + }); + let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| { + NumField::measure(key, Some(inset[k]), u).width(76.0).spinner().range(0.0, 15552.0).show(ui) + }); + if let Some(v) = nv { + // Linked, all four; else this side alone. + let mut o = [None; 4]; + if linked { + o = [Some(v); 4]; + } else { + o[k] = Some(v); + } + set = Some(o); + } + } + if place(ui, sub(b, 106.0, (FIELD_H + 5.0) / 2.0, 22.0, FIELD_H), |ui| { + widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, &tr("Make all settings the same"), vec2(22.0, 21.0)) + .clicked() + }) { + ui.data_mut(|d| d.insert_temp(link_id, !linked)); + } + if let Some(o) = set { + let _ = app.run("object.textFrameOptions", json!({"inset": o})); + } } /// Languages offered for text (InDesign-style names). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 608b587f8..52bd45ddc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -353,6 +353,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Auto-size (Text Frame Options › Auto-Size, `object.textFrameOptions {autoSize: off|heightOnly|widthOnly|heightAndWidth|heightAndWidthProportionally, autoSizeReference, useMinimumHeight, minimumHeight, useMinimumWidth, minimumWidth, noLineBreaks}`): the frame fits its text exactly after every edit (typing, pasting, style changes, option changes) in the same undo step (opening a file keeps the frame sizes it gives); it grows and shrinks around the reference point, which stays put in spread space for rotated frames too, never below the minimum height/width and never past 10,000 pt. Width Only and No Line Breaks set each paragraph on one line; Height and Width without No Line Breaks keeps the width; Keep Proportions scales both sides until the text fits. IDML keeps all the options (`AutoSizing…`, `…ForAutoSizing` attributes). Not covered: frames of a thread other than the last, vertical frames, type on a path, and multi-column balancing in Keep Proportions. - Balance Columns (Text Frame Options › Balance Columns, `object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`): in the frame the story ends in, the columns after the last explicit column break fill to about the same depth (the last may be shorter by a line per column); keep options hold, spanning and split paragraphs keep their own balancing, vertical justification then applies to each column as usual, and vertical frames balance their bands. A frame the text runs on from, or that is overset, fills normally. - Text Frame Options from the Type tool (Object › Text Frame Options…, Cmd+B, `object.textFrameOptions` without `ids`): with the insertion point in a frame, the options change the frame it is drawn in; with text selected, every frame that holds part of it. Options a frame already has add no undo step. +- Properties › Text Frame (DesignCraft's own layout): columns and gutter; Inset Spacing with Top, Bottom, Left and Right and a link that makes all four the same (one Inset for a non-rectangular frame); four Vertical Justification buttons (Top, Center, Bottom, Justify); neither insets nor vertical justification for type on a path; Options opens Text Frame Options. With the Type tool in a frame the section shows too and changes the frame that shows the insertion point, or every frame that holds part of the selected text (`object.textFrameOptions {inset, verticalJustification}`). - Text Frame Options dialog, laid out as InDesign's (General, Column Rules, Baseline Options, Auto-Size; framed Columns, Inset Spacing and Vertical Justification groups with spinner fields; Fixed Number shows each column's width as the fields change). Preview shows the edits on the page until OK (one undo step) or Cancel. An invalid value (such as a gutter that isn't a measure) takes the preview off the page, so the frame shows as it was, and the dialog's status line gives the reason; OK refuses the value too. Preview stays checked and shows the edits again once the value is valid. Vertical Justification › Paragraph Spacing Limit (`object.textFrameOptions {paragraphSpacingLimit}`, IDML `VerticalThreshold`): with Justify, the extra space goes between paragraphs up to the limit, the rest between lines. - Text Frame Options › Inset Spacing for a non-rectangular frame (an oval, a polygon, a frame with corner options; when every selected text frame is one, a mixed selection keeps the four sides): Top, Left, Bottom, Right and the link are dimmed, and one Inset field sets the distance kept between the text and the frame's outline (`object.textFrameOptions {inset: }`, all four sides). - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable). From 67a5cb273ef40ff3190900bd2e2d2df6241d41e4 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:27:13 -0800 Subject: [PATCH 245/328] Tables: table commands are disabled with the caret in footnote text (#2706) Footnote text is addressed as a cell, so with the insertion point in a footnote the table commands (Insert Row, Delete Column, Merge Cells, Table Options, Select Table, table styles) were enabled and then failed with "no table 18446744073709551615". They are now disabled with "place the insertion point in a table", as the cell commands already were. The caret's footnote offset is no longer looked up in the main story either, where it could land on a table's paragraph. table.get and the other commands that take any selection report the same message instead of the footnote address. A call that names a table still runs. --- ROADMAP.md | 1 + crates/engine/src/cmd/table/target.rs | 5 ++- crates/engine/src/tests/table.rs | 45 +++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index ee0f4e022..c06cfceaa 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -400,6 +400,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. - **2026-11-12** · A decoded placed image becomes a screen pixmap in its own buffer, premultiplied in place, and opaque pixels are left as they are: 120 ms becomes 7 ms for a 24-megapixel opaque photo, with the same pixels. No readiness percentage change. +- **2026-11-12** · With the insertion point in footnote text, the table commands (Insert Row, Delete Column, Merge Cells, Table Options, Select Table, table styles) are disabled, as they are outside a table, instead of failing with "no table 18446744073709551615". A call that names a table still runs. No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. - **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change. diff --git a/crates/engine/src/cmd/table/target.rs b/crates/engine/src/cmd/table/target.rs index 0240aff23..a939a09dd 100644 --- a/crates/engine/src/cmd/table/target.rs +++ b/crates/engine/src/cmd/table/target.rs @@ -8,10 +8,12 @@ use super::{ pub(super) fn in_table(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; let st = s.active().ok_or("no document open")?; - if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) { + // Footnote text is addressed as a cell too, but isn't in a table. + if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some_and(|c| c.footnote_id().is_none())) { return Ok(()); } if let Some(t) = st.selection.text + && t.cell.is_none() && st.doc.story(t.story).is_some_and(|x| x.table_at(t.focus).is_some()) { return Ok(()); @@ -81,6 +83,7 @@ pub(super) fn target(s: &Session, p: &Value, cmd: &str) -> Result { (c.story, c.table, Some(c.range)) } else if let Some(t) = st.selection.text { match t.cell { + Some(c) if c.footnote_id().is_some() => return Err(bad(cmd, "place the insertion point in a table")), Some(c) => (t.story, c.table, Some(CellRange::cell(c.row, c.col))), None => { let tid = doc.story(t.story).and_then(|x| x.table_at(t.focus)).ok_or_else(|| bad(cmd, "the insertion point is not in a table"))?; diff --git a/crates/engine/src/tests/table.rs b/crates/engine/src/tests/table.rs index 7626005f4..fd5323ffb 100644 --- a/crates/engine/src/tests/table.rs +++ b/crates/engine/src/tests/table.rs @@ -643,6 +643,51 @@ fn a_named_table_edit_keeps_a_footnote_caret() { check(&s); } +/// A caret in footnote text is not in a table: the table commands that need one are disabled +/// there, also when the caret's offset in the footnote falls on a table's paragraph in the main +/// story, and a call that names a table still runs. +#[test] +fn table_commands_are_disabled_in_footnote_text() { + let in_table = ["table.insertRow", "table.deleteColumn", "table.merge", "table.options", "table.selectTable", "style.table.apply"]; + let info = |s: &Session, id: &str| crate::cmd::find_command(id).unwrap().info(s); + for on_table in [false, true] { + let (mut s, sid, _) = session_with_frame(); + let tid = if on_table { + s.execute("story.setText", &json!({"story": sid, "text": "Hello"})).unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + let end = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.len(); + s.execute("text.select", &json!({"story": sid, "anchor": end, "focus": end})).unwrap(); + s.execute("footnote.insert", &json!({})).unwrap(); + tid + } else { + let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap(); + s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap(); + s.execute("footnote.insert", &json!({"text": "Note"})).unwrap(); + tid + }; + let before = s.doc().unwrap().selection.clone(); + let caret = before.text.unwrap(); + assert!(caret.cell.and_then(|c| c.footnote_id()).is_some(), "the caret is in the footnote"); + let story = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap(); + assert_eq!(story.table_at(caret.focus).is_some(), on_table, "focus {}", caret.focus); + for id in in_table { + let i = info(&s, id); + assert!(!i.enabled, "{id} {on_table}"); + assert_eq!(i.disabled_reason.as_deref(), Some("place the insertion point in a table"), "{id} {on_table}"); + assert!(matches!(s.execute(id, &json!({})), Err(crate::EngineError::Disabled(..))), "{id} {on_table}"); + } + // A query that takes any selection and names no table is told where to put the caret. + let error = s.execute("table.get", &json!({})).unwrap_err().to_string(); + assert!(error.contains("place the insertion point in a table"), "{on_table}: {error}"); + assert_eq!(s.doc().unwrap().selection, before); + s.execute("table.insertRow", &json!({"table": tid})).unwrap(); + assert_eq!(s.execute("table.get", &json!({"table": tid})).unwrap()["rows"].as_array().unwrap().len(), 3); + assert_eq!(s.doc().unwrap().selection, before); + check(&s); + } +} + /// With nothing selected, the table commands stay disabled for menus and for calls that name no /// table. #[test] From 0f792e1fe9375183881cc5b64d446d9821757543 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:32:12 -0800 Subject: [PATCH 246/328] Compose: vertical justification moves an object kept within its column with its line (#2720) * Text wrap: an object kept within its column moves with its line Vertical justification treated an object positioned from its anchor and kept within its column as fixed, so its wrap stopped Center, Bottom and Justify where the object started, although the object moves down with its anchor's line until it reaches the column's bottom. A line now moves down at most the room above the object plus the distance the object can move before the column stops it. The story's object-mark positions are now collected once per composition instead of once per frame that holds an anchored object. * Compose: Justify keeps the room under an object held at the column's top An object kept within its column and held at the column's top moves only after its anchor's row has moved down far enough to bring it off the top. Justify took that distance off a later line's room even when the anchor's row moved less, so with the anchor in the first row, which stays in place, the later line stopped that distance short of the object's wrap. A line now moves its room plus how far the anchor's row moves past that distance. --- crates/compose/src/lib.rs | 102 +++++++++++++++++++++++++----------- crates/compose/src/tests.rs | 86 ++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 30 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 333959626..ab2a9ede7 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3626,6 +3626,8 @@ struct FinishInput<'a> { fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let FinishInput { doc, story, frames, cols, notes, out, boxes, span_paras, split_paras, grid_paras, styles_tab } = input; notes.finish(doc, story, frames, cols, out); + // The story byte of each anchored object's mark, found once for every frame that holds one. + let mut marks: Option> = None; // Ranges, content heights and vertical justification. for (fi, ft) in out.frames.iter_mut().enumerate() { let f = &frames[fi]; @@ -3641,9 +3643,12 @@ fn finish_composition(input: FinishInput<'_>) -> ComposedStory { let before: Vec = ft.tables.iter().map(|t| ft.lines.get(t.line).map_or(0.0, |l| l.baseline)).collect(); let spanned = ft.columns.len() > 1 && ft.lines.iter().any(|l| span_paras.get(l.para) == Some(&true)) || ft.lines.iter().any(|l| split_paras.get(l.para) == Some(&true)); - let anchors: Vec = - if ft.objects.is_empty() { Vec::new() } else { story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect() }; - vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, &anchors); + let anchors: &[usize] = if ft.objects.is_empty() { + &[] + } else { + marks.get_or_insert_with(|| story.text.match_indices(designcraft_doc::OBJECT_MARK).map(|(i, _)| i).collect()) + }; + vertical_justify(ft, f, spanned, &doc.footnote_options, grid_paras, anchors); for (t, b) in ft.tables.iter_mut().zip(before) { let now = ft.lines.get(t.line).map_or(b, |l| l.baseline); t.shift(now - b); @@ -6077,18 +6082,19 @@ fn vertical_justify( None => true, }; // Each row moves no further than a text wrap under it allows. An object that moves with its - // anchor's row (Justify) limits how much further than that row a later row moves. + // anchor's row (Justify) lets a later row move its room plus how far the object moves. let mut row_of = vec![None; ft.lines.len()]; for (&i, &k) in idx.iter().zip(&rows) { row_of[i] = Some(k); } - let follow: Vec<(usize, usize, f64)> = follow + let follow: Vec<(usize, usize, f64, f64)> = follow .iter() - .filter_map(|&(i, a, room)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0)))) + .filter_map(|&(i, a, room, pin)| Some((row_of.get(i).copied().flatten()?, row_of.get(a).copied().flatten()?, room.max(0.0), pin))) .collect(); + // The object moves only once its anchor's row has moved `pin`. let clear = |shift: &[f64]| { idx.iter().zip(&rows).all(|(&i, &k)| shift[k] <= rooms[i].max(0.0) + 1e-9) - && follow.iter().all(|&(k, m, room)| shift[k] - shift[m] <= room + 1e-9) + && follow.iter().all(|&(k, m, room, pin)| shift[k] <= room + (shift[m] - pin).max(0.0) + 1e-9) }; // The lowest lines are tested first: they are the ones a narrowing outline stops. let fits = |shift: &[f64]| { @@ -6206,13 +6212,16 @@ fn vertical_justify( /// box. Beside or under a contour, the line moves down only as far as its band stays clear of the /// contour on its way down (to 0.01 pt). Only wraps that reach into a line's column (or the /// columns it spans) count, as when the lines are set. An anchored object that moves with the -/// lines being justified (inline, above the line, or positioned from its anchor and not kept -/// within its column) is skipped, except under Justify, where it moves with the row of its -/// anchor's line: its wrap is taken where the object sits before the lines move, and its rooms go -/// in the second list as (line, anchor's line, room), so a line moves down at most that much -/// further than the anchor's row. Justify keeps the first row in place, so its room stays -/// infinite. `anchors` holds the story byte of each anchored object's mark, by object index. -fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64)>) { +/// lines being justified (inline, above the line, or positioned from its anchor) is skipped, +/// except under Justify, where it moves with the row of its anchor's line: its wrap is taken where +/// the object sits before the lines move, and its rooms go in the second list as (line, anchor's +/// line, room, pin), so a line moves down at most the room plus how far the anchor's row moves +/// past `pin`. An object positioned from its anchor and kept within its column moves with its +/// anchor's row until it stops at the column's bottom, so in every mode a line moves down at most +/// the room under it plus the distance the object can move. Held at the column's top, the object +/// moves only after its anchor's row has moved `pin` (0 for the other objects), and until then a +/// line keeps the whole room. Justify keeps the first row in place, so its room stays infinite. `anchors` holds the story byte of each anchored object's mark, by object index. +fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[usize]) -> (Vec, Vec<(usize, usize, f64, f64)>) { const EPS: f64 = 1e-6; // One-sided wraps also block the column on the other side of the object: the x-range wrap // `e` keeps text out of in column `col`, from the object's x-range `a..b` there (None when that @@ -6247,23 +6256,43 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } } // An own-story anchored object whose anchor is on one of these lines and whose position - // follows its line moves with the text: the index in `ft.lines` of its anchor's line, and how - // much lower that line was when the wrap was taken (an earlier pass placed the object after - // moving the lines). - let moves_with_text = |e: &Exclusion| -> Option<(usize, f64)> { + // follows its line moves with the text: the index in `ft.lines` of its anchor's line, how + // much lower the object was when the wrap was taken (an earlier pass placed the object after + // moving the lines), and, for one kept within its column, how far its line moves before the + // object leaves the column's top and how far the object then moves before it stops at the + // column's bottom (none and infinite for the others). + let moves_with_text = |e: &Exclusion| -> Option<(usize, f64, f64, f64)> { let o = *by_anchor.get(&e.after?)?; - let follows = match &o.object.position { - designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => true, - // Kept within the column, it can stop at the column's edge instead of following. - designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, .. } => { - *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor && !keep_within_column + let l = ft.lines.get(o.line)?; + let now = l.baseline; + let dy = e.anchor_baseline.map_or(0.0, |b| b - now); + match &o.object.position { + designcraft_doc::AnchorPosition::Inline { .. } | designcraft_doc::AnchorPosition::AboveLine { .. } => { + Some((o.line, dy, 0.0, f64::INFINITY)) } - }; - let now = ft.lines.get(o.line).map_or(0.0, |l| l.baseline); - follows.then(|| (o.line, e.anchor_baseline.map_or(0.0, |b| b - now))) + designcraft_doc::AnchorPosition::Custom { y_relative, keep_within_column, y_offset, object_point, .. } + if *y_relative == designcraft_doc::anchored::AnchorRelative::Anchor => + { + if !keep_within_column { + return Some((o.line, dy, 0.0, f64::INFINITY)); + } + // Placed as the lines' final positions place it: from its anchor's baseline, + // held between the column's top and bottom. + let col = ft.columns.get(l.column as usize).copied().unwrap_or(f.area); + let h = o.size.1; + let ofy = [0.0, 0.5, 1.0][(*object_point / 3).min(2) as usize]; + let (lo, hi) = (col.y0, (col.y1 - h).max(col.y0)); + let place = |b: f64| b + y_offset - h * ofy; + let raw = place(now); + let y = raw.clamp(lo, hi); + let then = e.anchor_baseline.map_or(y, |b| place(b).clamp(lo, hi)); + Some((o.line, then - y, (lo - raw).max(0.0), (hi - y).max(0.0))) + } + designcraft_doc::AnchorPosition::Custom { .. } => None, + } }; // Each wrap's object is looked up once, not for every line. - let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); + let moving: Vec> = f.exclusions.iter().map(moves_with_text).collect(); // Justify keeps the first row (its segments and a table on them) in place, so wraps under it // set no limit. let first = ft.lines.iter().find(|l| in_col(l.column)).map(|l| l.baseline); @@ -6290,13 +6319,15 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u let col = Rect { x0: col.x0.min(x0), x1: col.x1.max(x1), ..col }; let meets = |(a, b): (f64, f64)| a < x1 - EPS && b > x0 + EPS; for (e, &anchor) in f.exclusions.iter().zip(&moving).filter(|(e, _)| e.wraps_line(start)) { - if anchor.is_some() && !justify { + // Center and Bottom move every row as far: only an object kept within its column, which + // can stop at the column's edges, holds the lines back. + if anchor.is_some_and(|(_, _, _, slack)| slack == f64::INFINITY) && !justify { continue; } // The wrap where its object sits before the lines move (moved up by `dy`), and how // far it lets this line move down (relative to its anchor's row for an object that // moves with the text). - let dy = anchor.map_or(0.0, |(_, dy)| dy); + let dy = anchor.map_or(0.0, |(_, dy, _, _)| dy); let cap = if anchor.is_some() { f64::INFINITY } else { room }; let mut room_e = f64::INFINITY; let r = Rect { y0: e.rect.y0 - dy, y1: e.rect.y1 - dy, ..e.rect }; @@ -6335,7 +6366,18 @@ fn wrap_rooms(ft: &FrameText, f: &FrameSpec, c: u32, spanned: bool, anchors: &[u } } match anchor { - Some((a, _)) if room_e.is_finite() => follow.push((line, a, room_e)), + // An object kept within its column moves once its line has moved `pin` (to leave + // the column's top) and stops after moving `slack` (at the column's bottom). + Some((a, _, pin, slack)) if room_e.is_finite() => { + if room_e >= pin { + if justify { + follow.push((line, a, room_e, pin)); + } + room = room.min(room_e + slack); + } else { + room = room.min(room_e); + } + } Some(_) => {} None => room = room.min(room_e), } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ccc71578d..a37729faa 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -890,6 +890,92 @@ fn vertical_justification_stops_at_an_anchored_object_kept_within_its_column() { ); } +/// An object positioned from its anchor and kept within its column moves with its anchor's line +/// until it reaches the column's bottom, so Bottom moves the lines above it down that far, not +/// only as far as where the object starts. +#[test] +fn vertical_justification_moves_an_object_kept_within_its_column_until_it_stops() { + use designcraft_doc::VerticalJustification::{Bottom, Center, Justify}; + for vj in [Bottom, Center, Justify] { + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = vj; + // Hung 40 pt under the first baseline, under the second line, and far above the column's + // bottom. + anchor_box(&mut d, sid, 1, 0.0, 40.0, true, WrapMode::BoundingBox); + if let designcraft_doc::AnchorPosition::Custom { keep_within_column, .. } = + &mut std::sync::Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).position + { + *keep_within_column = true; + } + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + let o = &cs.frames[0].objects[0]; + let (top, bottom) = (o.origin.y, o.origin.y + 60.0); + let l = lines[1]; + assert!(l.baseline <= top + 1e-6, "{vj:?}: the second line at {} meets the object at {top}..{bottom}", l.baseline); + match vj { + // The object stops at the column's bottom and the second line comes down onto it. + Bottom => { + assert!((bottom - 400.0).abs() < 1e-6, "{vj:?}: the object stopped at {top}..{bottom}, above the column's bottom"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Justify keeps the first line, and the object anchored in it, in place; the second + // line comes down onto the object. + Justify => { + assert!((top - lines[0].baseline - 40.0).abs() < 1e-6, "{vj:?}: the object moved to {top}..{bottom}"); + assert!(l.baseline > top - 0.01, "{vj:?}: the second line stopped at {}, above the object at {top}", l.baseline); + } + // Center moves the lines half of the room under them: the object moves with them. + _ => assert!(bottom < 400.0 - 1e-6 && l.baseline > 150.0, "{vj:?}: second line at {}, object at {top}..{bottom}", l.baseline), + } + } +} + +/// An object anchored in the first line, positioned from its anchor and kept within its column, +/// is held at the column's top. Justify keeps the first line in place, so the object stays there, +/// and the second line comes down onto the wider lower part of its contour. +#[test] +fn vertical_justify_keeps_the_room_under_an_object_held_at_the_columns_top() { + use designcraft_doc::anchored::AnchorRelative as R; + let (mut d, sid, fid) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 400.0), ParaAttrs::default()); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = designcraft_doc::VerticalJustification::Justify; + // Beside the lines at x 250..300 down to y 100, then x 100..300 down to y 160. + let pts = [ + Point::new(150.0, 0.0), + Point::new(200.0, 0.0), + Point::new(200.0, 160.0), + Point::new(0.0, 160.0), + Point::new(0.0, 100.0), + Point::new(150.0, 100.0), + ]; + let lid = d.default_layer(); + let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true)); + let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, path); + it.wrap.mode = WrapMode::Contour; + it.wrap.side = WrapSide::BothSides; + // 50 pt above the first baseline, so the column's top holds it. + let position = designcraft_doc::AnchorPosition::Custom { + x_relative: R::TextFrame, + y_relative: R::Anchor, + x_offset: 100.0, + y_offset: -50.0, + object_point: 0, + ref_point: 0, + keep_within_column: true, + spine_relative: false, + }; + d.story_mut(sid).unwrap().insert_object(1, designcraft_doc::AnchoredObject::new(it, position)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let lines = all_lines(&cs); + assert_eq!(lines.len(), 2); + let top = cs.frames[0].objects[0].origin.y; + assert!(lines[0].baseline < 50.0 && top.abs() < 1e-6, "the object is held at the column's top: {top}, {}", lines[0].baseline); + let wide = top + 100.0; + let b = lines[1].baseline; + assert!(b <= wide + 1e-6, "Justify moved the second line to {b}, into the contour's wider part at {wide}"); + assert!(b > wide - 0.01, "Justify stopped the second line at {b}, short of the contour's wider part at {wide}"); +} + /// Justify keeps the first line in place and moves later lines further, so an object anchored in /// the first line and hung under the last one still stops the lines after its anchor. #[test] From 33f0c21510bb765dcfc3fd2a6d87c17af3ddb9d4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:40:51 -0500 Subject: [PATCH 247/328] Estimate reduced JPEG cache and decode sizes --- crates/render/src/images.rs | 83 ++++++++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8ae0691c7..fd937903d 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -172,6 +172,54 @@ pub(crate) struct Want { pub on_screen: f64, } +/// Dimensions of the JPEG mip level selected for a request. `None` means the request uses the +/// full decode or is not an eligible JPEG, so warming must reserve its full decode size. +fn reduced_sizes(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let (mut w, mut h) = crate::image_size(bytes)?; + let ppt = w as f64 / width_pt.max(1e-6); + let mut sizes = vec![(w, h)]; + while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { + (w, h) = ((w / 2).max(1), (h / 2).max(1)); + sizes.push((w, h)); + } + Some(sizes) +} + +/// Cache and peak decode estimates for a group of requests that all use reduced JPEG mips. +fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { + let mut dims = None; + let mut levels = [false; 9]; + let mut peak = 0usize; + for w in wants { + let sizes = reduced_sizes(&w.bytes, w.page, w.width_pt, w.on_screen)?; + let level = sizes.len() - 1; + if level == 0 { + return None; + } + let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + for cached in shrink..=level { + levels[cached] = true; + } + let denom = 1u32 << shrink; + let (w_px, h_px) = sizes[0]; + // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. + let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; + peak = peak.max(decode_pixels.saturating_mul(8)); + if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { + dims = Some(sizes); + } + } + let dims = dims?; + let cached = levels.iter().enumerate().filter(|(_, keep)| **keep).fold(0usize, |n, (level, _)| { + let (w, h) = dims[level]; + n.saturating_add(w as usize * h as usize * 4) + }); + Some((cached, peak)) +} + /// Threads [`warm`] decodes on (1 on the web, which has none). fn workers() -> usize { #[cfg(target_arch = "wasm32")] @@ -270,7 +318,8 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let full = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let (size, decoding) = reduced_estimates(&wanted).unwrap_or(full); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -338,21 +387,12 @@ fn waited(job: &[Want]) { /// and halved from there, so a screen-sized level needs no full-size decode. `None` when the /// full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). fn reduced(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { - if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let id = Arc::as_ptr(bytes) as usize; if with(|c| c.bad.contains_key(&(id, page))) { return None; } // The level `mip` picks from a full decode, with each level's size as `halve` gives it. - let (mut w, mut h) = crate::image_size(bytes)?; - let ppt = w as f64 / width_pt.max(1e-6); - let mut sizes = vec![(w, h)]; - while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { - (w, h) = ((w / 2).max(1), (h / 2).max(1)); - sizes.push((w, h)); - } + let sizes = reduced_sizes(bytes, page, width_pt, on_screen)?; let level = u8::try_from(sizes.len() - 1).ok()?; if level == 0 { return None; @@ -506,10 +546,11 @@ mod tests { let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); let decoding = decode_peak_bytes(&d, 0); - assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); + let reserved = decoding * 3 / 2; + assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { @@ -526,8 +567,9 @@ mod tests { let (f, g) = (psd(5500), psd(5500)); let decoding = decode_peak_bytes(&f, 0); assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); - assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); - assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + let reserved = decoding * 3 / 2; + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(reserved, decode_peak_bytes(&g, 0) * 3 / 2)); + assert_eq!(warm(vec![want(&f), want(&g)]), reserved, "one decode at a time"); // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. let mut deep = Vec::new(); let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); @@ -601,6 +643,17 @@ mod tests { assert_eq!((full.width(), full.height()), (1024, 768)); } + #[test] + fn warm_estimates_a_jpegs_reduced_levels() { + let bytes = jpeg(1024, 768); + let want = Want { bytes: bytes.clone(), page: 0, width_pt: 1024.0, on_screen: 0.1 }; + let (cached, peak) = reduced_estimates(&[want]).unwrap(); + assert_eq!(cached, 128 * 96 * 4, "only the selected eighth-size mip is cached"); + assert_eq!(peak, 128 * 96 * 8, "only the selected eighth-size mip is decoded"); + let full = decode_sizes(&bytes, 0); + assert!(cached < full.0 && peak < full.1, "reduced estimates {cached}/{peak}, full {full:?}"); + } + #[test] fn reduced_levels_of_odd_sized_jpegs_have_the_halved_size() { let bytes = jpeg(1001, 771); From 764b06526bc4d4ff5f1ddb27d1478c3beb9729d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:41:55 -0500 Subject: [PATCH 248/328] Estimate reduced JPEG warm reservations --- crates/images/src/jpeg.rs | 30 ++++++++++++++++++++++++++++++ crates/images/src/lib.rs | 6 ++++++ crates/render/src/images.rs | 7 ++----- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index a4a2a0971..8e504d72c 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -65,6 +65,36 @@ pub(crate) fn decode_cmyk(bytes: &[u8]) -> Option<(CmykRaster, Option>)> /// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. pub(crate) const MAX_SHRINK: u8 = 3; +/// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder +/// cannot handle the JPEG, including its full-size resource limits. +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + use jpeg_decoder::{CodingProcess, PixelFormat}; + if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { + return None; + } + let mut d = jpeg_decoder::Decoder::new(bytes); + d.set_max_decoding_buffer_size(MAX_BYTES); + d.read_info().ok()?; + let info = d.info()?; + let colour = match info.pixel_format { + PixelFormat::RGB24 => true, + PixelFormat::L8 => false, + PixelFormat::L16 | PixelFormat::CMYK32 => return None, + }; + if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { + return None; + } + if info.coding_process == CodingProcess::DctProgressive { + let side = |n: u16| u64::from(n).next_multiple_of(32); + let components: u64 = if colour { 3 } else { 1 }; + if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + return None; + } + } + let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); + Some((reduced(info.width), reduced(info.height))) +} + /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for /// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, /// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. `None` as well for a diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index e925de471..07f91a467 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,6 +510,12 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the +/// reduced decoder cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + jpeg::reduced_size(bytes, shrink) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index fd937903d..4df71f42b 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,14 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in shrink..=level { levels[cached] = true; } - let denom = 1u32 << shrink; - let (w_px, h_px) = sizes[0]; - // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. - let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; - peak = peak.max(decode_pixels.saturating_mul(8)); + peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 437c53251152b651f2352edb0a4f803000bda24d Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Thu, 12 Nov 2026 14:42:10 -0800 Subject: [PATCH 249/328] Compose: count endnote, anchored object and cross-reference marks once per story (#2705) * Compose: count endnote, anchored object and cross-reference marks once per story Each paragraph of a story with endnotes, anchored objects or cross-references counted the marks before it from the story start, so composing the story read its text once per paragraph. The marks before each paragraph are now counted in one pass when composition starts. * Compose: test cross-reference mark counts past the first paragraph The mark-count fixture now puts a cross-reference in every paragraph, so the test checks nonzero cross-reference counts and that each paragraph shows its own cross-reference's text. --------- Co-authored-by: Dylan M. Taylor --- ROADMAP.md | 1 + crates/compose/src/lib.rs | 64 ++++++++++++++++++++++++++++++++--- crates/compose/src/tests.rs | 67 +++++++++++++++++++++++++++++++++++++ crates/compose/src/xref.rs | 17 +++++++++- 4 files changed, 144 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c06cfceaa..961d69281 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -396,6 +396,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m - **2026-11-12** · Properties › Text Frame shows the frame's inset spacing (Top, Bottom, Left and Right with a link that makes all four the same; one Inset for a non-rectangular frame) and four Vertical Justification buttons (Top, Center, Bottom, Justify), and the section also shows with the Type tool in a frame, where it changes the frame that shows the insertion point. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. +- **2026-11-12** · Composing a story with endnotes, anchored objects or cross-references counts their marks in one pass over the story, instead of counting again from the story start for every paragraph. No readiness percentage change. - **2026-11-12** · Center, Bottom and Justify vertical justification in a shaped frame test each moved line against the outline down to its baseline. The descenders of earlier lines may cross the outline, as the last line's do, so an outline that narrows under an earlier line no longer holds the text higher by that line's descent. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · A placed JPEG drawn at a half, a quarter or an eighth of its pixel size or less is decoded at that size straight from its compressed blocks, so the canvas, page thumbnails and loaded-graphic thumbnails no longer decode and keep the full-size picture for it. CMYK JPEGs and the full size still decode in full. No readiness percentage change. diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ab2a9ede7..81cdad56a 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1294,10 +1294,63 @@ struct SubstitutionInput<'a> { var_story: bool, var_cache: &'a mut HashMap<(Option, bool), Arc>>, notes: &'a mut Notes, + /// The marks in the story before `range`. + marks: MarkCounts, +} + +/// Endnote references, anchored-object marks and cross-reference marks in a stretch of story text. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct MarkCounts { + endnotes: usize, + objects: usize, + xrefs: usize, +} + +#[cfg(test)] +thread_local! { + /// Bytes of story text [`MarkCounts::of`] has read on this thread. + static MARK_BYTES_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +impl MarkCounts { + /// The marks in `text`. + fn of(text: &str) -> Self { + #[cfg(test)] + MARK_BYTES_SCANNED.with(|n| n.set(n.get() + text.len())); + let mut m = Self::default(); + for c in text.chars() { + match c { + designcraft_doc::ENDNOTE_REF => m.endnotes += 1, + designcraft_doc::OBJECT_MARK => m.objects += 1, + designcraft_doc::XREF_MARK => m.xrefs += 1, + _ => {} + } + } + m + } + + /// The marks before each paragraph of `ranges` (the story's paragraphs, in order), read in + /// one pass over the story. Empty when the story holds no endnotes, anchored objects or + /// cross-references. + fn before_paragraphs(story: &Story, ranges: &[Range]) -> Vec { + if story.endnotes.is_empty() && story.objects.is_empty() && story.xrefs.is_empty() { + return Vec::new(); + } + let mut total = Self::default(); + ranges + .iter() + .map(|r| { + let before = total; + let m = story.text.get(r.clone()).map_or_else(Self::default, Self::of); + total = Self { endnotes: total.endnotes + m.endnotes, objects: total.objects + m.objects, xrefs: total.xrefs + m.xrefs }; + before + }) + .collect() + } } fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { - let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes } = input; + let SubstitutionInput { doc, story, range: prange, props: pp, frame: cur_frame, opts, var_story, var_cache, notes, marks } = input; let var_values = if var_story { let page = opts.page.or_else(|| cur_frame.and_then(|f| f.page)); // A parent page itself (not composed for one of the pages it applies to). @@ -1319,13 +1372,13 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { }; if !story.endnotes.is_empty() { // Endnote reference numbers continue through the document. - let first = doc.endnote_start(story.id).saturating_add(story.text[..prange.start].matches(designcraft_doc::ENDNOTE_REF).count() as u32); + let first = doc.endnote_start(story.id).saturating_add(u32::try_from(marks.endnotes).unwrap_or(u32::MAX)); for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::ENDNOTE_REF).enumerate() { sub.notes.insert(prange.start + i, doc.endnote_options.label(first.saturating_add(k as u32))); } } if !story.objects.is_empty() { - let before = story.text[..prange.start].matches(designcraft_doc::OBJECT_MARK).count(); + let before = marks.objects; for (k, (i, _)) in story.text[prange.clone()].match_indices(designcraft_doc::OBJECT_MARK).enumerate() { let Some(o) = story.objects.get(before + k) else { continue }; let (w, h) = o.size(); @@ -1338,7 +1391,7 @@ fn paragraph_substitution(input: SubstitutionInput<'_>) -> SubstCtx { } } if !story.xrefs.is_empty() { - sub.xrefs = xref::texts_in(doc, story, prange.clone(), opts.xrefs.as_deref()); + sub.xrefs = xref::texts_after(doc, story, prange.clone(), marks.xrefs, opts.xrefs.as_deref()); } if notes.active() { notes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub); @@ -3157,6 +3210,8 @@ fn compose_run( let mut list_counter = ListCounter::default(); // Named lists number independently of layout: one pass up front, for the labels. let named_labels = named_list_labels(doc, story, ¶_ranges, &deleted); + // Endnote, anchored-object and cross-reference marks before each paragraph, for their numbers. + let marks_before = MarkCounts::before_paragraphs(story, ¶_ranges); // Border and shading of each paragraph set, drawn once the lines are in place. let mut boxes: Vec> = vec![None; np]; // Keep options: paragraphs are re-laid from a snapshot when a keep is violated, either forced @@ -3316,6 +3371,7 @@ fn compose_run( var_story, var_cache: &mut var_cache, notes: &mut notes, + marks: marks_before.get(pi).copied().unwrap_or_default(), }); #[cfg(test)] reuse::SHAPED.with(|n| n.set(n.get() + 1)); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a37729faa..a0eac4061 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8689,6 +8689,73 @@ fn spine_relative_anchored_notes_stay_in_the_outside_margin_on_both_pages() { const OBJECT_LEN: usize = designcraft_doc::OBJECT_MARK.len_utf8(); +/// A story of `paras` paragraphs, each with an inline anchored object at its start, an endnote +/// reference after it and a cross-reference that shows `Ref.` for paragraph `k`. +fn story_with_marks(paras: usize) -> (Document, StoryId) { + let text = vec!["Some words, a note and an object."; paras].join("\n"); + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 20_000.0), ParaAttrs::default()); + let starts: Vec = d.story(sid).unwrap().para_ranges().iter().map(|r| r.start).collect(); + let lid = d.default_layer(); + for (k, &s) in starts.iter().enumerate().rev() { + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + lid, + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let story = d.story_mut(sid).unwrap(); + story.insert_xref(s + 19, designcraft_doc::CrossRef { text: Some(format!("Ref{k}.")), ..Default::default() }); + story.insert_endnote(s + 10, "An endnote.", ParaFormat::default()); + story.insert_object(s, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + } + (d, sid) +} + +/// The marks before each paragraph match a count from the story start, for every kind of mark. +#[test] +fn mark_counts_before_each_paragraph_match_a_count_from_the_start() { + let (d, sid) = story_with_marks(5); + let story = d.story(sid).unwrap(); + let ranges = story.para_ranges(); + let counts = MarkCounts::before_paragraphs(story, &ranges); + assert_eq!(counts.len(), ranges.len()); + for (k, (r, m)) in ranges.iter().zip(&counts).enumerate() { + let head = &story.text[..r.start]; + assert_eq!(m.endnotes, head.matches(designcraft_doc::ENDNOTE_REF).count(), "paragraph {k}"); + assert_eq!(m.objects, head.matches(designcraft_doc::OBJECT_MARK).count(), "paragraph {k}"); + assert_eq!(m.xrefs, head.matches(designcraft_doc::XREF_MARK).count(), "paragraph {k}"); + assert_eq!(*m, MarkCounts { endnotes: k, objects: k, xrefs: k }, "paragraph {k}"); + } + // Each paragraph shows its own cross-reference's text, so the composer numbers the + // cross-references from the marks before the paragraph. + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let shown: String = cs.frames[0].lines.iter().flat_map(|l| l.glyphs.iter().filter(|g| g.visible).map(|g| g.rendered_char)).collect(); + let refs: Vec<&str> = shown.match_indices("Ref").map(|(i, _)| &shown[i..i + 5]).collect(); + assert_eq!(refs, ["Ref0.", "Ref1.", "Ref2.", "Ref3.", "Ref4."], "{shown:?}"); + // A story without endnotes, anchored objects or cross-references reads nothing. + let (plain, psid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let p = plain.story(psid).unwrap(); + assert!(MarkCounts::before_paragraphs(p, &p.para_ranges()).is_empty()); +} + +/// Composing a story with endnotes, anchored objects and cross-references reads its text for their numbers in one +/// pass, so four times the paragraphs read about four times the bytes, not sixteen times. +#[test] +fn composing_reads_marks_once_per_story() { + let scanned = |paras: usize| { + let (d, sid) = story_with_marks(paras); + MARK_BYTES_SCANNED.with(|n| n.set(0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(!cs.is_overset()); + assert_eq!(cs.frames[0].objects.len(), paras); + (MARK_BYTES_SCANNED.with(std::cell::Cell::get), d.story(sid).unwrap().text.len()) + }; + let (small, small_len) = scanned(40); + let (big, big_len) = scanned(160); + assert!(small > 0); + assert!(big * small_len <= 2 * small * big_len, "40 paragraphs read {small} of {small_len} bytes, 160 read {big} of {big_len}"); +} + #[test] fn anchored_object_wraps_its_own_storys_later_lines() { let text = [LOREM; 4].join(" "); diff --git a/crates/compose/src/xref.rs b/crates/compose/src/xref.rs index 1d72f1ee1..d658eb3d9 100644 --- a/crates/compose/src/xref.rs +++ b/crates/compose/src/xref.rs @@ -68,11 +68,26 @@ pub fn xref_text(doc: &Document, x: &xref::CrossRef, index: Option<&XrefIndex>) /// Generated text of the cross-references in `range` of `story`, by byte of their mark. pub fn texts_in(doc: &Document, story: &Story, range: std::ops::Range, index: Option<&XrefIndex>) -> HashMap { + if story.xrefs.is_empty() { + return HashMap::new(); + } + let before = story.text[..range.start].matches(XREF_MARK).count(); + texts_after(doc, story, range, before, index) +} + +/// [`texts_in`] for a caller that already knows `before`, the number of cross-reference marks in +/// `story` before `range`. +pub(crate) fn texts_after( + doc: &Document, + story: &Story, + range: std::ops::Range, + before: usize, + index: Option<&XrefIndex>, +) -> HashMap { let mut out = HashMap::new(); if story.xrefs.is_empty() { return out; } - let before = story.text[..range.start].matches(XREF_MARK).count(); for (k, (i, _)) in story.text[range.clone()].match_indices(XREF_MARK).enumerate() { if let Some(x) = story.xrefs.get(before + k) { out.insert(range.start + i, xref_text(doc, x, index)); From 067fc9712842f50779f3069aa3ff901f9b3a2acd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:45:02 -0500 Subject: [PATCH 250/328] Use iterator for reduced mip accounting --- crates/render/src/images.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4df71f42b..e2d49873c 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -201,8 +201,8 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; - for cached in shrink..=level { - levels[cached] = true; + for cached in levels.iter_mut().take(level + 1).skip(shrink) { + *cached = true; } peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { From 1c3285d8a3affaec03949c7fa2b610c4b94dcc34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:11 -0500 Subject: [PATCH 251/328] Count progressive JPEG buffers in warm budget --- crates/images/src/jpeg.rs | 16 +++++++++++----- crates/images/src/lib.rs | 7 ++++--- crates/render/src/images.rs | 4 ++-- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 8e504d72c..9db1709cc 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; @@ -84,15 +84,21 @@ pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { return None; } - if info.coding_process == CodingProcess::DctProgressive { + let progressive_bytes = if info.coding_process == CodingProcess::DctProgressive { let side = |n: u16| u64::from(n).next_multiple_of(32); let components: u64 = if colour { 3 } else { 1 }; - if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + let bytes = side(info.width) * side(info.height) * components * 2; + if bytes > MAX_BYTES as u64 { return None; } - } + usize::try_from(bytes).ok()? + } else { + 0 + }; let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); - Some((reduced(info.width), reduced(info.height))) + let (width, height) = (reduced(info.width), reduced(info.height)); + let output_bytes = width as usize * height as usize * 8; + Some((width, height, progressive_bytes.saturating_add(output_bytes))) } /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 07f91a467..9afb009fa 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,9 +510,10 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } -/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the -/// reduced decoder cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +/// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its +/// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder +/// cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { jpeg::reduced_size(bytes, shrink) } diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index e2d49873c..8e57ef448 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,11 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } - peak = peak.max(decoded_w as usize * decoded_h as usize * 8); + peak = peak.max(decode_peak); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 2eff7e822f799bb740d0bc0447a0c7cdead1c679 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:36 -0500 Subject: [PATCH 252/328] Name reduced JPEG estimate API --- crates/images/src/jpeg.rs | 2 +- crates/images/src/lib.rs | 4 ++-- crates/render/src/images.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 9db1709cc..b6ef06c09 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { +pub(crate) fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 9afb009fa..334a62ed9 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -513,8 +513,8 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option /// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its /// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder /// cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { - jpeg::reduced_size(bytes, shrink) +pub fn reduced_jpeg_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { + jpeg::reduced_estimate(bytes, shrink) } /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8e57ef448..01746f19e 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,7 +200,7 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_estimate(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } From 28d85282834b2861973b2b439e1d9cc639eabfd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:23:04 -0800 Subject: [PATCH 253/328] Images: fit the one-at-a-time warm test to the decode headroom With the 3/2 headroom on each decode, a 6,500 pixel square PSD reserves more than half the budget, so the small image can no longer decode beside it and the test failed before calling warm. 5,000 pixel square images still reserve more than half the budget as a pair and leave room for the small image beside one. --- crates/render/src/images.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 01746f19e..16890b591 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -536,19 +536,19 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 6,500 pixel square images fit the budget together, but decoding both at once would - // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); + // Two 5,000 pixel square images take less than half the budget cached, but decoding both + // at once would reserve more than half of it; the small image still decodes beside one. + let (d, e, small) = (psd(5000), psd(5000), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); - assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(2 * large <= BUDGET / 2); let decoding = decode_peak_bytes(&d, 0); let reserved = decoding * 3 / 2; assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); - assert!(peak >= decoding, "the large images were decoded ahead"); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= reserved, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); From dbb334c529d76e4f3d22afaa86c0a8b10f3a0216 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:27:11 -0800 Subject: [PATCH 254/328] Images: pick the images to decode ahead with the scaled stroke and effect bounds The draw path scales an item's stroke extent and effect outset by its transform before culling; the pass that picks images to decode ahead used the unscaled values, so a scaled image whose stroke or shadow reaches the view decoded on the render thread. --- crates/render/src/draw.rs | 7 +++++-- crates/render/src/tests.rs | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 91a492b2e..95e0a159c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -99,8 +99,11 @@ fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec