From d51a650a6285d5d62d846a2c0eb7b3fb07ff34c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 03:57:51 +0000 Subject: [PATCH 001/133] Anchored objects: select and resize them with the Selection tool An inline (or above-line, or custom) anchored object lives in its story, not on a spread, so the Selection tool never found it: a click selected the text frame around it. Now: - Selection gains `anchored: {story, index}`. `anchored.select` selects one; selecting items clears it. - The Selection tool selects an anchored object where composition placed it. A drag doesn't move it (it flows with the text) and a double click selects it rather than editing the text around it. The canvas draws its bounding box and handles. - A handle drag runs `anchored.resize {from, to}` (the object's own space): the frame resizes and crops its content, Cmd scales the content with it, Shift keeps the proportions; the text reflows live and the drag is one undo step. - Delete removes a selected anchored object from the text; Anchored Object Options and Release act on it. Objects in footnotes and table cells, and objects whose frame turns them, are not resized by handles yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- ROADMAP.md | 1 + crates/doc/src/selection.rs | 15 ++- crates/engine/src/cmd/anchored.rs | 182 +++++++++++++++++++++++++++++- crates/engine/src/cmd/edit.rs | 8 ++ crates/tools/src/anchored.rs | 77 +++++++++++++ crates/tools/src/lib.rs | 1 + crates/tools/src/select.rs | 67 ++++++++++- crates/tools/src/tests.rs | 53 +++++++++ crates/ui-egui/src/canvas.rs | 13 +++ docs/target-app-parity.md | 5 +- 10 files changed, 416 insertions(+), 6 deletions(-) create mode 100644 crates/tools/src/anchored.rs diff --git a/ROADMAP.md b/ROADMAP.md index 9bd0274ef..68cd77182 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-16** · Inline and other anchored objects can be selected and resized on the page: the Selection tool clicks one where it sits in the text and shows its handles, a handle drag resizes its frame (cropping; Cmd scales the content, Shift keeps proportions) while the text reflows, and Delete removes it from the text. Anchored Object Options and Release act on the selected object. Before, a click selected the text frame around it. No readiness percentage change. - **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index 2d28bf2c2..63ad1aa1b 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -61,6 +61,16 @@ impl TextSel { } } +/// An anchored object (inline, above line or custom) selected as an object: the `index`-th of +/// `story`'s [`crate::Story::objects`]. It lives in the text, not on a spread, so it isn't one of +/// [`Selection::items`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AnchoredSel { + pub story: StoryId, + pub index: usize, +} + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Selection { @@ -83,11 +93,14 @@ pub struct Selection { /// The page selected with the Page tool (absolute index). #[serde(default, skip_serializing_if = "Option::is_none")] pub page: Option, + /// An anchored object selected with the Selection tool. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub anchored: Option, } impl Selection { pub fn is_empty(&self) -> bool { - self.items.is_empty() && self.text.is_none() && self.cells.is_none() + self.items.is_empty() && self.text.is_none() && self.cells.is_none() && self.anchored.is_none() } pub fn len(&self) -> usize { self.items.len() diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index dc7127459..f2102f6ed 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use designcraft_doc::{ - AnchorPosition, AnchoredObject, Content, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign, + AnchorPosition, AnchoredObject, AnchoredSel, Content, Document, Item, ItemId, OBJECT_MARK, SpreadRef, StoryId, TextSel, anchored::AnchorAlign, }; use designcraft_geom::Affine; use serde_json::{Value, json}; @@ -40,6 +40,24 @@ pub fn specs() -> Vec { has_doc, release ), + cmd!( + noundo "anchored.select", + "Select Anchored Object", + [], + None, + "{story, index} — selects the anchored object as an object (the Selection tool clicking it); Delete removes it from the text, anchored.resize / options / release act on it", + has_doc, + select + ), + cmd!( + "anchored.resize", + "Resize Anchored Object", + [], + None, + "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it)} — the text reflows around the new size", + has_doc, + resize + ), cmd!(query "anchored.list", "Anchored Objects", [], None, "{story?} → [{story, index, pos, position, size}]", has_doc, |s, p| { let d = &s.doc()?.doc; let only = p.get("story").and_then(Value::as_u64).map(StoryId); @@ -164,9 +182,12 @@ fn insert(s: &mut Session, p: &Value) -> Result { /// `{story, index}`, or the anchored object at (or just before) the text insertion point. fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { if let (Some(sid), Some(k)) = (p.get("story").and_then(Value::as_u64), p.get("index").and_then(Value::as_u64)) { - return Ok((StoryId(sid), k as usize)); + return Ok((StoryId(sid), usize::try_from(k).map_err(|_| bad(cmd, "index out of range"))?)); } let st = s.doc()?; + if let Some(a) = st.selection.anchored { + return Ok((a.story, a.index)); + } let t = st .selection .text @@ -182,6 +203,81 @@ fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { Ok((t.story, story.text[..at].matches(OBJECT_MARK).count())) } +fn select(s: &mut Session, p: &Value) -> Result { + let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| bad("anchored.select", "missing story"))?; + let k = p.get("index").and_then(Value::as_u64).and_then(|k| usize::try_from(k).ok()).ok_or_else(|| bad("anchored.select", "missing index"))?; + let st = s.doc_mut()?; + if st.doc.story(sid).and_then(|x| x.objects.get(k)).is_none() { + return Err(bad("anchored.select", "no such anchored object")); + } + st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: k }), ..Default::default() }; + st.bump_revision(); + Ok(Value::Null) +} + +/// Resize an anchored object's frame from its bounds `from` to `to` (its own space). Its top-left +/// stays at the origin, where composition places it; the text reflows around the new size. +fn resize(s: &mut Session, p: &Value) -> Result { + let (sid, k) = object_ref(s, p, "anchored.resize")?; + let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?; + let to = super::rect_param(p, "to").ok_or_else(|| bad("anchored.resize", "missing to"))?; + let finite = |r: designcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); + if !finite(from) || !finite(to) || from.width().abs() < 1e-9 || from.height().abs() < 1e-9 { + return Err(bad("anchored.resize", "degenerate or non-finite rect")); + } + // At least a point each way, at most the largest page InDesign allows. + const MIN: f64 = 1.0; + const MAX: f64 = 15552.0; + let sx = to.width().abs().clamp(MIN, MAX) / from.width().abs(); + let sy = to.height().abs().clamp(MIN, MAX) / from.height().abs(); + let m = Affine::translate((to.x0.min(to.x1), to.y0.min(to.y1))) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); + let content = p.get("content").and_then(Value::as_bool).unwrap_or(false); + let strokes = s.prefs.scale_strokes; + s.edit(|d, _| { + let st = d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; + let o = st.objects.get_mut(k).ok_or_else(|| bad("anchored.resize", "no such anchored object"))?; + let o = Arc::make_mut(o); + let it = &mut o.item; + if it.locked { + return Err(bad("anchored.resize", "the object is locked")); + } + if content { + super::object::scale_item(it, m, (sx * sy).sqrt(), strokes); + } else if matches!(it.content, Content::Group { .. }) { + it.xf = m * it.xf; + } else { + let inner = it.xf.inverse() * m * it.xf; + super::object::bake(it, inner); + let r = it.inner_bounds(); + if let Content::Graphic(g) = &mut it.content + && let Some(xf) = g.fitted(r, g.auto_fit) + { + g.xf = xf; + } + } + // Composition places the object by its top-left: keep that at the origin. + let b = it.bounds(); + it.xf = Affine::translate((-b.x0, -b.y0)) * it.xf; + let size = o.size(); + st.rev = st.rev.wrapping_add(1); + Ok(json!({"size": [size.0, size.1]})) + }) +} + +/// Delete a selected anchored object: its mark leaves the text, and the object with it. +pub(crate) fn delete(s: &mut Session, a: AnchoredSel) -> Result { + let pos = { + let st = s.doc()?.doc.story(a.story).ok_or_else(|| bad("edit.clear", "no such story"))?; + st.text.match_indices(OBJECT_MARK).nth(a.index).map(|(i, _)| i).ok_or_else(|| bad("edit.clear", "no such anchored object"))? + }; + s.edit(|d, sel| { + let st = d.story_mut(a.story).ok_or(designcraft_doc::DocError::NoStory(a.story))?; + st.delete(pos..pos + OBJECT_MARK.len_utf8()); + *sel = designcraft_doc::Selection::default(); + Ok(json!({"deleted": 1})) + }) +} + fn options(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.options")?; let cur = s.doc()?.doc.story(sid).and_then(|st| st.objects.get(k).cloned()).ok_or_else(|| bad("anchored.options", "no such anchored object"))?; @@ -231,6 +327,88 @@ fn release(s: &mut Session, p: &Value) -> Result { mod tests { use super::*; + /// A text frame whose story holds a 24 × 40 inline box: (session, story). + fn inline_box() -> (Session, StoryId) { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Before after and more words."})).unwrap(); + let sid = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + let r = s.execute("frame.create", &json!({"rect": [450, 450, 474, 490]})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 7})).unwrap(); + (s, sid) + } + + #[test] + fn a_selected_inline_object_resizes_and_the_line_follows() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.anchored, Some(AnchoredSel { story: sid, index: 0 })); + assert!(sel.items.is_empty() && sel.text.is_none() && !sel.is_empty()); + // Taller by its bottom handle: the line grows to fit it; its top-left stays at the origin. + let r = s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).unwrap(); + assert_eq!(r["size"], json!([24.0, 60.0])); + let d = s.doc().unwrap().doc.clone(); + let b = d.story(sid).unwrap().objects[0].item.bounds(); + assert!(b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); + let cs = s.cache.get(&d, sid, None); + let o = &cs.frames[0].objects[0]; + assert!(cs.frames[0].lines[o.line].ascent >= 60.0); + // Narrower from its left handle: still at the origin, 10 pt wide. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 60], "to": [14, 0, 24, 60]})).unwrap(); + let o = s.doc().unwrap().doc.story(sid).unwrap().objects[0].clone(); + assert_eq!(o.size(), (10.0, 60.0)); + assert!(o.item.bounds().x0.abs() < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (24.0, 40.0)); + } + + #[test] + fn delete_removes_a_selected_anchored_object_from_the_text() { + let (mut s, sid) = inline_box(); + let before = s.doc().unwrap().doc.story(sid).unwrap().text.clone(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + assert_eq!(s.execute("edit.clear", &json!({})).unwrap()["deleted"], 1); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert!(st.objects.is_empty() && !st.text.contains(OBJECT_MARK)); + assert!(s.doc().unwrap().selection.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, before); + s.doc().unwrap().doc.check().unwrap(); + } + + #[test] + fn options_and_release_act_on_the_selected_anchored_object() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + s.execute("anchored.options", &json!({"position": "aboveLine"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].position, AnchorPosition::AboveLine { .. })); + s.execute("anchored.release", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.story(sid).unwrap().objects.is_empty()); + assert_eq!(s.doc().unwrap().selection.items.len(), 1, "the released item is selected"); + } + + #[test] + fn selecting_items_drops_an_anchored_selection_and_bad_input_is_refused() { + let (mut s, sid) = inline_box(); + assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 5})).is_err()); + assert!(s.execute("anchored.select", &json!({"story": 999_999, "index": 0})).is_err()); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + for bad in [ + json!({"from": [0, 0, 0, 40], "to": [0, 0, 24, 40]}), + json!({"from": [0, 0, 24, 40], "to": [0, 0, "wide", 40]}), + json!({"to": [0, 0, 1, 1]}), + ] { + assert!(s.execute("anchored.resize", &bad).is_err(), "{bad}"); + } + // Dragged inside out or to nothing: at least a point each way. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [24, 40, 24, 40]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (1.0, 1.0)); + s.execute("selection.set", &json!({"ids": []})).unwrap(); + assert!(s.doc().unwrap().selection.anchored.is_none()); + } + #[test] fn inline_object_flows_with_text_and_releases() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 9ee963317..b262b6f0d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -210,6 +210,7 @@ pub fn specs() -> Vec { } st.selection.text = None; st.selection.cells = None; + st.selection.anchored = None; st.bump_revision(); ok() }), @@ -218,6 +219,7 @@ pub fn specs() -> Vec { let st = s.doc_mut()?; st.selection.text = None; st.selection.cells = None; + st.selection.anchored = None; if let Some(i) = st.selection.items.iter().position(|x| *x == id) { st.selection.items.remove(i); } else { @@ -260,6 +262,12 @@ pub fn specs() -> Vec { if s.doc()?.selection.text.is_some() && p.get("ids").is_none() { return super::text::delete_selection(s); } + // A selected anchored object leaves the text. + if p.get("ids").is_none() + && let Some(a) = s.doc()?.selection.anchored + { + return super::anchored::delete(s, a); + } let ids = super::targets(s, p)?; // With a placed graphic itself selected (Direct Selection), only the graphic goes: its // frame stays, empty and selected (as in InDesign). Other items are deleted. diff --git a/crates/tools/src/anchored.rs b/crates/tools/src/anchored.rs new file mode 100644 index 000000000..6a897213c --- /dev/null +++ b/crates/tools/src/anchored.rs @@ -0,0 +1,77 @@ +//! Anchored objects on the canvas: where composition placed them, so the Selection tool can +//! select and resize them (they live in the text, not on a spread). + +use designcraft_compose::Cache; +use designcraft_doc::{AnchoredSel, Document, SpreadRef, StoryId}; +use designcraft_geom::{Affine, Rect}; + +use crate::layout::CanvasLayout; + +/// An anchored object as placed: its spread, its bounds there and on the canvas, and whether its +/// frame turns it (a turned object is selected but not resized by its handles). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Placed { + pub sel: AnchoredSel, + pub spread: SpreadRef, + pub spread_rect: Rect, + pub canvas_rect: Rect, + pub turned: bool, +} + +/// The anchored objects of `story` (every story's when `None`) composed in frames on the +/// canvas's spreads, in text order. Objects in footnotes and table cells are not included. +pub fn placed(doc: &Document, cache: &Cache, layout: &CanvasLayout, story: Option) -> Vec { + let mut out = Vec::new(); + let stories: Vec = match story { + Some(s) => vec![s], + None => doc.stories.iter().filter(|(_, s)| !s.objects.is_empty()).map(|(id, _)| *id).collect(), + }; + for sid in stories { + if doc.story(sid).is_none_or(|s| s.objects.is_empty()) { + continue; + } + let cs = cache.get(doc, sid, None); + for ft in &cs.frames { + if ft.objects.is_empty() { + continue; + } + let (Some(loc), Some(frame)) = (doc.find(ft.frame), doc.item(ft.frame)) else { continue }; + let layer = doc.layer(frame.layer); + if frame.hidden || layer.is_some_and(|l| !l.visible || l.locked) { + continue; + } + let Some(slot) = layout.slot(loc.spread) else { continue }; + let xf = doc.parent_xf(&loc) * doc.text_xf(frame); + let [a, b, c, d, _, _] = xf.as_coeffs(); + let turned = b.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0; + for o in &ft.objects { + let r = o.object.item.bounds(); + let r = Affine::translate(o.origin.to_vec2()).transform_rect_bbox(r); + let spread_rect = xf.transform_rect_bbox(r); + if ![spread_rect.x0, spread_rect.y0, spread_rect.x1, spread_rect.y1].iter().all(|v| v.is_finite()) { + continue; + } + out.push(Placed { + sel: AnchoredSel { story: sid, index: o.index }, + spread: loc.spread, + spread_rect, + canvas_rect: slot.xf.transform_rect_bbox(spread_rect), + turned, + }); + } + } + } + out +} + +/// The selected anchored object, as placed (`None` when it isn't shown on these spreads). +pub fn selected(doc: &Document, cache: &Cache, layout: &CanvasLayout, sel: Option) -> Option { + let sel = sel?; + placed(doc, cache, layout, Some(sel.story)).into_iter().find(|p| p.sel == sel) +} + +/// The anchored object under canvas point `p` (the last placed, so an object drawn over another +/// wins). +pub fn at(doc: &Document, cache: &Cache, layout: &CanvasLayout, p: designcraft_geom::Point) -> Option { + placed(doc, cache, layout, None).into_iter().rev().find(|o| o.canvas_rect.contains(p)) +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 33784f6fb..da4e37889 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod anchored; mod anchors; pub mod catalog; mod corners; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 891f1d4ab..34461b148 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -59,6 +59,15 @@ enum Drag { start_angle: f64, start_rotation: Option, }, + /// Resizing a selected anchored object by a handle: `from` its bounds on `spread` and `local` + /// its bounds in its own space, at pointer down. + AnchoredResize { + sel: designcraft_doc::AnchoredSel, + handle: usize, + from: Rect, + local: Rect, + spread: SpreadRef, + }, Marquee { start: Point, cur: Point, @@ -385,6 +394,18 @@ fn content_handle_at(cx: &ToolContext, p: Point) -> Option<(ItemId, usize)> { handles(b).iter().position(|h| (h.x - p.x).abs() <= tol && (h.y - p.y).abs() <= tol).map(|h| (id, h)) } +/// The selected anchored object (not turned by its frame) and the handle of it under `p`. +fn anchored_handle_at(cx: &ToolContext, p: Point) -> Option<(crate::anchored::Placed, usize)> { + let pl = crate::anchored::selected(cx.doc, cx.cache, cx.layout, cx.selection.anchored).filter(|pl| !pl.turned)?; + let tol = cx.tol(5.0); + let h = handles(pl.canvas_rect).iter().position(|h| (h.x - p.x).abs() <= tol && (h.y - p.y).abs() <= tol)?; + Some((pl, h)) +} + +fn anchored_select(pl: &crate::anchored::Placed) -> Action { + Action::Exec("anchored.select".into(), json!({"story": pl.sel.story.0, "index": pl.sel.index})) +} + fn handle_at(cx: &ToolContext, p: Point) -> Option { // With a placed graphic selected, the handles are the graphic's, not the frame's. if selected_graphic(cx).is_some() { @@ -661,6 +682,28 @@ impl Tool for SelectionTool { { return actions; } + // Anchored objects (inline graphics and the like): a press on a selected one's handle + // resizes it, a press on one selects it. They flow with the text, so a drag doesn't move + // them, and a double click selects rather than editing the text around them. + if !self.direct && !ev.mods.shift && matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) { + if let Some((pl, h)) = anchored_handle_at(cx, p) + && let Some(o) = cx.doc.story(pl.sel.story).and_then(|s| s.objects.get(pl.sel.index)) + { + let turns = cx.layout.slot(pl.spread).map_or(0, |s| s.rotation as usize); + let handle = (h + 8 - 2 * turns) % 8; + self.drag = Drag::AnchoredResize { sel: pl.sel, handle, from: pl.spread_rect, local: o.item.bounds(), spread: pl.spread }; + return vec![Action::Begin("Resize".into())]; + } + if handle_at(cx, p).is_none() + && let Some(pl) = crate::anchored::at(cx.doc, cx.cache, cx.layout, p) + { + self.drag = Drag::None; + if cx.selection.anchored == Some(pl.sel) { + return vec![Action::Handled]; + } + return vec![anchored_select(&pl)]; + } + } // The second press of a double click on a selection handle: Fit Frame to Content, along // that handle's side (a corner fits both). if !self.direct @@ -981,6 +1024,21 @@ impl Tool for SelectionTool { json!({"from": rect_json(from), "to": rect_json(to), "content": ev.mods.cmd, "distribute": distribute}), )] } + Drag::AnchoredResize { sel, handle, from, local, spread } => { + let to = resize_rect(from, handle, cx.layout.to_spread(spread, p), ev.mods); + // Spread → the object's own space (its frame may scale it). + let (kx, ky) = (local.width() / from.width().max(1e-9), local.height() / from.height().max(1e-9)); + let to_local = Rect::new( + local.x0 + (to.x0 - from.x0) * kx, + local.y0 + (to.y0 - from.y0) * ky, + local.x0 + (to.x1 - from.x0) * kx, + local.y0 + (to.y1 - from.y0) * ky, + ); + vec![Action::Preview( + "anchored.resize".into(), + json!({"story": sel.story.0, "index": sel.index, "from": rect_json(local), "to": rect_json(to_local), "content": ev.mods.cmd}), + )] + } Drag::ContentResize { id, handle, from, spread } => { let to = resize_rect(from, handle, cx.layout.to_spread(spread, p), ev.mods); vec![Action::Preview("transform.set".into(), json!({"ids": [id.0], "content": true, "bounds": rect_json(to)}))] @@ -1087,6 +1145,7 @@ impl Tool for SelectionTool { match d { Drag::Move { .. } | Drag::Resize { .. } + | Drag::AnchoredResize { .. } | Drag::ContentResize { .. } | Drag::Anchor { .. } | Drag::Rotate { .. } @@ -1183,9 +1242,15 @@ impl Tool for SelectionTool { if matches!(self.drag, Drag::Bracket { .. }) || (matches!(self.drag, Drag::None) && self.bracket_at(cx, p).is_some()) { return Cursor::PathBracket; } - if let Drag::ContentResize { handle, .. } = self.drag { + if let Drag::ContentResize { handle, .. } | Drag::AnchoredResize { handle, .. } = self.drag { return handle_cursor(handle); } + if !self.direct + && matches!(self.drag, Drag::None) + && let Some((_, h)) = anchored_handle_at(cx, p) + { + return handle_cursor(h); + } if matches!(self.drag, Drag::None) && !(self.direct && anchor_at(cx, p).is_some()) && let Some((_, h)) = content_handle_at(cx, p) diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index ee3b362f1..f603a509d 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1936,3 +1936,56 @@ fn loaded_text_cursor_threads_into_a_frame_inside_a_group() { assert_eq!(cx2.hit_text_frame(q).map(|(_, i)| i), None, "no text frame in that group"); assert_eq!(t2.cursor(&cx2, q, Mods::default()), Cursor::NotAllowed); } + +/// A text frame holding a 24 × 40 inline box after "Before": (document, story, the box's canvas rect). +fn inline_box_doc() -> (Document, designcraft_doc::StoryId) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 400.0), lid, "Before after", ParaFormat::default()).unwrap(); + let item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 24.0, 40.0))); + let obj = designcraft_doc::AnchoredObject::new(item, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 }); + d.story_mut(sid).unwrap().insert_object(7, obj); + (d, sid) +} + +#[test] +fn selection_tool_selects_an_inline_object_and_resizes_it_by_a_handle() { + let (d, sid) = inline_box_doc(); + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let pl = crate::anchored::placed(&d, &c, &l, None); + assert_eq!(pl.len(), 1); + let r = pl[0].canvas_rect; + assert!((r.width() - 24.0).abs() < 1e-6 && (r.height() - 40.0).abs() < 1e-6, "{r:?}"); + // A click on it selects it (not the text frame), and a drag doesn't move it. + let mut t = create("selection"); + let c0 = r.center(); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, c0.x, c0.y)), + vec![Action::Exec("anchored.select".into(), serde_json::json!({"story": sid.0, "index": 0}))] + ); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, c0.x + 30.0, c0.y)).is_empty()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, c0.x + 30.0, c0.y)).is_empty()); + // Selected, its bottom-right handle resizes it: the preview resizes it in its own space. + let s = Selection { anchored: Some(designcraft_doc::AnchoredSel { story: sid, index: 0 }), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let mut t = create("selection"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, r.x1, r.y1)), vec![Action::Begin("Resize".into())]); + match t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, r.x1 + 6.0, r.y1 + 10.0)).as_slice() { + [Action::Preview(cmd, p)] => { + assert_eq!(cmd, "anchored.resize"); + assert_eq!(p["from"], serde_json::json!([0.0, 0.0, 24.0, 40.0])); + assert_eq!(p["to"], serde_json::json!([0.0, 0.0, 30.0, 50.0])); + assert_eq!(p["content"], false); + } + other => panic!("{other:?}"), + } + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, r.x1 + 6.0, r.y1 + 10.0)), vec![Action::Commit]); + // Clicking the text beside it selects the frame as before. + let mut t = create("selection"); + let a = t.pointer( + &cx, + &PointerEvent::new(PointerKind::Down, 380.0 + l.xf(SpreadRef::Doc(0)).translation().x, 380.0 + l.xf(SpreadRef::Doc(0)).translation().y), + ); + assert!(matches!(a.as_slice(), [Action::Exec(c, _)] if c == "selection.set"), "{a:?}"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 34e1aa2fd..61916f47e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1203,6 +1203,19 @@ fn draw_selection(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Docum } } } + // A selected anchored object: its bounding box and handles where it sits in the text. + if let Some(pl) = designcraft_tools::anchored::selected(doc, &app.session.cache, layout, sel.anchored) { + let r = xf.rect(pl.canvas_rect); + painter.rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Middle); + painter.rect_filled(Rect::from_center_size(r.center(), vec2(3.5, 3.5)), 0.0, color); + if !pl.turned { + for h in designcraft_tools::select::handles(DRect::new(r.min.x as f64, r.min.y as f64, r.max.x as f64, r.max.y as f64)) { + let hr = Rect::from_center_size(pos2(h.x as f32, h.y as f32), vec2(6.5, 6.5)); + painter.rect_filled(hr, 0.0, Color32::WHITE); + painter.rect_stroke(hr, 0.0, Stroke::new(hair(painter), color), StrokeKind::Inside); + } + } + } let direct = matches!(app.session.tool_id(), "directSelection" | "pen" | "addAnchor" | "deleteAnchor" | "convertDirection"); if direct { for id in &sel.items { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6c6991edd..2b8763ad0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # DesignCraft parity with Adobe InDesign -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (anchored objects selected and resized with the Selection tool; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS) The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md) summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature @@ -282,7 +282,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - 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. -- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. +- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); the Selection tool selects one where it sits in the text (a click; a drag doesn't move it) and resizes it by its handles (cropping, or with Cmd scaling its content, Shift proportional) as the text reflows, and Delete removes it (`anchored.select`, `anchored.resize`); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. - Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands. - Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. @@ -461,6 +461,7 @@ Task notes that headed ROADMAP.md: | Date | Change | Summary | |---|---|---| +| 2026-10-16 | minor | Anchored objects: selected and resized with the Selection tool, deleted with Delete | | 2026-10-13 | minor | `.indd` and `.indt` open through storytold/indd-utils; INDD remaining work 10–30 h (real-file corpus); readiness unchanged until it is measured | | 2026-10-12 | minor | Text threads by hand; stage note and distance to alpha follow the gate (5–7 h, #165); percentages unchanged | | 2026-10-11 | minor | Spring-loaded Zoom navigation added to the working feature inventory (DC-1); readiness estimates unchanged | From 646ecdc2b90abd68686702001557916ca1511b8d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 05:29:11 +0000 Subject: [PATCH 002/133] Anchored objects: top and left handles resize without sliding the picture The text places an anchored object by its top-left, so a top or left handle drag couldn't move that edge: the frame grew from its top-left like a bottom or right drag, but the picture inside shifted by the drag (up for the top handles, left for the left ones). anchored.resize now takes the size of `to` from the top-left whichever handle is dragged, so the picture stays where it is in the frame. Test: top_and_left_handles_resize_without_sliding_the_picture (the picture moved by (10, 20) before). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/engine/src/cmd/anchored.rs | 46 ++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index f2102f6ed..bb00ffd7f 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Resize Anchored Object", [], None, - "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it)} — the text reflows around the new size", + "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it)} — it takes the size of `to` from its top-left (the text places it), and the text reflows around it", has_doc, resize ), @@ -215,8 +215,9 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Resize an anchored object's frame from its bounds `from` to `to` (its own space). Its top-left -/// stays at the origin, where composition places it; the text reflows around the new size. +/// Resize an anchored object's frame from its bounds `from` to the size of `to` (its own space), +/// from its top-left, which stays at the origin where composition places it; the text reflows +/// around the new size. fn resize(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.resize")?; let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?; @@ -230,7 +231,10 @@ fn resize(s: &mut Session, p: &Value) -> Result { const MAX: f64 = 15552.0; let sx = to.width().abs().clamp(MIN, MAX) / from.width().abs(); let sy = to.height().abs().clamp(MIN, MAX) / from.height().abs(); - let m = Affine::translate((to.x0.min(to.x1), to.y0.min(to.y1))) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); + // The text places the object, so it grows and shrinks from its top-left whichever handle is + // dragged: its content stays where it is in the frame (dragging the top or left handle + // doesn't slide the picture). + let m = Affine::translate((from.x0, from.y0)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); let content = p.get("content").and_then(Value::as_bool).unwrap_or(false); let strokes = s.prefs.scale_strokes; s.edit(|d, _| { @@ -364,6 +368,40 @@ mod tests { assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects[0].size(), (24.0, 40.0)); } + #[test] + fn top_and_left_handles_resize_without_sliding_the_picture() { + let (mut s, sid) = inline_box(); + let graphic = designcraft_doc::Graphic { + asset: designcraft_doc::AssetId(1), + size: (24.0, 40.0), + xf: Affine::IDENTITY, + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }; + s.edit(|d, _| { + Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item.content = Content::Graphic(graphic.clone()); + Ok(Value::Null) + }) + .unwrap(); + let at = |s: &Session| { + let it = s.doc().unwrap().doc.story(sid).unwrap().objects[0].item.clone(); + let Content::Graphic(g) = &it.content else { panic!() }; + ((it.xf * g.xf) * designcraft_geom::Point::ORIGIN, it.bounds()) + }; + let (p0, _) = at(&s); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + // Dragging the top handle up 20 and the left handle out 10: taller and wider, and the + // picture stays at the frame's top-left, as with the bottom and right handles. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [-10, -20, 24, 40]})).unwrap(); + let (p1, b) = at(&s); + assert!((b.width() - 34.0).abs() < 1e-9 && (b.height() - 60.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); + assert!((p1 - p0).hypot() < 1e-9, "the picture moved from {p0:?} to {p1:?}"); + } + #[test] fn delete_removes_a_selected_anchored_object_from_the_text() { let (mut s, sid) = inline_box(); From 9a59ca2924f23285d95e3b15b0dacde82107ef37 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 06:09:15 +0000 Subject: [PATCH 003/133] Anchored objects: resize by an outline, applied on release, as InDesign does Observed in InDesign: dragging a handle of an inline graphic moves only that edge of an outline (with a W/H readout) while the graphic stays where it is; on release the frame takes the new size, cropping the picture from the sides that moved, and the text places it again (a narrower frame snaps back to the left of its line). The Selection tool now draws that outline and readout during the drag and runs anchored.resize once on release, instead of reflowing the text live. anchored.resize again crops from the sides that moved (the previous commit's top-left-only resize is reverted): its test checks that the left and top handles crop those sides and the right and bottom handles leave the picture at the frame's corner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- ROADMAP.md | 2 +- crates/engine/src/cmd/anchored.rs | 48 +++++++++++++++----------- crates/tools/src/select.rs | 57 ++++++++++++++++++++++--------- crates/tools/src/tests.rs | 21 ++++++++---- docs/target-app-parity.md | 2 +- 5 files changed, 86 insertions(+), 44 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 68cd77182..c022059e3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,7 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. -- **2026-10-16** · Inline and other anchored objects can be selected and resized on the page: the Selection tool clicks one where it sits in the text and shows its handles, a handle drag resizes its frame (cropping; Cmd scales the content, Shift keeps proportions) while the text reflows, and Delete removes it from the text. Anchored Object Options and Release act on the selected object. Before, a click selected the text frame around it. No readiness percentage change. +- **2026-10-16** · Inline and other anchored objects can be selected and resized on the page: the Selection tool clicks one where it sits in the text and shows its handles, a handle drag shows an outline and the size, and on release the frame takes it (cropping from the sides that moved; Cmd scales the content, Shift keeps proportions) and the text reflows, and Delete removes it from the text. Anchored Object Options and Release act on the selected object. Before, a click selected the text frame around it. No readiness percentage change. - **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change. - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change. diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index bb00ffd7f..684cbc486 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Resize Anchored Object", [], None, - "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it)} — it takes the size of `to` from its top-left (the text places it), and the text reflows around it", + "{story?, index? (default: the selected anchored object), from: rect, to: rect (the object's bounds before and after, in its own space: [x0, y0, x1, y1]), content?: bool (scale its content with it; default: the frame alone resizes and crops it from the sides that moved)} — the text then places it again and reflows around it", has_doc, resize ), @@ -215,9 +215,10 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Resize an anchored object's frame from its bounds `from` to the size of `to` (its own space), -/// from its top-left, which stays at the origin where composition places it; the text reflows -/// around the new size. +/// Resize an anchored object's frame from its bounds `from` to `to` (its own space): the content +/// keeps its place while the edges move, so a frame made narrower from the left crops the +/// picture's left side. Its top-left then returns to the origin, where composition places it, +/// and the text reflows around the new size. fn resize(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.resize")?; let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?; @@ -231,10 +232,10 @@ fn resize(s: &mut Session, p: &Value) -> Result { const MAX: f64 = 15552.0; let sx = to.width().abs().clamp(MIN, MAX) / from.width().abs(); let sy = to.height().abs().clamp(MIN, MAX) / from.height().abs(); - // The text places the object, so it grows and shrinks from its top-left whichever handle is - // dragged: its content stays where it is in the frame (dragging the top or left handle - // doesn't slide the picture). - let m = Affine::translate((from.x0, from.y0)) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); + // The dragged edges move and the content stays where it was on the page (InDesign crops a + // picture from the side whose handle moved). Then the text places the object again by its + // top-left, so after a left or top handle the frame and picture shift together. + let m = Affine::translate((to.x0.min(to.x1), to.y0.min(to.y1))) * Affine::scale_non_uniform(sx, sy) * Affine::translate((-from.x0, -from.y0)); let content = p.get("content").and_then(Value::as_bool).unwrap_or(false); let strokes = s.prefs.scale_strokes; s.edit(|d, _| { @@ -369,7 +370,7 @@ mod tests { } #[test] - fn top_and_left_handles_resize_without_sliding_the_picture() { + fn a_left_or_top_handle_crops_that_side_of_the_picture() { let (mut s, sid) = inline_box(); let graphic = designcraft_doc::Graphic { asset: designcraft_doc::AssetId(1), @@ -383,23 +384,32 @@ mod tests { fill: Default::default(), }; s.edit(|d, _| { - Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item.content = Content::Graphic(graphic.clone()); + let it = &mut Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item; + // At the frame's top-left, in its inner space. + let inner = it.inner_bounds(); + it.content = Content::Graphic(designcraft_doc::Graphic { xf: Affine::translate((inner.x0, inner.y0)), ..graphic.clone() }); Ok(Value::Null) }) .unwrap(); - let at = |s: &Session| { + // The picture's top-left relative to the frame's. + let offset = |s: &Session| { let it = s.doc().unwrap().doc.story(sid).unwrap().objects[0].item.clone(); let Content::Graphic(g) = &it.content else { panic!() }; - ((it.xf * g.xf) * designcraft_geom::Point::ORIGIN, it.bounds()) + let b = it.bounds(); + ((it.xf * g.xf) * designcraft_geom::Point::ORIGIN - designcraft_geom::Point::new(b.x0, b.y0), b) }; - let (p0, _) = at(&s); s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); - // Dragging the top handle up 20 and the left handle out 10: taller and wider, and the - // picture stays at the frame's top-left, as with the bottom and right handles. - s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [-10, -20, 24, 40]})).unwrap(); - let (p1, b) = at(&s); - assert!((b.width() - 34.0).abs() < 1e-9 && (b.height() - 60.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); - assert!((p1 - p0).hypot() < 1e-9, "the picture moved from {p0:?} to {p1:?}"); + // The left handle 10 pt right and the top handle 20 pt down: the picture stayed put while + // those edges moved, so its left 10 and top 20 points are cropped. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [10, 20, 24, 40]})).unwrap(); + let (d, b) = offset(&s); + assert!((b.width() - 14.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9 && b.x0.abs() < 1e-9 && b.y0.abs() < 1e-9, "{b:?}"); + assert!((d.x + 10.0).abs() < 1e-9 && (d.y + 20.0).abs() < 1e-9, "{d:?}"); + // The right and bottom handles leave the picture at the frame's top-left. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 50]})).unwrap(); + let (d, _) = offset(&s); + assert!(d.x.abs() < 1e-9 && d.y.abs() < 1e-9, "{d:?}"); } #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 34461b148..d67488868 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -60,13 +60,16 @@ enum Drag { start_rotation: Option, }, /// Resizing a selected anchored object by a handle: `from` its bounds on `spread` and `local` - /// its bounds in its own space, at pointer down. + /// its bounds in its own space, at pointer down. As in InDesign, only an outline follows the + /// pointer (`to`, on the spread, with the pointer and Cmd); the object resizes on release, + /// when the text places it again. AnchoredResize { sel: designcraft_doc::AnchoredSel, handle: usize, from: Rect, local: Rect, spread: SpreadRef, + to: Option<(Rect, Point, bool)>, }, Marquee { start: Point, @@ -691,8 +694,8 @@ impl Tool for SelectionTool { { let turns = cx.layout.slot(pl.spread).map_or(0, |s| s.rotation as usize); let handle = (h + 8 - 2 * turns) % 8; - self.drag = Drag::AnchoredResize { sel: pl.sel, handle, from: pl.spread_rect, local: o.item.bounds(), spread: pl.spread }; - return vec![Action::Begin("Resize".into())]; + self.drag = Drag::AnchoredResize { sel: pl.sel, handle, from: pl.spread_rect, local: o.item.bounds(), spread: pl.spread, to: None }; + return vec![Action::Handled]; } if handle_at(cx, p).is_none() && let Some(pl) = crate::anchored::at(cx.doc, cx.cache, cx.layout, p) @@ -1024,20 +1027,10 @@ impl Tool for SelectionTool { json!({"from": rect_json(from), "to": rect_json(to), "content": ev.mods.cmd, "distribute": distribute}), )] } - Drag::AnchoredResize { sel, handle, from, local, spread } => { + Drag::AnchoredResize { sel, handle, from, local, spread, .. } => { let to = resize_rect(from, handle, cx.layout.to_spread(spread, p), ev.mods); - // Spread → the object's own space (its frame may scale it). - let (kx, ky) = (local.width() / from.width().max(1e-9), local.height() / from.height().max(1e-9)); - let to_local = Rect::new( - local.x0 + (to.x0 - from.x0) * kx, - local.y0 + (to.y0 - from.y0) * ky, - local.x0 + (to.x1 - from.x0) * kx, - local.y0 + (to.y1 - from.y0) * ky, - ); - vec![Action::Preview( - "anchored.resize".into(), - json!({"story": sel.story.0, "index": sel.index, "from": rect_json(local), "to": rect_json(to_local), "content": ev.mods.cmd}), - )] + self.drag = Drag::AnchoredResize { sel, handle, from, local, spread, to: Some((to, p, ev.mods.cmd)) }; + vec![Action::Handled] } Drag::ContentResize { id, handle, from, spread } => { let to = resize_rect(from, handle, cx.layout.to_spread(spread, p), ev.mods); @@ -1145,7 +1138,6 @@ impl Tool for SelectionTool { match d { Drag::Move { .. } | Drag::Resize { .. } - | Drag::AnchoredResize { .. } | Drag::ContentResize { .. } | Drag::Anchor { .. } | Drag::Rotate { .. } @@ -1153,6 +1145,22 @@ impl Tool for SelectionTool { | Drag::Bracket { .. } => { vec![Action::Commit] } + // Released: the object takes the outline's size and the text places it again. + Drag::AnchoredResize { sel, from, local, to: Some((to, _, cmd)), .. } => { + // Spread → the object's own space (its frame may scale it). + let (kx, ky) = (local.width() / from.width().max(1e-9), local.height() / from.height().max(1e-9)); + let to_local = Rect::new( + local.x0 + (to.x0 - from.x0) * kx, + local.y0 + (to.y0 - from.y0) * ky, + local.x0 + (to.x1 - from.x0) * kx, + local.y0 + (to.y1 - from.y0) * ky, + ); + vec![Action::Exec( + "anchored.resize".into(), + json!({"story": sel.story.0, "index": sel.index, "from": rect_json(local), "to": rect_json(to_local), "content": cmd}), + )] + } + Drag::AnchoredResize { to: None, .. } => vec![], Drag::Pending { .. } => match release { Some(id) => vec![Action::Exec("selection.toggle".into(), json!({"id": id}))], None => vec![], @@ -1221,6 +1229,21 @@ impl Tool for SelectionTool { Drag::Move { .. } | Drag::Resize { .. } | Drag::Rotate { .. } | Drag::Anchor { .. } => self.guides.clone(), // The whole graphic shows while it's resized, outside the frame too. Drag::ContentResize { id, .. } => vec![Overlay::ContentGhost(*id)], + // The outline the anchored object will take, and its size at the pointer. + Drag::AnchoredResize { spread, to: Some((to, p, _)), .. } => { + let r = cx.layout.xf(*spread).transform_rect_bbox(*to); + vec![ + Overlay::Path { path: designcraft_geom::Shape::to_path(&r, 0.1), color: [79, 153, 255], dashed: false }, + Overlay::Measure { + p: *p, + text: format!( + "W: {}\nH: {}", + designcraft_geom::format_measure(to.width(), cx.unit), + designcraft_geom::format_measure(to.height(), cx.unit) + ), + }, + ] + } Drag::None | Drag::Bracket { .. } => brackets(cx), _ => vec![], }; diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index f603a509d..3003a6ed3 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1966,21 +1966,30 @@ fn selection_tool_selects_an_inline_object_and_resizes_it_by_a_handle() { ); assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, c0.x + 30.0, c0.y)).is_empty()); assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, c0.x + 30.0, c0.y)).is_empty()); - // Selected, its bottom-right handle resizes it: the preview resizes it in its own space. + // Selected, its left handle drags an outline (the object stays as it is while dragging, as in + // InDesign); on release it resizes in its own space and the text places it again. let s = Selection { anchored: Some(designcraft_doc::AnchoredSel { story: sid, index: 0 }), ..Default::default() }; let cx = ctx(&d, &s, &c, &l); let mut t = create("selection"); - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, r.x1, r.y1)), vec![Action::Begin("Resize".into())]); - match t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, r.x1 + 6.0, r.y1 + 10.0)).as_slice() { - [Action::Preview(cmd, p)] => { + let left = Point::new(r.x0, r.center().y); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, left.x, left.y)), vec![Action::Handled]); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, left.x + 6.0, left.y)), vec![Action::Handled]); + let ov = t.overlays(&cx); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { path, .. } if (designcraft_geom::Shape::bounding_box(path).x0 - (r.x0 + 6.0)).abs() < 1e-6 && (designcraft_geom::Shape::bounding_box(path).x1 - r.x1).abs() < 1e-6)), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("W: 18"))), "{ov:?}"); + match t.pointer(&cx, &PointerEvent::new(PointerKind::Up, left.x + 6.0, left.y)).as_slice() { + [Action::Exec(cmd, p)] => { assert_eq!(cmd, "anchored.resize"); assert_eq!(p["from"], serde_json::json!([0.0, 0.0, 24.0, 40.0])); - assert_eq!(p["to"], serde_json::json!([0.0, 0.0, 30.0, 50.0])); + assert_eq!(p["to"], serde_json::json!([6.0, 0.0, 24.0, 40.0])); assert_eq!(p["content"], false); } other => panic!("{other:?}"), } - assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, r.x1 + 6.0, r.y1 + 10.0)), vec![Action::Commit]); + // A press on a handle without a drag changes nothing. + let mut t = create("selection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, r.x1, r.y1)); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, r.x1, r.y1)).is_empty()); // Clicking the text beside it selects the frame as before. let mut t = create("selection"); let a = t.pointer( diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b8763ad0..e858993d4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -282,7 +282,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - 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. -- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); the Selection tool selects one where it sits in the text (a click; a drag doesn't move it) and resizes it by its handles (cropping, or with Cmd scaling its content, Shift proportional) as the text reflows, and Delete removes it (`anchored.select`, `anchored.resize`); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. +- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); the Selection tool selects one where it sits in the text (a click; a drag doesn't move it) and resizes it by its handles (an outline follows the pointer with the size; on release the frame takes it, cropping the picture from the sides that moved, or with Cmd scaling it, Shift proportional, and the text reflows), and Delete removes it (`anchored.select`, `anchored.resize`); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. - Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands. - Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. From c1fe9c145731b825fe799707082d4f71ed6441c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 06:25:14 +0000 Subject: [PATCH 004/133] Anchored objects: the resize readout uses the document's units The W/H readout while dragging an anchored object's handle used the tool's unit, which the app leaves at picas, so a document set to inches read "15p6.323". It now formats W in the document's horizontal and H in its vertical ruler units, as its Control and Properties fields do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/tools/src/select.rs | 5 +++-- crates/tools/src/tests.rs | 14 +++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index d67488868..06b14068d 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1234,12 +1234,13 @@ impl Tool for SelectionTool { let r = cx.layout.xf(*spread).transform_rect_bbox(*to); vec![ Overlay::Path { path: designcraft_geom::Shape::to_path(&r, 0.1), color: [79, 153, 255], dashed: false }, + // In the document's ruler units, as its Control and Properties fields show them. Overlay::Measure { p: *p, text: format!( "W: {}\nH: {}", - designcraft_geom::format_measure(to.width(), cx.unit), - designcraft_geom::format_measure(to.height(), cx.unit) + designcraft_geom::format_measure(to.width(), cx.doc.settings.horizontal_units), + designcraft_geom::format_measure(to.height(), cx.doc.settings.vertical_units) ), }, ] diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 3003a6ed3..5e3fdc21b 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -1976,7 +1976,19 @@ fn selection_tool_selects_an_inline_object_and_resizes_it_by_a_handle() { assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, left.x + 6.0, left.y)), vec![Action::Handled]); let ov = t.overlays(&cx); assert!(ov.iter().any(|o| matches!(o, Overlay::Path { path, .. } if (designcraft_geom::Shape::bounding_box(path).x0 - (r.x0 + 6.0)).abs() < 1e-6 && (designcraft_geom::Shape::bounding_box(path).x1 - r.x1).abs() < 1e-6)), "{ov:?}"); - assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("W: 18"))), "{ov:?}"); + // A new document measures in picas: 18 pt is 1p6. + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("W: 1p6"))), "{ov:?}"); + // The readout is in the document's units (inches here), not the tool's default. + let mut din = d.clone(); + din.settings.horizontal_units = Unit::Inches; + din.settings.vertical_units = Unit::Inches; + let lin = CanvasLayout::new(&din, false); + let cxin = ctx(&din, &s, &c, &lin); + let mut t2 = create("selection"); + t2.pointer(&cxin, &PointerEvent::new(PointerKind::Down, left.x, left.y)); + t2.pointer(&cxin, &PointerEvent::new(PointerKind::Drag, left.x + 6.0, left.y)); + let ov = t2.overlays(&cxin); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.contains(" in") && !text.contains("pt"))), "{ov:?}"); match t.pointer(&cx, &PointerEvent::new(PointerKind::Up, left.x + 6.0, left.y)).as_slice() { [Action::Exec(cmd, p)] => { assert_eq!(cmd, "anchored.resize"); From ab2f105dc0865d3034f55318a23582bf23c32df3 Mon Sep 17 00:00:00 2001 From: con3code Date: Sat, 17 Oct 2026 14:38:45 +0900 Subject: [PATCH 005/133] Text: Space types an ideographic space after committed CJK text on macOS On macOS the window layer (winit) drops what the input method inserts when nothing is being composed and reports the key's own character, so Space in a Japanese or Chinese input mode typed a plain space instead of the ideographic one (U+3000) the input method sends. While the text before it was CJK text the input method committed, a plain space is now the ideographic one. Shift+Space stays plain, as the input methods have it; letters typed straight from the keys (the Roman mode) end that, and accents a Latin input method composes don't start it. Other systems report what the input method typed and are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/ui-egui/src/canvas.rs | 54 +++++++++++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 4 +++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 34e1aa2fd..642245dfb 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2461,7 +2461,13 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r egui::Event::Ime(ime) if wants_text => ime_event(app, ime, vi), // Keys the IME passes through come as text only while nothing is marked. egui::Event::Text(t) if wants_text && !composing => { - let _ = app.run("text.insert", json!({"text": t})); + let shift = ui.input(|i| i.modifiers.shift); + let typed = typed_text(&t, app.ime_cjk_typing, shift, cfg!(target_os = "macos")); + // Letters straight from the keys: the input method is in its Roman mode. + if !t.trim().is_empty() { + app.ime_cjk_typing = false; + } + let _ = app.run("text.insert", json!({"text": typed})); } // 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 => {} @@ -2531,6 +2537,18 @@ fn keyboard_pane(app: &DesignApp) -> bool { app.pane == app.focus_pane } +/// The text a key typed, given `text` as the window system reports it. +/// +/// On macOS the Space key in a Japanese or Chinese input mode types an ideographic space, but the +/// window layer drops what the input method inserts when nothing is being composed and reports +/// the key's own character, a plain space. While the text before it was CJK text the input +/// method committed (`cjk_typing`), a plain space is therefore the ideographic one; with Shift it +/// is the plain space, as the input methods have it. Letters typed straight from the keys (the +/// Roman mode) end that, and accents a Latin input method composes don't start it. +pub(crate) fn typed_text(text: &str, cjk_typing: bool, shift: bool, macos: bool) -> &str { + if macos && cjk_typing && !shift && text == " " { "\u{3000}" } else { text } +} + /// One input method event for the text caret: marked text previews in the story, a commit types. fn ime_event(app: &mut DesignApp, e: egui::ImeEvent, vi: designcraft_engine::ViewInfo) { let r = match e { @@ -2546,6 +2564,7 @@ fn ime_event(app: &mut DesignApp, e: egui::ImeEvent, vi: designcraft_engine::Vie } egui::ImeEvent::Commit(t) => { app.ime_marked = None; + app.ime_cjk_typing = t.chars().any(designcraft_compose::upright_in_vertical); app.session.tool_ime_commit(&t, vi).map_err(|e| e.to_string()) } // The web text agent's corrections and mobile Backspace: characters around the caret go. @@ -2978,6 +2997,19 @@ mod tests { use super::*; + /// The Space key after CJK text the input method committed is the ideographic space on + /// macOS (the window layer reports a plain one); Shift, the Roman mode and other systems keep + /// it. + #[test] + fn space_after_cjk_input_method_text_is_the_ideographic_space() { + assert_eq!(typed_text(" ", true, false, true), "\u{3000}"); + assert_eq!(typed_text(" ", true, true, true), " ", "Shift+Space"); + assert_eq!(typed_text(" ", false, false, true), " ", "Roman mode"); + assert_eq!(typed_text(" ", true, false, false), " ", "other systems report what the input method typed"); + assert_eq!(typed_text("a", true, false, true), "a"); + assert_eq!(typed_text(" ", true, false, true), " "); + } + #[test] fn a_press_after_a_drag_is_not_a_double_click() { let (delay, dist) = (0.3, 6.0); @@ -4534,6 +4566,26 @@ mod tests { egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) }) } + /// Space after Japanese the input method committed is the ideographic space on macOS, where + /// the window layer reports it as a plain one; after letters typed straight from the keys it + /// stays plain, and so does it after an accent a Latin input method composed. + #[test] + fn space_after_committed_cjk_text_types_an_ideographic_space() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + let space = if cfg!(target_os = "macos") { "\u{3000}" } else { " " }; + ime_frame(&mut app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &sid), format!("日本語{space}")); + ime_frame(&mut app, &ctx, vec![egui::Event::Text("ab".into())]); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab ")); + ime_frame(&mut app, &ctx, vec![preedit("´", 1), egui::Event::Ime(egui::ImeEvent::Commit("é".into()))]); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab é ")); + } + #[test] #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index fcb764c5a..becec51a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -619,6 +619,9 @@ pub struct DesignApp { /// 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, + /// The text typed last was Chinese, Japanese or Korean the input method committed (it is in + /// a CJK mode), not letters straight from the keys: see [`canvas::typed_text`]. + pub(crate) ime_cjk_typing: bool, /// The system IME must drop its marked text (see [`Self::take_ime_discard`]). pub(crate) ime_discard: bool, /// The canvas asked for the system IME in the last frame (the web build's text input has the @@ -696,6 +699,7 @@ impl DesignApp { in_control: false, object_clip_text: None, ime_marked: None, + ime_cjk_typing: false, ime_discard: false, canvas_ime: false, quit_requested: false, From 4b4c592d2d4b83f30cdf53ee2ba3b377570c2e28 Mon Sep 17 00:00:00 2001 From: con3code Date: Sat, 17 Oct 2026 23:06:34 +0900 Subject: [PATCH 006/133] Mojikumi: reduce middle dots first, never a full stop's space A line taken in (push-in) closed up every punctuation blank at once, the space after a full stop included. Following JLREQ 3.8.3, the quarter ems of middle dots now go first, then the half ems of brackets and commas, and the space after a full stop is not reduced. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/compose/src/tests.rs | 36 ++++++++++++++++++++++++++++++++++++ crates/doc/src/mojikumi.rs | 32 +++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 9d8f6be70..b5da87538 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5420,6 +5420,42 @@ fn mojikumi_does_not_restore_fullwidth_blanks_to_narrow_tracked_punctuation() { } } +/// Taking a closing bracket into a line (push-in) closes up the middle dot's quarter ems first, +/// then the comma's half em, and never the full stop's (JLREQ 3.8.3). +#[test] +fn mojikumi_push_in_reduces_middle_dots_first_and_never_a_full_stop() { + let family = "Mojikumi Reduction"; + let font = designcraft_fonts::testing::font_mapping(family, &[('漢', '‰'), ('・', '‰'), ('、', '‰'), ('。', '‰'), ('」', '‰')]).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let first = "漢・漢、漢。漢漢」"; + let para = ParaAttrs { mojikumi: Some("LineEndAllOneHalfEmEnum".into()), kinsoku_type: Some("KinsokuPushInFirst".into()), ..Default::default() }; + let compose = |text: &str, width: f64| { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 300.0), para.clone()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(family.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let line = all_lines(&cs)[0].clone(); + let em = line.glyphs[0].face.units_per_em() * line.glyphs[0].sx; + (line, em) + }; + let (natural, em) = compose(first, 500.0); + let width = natural.end_x - natural.x0; + let quarter = em / 4.0; + // How far each glyph of the first line moved, for a line `less` points short. + let moved = |less: f64| { + let (line, _) = compose(&format!("{first}漢漢漢"), width - less); + assert_eq!(line.range.end, first.len(), "the bracket is taken in"); + line.glyphs.iter().zip(&natural.glyphs).map(|(a, b)| a.x - b.x).collect::>() + }; + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + // Less than the middle dot's two quarter ems: all of it comes from around the dot. + let d = moved(quarter); + assert!(near(d[2], -quarter) && d[2..].iter().all(|&x| near(x, -quarter)), "{d:?}"); + // More: the dot's half em, then the comma's; the full stop's half em stays. + let d = moved(2.0 * quarter + 3.0); + assert!(near(d[2], -2.0 * quarter) && near(d[4], -2.0 * quarter - 3.0), "{d:?}"); + assert!(d[4..].iter().all(|&x| near(x, -2.0 * quarter - 3.0)), "{d:?}"); +} + #[test] fn mojikumi_one_em_line_end_set_sets_closing_punctuation_full_width_at_line_end() { let family = "Mojikumi Full Stop"; diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 415e26bc3..cefec8fb4 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -128,7 +128,17 @@ impl<'a> Rules<'a> { } let punctuation = trailing(left).max(leading(right)); if punctuation > 0.0 { - return Aki { min: 0.0, desired: punctuation, max: punctuation, priority: 1, discrete: false }; + // A line is taken in at the quarter ems of middle dots first, then at the half ems of + // brackets and commas; the space after a full stop is not reduced (JLREQ 3.8.3). + let quarter = trailing(left).max(leading(right)) < 0.5; + let full_stop = matches!(left, 6 | 31); + return Aki { + min: if full_stop { punctuation } else { 0.0 }, + desired: punctuation, + max: punctuation, + priority: if quarter { 1 } else { 2 }, + discrete: false, + }; } let roman = |c| matches!(c, 18 | 25); let ideograph = |c| matches!(c, 3 | 7..=9 | 11 | 12 | 24 | 33); @@ -273,4 +283,24 @@ mod tests { assert_eq!((a.min, a.desired, a.max, a.priority), (b.min, b.desired, b.max, b.priority), "{l}/{r}"); } } + + #[test] + fn middle_dots_reduce_first_and_a_full_stops_space_never() { + let styles = Styles::default(); + for set in ["LineEndAllOneHalfEmEnum", "LineEndAllOneEmEnum"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + let aki = |a: char, b: char| rules.pair(class(a), class(b)); + // Middle dots' quarter ems, then brackets' and commas' half ems, then wa-ō aki. + let (dot, after_dot, comma, close, open, wa_ou) = + (aki('漢', '・'), aki('・', '漢'), aki('、', '漢'), aki('」', '漢'), aki('漢', '「'), aki('漢', 'A')); + assert!(dot.priority == after_dot.priority && dot.priority < comma.priority, "{set}"); + assert!(comma.priority == close.priority && close.priority == open.priority && open.priority < wa_ou.priority, "{set}"); + assert_eq!((dot.min, comma.min, close.min, open.min), (0.0, 0.0, 0.0, 0.0), "{set}"); + // After a full stop the half em stays, before an opening bracket too. + for b in ['漢', '「'] { + let a = aki('。', b); + assert_eq!((a.min, a.desired), (0.5, 0.5), "{set}: 。{b}"); + } + } + } } From 6ca6f307b0146c94fe197698c38ef8388f9ac014 Mon Sep 17 00:00:00 2001 From: con3code Date: Sat, 17 Oct 2026 23:28:36 +0900 Subject: [PATCH 007/133] Text: only Japanese input methods type the ideographic space on Space Chinese and Korean input methods type plain spaces (Korean separates words with them), but a space after any committed CJK text became U+3000. The input method is now taken to be Japanese when its composition shows kana, as only Japanese ones do: pinyin, zhuyin and hangul compositions leave the space plain. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/ui-egui/src/canvas.rs | 65 +++++++++++++++++++++++++++--------- crates/ui-egui/src/lib.rs | 11 +++--- 2 files changed, 57 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 642245dfb..b24176214 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2462,10 +2462,10 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r // Keys the IME passes through come as text only while nothing is marked. egui::Event::Text(t) if wants_text && !composing => { let shift = ui.input(|i| i.modifiers.shift); - let typed = typed_text(&t, app.ime_cjk_typing, shift, cfg!(target_os = "macos")); + let typed = typed_text(&t, app.ime_japanese_typing, shift, cfg!(target_os = "macos")); // Letters straight from the keys: the input method is in its Roman mode. if !t.trim().is_empty() { - app.ime_cjk_typing = false; + app.ime_japanese_typing = false; } let _ = app.run("text.insert", json!({"text": typed})); } @@ -2539,14 +2539,21 @@ fn keyboard_pane(app: &DesignApp) -> bool { /// The text a key typed, given `text` as the window system reports it. /// -/// On macOS the Space key in a Japanese or Chinese input mode types an ideographic space, but the -/// window layer drops what the input method inserts when nothing is being composed and reports -/// the key's own character, a plain space. While the text before it was CJK text the input -/// method committed (`cjk_typing`), a plain space is therefore the ideographic one; with Shift it -/// is the plain space, as the input methods have it. Letters typed straight from the keys (the -/// Roman mode) end that, and accents a Latin input method composes don't start it. -pub(crate) fn typed_text(text: &str, cjk_typing: bool, shift: bool, macos: bool) -> &str { - if macos && cjk_typing && !shift && text == " " { "\u{3000}" } else { text } +/// On macOS the Space key in a Japanese input mode types an ideographic space, but the window +/// layer drops what the input method inserts when nothing is being composed and reports the key's +/// own character, a plain space. While the text before it was Japanese the input method committed +/// (`japanese_typing`), a plain space is therefore the ideographic one; with Shift it is the plain +/// space, as the input methods have it. Letters typed straight from the keys (the Roman mode) end +/// that. Chinese and Korean input methods type plain spaces (Korean separates words with them), +/// and accents a Latin input method composes are no input mode at all: none of them start it. +pub(crate) fn typed_text(text: &str, japanese_typing: bool, shift: bool, macos: bool) -> &str { + if macos && japanese_typing && !shift && text == " " { "\u{3000}" } else { text } +} + +/// Kana: what a Japanese input method shows while composing (hiragana, katakana, half-width +/// katakana). Chinese ones show pinyin, zhuyin or radicals, Korean ones jamo and syllables. +pub(crate) fn has_kana(text: &str) -> bool { + text.chars().any(|c| matches!(c, '\u{3040}'..='\u{30ff}' | '\u{31f0}'..='\u{31ff}' | '\u{ff66}'..='\u{ff9f}')) } /// One input method event for the text caret: marked text previews in the story, a commit types. @@ -2554,17 +2561,19 @@ fn ime_event(app: &mut DesignApp, e: egui::ImeEvent, vi: designcraft_engine::Vie let r = match e { egui::ImeEvent::Preedit { text, active_range_chars } => { app.ime_marked = Some(text.clone()).filter(|t| !t.is_empty()); + app.ime_kana_seen |= has_kana(&text); app.session.tool_preedit(&text, active_range_chars, vi).map_err(|e| e.to_string()) } // A bare line break confirms the composition (Enter with some IMEs): the marked text, not // a new paragraph. egui::ImeEvent::Commit(t) if t == "\n" || t == "\r" => { + app.ime_japanese_typing = std::mem::take(&mut app.ime_kana_seen); keep_marked_text(app); Ok(()) } egui::ImeEvent::Commit(t) => { app.ime_marked = None; - app.ime_cjk_typing = t.chars().any(designcraft_compose::upright_in_vertical); + app.ime_japanese_typing = std::mem::take(&mut app.ime_kana_seen) || has_kana(&t); app.session.tool_ime_commit(&t, vi).map_err(|e| e.to_string()) } // The web text agent's corrections and mobile Backspace: characters around the caret go. @@ -2594,6 +2603,7 @@ fn delete_surrounding(app: &mut DesignApp, before: usize, after: usize) -> Resul /// End a composition outside the IME (a click away, the canvas losing the keyboard): the marked /// text stays as typed, and the system IME is told to drop its copy. pub(crate) fn keep_marked_text(app: &mut DesignApp) { + app.ime_kana_seen = false; if app.ime_marked.take().is_some() { app.ime_discard = true; } @@ -2997,14 +3007,14 @@ mod tests { use super::*; - /// The Space key after CJK text the input method committed is the ideographic space on + /// The Space key after Japanese the input method committed is the ideographic space on /// macOS (the window layer reports a plain one); Shift, the Roman mode and other systems keep /// it. #[test] - fn space_after_cjk_input_method_text_is_the_ideographic_space() { + fn space_after_japanese_input_method_text_is_the_ideographic_space() { assert_eq!(typed_text(" ", true, false, true), "\u{3000}"); assert_eq!(typed_text(" ", true, true, true), " ", "Shift+Space"); - assert_eq!(typed_text(" ", false, false, true), " ", "Roman mode"); + assert_eq!(typed_text(" ", false, false, true), " ", "Roman mode, Chinese or Korean"); assert_eq!(typed_text(" ", true, false, false), " ", "other systems report what the input method typed"); assert_eq!(typed_text("a", true, false, true), "a"); assert_eq!(typed_text(" ", true, false, true), " "); @@ -4570,7 +4580,7 @@ mod tests { /// the window layer reports it as a plain one; after letters typed straight from the keys it /// stays plain, and so does it after an accent a Latin input method composed. #[test] - fn space_after_committed_cjk_text_types_an_ideographic_space() { + fn space_after_committed_japanese_types_an_ideographic_space() { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); let ctx = egui::Context::default(); let sid = typing_app(&mut app, &ctx, ""); @@ -4586,6 +4596,31 @@ mod tests { assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab é ")); } + /// Chinese and Korean input methods type plain spaces (Korean separates words with them), so + /// a space after their text stays plain. Japanese converted as it is typed (live conversion) + /// shows kana first and still gets the ideographic space. + #[test] + fn space_after_chinese_or_korean_input_stays_plain() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + let ideographic = if cfg!(target_os = "macos") { "\u{3000}" } else { " " }; + let mut want = String::new(); + for (preedits, commit, space) in [ + (vec!["ni", "nihao"], "你好", " "), + (vec!["ㄋ", "ㄋㄧˇ"], "你", " "), + (vec!["ㅎ", "하", "한"], "한국어", " "), + (vec!["に", "日本"], "日本", ideographic), + ] { + let mut events: Vec = preedits.iter().map(|p| preedit(p, p.chars().count())).collect(); + events.push(egui::Event::Ime(egui::ImeEvent::Commit(commit.into()))); + ime_frame(&mut app, &ctx, events); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + want += &format!("{commit}{space}"); + assert_eq!(story_text(&mut app, &sid), want, "{commit}"); + } + } + #[test] #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index becec51a8..679b69373 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -619,9 +619,11 @@ pub struct DesignApp { /// 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, - /// The text typed last was Chinese, Japanese or Korean the input method committed (it is in - /// a CJK mode), not letters straight from the keys: see [`canvas::typed_text`]. - pub(crate) ime_cjk_typing: bool, + /// The text typed last was Japanese the input method committed (it is in its kana mode), not + /// letters straight from the keys: see [`canvas::typed_text`]. + pub(crate) ime_japanese_typing: bool, + /// The composition under way has shown kana: the input method is a Japanese one. + pub(crate) ime_kana_seen: bool, /// The system IME must drop its marked text (see [`Self::take_ime_discard`]). pub(crate) ime_discard: bool, /// The canvas asked for the system IME in the last frame (the web build's text input has the @@ -699,7 +701,8 @@ impl DesignApp { in_control: false, object_clip_text: None, ime_marked: None, - ime_cjk_typing: false, + ime_japanese_typing: false, + ime_kana_seen: false, ime_discard: false, canvas_ime: false, quit_requested: false, From 4b05bb380458bd32c0c52c84ed4d79c42b18510a Mon Sep 17 00:00:00 2001 From: con3code Date: Sat, 17 Oct 2026 23:42:21 +0900 Subject: [PATCH 008/133] Mojikumi: the JLREQ reduction order in the Japanese sets only The Chinese sets keep reducing every punctuation blank together, a full stop's included, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/doc/src/mojikumi.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index cefec8fb4..6bef0e60c 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -128,15 +128,17 @@ impl<'a> Rules<'a> { } let punctuation = trailing(left).max(leading(right)); if punctuation > 0.0 { - // A line is taken in at the quarter ems of middle dots first, then at the half ems of - // brackets and commas; the space after a full stop is not reduced (JLREQ 3.8.3). - let quarter = trailing(left).max(leading(right)) < 0.5; + // The Japanese sets take a line in at the quarter ems of middle dots first, then at the + // half ems of brackets and commas, and don't reduce the space after a full stop + // (JLREQ 3.8.3). The Chinese sets reduce all punctuation blanks together. + let japanese = self.base != Base::Chinese; + let quarter = punctuation < 0.5; let full_stop = matches!(left, 6 | 31); return Aki { - min: if full_stop { punctuation } else { 0.0 }, + min: if japanese && full_stop { punctuation } else { 0.0 }, desired: punctuation, max: punctuation, - priority: if quarter { 1 } else { 2 }, + priority: if japanese && !quarter { 2 } else { 1 }, discrete: false, }; } @@ -302,5 +304,13 @@ mod tests { assert_eq!((a.min, a.desired), (0.5, 0.5), "{set}: 。{b}"); } } + // The Chinese sets are unchanged: every punctuation blank reduces together, to nothing. + for set in ["SimpChineseDefault", "TradChineseDefault"] { + let rules = Rules::resolve(&styles, set).unwrap().unwrap(); + for (a, b) in [('漢', '・'), ('、', '漢'), ('」', '漢'), ('漢', '「'), ('。', '漢')] { + let aki = rules.pair(class(a), class(b)); + assert_eq!((aki.min, aki.priority), (0.0, 1), "{set}: {a}{b}"); + } + } } } From 4db54f5d475a159e2bf55ce93d0b3eb4bbcc21e4 Mon Sep 17 00:00:00 2001 From: con3code Date: Tue, 20 Oct 2026 19:33:13 +0900 Subject: [PATCH 009/133] Mojikumi: the reduction tier follows the character classes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/doc/src/mojikumi.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 6bef0e60c..3b2a917b5 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -128,17 +128,20 @@ impl<'a> Rules<'a> { } let punctuation = trailing(left).max(leading(right)); if punctuation > 0.0 { - // The Japanese sets take a line in at the quarter ems of middle dots first, then at the - // half ems of brackets and commas, and don't reduce the space after a full stop - // (JLREQ 3.8.3). The Chinese sets reduce all punctuation blanks together. + // The Japanese sets take a line in at the quarter ems of middle dots (・:;) first, then + // at the half ems of brackets and commas, and don't reduce the space after a full stop + // (JLREQ 3.8.3). !? share the first tier: JLREQ sets them solid (Table 1) and + // gives the quarter em only as an alternative (3.1.6), so reducing it first returns + // to that default. The tier follows the character classes, not the blank's size. The + // Chinese sets reduce all punctuation blanks together. let japanese = self.base != Base::Chinese; - let quarter = punctuation < 0.5; + let bracket_or_comma = matches!(left, 2 | 6 | 21 | 28..=31) || matches!(right, 1 | 26 | 27); let full_stop = matches!(left, 6 | 31); return Aki { min: if japanese && full_stop { punctuation } else { 0.0 }, desired: punctuation, max: punctuation, - priority: if japanese && !quarter { 2 } else { 1 }, + priority: if japanese && bracket_or_comma { 2 } else { 1 }, discrete: false, }; } @@ -298,6 +301,12 @@ mod tests { assert!(dot.priority == after_dot.priority && dot.priority < comma.priority, "{set}"); assert!(comma.priority == close.priority && close.priority == open.priority && open.priority < wa_ou.priority, "{set}"); assert_eq!((dot.min, comma.min, close.min, open.min), (0.0, 0.0, 0.0, 0.0), "{set}"); + // The tier follows the class: :;!? share the middle dots' tier, and a bracket's half + // em beside a middle dot stays with the brackets. + for (a, b) in [('漢', ':'), (';', '漢'), ('漢', '!'), ('?', '漢')] { + assert_eq!(aki(a, b).priority, dot.priority, "{set}: {a}{b}"); + } + assert_eq!(aki('・', '「').priority, open.priority, "{set}: ・「"); // After a full stop the half em stays, before an opening bracket too. for b in ['漢', '「'] { let a = aki('。', b); From 6bf98c0d2044e3af48d0ff764cb7501b5c12df44 Mon Sep 17 00:00:00 2001 From: con3code Date: Tue, 20 Oct 2026 19:33:13 +0900 Subject: [PATCH 010/133] IME: Japanese typing ends when the caret changes story or leaves the text Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/ui-egui/src/canvas.rs | 33 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 4 ++++ 2 files changed, 37 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b24176214..a0a7d50c4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2628,8 +2628,16 @@ fn ime_output(app: &mut DesignApp, ctx: &egui::Context, xf: &Xf) { let Some((a, b)) = caret else { // The IME goes away with its marked text: keep that text as typed, like a click away. keep_marked_text(app); + app.ime_japanese_typing = false; + app.ime_caret_story = None; return; }; + // In another story (or document) the input mode may have changed unseen: start plain. + let here = app.session.active_index().zip(app.session.active().and_then(|st| st.selection.text).map(|t| t.story)); + if here != app.ime_caret_story { + app.ime_japanese_typing = false; + app.ime_caret_story = here; + } let r = Rect::from_two_pos(xf.to_screen(a), xf.to_screen(b)).expand(1.0); // The composition ended outside the IME (a click, a command): the IME drops what it has marked. let interrupt = app.ime_marked.is_some() && !app.session.tool_composing(); @@ -4596,6 +4604,31 @@ mod tests { assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab é ")); } + /// The caret moving to another story, or leaving the text, ends Japanese typing: the input + /// mode may have changed without an event the app sees (the Eisu key, say). + #[test] + fn japanese_typing_ends_with_the_story_or_the_text_caret() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let first = typing_app(&mut app, &ctx, ""); + let commit = |app: &mut DesignApp| { + ime_frame(app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); + assert!(app.ime_japanese_typing); + }; + commit(&mut app); + let f = app.session.execute("frame.create", &json!({"rect": [36, 260, 300, 400], "content": "text", "text": ""})).unwrap(); + let second = f["story"].clone(); + app.session.execute("text.select", &json!({"story": second, "anchor": 0, "focus": 0})).unwrap(); + ime_frame(&mut app, &ctx, vec![]); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &second), " "); + assert_eq!(story_text(&mut app, &first), "日本語"); + commit(&mut app); + app.select_tool("rectangleFrame"); + ime_frame(&mut app, &ctx, vec![]); + assert!(!app.ime_japanese_typing); + } + /// Chinese and Korean input methods type plain spaces (Korean separates words with them), so /// a space after their text stays plain. Japanese converted as it is typed (live conversion) /// shows kana first and still gets the ideographic space. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 679b69373..9b3eade7f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -624,6 +624,9 @@ pub struct DesignApp { pub(crate) ime_japanese_typing: bool, /// The composition under way has shown kana: the input method is a Japanese one. pub(crate) ime_kana_seen: bool, + /// The document and story the text caret was in last frame. Moving to another one, or leaving + /// the text, ends `ime_japanese_typing`. + pub(crate) ime_caret_story: Option<(usize, designcraft_doc::StoryId)>, /// The system IME must drop its marked text (see [`Self::take_ime_discard`]). pub(crate) ime_discard: bool, /// The canvas asked for the system IME in the last frame (the web build's text input has the @@ -703,6 +706,7 @@ impl DesignApp { ime_marked: None, ime_japanese_typing: false, ime_kana_seen: false, + ime_caret_story: None, ime_discard: false, canvas_ime: false, quit_requested: false, From 77184d067ad2d80867dddf7636ff5bf4f3733382 Mon Sep 17 00:00:00 2001 From: con3code Date: Tue, 20 Oct 2026 19:52:41 +0900 Subject: [PATCH 011/133] =?UTF-8?q?Mojikumi:=20test=20the=20bracket=20tier?= =?UTF-8?q?=20with=20=EF=BC=81=E3=80=8C,=20which=20#1222=20leaves=20alone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/doc/src/mojikumi.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 3b2a917b5..1a67ff65d 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -302,11 +302,11 @@ mod tests { assert!(comma.priority == close.priority && close.priority == open.priority && open.priority < wa_ou.priority, "{set}"); assert_eq!((dot.min, comma.min, close.min, open.min), (0.0, 0.0, 0.0, 0.0), "{set}"); // The tier follows the class: :;!? share the middle dots' tier, and a bracket's half - // em beside a middle dot stays with the brackets. + // em beside one of them stays with the brackets. for (a, b) in [('漢', ':'), (';', '漢'), ('漢', '!'), ('?', '漢')] { assert_eq!(aki(a, b).priority, dot.priority, "{set}: {a}{b}"); } - assert_eq!(aki('・', '「').priority, open.priority, "{set}: ・「"); + assert_eq!(aki('!', '「').priority, open.priority, "{set}: !「"); // After a full stop the half em stays, before an opening bracket too. for b in ['漢', '「'] { let a = aki('。', b); From c2ef34f1f50fd6e168128af64453d69eea30f003 Mon Sep 17 00:00:00 2001 From: con3code Date: Sun, 25 Oct 2026 15:31:57 +0900 Subject: [PATCH 012/133] Text: Shift+Space and a moved caret decide the ideographic space as typed The Shift held at the space counts, not the one at the frame's end, and a caret moved earlier in the frame resets Japanese typing before the space is converted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/ui-egui/src/canvas.rs | 80 +++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 29 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 761c1e9c6..0383331e7 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1671,19 +1671,15 @@ fn field_focused_id(ctx: &egui::Context) -> egui::Id { pub fn begin_frame(ctx: &egui::Context) { let (id, focused) = (field_focused_id(ctx), ctx.text_edit_focused()); ctx.data_mut(|d| d.insert_temp(id, focused)); - #[cfg(not(target_arch = "wasm32"))] - { - let now = ctx.input(|i| i.modifiers); - // The modifiers last frame ended with are the ones this frame's events began with. - ctx.data_mut(|d| { - let (_, end) = d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id()).unwrap_or((now, now)); - d.insert_temp(modifiers_id(), (end, now)); - }); - } + let now = ctx.input(|i| i.modifiers); + // The modifiers last frame ended with are the ones this frame's events began with. + ctx.data_mut(|d| { + let (_, end) = d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id()).unwrap_or((now, now)); + d.insert_temp(modifiers_id(), (end, now)); + }); } /// (held when this frame's events began, held after them). -#[cfg(not(target_arch = "wasm32"))] fn modifiers_id() -> egui::Id { egui::Id::new("canvas-frame-modifiers") } @@ -2649,28 +2645,26 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r // text must not delete the character before it). let composing_at_start = app.session.tool_composing(); let evs = ui.input(|i| i.events.clone()); - // Native only: egui-winit sends a ⌘+V chord as a paste without its key press, so the modifiers - // held at the paste tell Paste in Place from Paste. The web also gets the key press, and the - // shortcut table has already run the command. A chord's modifiers may be released in the same - // frame, hence the modifiers held at each event. - #[cfg(not(target_arch = "wasm32"))] + // The modifiers held at each event: they may be released later in the same frame. Shift+Space + // needs them, and so does Paste in Place natively, where egui-winit sends a ⌘+V chord as a + // paste without its key press (the web also gets the key press, and the shortcut table has + // already run the command). let mut held = ui.data(|d| d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id())).map_or_else(|| ui.input(|i| i.modifiers), |(start, _)| start); for e in evs { + if let egui::Event::ModifiersChanged(m) = &e { + held = *m; + } #[cfg(not(target_arch = "wasm32"))] - let chord = { - if let egui::Event::ModifiersChanged(m) = &e { - held = *m; - } - if matches!(e, egui::Event::Paste(_)) { crate::menus::paste_chord_command(app, held) } else { None } - }; + let chord = if matches!(e, egui::Event::Paste(_)) { crate::menus::paste_chord_command(app, held) } else { None }; let composing = composing_at_start || app.session.tool_composing(); match e { egui::Event::Ime(ime) if wants_text => ime_event(app, ime, vi), // Keys the IME passes through come as text only while nothing is marked. egui::Event::Text(t) if wants_text && !composing => { - let shift = ui.input(|i| i.modifiers.shift); - let typed = typed_text(&t, app.ime_japanese_typing, shift, cfg!(target_os = "macos")); + // The caret may have moved to another story earlier this frame (a click). + ime_follow_caret(app); + let typed = typed_text(&t, app.ime_japanese_typing, held.shift, cfg!(target_os = "macos")); // Letters straight from the keys: the input method is in its Roman mode. if !t.trim().is_empty() { app.ime_japanese_typing = false; @@ -2832,6 +2826,16 @@ pub(crate) fn keep_marked_text(app: &mut DesignApp) { } } +/// In another story (or document) the input mode may have changed unseen: Japanese typing starts +/// over when the caret gets there. +fn ime_follow_caret(app: &mut DesignApp) { + let here = app.session.active_index().zip(app.session.active().and_then(|st| st.selection.text).map(|t| t.story)); + if here != app.ime_caret_story { + app.ime_japanese_typing = false; + app.ime_caret_story = here; + } +} + /// While the text caret is in the canvas, let the system IME compose (egui-winit allows it only in /// frames that set `ime`; the web build focuses its hidden text input then) and keep the candidate /// window at the caret, through zoom, scrolling, view rotation and vertical text. @@ -2849,12 +2853,7 @@ fn ime_output(app: &mut DesignApp, ctx: &egui::Context, xf: &Xf) { app.ime_caret_story = None; return; }; - // In another story (or document) the input mode may have changed unseen: start plain. - let here = app.session.active_index().zip(app.session.active().and_then(|st| st.selection.text).map(|t| t.story)); - if here != app.ime_caret_story { - app.ime_japanese_typing = false; - app.ime_caret_story = here; - } + ime_follow_caret(app); let r = Rect::from_two_pos(xf.to_screen(a), xf.to_screen(b)).expand(1.0); // The composition ended outside the IME (a click, a command): the IME drops what it has marked. let interrupt = app.ime_marked.is_some() && !app.session.tool_composing(); @@ -5655,6 +5654,20 @@ mod tests { assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab é ")); } + /// Shift+Space stays plain even when Shift comes up later in the same frame: the Shift held + /// at the space counts, not the one at the frame's end. + #[test] + fn shift_space_stays_plain_when_shift_is_released_in_the_same_frame() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + ime_frame(&mut app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); + let shift = egui::Event::ModifiersChanged(egui::Modifiers::SHIFT); + let up = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + ime_frame(&mut app, &ctx, vec![shift, egui::Event::Text(" ".into()), up]); + assert_eq!(story_text(&mut app, &sid), "日本語 "); + } + /// The caret moving to another story, or leaving the text, ends Japanese typing: the input /// mode may have changed without an event the app sees (the Eisu key, say). #[test] @@ -5674,6 +5687,15 @@ mod tests { ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); assert_eq!(story_text(&mut app, &second), " "); assert_eq!(story_text(&mut app, &first), "日本語"); + // Japanese typed in the first story, then the caret moves and a space comes in the same + // frame: still the new story's plain space. + app.session.execute("text.select", &json!({"story": first, "anchor": 0, "focus": 0})).unwrap(); + ime_frame(&mut app, &ctx, vec![]); + commit(&mut app); + app.session.execute("text.select", &json!({"story": second, "anchor": 1, "focus": 1})).unwrap(); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &second), " "); + assert_eq!(story_text(&mut app, &first), "日本語日本語"); commit(&mut app); app.select_tool("rectangleFrame"); ime_frame(&mut app, &ctx, vec![]); From bf42dee573fa19b83ed01de81bb5e3c8b5a1fa76 Mon Sep 17 00:00:00 2001 From: con3code Date: Sun, 25 Oct 2026 16:24:24 +0900 Subject: [PATCH 013/133] Text: a cancelled Japanese composition does not make the next one Japanese Kana seen while composing are cleared when a new composition starts, so a composition cancelled with Escape no longer turns the space after a later Chinese or accented commit into an ideographic one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013phQ3ekq6uGBEWD6FjFYG2 --- crates/ui-egui/src/canvas.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0383331e7..44198722f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2771,6 +2771,11 @@ pub(crate) fn has_kana(text: &str) -> bool { fn ime_event(app: &mut DesignApp, e: egui::ImeEvent, vi: designcraft_engine::ViewInfo) { let r = match e { egui::ImeEvent::Preedit { text, active_range_chars } => { + // A new composition: kana from one the input method cancelled (Escape) don't count. + // The empty preedit before a commit keeps them, as something is still marked then. + if app.ime_marked.is_none() { + app.ime_kana_seen = false; + } app.ime_marked = Some(text.clone()).filter(|t| !t.is_empty()); app.ime_kana_seen |= has_kana(&text); app.session.tool_preedit(&text, active_range_chars, vi).map_err(|e| e.to_string()) @@ -5727,6 +5732,19 @@ mod tests { } } + /// Kana from a composition cancelled with Escape (the input method clears the marked text and + /// commits nothing) don't make the next composition Japanese. + #[test] + fn a_cancelled_japanese_composition_does_not_carry_over() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + ime_frame(&mut app, &ctx, vec![preedit("にほ", 2), preedit("", 0)]); + ime_frame(&mut app, &ctx, vec![preedit("ni", 2), preedit("", 0), egui::Event::Ime(egui::ImeEvent::Commit("你".into()))]); + ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); + assert_eq!(story_text(&mut app, &sid), "你 "); + } + #[test] #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { From e0c3590f6a26d2e36fd52905dcdece4ba9983532 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 19:18:13 +0500 Subject: [PATCH 014/133] A dashed stroke with no pattern of its own draws dashed (#1467) An IDML `StrokeStyle/$ID/Dashed` names no dash array, and `type: "dashed"` on a cell stroke sets none either, so the stroke drew **solid**: a dashed rule came back solid from a round trip, and a dashed cell stroke never dashed at all. `StrokeType::dashes(weight)` answers the pattern to draw, falling back to three weights on and two off -- which is what a dashed paragraph border and a dashed cell stroke already resolved to, so the three agree now. A pattern that is present but degenerate is left alone, so `expandable_dashes` still draws it solid rather than expanding 10^8 dashes along an edge. Every drawing site goes through it: the renderer, the PDF exporter, the deck exporter and paragraph borders. Rebased onto the post-split main: StrokeType and expandable_dashes are in doc/item/paint.rs, the renderer's stroke setup in render/stroke.rs, and the PDF one in pdf/export/paint.rs. The render test went to render/tests.rs. --- crates/compose/src/parabox.rs | 5 +--- crates/doc/src/item/paint.rs | 45 ++++++++++++++++++++++++++++++++++ crates/pdf/src/export/paint.rs | 6 ++--- crates/pptx/src/slide.rs | 4 +-- crates/render/src/stroke.rs | 6 +++-- crates/render/src/tests.rs | 35 ++++++++++++++++++++++++++ crates/render/src/text.rs | 7 +++--- 7 files changed, 94 insertions(+), 14 deletions(-) diff --git a/crates/compose/src/parabox.rs b/crates/compose/src/parabox.rs index f6b90e127..5bef92d09 100644 --- a/crates/compose/src/parabox.rs +++ b/crates/compose/src/parabox.rs @@ -349,10 +349,7 @@ fn stroke_outline(path: &BezPath, w: f64, kind: &StrokeType, cap: Cap, join: Joi Join::Bevel => kurbo::Join::Bevel, }); let dashes: Option> = match kind { - StrokeType::Dashed { pattern } => { - let p: Vec = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect(); - Some(if p.iter().sum::() > 1e-3 { p } else { vec![3.0 * w, 2.0 * w] }) - } + StrokeType::Dashed { .. } => kind.dashes(w), StrokeType::Dotted => { st = st.with_caps(kurbo::Cap::Round); Some(vec![0.0, 2.0 * w]) diff --git a/crates/doc/src/item/paint.rs b/crates/doc/src/item/paint.rs index 04d8323fc..76372bd45 100644 --- a/crates/doc/src/item/paint.rs +++ b/crates/doc/src/item/paint.rs @@ -191,6 +191,27 @@ impl StrokeType { && length / period <= MAX_DASH_PERIODS } + /// The dash pattern to draw for a dashed stroke `weight` points wide, or `None` for a type + /// that is not dashed. + /// + /// A dashed stroke with no pattern of its own is drawn three weights on, two off: that is + /// what `type: "dashed"` on a table cell stroke and a dashed paragraph border have always + /// resolved to, and it is the only pattern an IDML `StrokeStyle/$ID/Dashed` carries (the + /// built-in dashed styles name no array). Without it such a stroke drew solid (#1467). + pub fn dashes(&self, weight: f64) -> Option> { + let StrokeType::Dashed { pattern } = self else { return None }; + let kept: Vec = pattern.iter().copied().filter(|v| v.is_finite() && *v >= 0.0).collect(); + // No pattern at all (or only zeros, which no command accepts and only a file can carry): + // the dashes come from the weight. A pattern that is there but degenerate is left alone, + // so [`StrokeType::expandable_dashes`] still draws it solid rather than expanding 10^8 + // dashes along an edge. + if kept.iter().all(|v| *v == 0.0) { + let w = weight.max(1.0); + return Some(vec![w * 3.0, w * 2.0]); + } + Some(kept) + } + /// The bands of a striped type (start, width as fractions of the weight). pub fn bands(&self) -> Option> { Some(match self { @@ -355,3 +376,27 @@ impl Stroke { self.swatch == designcraft_color::swatch::NONE || self.weight <= 0.0 } } + +/// A dashed stroke with no pattern of its own — an IDML `StrokeStyle/$ID/Dashed`, or +/// `type: "dashed"` with no array — dashes by its weight instead of drawing solid (#1467). +#[test] +fn a_dashed_stroke_without_a_pattern_dashes_by_its_weight() { + let dashed = |p: Vec| StrokeType::Dashed { pattern: p }; + assert_eq!(dashed(vec![]).dashes(1.0), Some(vec![3.0, 2.0])); + assert_eq!(dashed(vec![]).dashes(4.0), Some(vec![12.0, 8.0])); + // A hairline still dashes visibly: the weight counts as at least a point. + assert_eq!(dashed(vec![]).dashes(0.25), Some(vec![3.0, 2.0])); + // Only zeros is nothing specified too (no command accepts such a pattern). + assert_eq!(dashed(vec![0.0, 0.0]).dashes(2.0), Some(vec![6.0, 4.0])); + // A pattern of its own is kept, as are the entries of a degenerate one, which + // `expandable_dashes` then refuses so that it draws solid rather than expanding forever. + assert_eq!(dashed(vec![6.0, 3.0]).dashes(2.0), Some(vec![6.0, 3.0])); + assert_eq!(dashed(vec![1e-6, 1e-6]).dashes(2.0), Some(vec![1e-6, 1e-6])); + assert!(!StrokeType::expandable_dashes(&[1e-6, 1e-6], 200.0)); + // Negative and non-finite entries are dropped, as every drawing site did before. + assert_eq!(dashed(vec![6.0, -1.0, f64::NAN, 3.0]).dashes(1.0), Some(vec![6.0, 3.0])); + // Nothing else has dashes. + assert_eq!(StrokeType::Solid.dashes(1.0), None); + assert_eq!(StrokeType::Dotted.dashes(1.0), None); + assert_eq!(StrokeType::Style { name: "x".into() }.dashes(1.0), None); +} diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index 026b78674..1253142dd 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -164,13 +164,13 @@ impl Exporter<'_> { // Viewers expand dashes too: a degenerate pattern draws solid, as on screen. let length = designcraft_doc::path_length_bound(bp); let dash = match &kind { - StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => { + StrokeType::Dashed { .. } => kind.dashes(st.weight).filter(|p| StrokeType::expandable_dashes(p, length)).map(|pattern| { let mut pat: Vec = pattern.iter().map(|v| v.max(0.0) as f32).collect(); if pat.len() % 2 == 1 { pat.extend(pat.clone()); } - Some(StrokeDash { array: pat, offset: 0.0 }) - } + StrokeDash { array: pat, offset: 0.0 } + }), StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], length) => { cap = krilla::paint::LineCap::Round; Some(StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }) diff --git a/crates/pptx/src/slide.rs b/crates/pptx/src/slide.rs index 03fd0e8b9..4f730c5f0 100644 --- a/crates/pptx/src/slide.rs +++ b/crates/pptx/src/slide.rs @@ -476,8 +476,8 @@ impl<'a> Exporter<'a> { }; let w = s.weight; let dash = match &s.kind { - StrokeType::Dashed { pattern } if pattern.iter().any(|v| *v > 0.0) => { - let mut v: Vec = pattern.iter().map(|x| x.max(0.0)).collect(); + StrokeType::Dashed { .. } if s.kind.dashes(w).is_some_and(|p| p.iter().any(|v| *v > 0.0)) => { + let mut v: Vec = s.kind.dashes(w).unwrap_or_default(); if v.len() % 2 == 1 { v.extend(v.clone()); } diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index bff888b09..a31ce6cc7 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -31,8 +31,10 @@ impl Renderer { let kind = f.doc.stroke_kind(&st.kind); let length = designcraft_doc::path_length_bound(bp); match &kind { - StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => { - stroke = stroke.with_dashes(0.0, pattern.iter().copied()) + StrokeType::Dashed { .. } => { + if let Some(p) = kind.dashes(st.weight).filter(|p| StrokeType::expandable_dashes(p, length)) { + stroke = stroke.with_dashes(0.0, p); + } } StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], length) => { stroke = stroke.with_dashes(0.0, [0.0, st.weight * 2.0]).with_caps(kurbo::Cap::Round) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 708b6bd43..e87832271 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -669,3 +669,38 @@ fn content_crop_box_is_measured_without_rendering_the_page() { assert!(frac.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-6), "{frac:?} vs {want:?}"); assert!((size.0 - 400.0).abs() < 1e-3 && (size.1 - 497.0).abs() < 1e-3, "{size:?}"); } + +/// An IDML `StrokeStyle/$ID/Dashed` names no dash array, and `type: "dashed"` on a cell +/// stroke sets none either, so the stroke drew **solid** — a dashed rule came back solid from +/// an IDML round trip (#1467). With no pattern of its own it draws three weights on, two off, +/// which is what a dashed paragraph border and a cell stroke already resolved to. +#[test] +fn a_dashed_stroke_without_a_pattern_draws_dashed() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let mut line = |y: f64, kind: designcraft_doc::StrokeType| { + let id = designcraft_doc::ItemId(d.alloc()); + let path = designcraft_geom::shapes::line(designcraft_geom::Point::new(100.0, y), designcraft_geom::Point::new(400.0, y)); + let mut it = Item::new(id, lid, designcraft_doc::Shape::GraphicLine, path); + it.stroke = designcraft_doc::Stroke { swatch: designcraft_color::swatch::BLACK.into(), weight: 2.0, kind, ..Default::default() }; + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + }; + // Weight 2, so the dashes are 6 pt on and 4 pt off from x = 100. + line(200.0, designcraft_doc::StrokeType::Dashed { pattern: vec![] }); + line(300.0, designcraft_doc::StrokeType::Dashed { pattern: vec![6.0, 4.0] }); + line(400.0, designcraft_doc::StrokeType::Solid); + let cache = Cache::new(); + let mut r = Renderer::new(); + r.threads = 0; + let img = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap(); + let ink = |x: u32, y: u32| img.pixel(x, y)[0] < 64; + let paper = |x: u32, y: u32| img.pixel(x, y)[0] > 192; + for y in [200, 300] { + assert!(ink(102, y), "{y}: the first dash"); + assert!(paper(108, y), "{y}: the first gap"); + assert!(ink(112, y), "{y}: the second dash"); + assert!(paper(118, y), "{y}: the second gap"); + } + // The solid line has no gaps, which is how the dashed ones looked before. + assert!(ink(102, 400) && ink(108, 400) && ink(112, 400) && ink(118, 400)); +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index c29107c36..74c556d0b 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -605,9 +605,10 @@ pub(crate) fn cell_stroke(kind: &designcraft_doc::StrokeType, weight: f64, lengt use designcraft_doc::StrokeType; let st = kurbo::Stroke::new(weight).with_caps(kurbo::Cap::Square); match kind { - StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, length) => { - st.with_caps(kurbo::Cap::Butt).with_dashes(0.0, pattern.iter().copied()) - } + StrokeType::Dashed { .. } => match kind.dashes(weight).filter(|p| StrokeType::expandable_dashes(p, length)) { + Some(p) => st.with_caps(kurbo::Cap::Butt).with_dashes(0.0, p), + None => st, + }, StrokeType::Dotted if StrokeType::expandable_dashes(&[0.0, weight * 2.0], length) => { st.with_dashes(0.0, [0.0, weight * 2.0]).with_caps(kurbo::Cap::Round) } From 605bc0832ab22cc7ae516f95ade4d57076e42c20 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 18:26:30 +0000 Subject: [PATCH 015/133] M6: the anchored-object crop test fills upstream's new Graphic.layer_options Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/engine/src/cmd/anchored.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index ae241d67e..d35b70bcf 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -390,6 +390,7 @@ mod tests { crop: [0.0; 4], wrap: Default::default(), fill: Default::default(), + layer_options: Default::default(), }; s.edit(|d, _| { let it = &mut Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item; From fbbb9252eeddae11b23e7b5526600328faebaaae Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 14:03:19 +0500 Subject: [PATCH 016/133] Dash a table edge in PDF export through the shared rule The table-edge stroke in PDF export matched the raw `Dashed` pattern, so an edge with no pattern of its own (what `type: "dashed"` and an IDML `StrokeStyle/$ID/Dashed` resolve to) failed `expandable_dashes` and fell through to a solid, square-capped stroke. The renderer and the item stroke dashed it, so the PDF disagreed with the screen. It now goes through `StrokeType::dashes` like every other stroke: a weight-2 dashed edge exports `2 w[6 4]0 d` instead of `2 J` with no dash array. --- crates/pdf/src/tests.rs | 29 +++++++++++++++++++++++++++++ crates/pdf/src/text.rs | 29 ++++++++++++++++------------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2accc79fa..cb0356520 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -218,6 +218,35 @@ fn table_gradient_fill_exports_a_shading() { assert!(pdf.contains("/ShadingType 2") || pdf.contains("/ShadingType2"), "table fill must export a linear gradient"); } +/// A table edge's dashed stroke carries no dash array of its own, so matching the raw pattern +/// exported it solid while the renderer dashed it -- the PDF disagreed with the screen (#1467, +/// noted in review). The edge goes through `StrokeType::dashes` like every other stroke. +#[test] +fn a_dashed_table_edge_exports_dashed() { + let table = |kind: designcraft_doc::StrokeType| { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 300.0), lid, "", ParaFormat::default()).unwrap(); + let mut t = designcraft_doc::Table::new(1, 1, 2, 0, 0, 200.0); + t.rows[0].height = 40.0; + t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + t.options.border.weight = 2.0; + t.options.border.kind = kind; + d.story_mut(sid).unwrap().insert_table(0, t); + uncompressed(&d, PdfOptions::default()) + }; + // `d` is the PDF dash operator; krilla writes it `[a b]0 d`, with no space before the phase. + let ops = |pdf: &str| pdf.replace("]0 d", "] 0 d"); + + // Dashed with no pattern of its own: three weights on, two off, as the renderer draws it. + let dashed = ops(&table(designcraft_doc::StrokeType::Dashed { pattern: vec![] })); + assert!(dashed.contains("] 0 d"), "a dashed edge exports a dash array"); + assert!(dashed.contains("[6 4] 0 d"), "three weights on, two off at weight 2"); + + // A solid edge still writes no dash array, so the check above means something. + assert!(!ops(&table(designcraft_doc::StrokeType::Solid)).contains("] 0 d"), "a solid edge exports none"); +} + #[test] fn tables_export_cell_text() { let mut d = Document::new(&NewDocument::default()); diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index ba44cf713..6ef33264b 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -386,22 +386,25 @@ impl Exporter<'_> { s.set_fill(None); continue; } - let (cap, dash) = match &kind { - designcraft_doc::StrokeType::Dashed { pattern } - if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) => - { - let mut pat: Vec = pattern.iter().map(|v| v.max(0.0) as f32).collect(); - if pat.len() % 2 == 1 { - pat.extend(pat.clone()); - } - (krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 })) + let len = seg.a.distance(seg.b); + let expandable = |p: &[f64]| designcraft_doc::StrokeType::expandable_dashes(p, len); + // Through the resolved pattern, so a `Dashed` with none of its own dashes by its + // weight here as well. Matching the raw pattern left a table edge exporting solid + // while the renderer and the item stroke dashed it (noted in review). + let dashed = kind.dashes(st.weight).filter(|p| expandable(p)).map(|pattern| { + let mut pat: Vec = pattern.iter().map(|v| v.max(0.0) as f32).collect(); + if pat.len() % 2 == 1 { + pat.extend(pat.clone()); } - designcraft_doc::StrokeType::Dotted - if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) => - { + (krilla::paint::LineCap::Butt, krilla::paint::StrokeDash { array: pat, offset: 0.0 }) + }); + let (cap, dash) = match dashed { + Some((cap, d)) => (cap, Some(d)), + // A pattern that cannot be expanded still draws solid, as before. + None if matches!(kind, designcraft_doc::StrokeType::Dotted) && expandable(&[0.0, st.weight * 2.0]) => { (krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 })) } - _ => (krilla::paint::LineCap::Square, None), + None => (krilla::paint::LineCap::Square, None), }; s.set_fill(None); s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() })); From adf0e57132292d1fef573f4d675e1759bb8491e4 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 15 Oct 2026 08:39:24 +0200 Subject: [PATCH 017/133] IDML import: style names ending in a space, layers of group items A BasedOn reference to a style whose name ends in a space was trimmed before it was looked up, so the base style went missing and its font and colour with it. The reference is now looked up as written first. Items inside a group or pasted into a frame carry no ItemLayer in IDML: they sit on their parent's layer. They were put on the first layer, which may be hidden or locked, and took their text wrap and editing with it. --- crates/idml/src/import.rs | 4 ++ crates/idml/src/import/item.rs | 6 ++- crates/idml/src/import/styles.rs | 7 +++- crates/idml/src/tests.rs | 70 ++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index 161594e1e..eef282866 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -169,6 +169,9 @@ struct Importer<'r> { para_els: HashMap, layers: Vec, layer_ids: HashMap, + /// The layer of the group (or frame) whose children are being read: IDML gives children no + /// ItemLayer of their own, they sit on their parent's layer. + parent_layer: Option, stories: BTreeMap, story_ids: HashMap, parents: Vec, @@ -250,6 +253,7 @@ impl<'r> Importer<'r> { para_els: HashMap::new(), layers: Vec::new(), layer_ids: HashMap::new(), + parent_layer: None, stories: BTreeMap::new(), story_ids: HashMap::new(), parents: Vec::new(), diff --git a/crates/idml/src/import/item.rs b/crates/idml/src/import/item.rs index d25044dc6..ddb8e7bf2 100644 --- a/crates/idml/src/import/item.rs +++ b/crates/idml/src/import/item.rs @@ -60,7 +60,7 @@ impl<'r> Importer<'r> { if let Some(s) = e.get("Self") { self.item_ids.insert(s.to_string(), id); } - let layer = e.get("ItemLayer").and_then(|l| self.layer_ids.get(l)).copied().unwrap_or_else(|| self.layers[0].id); + let layer = e.get("ItemLayer").and_then(|l| self.layer_ids.get(l)).copied().or(self.parent_layer).unwrap_or_else(|| self.layers[0].id); let path = e.prop_el("PathGeometry").map(path_of).unwrap_or_default(); let mut it = Item::new(id, layer, shape, path); it.xf = parent * parse_affine(e.get("ItemTransform")); @@ -223,11 +223,13 @@ impl<'r> Importer<'r> { } "Group" => { let mut kids = Vec::new(); + let outer = self.parent_layer.replace(item.layer); for c in e.elements() { if let Some(k) = self.item(c, Affine::IDENTITY) { kids.push(Arc::new(k)); } } + self.parent_layer = outer; item.content = Content::Group { items: kids }; item.fill = Fill::none(); item.stroke = Stroke::none(); @@ -251,12 +253,14 @@ impl<'r> Importer<'r> { } } else { // Page items pasted into this frame (Paste Into). + let outer = self.parent_layer.replace(item.layer); let kids: Vec> = e .elements() .filter(|c| matches!(c.local(), "Rectangle" | "Oval" | "Polygon" | "GraphicLine" | "Group" | "TextFrame")) .filter_map(|c| self.item(c, Affine::IDENTITY)) .map(Arc::new) .collect(); + self.parent_layer = outer; if !kids.is_empty() { item.content = Content::Group { items: kids }; } diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 5719393a2..ca245e4db 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -202,8 +202,11 @@ impl<'r> Importer<'r> { } fn based_on(&self, e: &El, para: bool) -> Option { - let b = e.prop("BasedOn")?; - let b = b.trim(); + let raw = e.prop("BasedOn")?; + // Style names may end in a space ("arabic purple "): look the reference up as written + // before trimming it. + let known = if para { self.para_names.contains_key(&raw) } else { self.char_names.contains_key(&raw) }; + let b = if known { raw.as_str() } else { raw.trim() }; if para { if let Some(n) = self.para_names.get(b) { return Some(n.clone()); diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 0d078c63c..4fc8288dd 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2221,6 +2221,43 @@ fn layers_import_and_export_in_stacking_order() { assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id); } +/// A character style based on one whose name ends in a space ("arabic purple ") inherits from +/// it: the reference was trimmed, the base went missing and its font and colour with it. +#[test] +fn based_on_a_style_name_ending_in_a_space() { + let styles = STYLES.replace( + r#""#, + r#" + Source Sans 3 + + + CharacterStyle/purple + + "#, + ); + let story = STORY.replace("CharacterStyle/Strong", "CharacterStyle/purple 23 pt "); + let pkg = zip_files(&[ + ("designmap.xml", DESIGNMAP), + ("Resources/Graphic.xml", GRAPHIC), + ("Resources/Styles.xml", &styles), + ("Resources/Preferences.xml", PREFS), + ("MasterSpreads/MasterSpread_m1.xml", MASTER), + ("Spreads/Spread_sp1.xml", SPREAD), + ("Stories/Story_s1.xml", &story), + ]); + let d = import_idml(&pkg).unwrap(); + let st = d.styles.character.iter().find(|c| c.name == "purple 23 pt ").expect("the derived style"); + assert_eq!(st.based_on.as_deref(), Some("purple ")); + let sid = *d.stories.keys().next().unwrap(); + let story = d.story(sid).unwrap(); + let at = story.text.find("bold").unwrap(); + let (_, base) = d.styles.resolve_para(&story.paras[0]); + let props = d.styles.resolve_char(&base, story.char_format_at(at + 1)); + assert_eq!(props.font_family, "Source Sans 3"); + let fill = d.styles.char_style_attrs("purple ").fill.expect("the base style's colour"); + assert_eq!(props.fill, fill); +} + /// Synthetic forward references: both a body anchor and a footnote anchor own /// a group containing a text frame whose story is serialized later. #[test] @@ -2868,6 +2905,39 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() { check(&import_idml(&export_idml(&d)).unwrap()); } +/// The items of a group carry no ItemLayer in IDML: they sit on the group's layer, not on the +/// front layer (which may be hidden or locked and took their wrap and editing with it). +#[test] +fn group_children_sit_on_the_groups_layer() { + let designmap = r#" + + + + "#; + let rect = |me: &str| { + format!( + r#" + + "# + ) + }; + let spread = format!( + r#" + + {}{} + "#, + rect("a"), + rect("b") + ); + let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap(); + let background = d.layers.iter().find(|l| l.name == "Background").unwrap().id; + let g = &d.spreads[0].items[0]; + assert_eq!(g.layer, background); + let mut layers = Vec::new(); + g.walk(&mut |it| layers.push(it.layer)); + assert!(layers.iter().all(|l| *l == background), "{layers:?}"); +} + /// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is /// set in that family instead of counting as a missing font drawn in the fallback. #[test] From 5a9640855269e29ef06a30f23177368fd2b0547d Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 15 Oct 2026 08:52:09 +0200 Subject: [PATCH 018/133] PDF export: an empty .notdef prints as nothing Where a font's .notdef glyph is empty, InDesign shows a box on screen but exports nothing in its place. The PDF now does the same; the screen keeps the box, and Preflight still lists the character. --- crates/pdf/src/tests.rs | 6 +++--- crates/pdf/src/text.rs | 8 +++++++- docs/cjk.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2accc79fa..db3b26b09 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -560,7 +560,7 @@ fn pdfa_leaves_out_form_fields_added_after_validation() { } #[test] -fn missing_glyphs_print_as_boxes() { +fn missing_glyphs_print_as_the_fonts_notdef() { // Source Serif 4 lacks 語: its .notdef box is drawn as a path, not as a .notdef glyph // (which PDF/A and PDF/UA forbid). let boxes = |paths: &[kurbo::Rect]| paths.iter().filter(|r| r.width() > 1.0 && r.width() < 12.0 && r.height() > 3.0 && r.height() < 12.0).count(); @@ -571,7 +571,7 @@ fn missing_glyphs_print_as_boxes() { assert_eq!(boxes(&paths), 1, "{paths:?}"); let a = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..Default::default() }); assert!(a.is_ok(), "PDF/A takes the box: {:?}", a.err()); - // A font whose .notdef is empty: the box DesignCraft draws for it. + // A font whose .notdef is empty prints nothing there, as InDesign exports it. const FAMILY: &str = "DC Test PDF Empty Notdef"; let font = designcraft_fonts::testing::font_mapping(FAMILY, &[('a', 'a'), ('b', 'b')]).unwrap(); designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::with_empty_notdef(font).unwrap()); @@ -580,7 +580,7 @@ fn missing_glyphs_print_as_boxes() { d.story_mut(sid).unwrap().format_chars(0.."a語b".len(), |f| f.over.font_family = Some(FAMILY.into())); let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap()); assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::>(), ["a", "b"], "{glyphs:?}"); - assert_eq!(boxes(&paths), 1, "{paths:?}"); + assert_eq!(boxes(&paths), 0, "{paths:?}"); } #[test] diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index ba44cf713..1b02c1656 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -521,7 +521,8 @@ impl Exporter<'_> { } else { stroke }; - // A missing glyph is drawn as its box: PDF/A and PDF/UA forbid showing .notdef as text. + // A missing glyph is drawn as the font's .notdef outline: PDF/A and PDF/UA forbid showing + // .notdef as text. if g0.gid == 0 { self.paint_outlines(s, &glyph_outlines(glyphs, size, tan), origin, fill, stroke, weight); } else if let Some(font) = self.font(&face) { @@ -650,6 +651,11 @@ fn glyph_outlines(glyphs: &[PlacedGlyph], size: f64, tan: f64) -> BezPath { let Some(g0) = glyphs.first() else { return bp }; let k = size / g0.face.upem; for g in glyphs { + // A .notdef the font leaves empty prints as nothing, as InDesign exports it (the screen + // shows a box, and Preflight lists the character). + if g.gid == 0 && db.missing_box(&g.face).is_some() { + continue; + } let dy = g.y - g0.y; let a = Affine::translate(((g.x - g0.x + tan * dy) / (g0.sx / g0.sy), dy)) * Affine::scale(k); let mut o = (*db.outline(&g.face, g.gid)).clone(); diff --git a/docs/cjk.md b/docs/cjk.md index 4ee48dc06..22a566284 100644 --- a/docs/cjk.md +++ b/docs/cjk.md @@ -48,7 +48,7 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built | Grid alignment | against the baseline grid: roman baseline, em box top / centre / bottom, ICF top / bottom; first line only; gyoudori (auto or N grid lines) and paragraph gyoudori (`type.gridSettings`, IDML `GridAlignment`, `GridGyoudori`, `ParagraphGyoudori`). No frame grid; vertical frames have no baseline grid | | Composite fonts | done: model, `style.compositeFont.*`, shaping, IDML, font list, replace and Preflight; no dialog | | Languages | Japanese, Korean, Simplified and Traditional Chinese reach the shaper (`locl`), font fallback, line breaking and typographer's quotes; IDML language names are kept as written; locale codes (`ja_JP`, `ko-KR`, `de_DE_2006`) are their language and region, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`) | -| Missing glyphs | as in InDesign: characters the applied font lacks are drawn as its missing-glyph box (screen and PDF) and listed by Preflight; the document setting Draw Missing Glyphs from Fallback Fonts (Preferences › Composition, off in new documents and IDML imports, on in documents saved before it existed) draws them from fallback fonts instead | +| Missing glyphs | as in InDesign: characters the applied font lacks are drawn as its missing-glyph box (screen and PDF; an empty one shows as a drawn box on screen and prints as nothing) and listed by Preflight; the document setting Draw Missing Glyphs from Fallback Fonts (Preferences › Composition, off in new documents and IDML imports, on in documents saved before it existed) draws them from fallback fonts instead | | Font menus | Western families first, then Japanese, Simplified Chinese, Traditional Chinese and Korean groups (from the font's `meta` languages, CJK family names, OS/2 code pages, else its coverage); CJK families under their native names unless Preferences › Type › Show Font Names in English; the order is recalled from InDesign, not observed | | CJK fonts | Japanese faces (Shippori Mincho first) from the optional craft-fonts build input, in the font menus for users to apply; fallback by language (with fallback fonts on) (Japanese: the craft-fonts faces, then system fonts; Simplified and Traditional Chinese, Korean: system fonts); document fonts: the fonts of a `Document Fonts` folder beside an opened file belong to that document (composition, export, font menus), ahead of installed fonts of the same name, and are forgotten when it closes; Package copies every font file that draws text, fallback fonts included (licence permitting). Font files stay in memory for the session (reopening a document reuses them) and aren't read on the web | | Interface | Preferences › Type › Show CJK Features (`cjkFeatures`; until set, on for a Japanese, Chinese or Korean interface) shows the CJK-only menu items (Type › Tate-Chu-Yoko, Ruby…, Kenten, Warichu); layout, IDML and commands work either way | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3443ca8e6..ff7845c20 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -295,7 +295,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands. - Linked text files: `file.place {link: true}` or Preferences › File Handling › Create Links When Placing Text Files keeps a placed .docx/.rtf/.txt story linked to its file (path, size and hash, and the style map and conflict option used). The Links panel shows it OK / Modified / Missing; Update imports the file again into the same frames and thread with the saved style map, replacing edits made in the layout (the Links panel and menu ask first; the `links.update` command updates and returns a warning; undoable); Relink, Go To and Unlink. Saved in the native format; IDML exports the text unlinked. - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`. Type › Reload Fonts (`font.reload`) scans the font folders again and reads again the installed font files edited or removed since they were read, then recomposes the open documents: a font installed or edited while DesignCraft runs needs no restart (#328, #547). InDesign notices such changes by itself. -- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts. +- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef, as a path in PDF, so PDF/A and PDF/UA exports take it); when the font's .notdef is empty the screen shows a drawn box and the PDF, as InDesign's, nothing, and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts. - Damage-region repaint: after an edit the canvas re-renders only the frames whose composed text (or the items that) changed and patches its texture — pixel-identical to a full render; typing in a frame repaints in under a millisecond instead of a full-viewport render (22 ms measured on the sample). - Native engine saves, Save a Copy, snippets, books, libraries, swatches and engine/MCP exports use same-folder atomic replacement through craft-libs/craft-atomic, as do desktop Services writes and CLI raster exports. Failed writes before replacement retain the original, and already-open readers retain the old bytes. On Unix a new file gets the permissions ordinary file creation gives it (the umask applies) and a replaced file keeps its permissions. Parent-folder flushing is best effort, so this is not a power-loss durability guarantee. - Save As prepares destination-relative data-source paths before writing and installs them only after a successful save. Failed Save As retains the document, saved state and history; Save a Copy rebases only the saved copy. Library and book collection edits likewise update live values only after persistence succeeds. From 0444d88777800f171e8e9a8f8157e1199aba841b Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 29 Oct 2026 16:16:34 +0100 Subject: [PATCH 019/133] IDML import: BasedOn on lines of its own, layers of pasted-in items tested - A BasedOn reference written on lines of its own (an indented file) to a style whose name ends in a space lost that space: it didn't match as written, so it was trimmed and the base style went missing. Now only the whitespace before the reference and from the first line break after it goes when that names a style; otherwise it is trimmed as before. - The group layer test also covers an item pasted into a frame: it sits on the frame's layer. --- crates/idml/src/import/styles.rs | 21 +++++++++++--- crates/idml/src/tests.rs | 48 ++++++++++++++++++++++++++++---- 2 files changed, 59 insertions(+), 10 deletions(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index ca245e4db..8bd76f771 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -203,10 +203,11 @@ impl<'r> Importer<'r> { fn based_on(&self, e: &El, para: bool) -> Option { let raw = e.prop("BasedOn")?; - // Style names may end in a space ("arabic purple "): look the reference up as written - // before trimming it. - let known = if para { self.para_names.contains_key(&raw) } else { self.char_names.contains_key(&raw) }; - let b = if known { raw.as_str() } else { raw.trim() }; + // Style names may end in a space: use the reference as written, or without the line + // breaks and indentation an indented file puts around it, when that names a style; only + // otherwise trim it. + let names = if para { &self.para_names } else { &self.char_names }; + let b = [raw.as_str(), unindented(&raw)].into_iter().find(|r| names.contains_key(*r)).unwrap_or_else(|| raw.trim()); if para { if let Some(n) = self.para_names.get(b) { return Some(n.clone()); @@ -351,3 +352,15 @@ impl<'r> Importer<'r> { } } } + +/// `r` without the whitespace an indented file puts around an element's text: all of it before +/// (a style reference never starts with a space), and after it from the first line break on (a +/// name's own trailing spaces come before that). +fn unindented(r: &str) -> &str { + let r = r.trim_start(); + let text = r.trim_end().len(); + match r.get(text..).and_then(|tail| tail.find(['\n', '\r'])) { + Some(i) => r.get(..text + i).unwrap_or(r), + None => r, + } +} diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 4fc8288dd..b9ba109ea 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2258,6 +2258,35 @@ fn based_on_a_style_name_ending_in_a_space() { assert_eq!(props.fill, fill); } +/// A BasedOn on lines of its own (an indented file) that names a style whose name ends in a +/// space: only the line breaks and indentation around the reference go, not the name's space. +#[test] +fn based_on_on_lines_of_its_own_keeps_a_trailing_space() { + let styles = STYLES.replace( + r#""#, + &[ + r#""#, + r#""#, + "\n CharacterStyle/purple \n ", + r#""#, + ] + .concat(), + ); + let pkg = zip_files(&[ + ("designmap.xml", DESIGNMAP), + ("Resources/Graphic.xml", GRAPHIC), + ("Resources/Styles.xml", &styles), + ("Resources/Preferences.xml", PREFS), + ("MasterSpreads/MasterSpread_m1.xml", MASTER), + ("Spreads/Spread_sp1.xml", SPREAD), + ("Stories/Story_s1.xml", STORY), + ]); + let d = import_idml(&pkg).unwrap(); + let st = d.styles.character.iter().find(|c| c.name == "purple 23 pt ").expect("the derived style"); + assert_eq!(st.based_on.as_deref(), Some("purple ")); + assert!(d.styles.char_style_attrs("purple 23 pt ").fill.is_some(), "the base style's colour"); +} + /// Synthetic forward references: both a body anchor and a footnote anchor own /// a group containing a text frame whose story is serialized later. #[test] @@ -2905,8 +2934,9 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() { check(&import_idml(&export_idml(&d)).unwrap()); } -/// The items of a group carry no ItemLayer in IDML: they sit on the group's layer, not on the -/// front layer (which may be hidden or locked and took their wrap and editing with it). +/// The items of a group, and those pasted into a frame, carry no ItemLayer in IDML: they sit on +/// the group's or the frame's layer, not on the front layer (which may be hidden or locked and +/// took their wrap and editing with it). #[test] fn group_children_sit_on_the_groups_layer() { let designmap = r#" @@ -2925,16 +2955,22 @@ fn group_children_sit_on_the_groups_layer() { r#" {}{} + {} "#, rect("a"), - rect("b") + rect("b"), + // A frame with an item pasted into it. + rect("f").replace(r#"Self="f""#, r#"Self="f" ItemLayer="L1""#).replace("", &format!("{}", rect("c"))) ); let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap(); let background = d.layers.iter().find(|l| l.name == "Background").unwrap().id; - let g = &d.spreads[0].items[0]; - assert_eq!(g.layer, background); + let items = &d.spreads[0].items; + assert!(items.len() == 2 && items[1].shape == Shape::Rectangle && items[1].has_nested_items(), "{items:?}"); let mut layers = Vec::new(); - g.walk(&mut |it| layers.push(it.layer)); + for it in items { + it.walk(&mut |i| layers.push(i.layer)); + } + assert_eq!(layers.len(), 6); assert!(layers.iter().all(|l| *l == background), "{layers:?}"); } From 262a22695d57d1bf6191e930dde41452ceb3500e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 17:12:31 +0000 Subject: [PATCH 020/133] Anchored objects: respect item and layer locks; placing clears the selection anchored.select, anchored.resize and Delete (edit.clear) refuse an anchored object that is locked or on a locked layer, or whose text frame is (it stays in the text with its marker), and the Selection tool doesn't pick one. Placing media and math (place_media, mathexpr) select the new frame alone, clearing a selected anchored object. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CgGsJkVe5GYG9qK6VFdECa --- crates/engine/src/cmd/anchored.rs | 91 +++++++++++++++++++++++++++++-- crates/engine/src/cmd/mathexpr.rs | 2 + crates/engine/src/cmd/media.rs | 1 + crates/tools/src/anchored.rs | 5 ++ 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index d35b70bcf..7173068c9 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -188,6 +188,33 @@ fn insert(s: &mut Session, p: &Value) -> Result { } /// `{story, index}`, or the anchored object at (or just before) the text insertion point. +/// Whether the `k`-th anchored object of story `sid` can't be selected or changed: it, or the text +/// frame holding it, is locked or on a locked layer (as for other page items). +fn is_locked(s: &Session, sid: StoryId, k: usize) -> Result { + let d = &s.doc()?.doc; + let locked = |it: &designcraft_doc::Item| it.locked || d.layer(it.layer).is_some_and(|l| l.locked); + let o = d.story(sid).and_then(|st| st.objects.get(k)).ok_or_else(|| bad("anchored", "no such anchored object"))?; + if locked(&o.item) { + return Ok(true); + } + // The frame composition placed it in; before it is placed, any of the story's frames. + let cs = s.cache.get(d, sid, None); + let host = cs.frames.iter().find(|ft| ft.objects.iter().any(|x| x.index == k)).map(|ft| ft.frame); + let frames: Vec = match host { + Some(f) => vec![f], + None => d.story(sid).map(|st| st.frames.clone()).unwrap_or_default(), + }; + Ok(frames.iter().filter_map(|f| d.item(*f)).any(locked)) +} + +/// [`is_locked`] as the error a command returns. +fn check_unlocked(s: &Session, sid: StoryId, k: usize, cmd: &str) -> Result<()> { + if is_locked(s, sid, k)? { + return Err(bad(cmd, "the anchored object or its frame is locked, or on a locked layer")); + } + Ok(()) +} + fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { if let (Some(sid), Some(k)) = (p.get("story").and_then(Value::as_u64), p.get("index").and_then(Value::as_u64)) { return Ok((StoryId(sid), usize::try_from(k).map_err(|_| bad(cmd, "index out of range"))?)); @@ -214,10 +241,11 @@ fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { fn select(s: &mut Session, p: &Value) -> Result { let sid = p.get("story").and_then(Value::as_u64).map(StoryId).ok_or_else(|| bad("anchored.select", "missing story"))?; let k = p.get("index").and_then(Value::as_u64).and_then(|k| usize::try_from(k).ok()).ok_or_else(|| bad("anchored.select", "missing index"))?; - let st = s.doc_mut()?; - if st.doc.story(sid).and_then(|x| x.objects.get(k)).is_none() { + if s.doc()?.doc.story(sid).and_then(|x| x.objects.get(k)).is_none() { return Err(bad("anchored.select", "no such anchored object")); } + check_unlocked(s, sid, k, "anchored.select")?; + let st = s.doc_mut()?; st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: k }), ..Default::default() }; st.bump_revision(); Ok(Value::Null) @@ -229,6 +257,7 @@ fn select(s: &mut Session, p: &Value) -> Result { /// and the text reflows around the new size. fn resize(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.resize")?; + check_unlocked(s, sid, k, "anchored.resize")?; let from = super::rect_param(p, "from").ok_or_else(|| bad("anchored.resize", "missing from"))?; let to = super::rect_param(p, "to").ok_or_else(|| bad("anchored.resize", "missing to"))?; let finite = |r: designcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()); @@ -251,9 +280,6 @@ fn resize(s: &mut Session, p: &Value) -> Result { let o = st.objects.get_mut(k).ok_or_else(|| bad("anchored.resize", "no such anchored object"))?; let o = Arc::make_mut(o); let it = &mut o.item; - if it.locked { - return Err(bad("anchored.resize", "the object is locked")); - } if content { super::object::scale_item(it, m, (sx * sy).sqrt(), strokes); } else if matches!(it.content, Content::Group { .. }) { @@ -279,6 +305,8 @@ fn resize(s: &mut Session, p: &Value) -> Result { /// Delete a selected anchored object: its mark leaves the text, and the object with it. pub(crate) fn delete(s: &mut Session, a: AnchoredSel) -> Result { + // A locked object keeps its place in the text (Delete does nothing to it, as to a locked item). + check_unlocked(s, a.story, a.index, "edit.clear")?; let pos = { let st = s.doc()?.doc.story(a.story).ok_or_else(|| bad("edit.clear", "no such story"))?; st.text.match_indices(OBJECT_MARK).nth(a.index).map(|(i, _)| i).ok_or_else(|| bad("edit.clear", "no such anchored object"))? @@ -351,6 +379,59 @@ mod tests { (s, sid) } + /// A locked anchored object, one on a locked layer, or one in a locked frame or a frame on a + /// locked layer can't be selected, resized or deleted: it stays in the text with its marker. + #[test] + fn locked_anchored_objects_are_left_alone() { + type Lock = fn(&mut designcraft_doc::Document, StoryId); + let lock_object: Lock = |d, sid| Arc::make_mut(&mut d.story_mut(sid).unwrap().objects[0]).item.locked = true; + let lock_object_layer: Lock = |d, sid| { + let layer = d.story(sid).unwrap().objects[0].item.layer; + d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true; + }; + let lock_frame: Lock = |d, sid| { + let f = d.story(sid).unwrap().frames[0]; + d.item_mut(f).unwrap().locked = true; + }; + let lock_frame_layer: Lock = |d, sid| { + let f = d.story(sid).unwrap().frames[0]; + let layer = d.item(f).unwrap().layer; + d.layers.iter_mut().find(|l| l.id == layer).unwrap().locked = true; + }; + for (what, lock) in + [("object", lock_object), ("its layer", lock_object_layer), ("its frame", lock_frame), ("its frame's layer", lock_frame_layer)] + { + let (mut s, sid) = inline_box(); + // Selected before it is locked, so Delete and Resize meet the lock themselves. + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + s.edit(|d, _| { + lock(d, sid); + Ok(Value::Null) + }) + .unwrap(); + assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).is_err(), "{what}: select"); + assert!(s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).is_err(), "{what}: resize"); + assert!(s.execute("edit.clear", &json!({})).is_err(), "{what}: delete"); + let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); + assert_eq!(st.objects.len(), 1, "{what}: the object stays"); + assert_eq!(st.text.matches(OBJECT_MARK).count(), 1, "{what}: and its marker"); + assert_eq!(st.objects[0].size(), (24.0, 40.0), "{what}: at its size"); + } + } + + /// Placing a graphic selects the new frame alone: a selected anchored object is deselected. + #[test] + fn placing_a_graphic_deselects_an_anchored_object() { + let (mut s, sid) = inline_box(); + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + // A video (any bytes: media is placed by its name) gets a media frame of its own. + let b64 = crate::cmd::base64_encode(b"not really a video"); + let r = s.execute("file.place", &json!({"name": "clip.mp4", "base64": b64, "x": 500, "y": 500})).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.items, [ItemId(r["id"].as_u64().unwrap())]); + assert_eq!(sel.anchored, None, "not both the new frame and the anchored object"); + } + #[test] fn a_selected_inline_object_resizes_and_the_line_follows() { let (mut s, sid) = inline_box(); diff --git a/crates/engine/src/cmd/mathexpr.rs b/crates/engine/src/cmd/mathexpr.rs index e5342f79c..6a7835c87 100644 --- a/crates/engine/src/cmd/mathexpr.rs +++ b/crates/engine/src/cmd/mathexpr.rs @@ -92,6 +92,8 @@ fn insert(s: &mut Session, p: &Value) -> Result { let id = it.id; d.insert_item(spread, it, None)?; sel.items = vec![id]; + sel.text = None; + sel.anchored = None; Ok(json!({"id": id.0})) }) } diff --git a/crates/engine/src/cmd/media.rs b/crates/engine/src/cmd/media.rs index a4e3f5ae6..52740084a 100644 --- a/crates/engine/src/cmd/media.rs +++ b/crates/engine/src/cmd/media.rs @@ -71,6 +71,7 @@ pub(crate) fn place_media(s: &mut Session, p: &Value, name: String, mime: &str, }; sel.items = vec![id]; sel.text = None; + sel.anchored = None; Ok(json!({"id": id.0, "asset": aid.0, "media": true})) }) } diff --git a/crates/tools/src/anchored.rs b/crates/tools/src/anchored.rs index 6a897213c..d0febac0b 100644 --- a/crates/tools/src/anchored.rs +++ b/crates/tools/src/anchored.rs @@ -45,6 +45,11 @@ pub fn placed(doc: &Document, cache: &Cache, layout: &CanvasLayout, story: Optio let [a, b, c, d, _, _] = xf.as_coeffs(); let turned = b.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0; for o in &ft.objects { + // A locked object (or one on a locked layer) can't be selected, as other items. + let it = &o.object.item; + if it.locked || doc.layer(it.layer).is_some_and(|l| l.locked) { + continue; + } let r = o.object.item.bounds(); let r = Affine::translate(o.origin.to_vec2()).transform_rect_bbox(r); let spread_rect = xf.transform_rect_bbox(r); From e70ac0af942611581338a425e41ab773477cc927 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:17:07 +0100 Subject: [PATCH 021/133] Styles: a renamed or deleted style takes its Running Headers and list label styles along (#1794) redirect_style_refs never visited the document's text variables, and rename_char_refs skipped bullet_char_style and number_char_style. Renaming a style, or deleting it with a replacement, left Running Header variables and bullet/number character styles on a name no style has: headers showed only their before/after text and labels lost the style's formatting. Running Headers move only when they are of the renamed style's kind, since a paragraph and a character style may share a name. --- crates/engine/src/cmd/style/paragraph.rs | 113 +++++++++++++++++++++-- 1 file changed, 107 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 16671fbd8..4edd287d2 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -587,7 +587,7 @@ pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { _ => {} } if let Some(n) = rename.clone() { - // Every use: other styles, stories, table cells, footnotes, object styles. + // Every use: other styles, stories, table cells, footnotes, object styles, running headers. rename_style(d, true, &name, &n); } ok() @@ -705,14 +705,30 @@ fn redirect_style_refs(d: &mut designcraft_doc::Document, para: bool, from: &str st.rev = st.rev.wrapping_add(1); }); } + rename_running_headers(d, para, from, to); } -/// Point the nested, nested line and GREP styles, and the drop cap style, of paragraph -/// attributes at a renamed (or deleted, pointed at its replacement) character style. +/// Point the Running Header variables that pick up paragraph (`para`) or character style `from` +/// at `to`. A variable of the other kind keeps its style, even under the same name. +fn rename_running_headers(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) { + for v in &mut d.text_variables { + if let designcraft_doc::vars::VarKind::RunningHeader { style, character, .. } = &mut v.kind + && *character != para + && style == from + { + *style = to.to_string(); + } + } +} + +/// Point the nested, nested line and GREP styles, the drop cap style, and the bullet and number +/// character styles, of paragraph attributes at a renamed (or deleted, pointed at its +/// replacement) character style. fn rename_char_refs(p: &mut ParaAttrs, from: &str, to: &str) { let names = p.nested_styles.iter_mut().flatten().map(|n| &mut n.style); let names = names.chain(p.nested_line_styles.iter_mut().flatten().map(|n| &mut n.style)); let names = names.chain(p.drop_cap_style.iter_mut()); + let names = names.chain(p.bullet_char_style.iter_mut().chain(p.number_char_style.iter_mut())); for n in names.chain(p.grep_styles.iter_mut().flatten().map(|g| &mut g.style)) { if n == from { *n = to.to_string(); @@ -811,7 +827,7 @@ fn delete_style(s: &mut Session, p: &Value, para: bool) -> Result { } // The replacement keeps its own Export Tagging. st.export_tags.remove(&export_tag_key(para, &name)); - // Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults. + // Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults, list labels, running headers. redirect_style_refs(d, para, &name, &repl); ok() }) @@ -900,7 +916,7 @@ pub(super) fn edit_char(s: &mut Session, p: &Value) -> Result { st.based_on = b; } if let Some(n) = &rename { - // Every use: other styles, stories, table cells, nested and GREP styles, footnotes. + // Every use: other styles, stories, table cells, nested and GREP styles, list labels, footnotes, running headers. rename_style(d, false, &name, n); } ok() @@ -1088,6 +1104,7 @@ mod cjk_tests { #[cfg(test)] mod delete_tests { + use designcraft_doc::vars::{TextVariable, VarKind}; use designcraft_doc::{CellStyle, ObjectStyle, StoryId, Toc, TocEntry}; use serde_json::json; @@ -1098,6 +1115,15 @@ mod delete_tests { serde_json::to_string(&*s.doc().unwrap().doc).unwrap().contains(&format!("\"{name}\"")) } + /// The style the Running Header variable `name` picks up, and whether it's a character style. + fn header(s: &Session, name: &str) -> (String, bool) { + let d = &s.doc().unwrap().doc; + match &d.text_variables[d.variable(name).unwrap()].kind { + VarKind::RunningHeader { style, character, .. } => (style.clone(), *character), + k => panic!("`{name}` is {k:?}"), + } + } + fn char_doc() -> (Session, u64) { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); @@ -1109,9 +1135,11 @@ mod delete_tests { "nestedStyles": [{"style": "Emphasis", "through": true, "count": 1, "until": {"kind": "words"}}], "grepStyles": [{"style": "Emphasis", "pattern": "\\d+"}], "nestedLineStyles": [{"style": "Emphasis", "lines": 1}], - "dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis"}); + "dropCapLines": 2, "dropCapChars": 1, "dropCapStyle": "Emphasis", + "listType": "bullets", "bulletCharStyle": "Emphasis", "numberCharStyle": "Emphasis"}); s.execute("style.paragraph.create", &json!({"name": "Lead", "para": refs})).unwrap(); s.execute("footnote.options", &json!({"refCharStyle": "Emphasis"})).unwrap(); + s.execute("variables.define", &json!({"name": "Term", "type": "runningHeader", "style": "Emphasis", "character": true})).unwrap(); let sid = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hi there"})).unwrap()["story"] .as_u64() .unwrap(); @@ -1142,6 +1170,10 @@ mod delete_tests { assert_eq!(lead.grep_styles.as_ref().unwrap()[0].style, "Strong"); assert_eq!(lead.nested_line_styles.as_ref().unwrap()[0].style, "Strong"); assert_eq!(lead.drop_cap_style.as_deref(), Some("Strong")); + assert_eq!((lead.bullet_char_style.as_deref(), lead.number_char_style.as_deref()), (Some("Strong"), Some("Strong"))); + let local = &d.story(StoryId(sid)).unwrap().paras[0].para; + assert_eq!((local.bullet_char_style.as_deref(), local.number_char_style.as_deref()), (Some("Strong"), Some("Strong"))); + assert_eq!(header(&s, "Term"), ("Strong".into(), true)); assert_eq!(d.footnote_options.ref_char_style, "Strong"); assert_eq!(d.styles.default_character, "Strong"); // One undo step brings the style and every use back. @@ -1149,6 +1181,8 @@ mod delete_tests { s.execute("edit.undo", &json!({})).unwrap(); assert!(s.doc().unwrap().doc.styles.char_style("Emphasis").is_some()); assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().chars[0].format.style, "Emphasis"); + assert_eq!(header(&s, "Term"), ("Emphasis".into(), true)); + assert_eq!(s.doc().unwrap().doc.styles.para("Lead").unwrap().para.bullet_char_style.as_deref(), Some("Emphasis")); } #[test] @@ -1159,6 +1193,9 @@ mod delete_tests { let d = s.doc().unwrap().doc.clone(); assert_eq!(d.styles.char_style("Child").unwrap().based_on, None); assert_eq!(d.footnote_options.ref_char_style, designcraft_doc::NO_CHAR_STYLE); + let lead = &d.styles.para("Lead").unwrap().para; + assert_eq!(lead.bullet_char_style.as_deref(), Some(designcraft_doc::NO_CHAR_STYLE)); + assert_eq!(header(&s, "Term"), (designcraft_doc::NO_CHAR_STYLE.into(), true)); } /// Replacing a style with its own descendant rebases the deleted style's children on its @@ -1216,6 +1253,8 @@ mod delete_tests { d.endnote_options.para_style = "Table Body".into(); d.endnote_options.heading_style = "Table Body".into(); d.settings.epub_split = designcraft_doc::EpubSplit::Style("Table Body".into()); + let kind = VarKind::RunningHeader { style: "Table Body".into(), use_: Default::default(), character: false }; + d.text_variables.push(TextVariable::new("Section", kind)); d.toc = Some(Toc { story, title: "Contents".into(), @@ -1236,9 +1275,71 @@ mod delete_tests { assert_eq!(d.styles.default_paragraph, "Body"); assert_eq!(d.endnote_options.heading_style, "Body"); assert_eq!(d.settings.epub_split, designcraft_doc::EpubSplit::Style("Body".into()), "EPUB Split Document follows the replacement"); + assert_eq!(header(&s, "Section"), ("Body".into(), false)); let after = s.execute("preflight.run", &json!({})).unwrap(); assert!(!after.to_string().contains("Table Body"), "{after}"); } + + /// #1794: a rename moves the Running Headers of the style's kind (only those: a paragraph and a + /// character style can share a name) and the bullet and number character styles, of styles + /// and of local paragraph formatting. The headers still show their text on the page and the + /// labels keep their style's size; one undo each puts the old names back. + #[test] + fn renaming_a_style_moves_running_headers_and_list_label_styles() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Chapter"})).unwrap(); + s.execute("style.character.create", &json!({"name": "Dot", "chars": {"size": 30}})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Item", "para": {"listType": "bullets", "bulletCharStyle": "Dot"}})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 400], "content": "text", "text": "Origins\nFirst\nSecond"})).unwrap(); + let sid = r["story"].as_u64().unwrap(); + let select = |s: &mut Session, anchor: usize, focus: usize| { + s.execute("text.select", &json!({"story": sid, "anchor": anchor, "focus": focus})).unwrap(); + }; + select(&mut s, 0, 0); + s.execute("style.paragraph.apply", &json!({"name": "Chapter"})).unwrap(); + select(&mut s, 8, 8); + s.execute("style.paragraph.apply", &json!({"name": "Item"})).unwrap(); + select(&mut s, 14, 14); + s.execute("type.para", &json!({"attrs": {"listType": "numbers", "numberCharStyle": "Dot"}})).unwrap(); + select(&mut s, 14, 17); + s.execute("style.character.apply", &json!({"name": "Dot"})).unwrap(); + let vars = [("Chapter Head", "Chapter", false), ("Dot Head", "Dot", true), ("Para Dot", "Dot", false), ("Char Chapter", "Chapter", true)]; + for (name, style, character) in vars { + s.execute("variables.define", &json!({"name": name, "type": "runningHeader", "style": style, "character": character})).unwrap(); + } + // What the four headers show on page 1, and the list labels' (character, size). + let shown = |s: &Session| { + let d = s.doc().unwrap().doc.clone(); + let values = designcraft_compose::vars::values(&d, Some(0), Some(&s.cache.running_index(&d))); + let values: Vec = vars.iter().map(|(name, ..)| values[d.variable(name).unwrap()].clone()).collect(); + let cs = s.cache.get(&d, StoryId(sid), Some(0)); + let glyphs = cs.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs); + let labels = glyphs.filter(|g| g.generated_text.is_some() && g.rendered_char != '\t'); + let labels: Vec<(char, f64)> = labels.map(|g| (g.rendered_char, cs.styles[g.style as usize].size)).collect(); + (values, labels) + }; + let before = shown(&s); + assert_eq!(before.0, ["Origins", "Sec", "", ""]); + assert_eq!(before.1, [('\u{2022}', 30.0), ('1', 30.0), ('.', 30.0)], "the labels are set in Dot"); + + s.execute("style.paragraph.edit", &json!({"name": "Chapter", "rename": "Title"})).unwrap(); + s.execute("style.character.edit", &json!({"name": "Dot", "rename": "Marker"})).unwrap(); + let headers: Vec<_> = vars.iter().map(|(name, ..)| header(&s, name)).collect(); + let expect = [("Title", false), ("Marker", true), ("Dot", false), ("Chapter", true)]; + assert_eq!(headers, expect.map(|(n, c)| (n.to_string(), c))); + let d = s.doc().unwrap().doc.clone(); + assert_eq!(d.styles.para("Item").unwrap().para.bullet_char_style.as_deref(), Some("Marker")); + assert_eq!(d.story(StoryId(sid)).unwrap().paras[2].para.number_char_style.as_deref(), Some("Marker")); + assert_eq!(shown(&s), before, "the headers and labels look as they did"); + + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let headers: Vec<_> = vars.iter().map(|(name, ..)| header(&s, name)).collect(); + assert_eq!(headers, vars.map(|(_, style, c)| (style.to_string(), c))); + assert_eq!(s.doc().unwrap().doc.styles.para("Item").unwrap().para.bullet_char_style.as_deref(), Some("Dot")); + assert_eq!(shown(&s), before); + } } #[cfg(test)] From 525b8844b135efa3efb57c870809ccd2be3996d6 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:04:34 +0100 Subject: [PATCH 022/133] Styles: doc comments on style.paragraph.edit, style.character.edit and the char_doc fixture --- crates/engine/src/cmd/style/paragraph.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 4edd287d2..034515048 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -522,6 +522,8 @@ fn CharProps_to_attrs(p: &designcraft_doc::CharProps) -> CharAttrs { designcraft_doc::CharProps::common([p]) } +/// `style.paragraph.edit`: change a paragraph style's attributes, based-on, next style or name; +/// a rename follows the style into every use. pub(super) fn edit_para(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style.paragraph.edit", "missing name"))?.to_string(); let chars: CharAttrs = attrs("style.paragraph.edit", "chars", p, |a: &mut CharAttrs, k, v| a.set_json(k, v))?; @@ -869,6 +871,8 @@ pub(super) fn create_char(s: &mut Session, p: &Value) -> Result { }) } +/// `style.character.edit`: change a character style's attributes, based-on or name; a rename +/// follows the style into every use. pub(super) fn edit_char(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style.character.edit", "missing name"))?.to_string(); if name == designcraft_doc::NO_CHAR_STYLE { @@ -1124,6 +1128,10 @@ mod delete_tests { } } + /// A document whose character style `Emphasis` is used everywhere one can be: as a based-on + /// parent, on text, in a paragraph style's and a paragraph's nested, nested line, GREP, drop + /// cap, bullet and number styles, as the footnote reference style, the default character + /// style and a character Running Header. Returns the session and the text's story. fn char_doc() -> (Session, u64) { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); From 2a08c20f3430ec01a7f83def77e86713f51d9f57 Mon Sep 17 00:00:00 2001 From: con3code Date: Wed, 4 Nov 2026 09:20:38 +0900 Subject: [PATCH 023/133] Mojikumi: name the character classes in the reduction tiers From the review: the class numbers in the bracket-or-comma and full-stop tests get the characters they stand for. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/mojikumi.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/doc/src/mojikumi.rs b/crates/doc/src/mojikumi.rs index 1a67ff65d..e0c5588d0 100644 --- a/crates/doc/src/mojikumi.rs +++ b/crates/doc/src/mojikumi.rs @@ -135,7 +135,10 @@ impl<'a> Rules<'a> { // to that default. The tier follows the character classes, not the blank's size. The // Chinese sets reduce all punctuation blanks together. let japanese = self.base != Base::Chinese; + // After: closing brackets (2, 28 」, 29 )), full stops (6 。, 31 .) and commas + // (21 、, 30 ,). Before: opening brackets (1, 26 「, 27 (). let bracket_or_comma = matches!(left, 2 | 6 | 21 | 28..=31) || matches!(right, 1 | 26 | 27); + // Full stops: 6 。 and 31 .. let full_stop = matches!(left, 6 | 31); return Aki { min: if japanese && full_stop { punctuation } else { 0.0 }, From fd04ea2a568d309cc84ab83cbbdea826af284fb9 Mon Sep 17 00:00:00 2001 From: con3code Date: Wed, 4 Nov 2026 09:52:08 +0900 Subject: [PATCH 024/133] IME: read the macOS input source instead of guessing the Japanese mode From the review: the mode guessed from the last commit was wrong after Eisu or a switch to ABC. The app now reads the selected keyboard input source (NSTextInputContext, no unsafe) before each frame, and Space types U+3000 while it is a Japanese input method in a full-width mode. The commit-based state is gone. Co-Authored-By: Claude Opus 5.5 --- apps/designcraft/src/main.rs | 11 ++ crates/ui-egui/src/app.rs | 4 +- crates/ui-egui/src/app/ime.rs | 8 ++ crates/ui-egui/src/canvas/ime.rs | 62 ++++------ crates/ui-egui/src/canvas/input.rs | 12 +- crates/ui-egui/src/canvas/tests.rs | 179 ++++++++++------------------- crates/ui-egui/src/lib.rs | 12 +- 7 files changed, 108 insertions(+), 180 deletions(-) diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index ea0747a46..964421fab 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -89,6 +89,8 @@ impl eframe::App for App { self.startup.opening(apple_events::poll(&self.apple_events, &mut self.app, ui.ctx())); } } + #[cfg(target_os = "macos")] + self.app.set_input_source(selected_input_source()); self.app.ui(ui); self.startup.leave(); #[cfg(target_os = "macos")] @@ -123,6 +125,15 @@ fn discard_marked_text() { } } +/// The keyboard input source macOS has selected (its ID), or `None` without a key window. Space +/// in a Japanese input mode types an ideographic space, which winit reports as a plain one. +#[cfg(target_os = "macos")] +fn selected_input_source() -> Option { + let mtm = objc2::MainThreadMarker::new()?; + let id = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)?.selectedKeyboardInputSource()?; + Some(id.to_string()) +} + /// Orderly OS termination can bypass egui's cancelable close event. Finish only a complete, /// current quit plan; otherwise preserve every live document, including edits after the timer. fn preserve_documents_on_exit(app: &mut DesignApp) -> Result<(), String> { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 9c9acb462..5602ee644 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -112,9 +112,7 @@ impl DesignApp { in_control: false, object_clip_text: None, ime_marked: None, - ime_japanese_typing: false, - ime_kana_seen: false, - ime_caret_story: None, + input_source: None, ime_discard: false, canvas_ime: false, ime_tracker: egui::ime_context::ImeContextTracker::new(), diff --git a/crates/ui-egui/src/app/ime.rs b/crates/ui-egui/src/app/ime.rs index 6f36d7235..8b9ab7af1 100644 --- a/crates/ui-egui/src/app/ime.rs +++ b/crates/ui-egui/src/app/ime.rs @@ -9,6 +9,14 @@ impl DesignApp { std::mem::take(&mut self.ime_discard) } + /// The keyboard input source the system has selected now (macOS: its ID), read by the host + /// before each frame. The window layer reports Space as a plain space even in a Japanese + /// input mode, where the input method types an ideographic one; the source tells them apart + /// (see `canvas::ime::japanese_input_source`). + pub fn set_input_source(&mut self, id: Option) { + self.input_source = id; + } + /// Did the canvas ask for the system IME in the last frame (a Type tool caret)? The web /// build's hidden text input has the keyboard then, so text events hold what the browser /// typed (see [`drop_key_name_text`]). diff --git a/crates/ui-egui/src/canvas/ime.rs b/crates/ui-egui/src/canvas/ime.rs index d28d727dc..1ce5f29c8 100644 --- a/crates/ui-egui/src/canvas/ime.rs +++ b/crates/ui-egui/src/canvas/ime.rs @@ -28,35 +28,35 @@ fn drop_stale_ime_events(app: &mut DesignApp) { app.ime_interrupt = true; } -/// The text a key typed, given `text` as the window system reports it. -/// -/// On macOS the Space key in a Japanese input mode types an ideographic space, but the window -/// layer drops what the input method inserts when nothing is being composed and reports the key's -/// own character, a plain space. While the text before it was Japanese the input method committed -/// (`japanese_typing`), a plain space is therefore the ideographic one; with Shift it is the plain -/// space, as the input methods have it. Letters typed straight from the keys (the Roman mode) end -/// that. Chinese and Korean input methods type plain spaces (Korean separates words with them), -/// and accents a Latin input method composes are no input mode at all: none of them start it. -pub(crate) fn typed_text(text: &str, japanese_typing: bool, shift: bool, macos: bool) -> &str { - if macos && japanese_typing && !shift && text == " " { "\u{3000}" } else { text } +/// Is `id`, a macOS keyboard input source, a Japanese input method in a mode whose Space types an +/// ideographic space? Input methods name their modes after a `Japanese` part: none for hiragana +/// (`com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese`, `…Kawasemi4.Japanese`, Google's +/// `…Japanese.base`), then `Katakana` or `FullWidthRoman`. Their Roman, half-width and code +/// modes, plain keyboard layouts (`com.apple.keylayout.ABC`) and Chinese and Korean input +/// methods type a plain space, and so does any mode not named here. +pub(crate) fn japanese_input_source(id: &str) -> bool { + let mut parts = id.split('.'); + if !parts.any(|p| p == "Japanese") { + return false; + } + matches!(parts.collect::>().as_slice(), [] | ["base" | "Katakana" | "FullWidthRoman"]) } -/// Kana: what a Japanese input method shows while composing (hiragana, katakana, half-width -/// katakana). Chinese ones show pinyin, zhuyin or radicals, Korean ones jamo and syllables. -pub(crate) fn has_kana(text: &str) -> bool { - text.chars().any(|c| matches!(c, '\u{3040}'..='\u{30ff}' | '\u{31f0}'..='\u{31ff}' | '\u{ff66}'..='\u{ff9f}')) +/// The text a key typed, given `text` as the window system reports it. +/// +/// On macOS the window layer drops what the input method inserts when nothing is being composed +/// and reports the key's own character: Space in a Japanese input mode comes as a plain space, +/// where the input method types an ideographic one. With the selected input source in such a +/// mode (`japanese`), a plain space is therefore the ideographic one; with Shift it stays plain, +/// as the input methods have it. +pub(crate) fn typed_text(text: &str, japanese: bool, shift: bool) -> &str { + if japanese && !shift && text == " " { "\u{3000}" } else { text } } /// One input method event for the text caret: marked text previews in the story, a commit types. pub(super) fn ime_event(app: &mut DesignApp, ctx: &egui::Context, e: egui::ImeEvent, vi: designcraft_engine::ViewInfo) { let r = match e { egui::ImeEvent::Preedit { text, active_range_chars } => { - // A new composition: kana from one the input method cancelled (Escape) don't count. - // The empty preedit before a commit keeps them, as something is still marked then. - if app.ime_marked.is_none() { - app.ime_kana_seen = false; - } - app.ime_kana_seen |= has_kana(&text); if text.is_empty() { app.ime_marked = None; app.ime_target = None; @@ -81,15 +81,11 @@ pub(super) fn ime_event(app: &mut DesignApp, ctx: &egui::Context, e: egui::ImeEv // A bare line break confirms the composition (Enter with some IMEs): the marked text, not // a new paragraph. egui::ImeEvent::Commit(t) if t == "\n" || t == "\r" => { - app.ime_japanese_typing = std::mem::take(&mut app.ime_kana_seen); finish_pending_ime_delete(app, ctx); keep_marked_text(app); Ok(()) } - egui::ImeEvent::Commit(t) => { - app.ime_japanese_typing = std::mem::take(&mut app.ime_kana_seen) || has_kana(&t); - ime_commit(app, ctx, &t, vi) - } + egui::ImeEvent::Commit(t) => ime_commit(app, ctx, &t, vi), // The web text agent's corrections and mobile Backspace: characters around the caret go. // These are held for the Commit in the same batch so both mutations are one undo step. egui::ImeEvent::DeleteSurrounding { before_chars, after_chars } => { @@ -357,7 +353,6 @@ fn ime_compare_window(after_text: &str, after_win: std::ops::Range, post: /// End a composition outside the IME (a click away, the canvas losing the keyboard): the marked /// text stays as typed, and the system IME is told to drop its copy. pub(crate) fn keep_marked_text(app: &mut DesignApp) { - app.ime_kana_seen = false; if app.ime_marked.take().is_some() { app.ime_discard = true; } @@ -379,16 +374,6 @@ pub(crate) struct CanvasIme { caret: Option, } -/// In another story (or document) the input mode may have changed unseen: Japanese typing starts -/// over when the caret gets there. -pub(super) fn ime_follow_caret(app: &mut DesignApp) { - let here = app.session.active_index().zip(app.session.active().and_then(|st| st.selection.text).map(|t| t.story)); - if here != app.ime_caret_story { - app.ime_japanese_typing = false; - app.ime_caret_story = here; - } -} - /// While the text caret is in the canvas, let the system IME compose (egui-winit allows it only in /// frames that set `ime`; the web build focuses its hidden text input then) and keep the candidate /// window at the caret, through zoom, scrolling, view rotation and vertical text. @@ -421,12 +406,9 @@ pub(crate) fn ime_observe(app: &mut DesignApp, ctx: &egui::Context) { let Some(r) = canvas.caret.filter(|_| ours) else { // The IME goes away with its marked text: keep that text as typed, like a click away. keep_marked_text(app); - app.ime_japanese_typing = false; - app.ime_caret_story = None; app.ime_tracker.observe(viewport, None); return; }; - ime_follow_caret(app); // The composition ended outside the IME (a click, a command): the IME drops what it has marked. let interrupt = app.ime_interrupt || (app.ime_marked.is_some() && !app.session.tool_composing()); app.ime_interrupt = false; diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 056b62d93..58c82487a 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,6 +1,6 @@ use super::column_guides::{COLUMN_DRAG, ColumnDrag, column_guide_drag}; use super::guides::guide_drag; -use super::ime::{finish_pending_ime_delete, ime_event, ime_follow_caret, typed_text}; +use super::ime::{finish_pending_ime_delete, ime_event, japanese_input_source, typed_text}; use super::rulers::zero_point_drag; use super::scroll::{mods, navigation_space, pan, spring_zoom_input, spring_zoom_mode, wheel_alt}; use super::view::zoom_at; @@ -294,14 +294,8 @@ fn note_release(ui: &egui::Ui, clicks_id: egui::Id, latest: Option, now: f /// Text typed with no composition: into the story the caret is in now. fn insert_typed(app: &mut DesignApp, t: &str, shift: bool) { - // The caret may have moved to another story earlier this frame (a click). - ime_follow_caret(app); - let typed = typed_text(t, app.ime_japanese_typing, shift, cfg!(target_os = "macos")); - // Letters straight from the keys: the input method is in its Roman mode. - if !t.trim().is_empty() { - app.ime_japanese_typing = false; - } - let _ = app.run("text.insert", json!({"text": typed})); + let japanese = app.input_source.as_deref().is_some_and(japanese_input_source); + let _ = app.run("text.insert", json!({"text": typed_text(t, japanese, shift)})); } /// Give an open menu priority, then handle wheel/zoom/pan, spring Zoom, guide drags and primary pointer routing. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 515094ffe..74434743e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1,22 +1,8 @@ use designcraft_geom::Unit; use egui_kittest::{Harness, kittest::Queryable}; -use super::ime::typed_text; use super::*; -/// The Space key after Japanese the input method committed is the ideographic space on -/// macOS (the window layer reports a plain one); Shift, the Roman mode and other systems keep -/// it. -#[test] -fn space_after_japanese_input_method_text_is_the_ideographic_space() { - assert_eq!(typed_text(" ", true, false, true), "\u{3000}"); - assert_eq!(typed_text(" ", true, true, true), " ", "Shift+Space"); - assert_eq!(typed_text(" ", false, false, true), " ", "Roman mode, Chinese or Korean"); - assert_eq!(typed_text(" ", true, false, false), " ", "other systems report what the input method typed"); - assert_eq!(typed_text("a", true, false, true), "a"); - assert_eq!(typed_text(" ", true, false, true), " "); -} - /// A place-cursor drag past its 3-point threshold but short of egui's drag distance previews /// a frame, and the release places that frame: what's shown is what lands. #[test] @@ -2502,112 +2488,6 @@ fn native_gui_font_inventory_keeps_exact_regular_and_missing_style_diagnostics() assert!(missing["source"].is_null(), "{missing}"); } -/// Space after Japanese the input method committed is the ideographic space on macOS, where -/// the window layer reports it as a plain one; after letters typed straight from the keys it -/// stays plain, and so does it after an accent a Latin input method composed. -#[test] -fn space_after_committed_japanese_types_an_ideographic_space() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, ""); - let space = if cfg!(target_os = "macos") { "\u{3000}" } else { " " }; - ime_frame(&mut app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &sid), format!("日本語{space}")); - ime_frame(&mut app, &ctx, vec![egui::Event::Text("ab".into())]); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab ")); - ime_frame(&mut app, &ctx, vec![preedit("´", 1), egui::Event::Ime(egui::ImeEvent::Commit("é".into()))]); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &sid), format!("日本語{space}ab é ")); -} - -/// Shift+Space stays plain even when Shift comes up later in the same frame: the Shift held -/// at the space counts, not the one at the frame's end. -#[test] -fn shift_space_stays_plain_when_shift_is_released_in_the_same_frame() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, ""); - ime_frame(&mut app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); - let shift = egui::Event::ModifiersChanged(egui::Modifiers::SHIFT); - let up = egui::Event::ModifiersChanged(egui::Modifiers::NONE); - ime_frame(&mut app, &ctx, vec![shift, egui::Event::Text(" ".into()), up]); - assert_eq!(story_text(&mut app, &sid), "日本語 "); -} - -/// The caret moving to another story, or leaving the text, ends Japanese typing: the input -/// mode may have changed without an event the app sees (the Eisu key, say). -#[test] -fn japanese_typing_ends_with_the_story_or_the_text_caret() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let first = typing_app(&mut app, &ctx, ""); - let commit = |app: &mut DesignApp| { - ime_frame(app, &ctx, vec![preedit("にほんご", 4), egui::Event::Ime(egui::ImeEvent::Commit("日本語".into()))]); - assert!(app.ime_japanese_typing); - }; - commit(&mut app); - let f = app.session.execute("frame.create", &json!({"rect": [36, 260, 300, 400], "content": "text", "text": ""})).unwrap(); - let second = f["story"].clone(); - app.session.execute("text.select", &json!({"story": second, "anchor": 0, "focus": 0})).unwrap(); - ime_frame(&mut app, &ctx, vec![]); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &second), " "); - assert_eq!(story_text(&mut app, &first), "日本語"); - // Japanese typed in the first story, then the caret moves and a space comes in the same - // frame: still the new story's plain space. - app.session.execute("text.select", &json!({"story": first, "anchor": 0, "focus": 0})).unwrap(); - ime_frame(&mut app, &ctx, vec![]); - commit(&mut app); - app.session.execute("text.select", &json!({"story": second, "anchor": 1, "focus": 1})).unwrap(); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &second), " "); - assert_eq!(story_text(&mut app, &first), "日本語日本語"); - commit(&mut app); - app.select_tool("rectangleFrame"); - ime_frame(&mut app, &ctx, vec![]); - assert!(!app.ime_japanese_typing); -} - -/// Chinese and Korean input methods type plain spaces (Korean separates words with them), so -/// a space after their text stays plain. Japanese converted as it is typed (live conversion) -/// shows kana first and still gets the ideographic space. -#[test] -fn space_after_chinese_or_korean_input_stays_plain() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, ""); - let ideographic = if cfg!(target_os = "macos") { "\u{3000}" } else { " " }; - let mut want = String::new(); - for (preedits, commit, space) in [ - (vec!["ni", "nihao"], "你好", " "), - (vec!["ㄋ", "ㄋㄧˇ"], "你", " "), - (vec!["ㅎ", "하", "한"], "한국어", " "), - (vec!["に", "日本"], "日本", ideographic), - ] { - let mut events: Vec = preedits.iter().map(|p| preedit(p, p.chars().count())).collect(); - events.push(egui::Event::Ime(egui::ImeEvent::Commit(commit.into()))); - ime_frame(&mut app, &ctx, events); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - want += &format!("{commit}{space}"); - assert_eq!(story_text(&mut app, &sid), want, "{commit}"); - } -} - -/// Kana from a composition cancelled with Escape (the input method clears the marked text and -/// commits nothing) don't make the next composition Japanese. -#[test] -fn a_cancelled_japanese_composition_does_not_carry_over() { - let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); - let ctx = egui::Context::default(); - let sid = typing_app(&mut app, &ctx, ""); - ime_frame(&mut app, &ctx, vec![preedit("にほ", 2), preedit("", 0)]); - ime_frame(&mut app, &ctx, vec![preedit("ni", 2), preedit("", 0), egui::Event::Ime(egui::ImeEvent::Commit("你".into()))]); - ime_frame(&mut app, &ctx, vec![egui::Event::Text(" ".into())]); - assert_eq!(story_text(&mut app, &sid), "你 "); -} - #[test] #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may. fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() { @@ -3140,3 +3020,62 @@ fn leaving_parent_editing_for_the_left_page_of_a_spread_keeps_that_page_selected h.run_steps(3); assert_eq!(current_page(h.state()), Some(1)); } + +/// macOS input sources whose Space types an ideographic space: a Japanese input method's +/// hiragana, katakana and full-width modes. Its Roman, half-width and code modes, keyboard +/// layouts and Chinese and Korean input methods type a plain one. +#[test] +fn japanese_input_sources_are_told_by_their_mode() { + use super::ime::japanese_input_source; + for id in [ + "com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese", + "com.apple.inputmethod.Kotoeri.KanaTyping.Japanese", + "com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese.Katakana", + "com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese.FullWidthRoman", + "jp.monokakido.inputmethod.Kawasemi4.Japanese", + "com.google.inputmethod.Japanese.base", + ] { + assert!(japanese_input_source(id), "{id}"); + } + for id in [ + "com.apple.inputmethod.Kotoeri.RomajiTyping.Roman", + "com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese.HalfWidthKana", + "jp.monokakido.inputmethod.Kawasemi4.Japanese.HalfWidthRoman", + "jp.monokakido.inputmethod.Kawasemi4.Japanese.Code", + "jp.monokakido.inputmethod.Kawasemi4.Roman", + "com.google.inputmethod.Japanese.Roman", + "com.apple.keylayout.ABC", + "com.apple.inputmethod.SCIM.ITABC", + "com.apple.inputmethod.TCIM.Zhuyin", + "com.apple.inputmethod.Korean.2SetKorean", + "", + ] { + assert!(!japanese_input_source(id), "{id}"); + } +} + +/// Space in a Japanese input mode is the ideographic space, which the window layer reports as a +/// plain one; with Shift, in the Roman mode, in a keyboard layout, with a Chinese or Korean input +/// method or with no source known it stays plain. Shift counts as held at the space, even when it +/// comes up later in the same frame. +#[test] +fn space_follows_the_selected_input_source() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let sid = typing_app(&mut app, &ctx, ""); + let space = egui::Event::Text(" ".into()); + let source = |app: &mut DesignApp, id: Option<&str>, events: Vec| { + app.set_input_source(id.map(str::to_owned)); + ime_frame(app, &ctx, events); + }; + let japanese = Some("com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese"); + source(&mut app, japanese, vec![space.clone()]); + let (shift, up) = (egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + source(&mut app, japanese, vec![shift, space.clone(), up]); + source(&mut app, Some("com.apple.inputmethod.Kotoeri.RomajiTyping.Roman"), vec![space.clone()]); + source(&mut app, Some("com.apple.keylayout.ABC"), vec![space.clone()]); + source(&mut app, Some("com.apple.inputmethod.Korean.2SetKorean"), vec![space.clone()]); + source(&mut app, None, vec![space.clone()]); + source(&mut app, japanese, vec![egui::Event::Text("a".into()), space]); + assert_eq!(story_text(&mut app, &sid), "\u{3000} a\u{3000}"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 15be4f58f..d5779bb10 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -253,14 +253,10 @@ pub struct DesignApp { /// 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, - /// The text typed last was Japanese the input method committed (it is in its kana mode), not - /// letters straight from the keys: see [`canvas::typed_text`]. - pub(crate) ime_japanese_typing: bool, - /// The composition under way has shown kana: the input method is a Japanese one. - pub(crate) ime_kana_seen: bool, - /// The document and story the text caret was in last frame. Moving to another one, or leaving - /// the text, ends `ime_japanese_typing`. - pub(crate) ime_caret_story: Option<(usize, designcraft_doc::StoryId)>, + /// The keyboard input source the system has selected, as the host last read it (macOS: its + /// ID, such as `com.apple.inputmethod.Kotoeri.RomajiTyping.Japanese`). `None` where the host + /// can't tell: see [`Self::set_input_source`]. + pub(crate) input_source: Option, /// The system IME must drop its marked text (see [`Self::take_ime_discard`]). pub(crate) ime_discard: bool, /// The canvas asked for the system IME in the last frame (the web build's text input has the From 8541a21d47862051a881c5fc4cca21a8ab4017af Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 4 Nov 2026 13:27:20 +0500 Subject: [PATCH 025/133] PPTX: table edges write the same dash pattern as frames, computed once --- crates/pptx/src/slide.rs | 43 +++++++++++++++++++++++----------------- crates/pptx/src/table.rs | 13 +++--------- crates/pptx/src/tests.rs | 21 ++++++++++++++++++++ 3 files changed, 49 insertions(+), 28 deletions(-) diff --git a/crates/pptx/src/slide.rs b/crates/pptx/src/slide.rs index 4f730c5f0..98fc66e65 100644 --- a/crates/pptx/src/slide.rs +++ b/crates/pptx/src/slide.rs @@ -475,24 +475,7 @@ impl<'a> Exporter<'a> { StrokeAlign::Center => "", }; let w = s.weight; - let dash = match &s.kind { - StrokeType::Dashed { .. } if s.kind.dashes(w).is_some_and(|p| p.iter().any(|v| *v > 0.0)) => { - let mut v: Vec = s.kind.dashes(w).unwrap_or_default(); - if v.len() % 2 == 1 { - v.extend(v.clone()); - } - let mut d = String::from(""); - for pair in v.chunks(2) { - if let [a, b] = pair { - let _ = write!(d, "", pct(a / w), pct(b / w)); - } - } - d.push_str(""); - d - } - StrokeType::Dotted => "".into(), - _ => "".into(), - }; + let dash = line_dash(&s.kind, w); let join = match s.join { Join::Miter => format!("", pct(s.miter_limit.max(1.0))), Join::Round => "".into(), @@ -748,3 +731,27 @@ fn encode_png(rgba: Vec, w: u32, h: u32) -> Option> { img.write_to(&mut out, image::ImageFormat::Png).ok()?; Some(out.into_inner()) } + +/// The dash element of a line `w` points wide: the stroke's own dash pattern (or the one a dashed +/// stroke with none is drawn with, [`StrokeType::dashes`]) as a ``, in thousandths of +/// a percent of the width, or a preset for dotted and solid lines. Item strokes and table edges +/// both write it, so a dashed table edge keeps the same pattern as a dashed frame. +pub(crate) fn line_dash(kind: &StrokeType, w: f64) -> String { + match kind.dashes(w).filter(|_| w > 0.0) { + Some(mut v) => { + if v.len() % 2 == 1 { + v.extend(v.clone()); + } + let mut d = String::from(""); + for pair in v.chunks(2) { + if let [a, b] = pair { + let _ = write!(d, "", pct(a / w), pct(b / w)); + } + } + d.push_str(""); + d + } + None if matches!(kind, StrokeType::Dotted) => "".into(), + None => "".into(), + } +} diff --git a/crates/pptx/src/table.rs b/crates/pptx/src/table.rs index 0c8bd27d7..e0aaf2b86 100644 --- a/crates/pptx/src/table.rs +++ b/crates/pptx/src/table.rs @@ -4,7 +4,6 @@ use std::fmt::Write as _; use designcraft_compose::{FrameText, PlacedCell, StrokeSeg, TableFrag}; -use designcraft_doc::StrokeType; use designcraft_geom::{Affine, Rect}; use crate::slide::{Exporter, box_of}; @@ -55,15 +54,9 @@ fn border(ex: &mut Exporter, tag: &str, s: Option<&StrokeSeg>, k: f64, opacity: let Some(s) = s.filter(|s| s.stroke.weight > 0.0) else { return format!("") }; let st = &s.stroke; let Some(c) = ex.color(&st.color, st.tint, opacity) else { return format!("") }; - let dash = match st.kind { - StrokeType::Dashed { .. } => "dash", - StrokeType::Dotted => "sysDot", - _ => "solid", - }; - format!( - "{c}", - emu_len(st.weight * k) - ) + // The pattern items use, not the fixed `dash` preset, so a dashed edge matches the PDF. + let dash = crate::slide::line_dash(&st.kind, st.weight); + format!("{c}{dash}", emu_len(st.weight * k)) } fn table(ex: &mut Exporter, t: &TableFrag, m: Affine, k: f64, opacity: f32) { diff --git a/crates/pptx/src/tests.rs b/crates/pptx/src/tests.rs index 253c5d260..096bd6f13 100644 --- a/crates/pptx/src/tests.rs +++ b/crates/pptx/src/tests.rs @@ -123,6 +123,27 @@ fn shapes_keep_geometry_fill_stroke_and_effects() { assert!(s.contains("rot=\"1800000\""), "{s}"); } +/// A dashed table edge with no pattern of its own is written with the pattern a dashed frame +/// gets (three weights on, two off), not PowerPoint's fixed `dash` preset, so it matches the +/// PDF and the screen. +#[test] +fn a_dashed_table_edge_keeps_the_dash_pattern() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 300.0), lid, "", ParaFormat::default()).unwrap(); + let mut t = designcraft_doc::Table::new(1, 1, 2, 0, 0, 200.0); + t.rows[0].height = 40.0; + t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly; + t.options.border.weight = 2.0; + t.options.border.kind = StrokeType::Dashed { pattern: vec![] }; + d.story_mut(sid).unwrap().insert_table(0, t); + let mut z = export(&d, &PptxOptions::default()); + let s = part(&mut z, "ppt/slides/slide1.xml"); + assert!(s.contains(""), "the table is exported as a table: {s}"); + assert!(s.contains(""), "6 on, 4 off for a 2 pt edge: {s}"); + assert!(!s.contains(""), "{s}"); +} + #[test] fn composed_lines_become_line_breaks_with_the_story_text() { let mut d = Document::new(&NewDocument::default()); From af9314a9f62f4a78143712f0ea64480924a5f68f Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 4 Nov 2026 14:21:27 +0500 Subject: [PATCH 026/133] Canvas: a frame slanted by its own width keeps its X corner to corner (#2280) The X of an empty four-cornered path fell back to the bounds when either diagonal was near an axis. A frame slanted by about its own width has one near-vertical diagonal, so its X ran past the parallelogram's corners and jumped between corners and bounds while the points were dragged. A rectangle whose points were moved keeps an edge on its bounds, which a diamond never has, so that now keeps the corner X too. Diamonds keep the bounds as before, however far a point is moved; switching the diagonal test to 'either crosses' instead would have turned an edited diamond's X into a tilted plus once a point moved 15 pt. --- crates/ui-egui/src/canvas/frames.rs | 18 ++++++- crates/ui-egui/src/canvas/tests.rs | 73 +++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index e897d689f..0e9f1ed8a 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -142,7 +142,9 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { // A rectangle (slanted or not: four corner points, no handles). Ellipses, polygons (a // four-sided one is a diamond) and curved paths keep the X across their bounds. Edited points // make any of them a path: a four-cornered one whose corners would cross as a plus (a diamond, - // edited) keeps the bounds too. + // edited) keeps the bounds too. A rectangle whose points were moved keeps an edge on its + // bounds, which a diamond never has: slanted by about its own width, one of its diagonals is + // near vertical, and the X still joins its corners (#2280). let crosses = |a: Point, b: Point| { let d = b - a; d.x.abs() > 0.18 * d.hypot() && d.y.abs() > 0.18 * d.hypot() @@ -152,7 +154,7 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { && sp.closed && let [c0, c1, c2, c3] = sp.anchors.as_slice() && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && (it.shape == designcraft_doc::Shape::Rectangle || (crosses(c0.p, c2.p) && crosses(c1.p, c3.p))) + && (it.shape == designcraft_doc::Shape::Rectangle || edge_on_bounds([c0.p, c1.p, c2.p, c3.p]) || (crosses(c0.p, c2.p) && crosses(c1.p, c3.p))) { return [(c0.p, c2.p), (c1.p, c3.p)]; } @@ -160,6 +162,18 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))] } +/// Whether an edge of the quadrilateral `c` lies along a side of its bounds. +fn edge_on_bounds(c: [Point; 4]) -> bool { + let (x0, x1) = (c.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max)); + let (y0, y1) = (c.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)); + let eps = 1e-9 * (x1 - x0 + y1 - y0).max(1.0); + let near = |a: f64, b: f64| (a - b).abs() <= eps; + (0..4).any(|k| { + let (a, b) = (c[k], c[(k + 1) % 4]); + (near(a.x, b.x) && (near(a.x, x0) || near(a.x, x1))) || (near(a.y, b.y) && (near(a.y, y0) || near(a.y, y1))) + }) +} + /// Layer colour of the first selected item: live-corner marks are outlined in it. pub(super) fn selection_color(app: &DesignApp) -> Color32 { let fallback = Color32::from_rgb(79, 153, 255); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9267a6cda..722b8933b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -197,6 +197,79 @@ fn an_empty_frames_x_follows_its_corners() { assert!(lines.iter().all(|(a, b)| (a.x - b.x).abs() > 1e-6 && (a.y - b.y).abs() > 1e-6), "an edited diamond: {lines:?}"); } +/// A frame slanted by about its own width has one diagonal near vertical. The X fell back to the +/// bounds when either diagonal was near an axis, so while the top points were dragged across that +/// range it jumped from the corners to the bounds and back; only a diamond, both of whose +/// diagonals are near an axis, keeps the bounds (#2280). +#[test] +fn a_frame_slanted_by_its_own_width_keeps_its_x_corner_to_corner() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + // 60 pt wide, 100 pt tall, as in the issue. + let id = app.run("frame.create", json!({"rect": [100, 100, 160, 200]})).unwrap()["id"].as_u64().unwrap(); + let item = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); + let it = item(&app); + let top: Vec = + it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).y < 150.0).map(|(k, _)| json!([0, k])).collect(); + assert_eq!(top.len(), 2); + // Drag the top points right in 6 pt steps, to 150 pt: the 42-78 pt range the issue names, + // where a diagonal is within the vertical tolerance, is crossed on the way. + for step in 0..=25 { + if step > 0 { + app.run("path.moveAnchors", json!({"id": id, "anchors": top, "dx": 6, "dy": 0})).unwrap(); + } + let it = item(&app); + let corners: Vec = it.path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + let at_corner = |p: Point| corners.iter().any(|c| (*c - p).hypot() < 1e-9); + for (a, b) in frame_x(&it) { + assert!(at_corner(a) && at_corner(b), "slanted {} pt: the X runs {a:?}-{b:?}, not between the corners {corners:?}", step * 6); + } + } + let corner_x = |app: &DesignApp, id: u64| { + let it = app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone(); + let corners: Vec = it.path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + frame_x(&it).iter().all(|(a, b)| [a, b].iter().all(|p| corners.iter().any(|c| (*c - **p).hypot() < 1e-9))) + }; + // A wide frame slanted further than its height, and one corner moved alone (a trapezoid). + let wide = app.run("frame.create", json!({"rect": [300, 100, 400, 160]})).unwrap()["id"].as_u64().unwrap(); + let it = item_of(&app, wide); + let top: Vec = + it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).y < 130.0).map(|(k, _)| json!([0, k])).collect(); + app.run("path.moveAnchors", json!({"id": wide, "anchors": top, "dx": 90, "dy": 0})).unwrap(); + assert!(corner_x(&app, wide), "a 100x60 frame slanted 90 pt"); + let trap = app.run("frame.create", json!({"rect": [500, 100, 560, 200]})).unwrap()["id"].as_u64().unwrap(); + let it = item_of(&app, trap); + let corner: Vec = it.path.subpaths[0] + .anchors + .iter() + .enumerate() + .filter(|(_, a)| (it.xf * a.p).y < 150.0 && (it.xf * a.p).x < 530.0) + .map(|(k, _)| json!([0, k])) + .collect(); + app.run("path.moveAnchors", json!({"id": trap, "anchors": corner, "dx": 50, "dy": 0})).unwrap(); + assert!(corner_x(&app, trap), "a trapezoid"); + // Slanted the other way: the right edge moved down by the frame's height. + let down = app.run("frame.create", json!({"rect": [700, 100, 760, 200]})).unwrap()["id"].as_u64().unwrap(); + let it = item_of(&app, down); + let right: Vec = + it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).x > 730.0).map(|(k, _)| json!([0, k])).collect(); + app.run("path.moveAnchors", json!({"id": down, "anchors": right, "dx": 0, "dy": 100})).unwrap(); + assert!(corner_x(&app, down), "a frame whose right edge moved down 100 pt"); + // A diamond keeps the bounds however far one of its points is moved sideways: no edge of it + // lies on its bounds. + for dx in [15, 30] { + let p = app.run("frame.create", json!({"rect": [300, 300, 400, 360], "shape": "polygon", "sides": 4, "starInset": 0})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("path.moveAnchors", json!({"id": p, "anchors": [[0, 0]], "dx": dx, "dy": 0})).unwrap(); + assert!(!corner_x(&app, p), "a diamond with a point moved {dx} pt"); + } +} + +fn item_of(app: &DesignApp, id: u64) -> designcraft_doc::Item { + app.session.active().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().clone() +} + /// Each preview mode's shown area: Preview stops at the trim, Bleed reaches the bleed box and /// Slug the slug box. A slug narrower than the bleed never pulls the edge back in. #[test] From 724ffeb516d9825be1c82223df185eaa948a2bf3 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 4 Nov 2026 15:10:06 +0500 Subject: [PATCH 027/133] Canvas: a diamond with a point moved in line with another keeps the bounds X One edge on the bounds was taken for a rectangle with moved points. A diamond whose point is moved in line with the next one has one too, and its X flipped to the corners at exactly that position (noted in review). A rectangle with points moved along one axis keeps two opposite edges on its bounds; a diamond never does. --- crates/ui-egui/src/canvas/frames.rs | 22 +++++++++++++--------- crates/ui-egui/src/canvas/tests.rs | 7 ++++--- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 0e9f1ed8a..0a6cc45d0 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -142,9 +142,10 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { // A rectangle (slanted or not: four corner points, no handles). Ellipses, polygons (a // four-sided one is a diamond) and curved paths keep the X across their bounds. Edited points // make any of them a path: a four-cornered one whose corners would cross as a plus (a diamond, - // edited) keeps the bounds too. A rectangle whose points were moved keeps an edge on its - // bounds, which a diamond never has: slanted by about its own width, one of its diagonals is - // near vertical, and the X still joins its corners (#2280). + // edited) keeps the bounds too. A rectangle whose points were moved along one axis keeps two + // opposite edges on its bounds, which a diamond never has (one of its points moved in line with + // another gives it one): slanted by about its own width, one of its diagonals is near vertical, + // and the X still joins its corners (#2280). let crosses = |a: Point, b: Point| { let d = b - a; d.x.abs() > 0.18 * d.hypot() && d.y.abs() > 0.18 * d.hypot() @@ -154,7 +155,9 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { && sp.closed && let [c0, c1, c2, c3] = sp.anchors.as_slice() && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && (it.shape == designcraft_doc::Shape::Rectangle || edge_on_bounds([c0.p, c1.p, c2.p, c3.p]) || (crosses(c0.p, c2.p) && crosses(c1.p, c3.p))) + && (it.shape == designcraft_doc::Shape::Rectangle + || opposite_edges_on_bounds([c0.p, c1.p, c2.p, c3.p]) + || (crosses(c0.p, c2.p) && crosses(c1.p, c3.p))) { return [(c0.p, c2.p), (c1.p, c3.p)]; } @@ -162,16 +165,17 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))] } -/// Whether an edge of the quadrilateral `c` lies along a side of its bounds. -fn edge_on_bounds(c: [Point; 4]) -> bool { +/// Whether two opposite edges of the quadrilateral `c` each lie along a side of its bounds. +fn opposite_edges_on_bounds(c: [Point; 4]) -> bool { let (x0, x1) = (c.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max)); let (y0, y1) = (c.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)); let eps = 1e-9 * (x1 - x0 + y1 - y0).max(1.0); let near = |a: f64, b: f64| (a - b).abs() <= eps; - (0..4).any(|k| { - let (a, b) = (c[k], c[(k + 1) % 4]); + let on = |k: usize| { + let (a, b) = (c[k % 4], c[(k + 1) % 4]); (near(a.x, b.x) && (near(a.x, x0) || near(a.x, x1))) || (near(a.y, b.y) && (near(a.y, y0) || near(a.y, y1))) - }) + }; + (on(0) && on(2)) || (on(1) && on(3)) } /// Layer colour of the first selected item: live-corner marks are outlined in it. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 722b8933b..1cbdfbabe 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -255,9 +255,10 @@ fn a_frame_slanted_by_its_own_width_keeps_its_x_corner_to_corner() { it.path.subpaths[0].anchors.iter().enumerate().filter(|(_, a)| (it.xf * a.p).x > 730.0).map(|(k, _)| json!([0, k])).collect(); app.run("path.moveAnchors", json!({"id": down, "anchors": right, "dx": 0, "dy": 100})).unwrap(); assert!(corner_x(&app, down), "a frame whose right edge moved down 100 pt"); - // A diamond keeps the bounds however far one of its points is moved sideways: no edge of it - // lies on its bounds. - for dx in [15, 30] { + // A diamond keeps the bounds however far one of its points is moved sideways, and when the + // move puts it in line with the next point, giving the diamond one edge on its bounds (noted in + // review): only a rectangle has two opposite ones. + for dx in [15, 30, 50] { let p = app.run("frame.create", json!({"rect": [300, 300, 400, 360], "shape": "polygon", "sides": 4, "starInset": 0})).unwrap()["id"] .as_u64() .unwrap(); From c3fb5f8eb7e2ae2194f661038dbe7d716adc381b Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 4 Nov 2026 16:09:01 +0500 Subject: [PATCH 028/133] Canvas: a frame with one corner moved keeps its X corner to corner Two opposite edges on the bounds missed a rectangle with one corner moved: its two other edges stay on the bounds side by side, and its X fell back to the bounds (noted in review). Any two edges on the bounds now count; a diamond has at most one. --- crates/ui-egui/src/canvas/frames.rs | 17 +++++++++-------- crates/ui-egui/src/canvas/tests.rs | 13 +++++++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 0a6cc45d0..64a28822c 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -142,10 +142,11 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { // A rectangle (slanted or not: four corner points, no handles). Ellipses, polygons (a // four-sided one is a diamond) and curved paths keep the X across their bounds. Edited points // make any of them a path: a four-cornered one whose corners would cross as a plus (a diamond, - // edited) keeps the bounds too. A rectangle whose points were moved along one axis keeps two - // opposite edges on its bounds, which a diamond never has (one of its points moved in line with - // another gives it one): slanted by about its own width, one of its diagonals is near vertical, - // and the X still joins its corners (#2280). + // edited) keeps the bounds too. A rectangle whose points were moved keeps two edges on its + // bounds (opposite ones when a side was slanted, adjacent ones when one corner moved), which a + // diamond doesn't have (one of its points moved in line with another gives it one): slanted by + // about its own width, one of its diagonals is near vertical, and the X still joins its + // corners (#2280). let crosses = |a: Point, b: Point| { let d = b - a; d.x.abs() > 0.18 * d.hypot() && d.y.abs() > 0.18 * d.hypot() @@ -156,7 +157,7 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { && let [c0, c1, c2, c3] = sp.anchors.as_slice() && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) && (it.shape == designcraft_doc::Shape::Rectangle - || opposite_edges_on_bounds([c0.p, c1.p, c2.p, c3.p]) + || edges_on_bounds([c0.p, c1.p, c2.p, c3.p]) >= 2 || (crosses(c0.p, c2.p) && crosses(c1.p, c3.p))) { return [(c0.p, c2.p), (c1.p, c3.p)]; @@ -165,8 +166,8 @@ pub(super) fn frame_x(it: &Item) -> [(Point, Point); 2] { [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))] } -/// Whether two opposite edges of the quadrilateral `c` each lie along a side of its bounds. -fn opposite_edges_on_bounds(c: [Point; 4]) -> bool { +/// How many edges of the quadrilateral `c` lie along a side of its bounds. +fn edges_on_bounds(c: [Point; 4]) -> usize { let (x0, x1) = (c.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max)); let (y0, y1) = (c.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)); let eps = 1e-9 * (x1 - x0 + y1 - y0).max(1.0); @@ -175,7 +176,7 @@ fn opposite_edges_on_bounds(c: [Point; 4]) -> bool { let (a, b) = (c[k % 4], c[(k + 1) % 4]); (near(a.x, b.x) && (near(a.x, x0) || near(a.x, x1))) || (near(a.y, b.y) && (near(a.y, y0) || near(a.y, y1))) }; - (on(0) && on(2)) || (on(1) && on(3)) + (0..4).filter(|&k| on(k)).count() } /// Layer colour of the first selected item: live-corner marks are outlined in it. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 1cbdfbabe..fa3226770 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -248,6 +248,19 @@ fn a_frame_slanted_by_its_own_width_keeps_its_x_corner_to_corner() { .collect(); app.run("path.moveAnchors", json!({"id": trap, "anchors": corner, "dx": 50, "dy": 0})).unwrap(); assert!(corner_x(&app, trap), "a trapezoid"); + // One corner moved (50, 1): its two other edges stay on the bounds, side by side (noted in + // review). + let nudged = app.run("frame.create", json!({"rect": [900, 100, 960, 200]})).unwrap()["id"].as_u64().unwrap(); + let it = item_of(&app, nudged); + let corner: Vec = it.path.subpaths[0] + .anchors + .iter() + .enumerate() + .filter(|(_, a)| (it.xf * a.p).y < 150.0 && (it.xf * a.p).x < 930.0) + .map(|(k, _)| json!([0, k])) + .collect(); + app.run("path.moveAnchors", json!({"id": nudged, "anchors": corner, "dx": 50, "dy": 1})).unwrap(); + assert!(corner_x(&app, nudged), "a frame with one corner moved (50, 1)"); // Slanted the other way: the right edge moved down by the frame's height. let down = app.run("frame.create", json!({"rect": [700, 100, 760, 200]})).unwrap()["id"].as_u64().unwrap(); let it = item_of(&app, down); From b8095b5be63d4793211f58f296bb0a1235430900 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:57:38 +0000 Subject: [PATCH 029/133] Apply review fixes - crates/pptx/src/slide.rs - crates/compose/src/lib.rs --- crates/compose/src/lib.rs | 9 +++++---- crates/pptx/src/slide.rs | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f110c0ecc..bc4c9751f 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5401,8 +5401,9 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin let mut line = designcraft_geom::BezPath::new(); line.move_to((rect.x0, y)); line.line_to((rect.x1, y)); - let path = match &kind { - StrokeType::Dashed { pattern } if StrokeType::expandable_dashes(pattern, len) => { + let dashes = kind.dashes(w).filter(|p| StrokeType::expandable_dashes(p, len)); + let path = match (&kind, dashes) { + (StrokeType::Dashed { .. }, Some(pattern)) => { let mut p = designcraft_geom::BezPath::new(); let (mut x, mut k, mut on) = (rect.x0, 0, true); while x < rect.x1 { @@ -5417,7 +5418,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin } Some(p) } - StrokeType::Dotted if StrokeType::expandable_dashes(&[w, w], len) => { + (StrokeType::Dotted, _) if StrokeType::expandable_dashes(&[w, w], len) => { let mut p = designcraft_geom::BezPath::new(); let mut x = rect.x0 + w / 2.0; while x <= rect.x1 - w / 2.0 + 1e-9 { @@ -5426,7 +5427,7 @@ fn rule_decos(doc: &Document, r: &designcraft_doc::Rule, rect: Rect, (color, tin } Some(p) } - k => k.outline(&line, w, 0.05), + (k, _) => k.outline(&line, w, 0.05), }; out.push(Deco { rect, color, tint, path, ..Deco::default() }); out diff --git a/crates/pptx/src/slide.rs b/crates/pptx/src/slide.rs index 98fc66e65..946db5dfc 100644 --- a/crates/pptx/src/slide.rs +++ b/crates/pptx/src/slide.rs @@ -737,7 +737,7 @@ fn encode_png(rgba: Vec, w: u32, h: u32) -> Option> { /// a percent of the width, or a preset for dotted and solid lines. Item strokes and table edges /// both write it, so a dashed table edge keeps the same pattern as a dashed frame. pub(crate) fn line_dash(kind: &StrokeType, w: f64) -> String { - match kind.dashes(w).filter(|_| w > 0.0) { + match kind.dashes(w).filter(|p| w > 0.0 && p.len() <= designcraft_doc::MAX_DASH_ENTRIES) { Some(mut v) => { if v.len() % 2 == 1 { v.extend(v.clone()); From af5d517176f3ceba453440e065d165bd5e397aad Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:02:44 +0000 Subject: [PATCH 030/133] Apply review fixes - crates/ui-egui/src/canvas/frames.rs - crates/ui-egui/src/canvas/tests.rs --- crates/ui-egui/src/canvas/frames.rs | 11 ++++++----- crates/ui-egui/src/canvas/tests.rs | 5 +++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/frames.rs b/crates/ui-egui/src/canvas/frames.rs index 64a28822c..58e0b334e 100644 --- a/crates/ui-egui/src/canvas/frames.rs +++ b/crates/ui-egui/src/canvas/frames.rs @@ -172,11 +172,12 @@ fn edges_on_bounds(c: [Point; 4]) -> usize { let (y0, y1) = (c.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), c.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max)); let eps = 1e-9 * (x1 - x0 + y1 - y0).max(1.0); let near = |a: f64, b: f64| (a - b).abs() <= eps; - let on = |k: usize| { - let (a, b) = (c[k % 4], c[(k + 1) % 4]); - (near(a.x, b.x) && (near(a.x, x0) || near(a.x, x1))) || (near(a.y, b.y) && (near(a.y, y0) || near(a.y, y1))) - }; - (0..4).filter(|&k| on(k)).count() + let on = |a: Point, b: Point| (near(a.x, b.x) && (near(a.x, x0) || near(a.x, x1))) || (near(a.y, b.y) && (near(a.y, y0) || near(a.y, y1))); + // Three points in line along a side make a diagonal an edge (a triangle): it keeps the bounds X. + if on(c[0], c[2]) || on(c[1], c[3]) { + return 0; + } + (0..4).filter(|&k| on(c[k], c[(k + 1) % 4])).count() } /// Layer colour of the first selected item: live-corner marks are outlined in it. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index fa3226770..24e60e417 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -278,6 +278,11 @@ fn a_frame_slanted_by_its_own_width_keeps_its_x_corner_to_corner() { app.run("path.moveAnchors", json!({"id": p, "anchors": [[0, 0]], "dx": dx, "dy": 0})).unwrap(); assert!(!corner_x(&app, p), "a diamond with a point moved {dx} pt"); } + let p = app.run("frame.create", json!({"rect": [300, 300, 400, 360], "shape": "polygon", "sides": 4, "starInset": 0})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("path.moveAnchors", json!({"id": p, "anchors": [[0, 0], [0, 2]], "dx": 50, "dy": 0})).unwrap(); + assert!(!corner_x(&app, p), "a diamond whose top and bottom points were moved onto its right side"); } fn item_of(app: &DesignApp, id: u64) -> designcraft_doc::Item { From 443e7641a77beb7b7af3bc3654153cdd94c0965e Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 15 Oct 2026 08:41:39 +0200 Subject: [PATCH 031/133] Leading: empty paragraphs as in InDesign Under the Japanese composers' leading models an empty line (an empty paragraph) measures its leading from its paragraph mark's em box, as in InDesign, so it keeps the leading like any other line. It measured from its baseline instead: under Aki Below the empty line rose by the em box top's height above the baseline and the line after it dropped by as much. --- crates/compose/src/lib.rs | 46 ++++++++++++++++++++++++++++++------- crates/compose/src/tests.rs | 25 ++++++++++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..22a26d212 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1458,7 +1458,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { Some(mark) if j + 1 == breaks.len() => next_lead.max(mark), _ => next_lead, }; - let (next_reference, next_model) = cjk_line_reference(next_glyphs); + let (next_reference, next_model) = line_reference(next_glyphs, db, mark_chars, pp); down += prev_aki.unwrap_or(next_lead) + prev - next_reference; prev = next_reference; prev_aki = aki_below(next_model, next_lead); @@ -1979,7 +1979,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi Some(m) if k + 1 == breaks.len() => lead.max(m), _ => lead, }; - let (reference, model) = cjk_line_reference(line_glyphs); + let (reference, model) = line_reference(line_glyphs, db, mark_chars, pp); let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead }; let position = position_line(PositionLineInput { frame: f, @@ -4112,8 +4112,12 @@ fn em_box_top(face: &designcraft_fonts::FontFace, size: f64) -> f64 { /// Em box relative to the baseline. Font ascender/descender proportions locate it; /// the box's total extent is the em, rather than the font's optional line gap. fn cjk_em_box(g: &Glyph) -> (f64, f64) { - let height = g.face.units_per_em() * g.sy.abs(); - let top = -height * g.ascent / (g.ascent + g.descent).max(1e-9); + em_box(g.face.units_per_em() * g.sy.abs(), g.ascent, g.descent) +} +/// An em box `height` tall relative to the baseline, placed by the font's `ascent` and `descent` +/// proportions (see [`cjk_em_box`]). +fn em_box(height: f64, ascent: f64, descent: f64) -> (f64, f64) { + let top = -height * ascent / (ascent + descent).max(1e-9); (top, top + height) } /// The ideographic character face (ICF) box relative to the baseline: the em box of @@ -4155,16 +4159,42 @@ fn cjk_alignment_shift(g: &Glyph, reference: &Glyph) -> f64 { fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingModel) { use designcraft_doc::cjk::LeadingModel as L; let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return (0.0, L::Roman) }; - let (top, bottom) = cjk_em_box(g); - let reference = match g.leading_model { + (leading_reference(g.leading_model, cjk_em_box(g)), g.leading_model) +} + +/// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph) has no +/// character to measure from: it measures from its paragraph mark's em box under the mark's +/// leading model (`mark`: its font, size and model), as in InDesign, so it keeps the leading like +/// any other line instead of moving by the em box's offset from the baseline. Only the Japanese +/// composers use a leading model. +fn line_reference( + line: &[Glyph], + db: &ScopedFonts<'_>, + mark: &designcraft_doc::CharProps, + pp: &ParaProps, +) -> (f64, designcraft_doc::cjk::LeadingModel) { + use designcraft_doc::cjk::LeadingModel as L; + if !line.is_empty() { + return cjk_line_reference(line); + } + if !pp.composer.japanese() || mark.leading_model == L::Roman { + return (0.0, L::Roman); + } + let face = db.face(&mark.font_family, &mark.font_style); + (leading_reference(mark.leading_model, em_box(mark.size * mark.v_scale, face.ascent, face.descent)), mark.leading_model) +} + +/// Where `model` measures leading from, for an em box at `top..bottom` from the baseline. +fn leading_reference(model: designcraft_doc::cjk::LeadingModel, (top, bottom): (f64, f64)) -> f64 { + use designcraft_doc::cjk::LeadingModel as L; + match model { L::Roman => 0.0, // "Space below" measures from the em box top (Em Box Top/Right), "space above" from its // bottom (Em Box Bottom/Left). L::AkiBelow => top, L::AkiAbove => bottom, L::Center | L::CenterDown => (top + bottom) / 2.0, - }; - (reference, g.leading_model) + } } fn line_metrics( diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a47e27f45..8de242f65 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4541,6 +4541,31 @@ fn empty_paragraph_uses_its_own_mark_not_the_previous_one() { assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline); } +/// Under a leading model an empty paragraph keeps the leading like any other line: its line +/// measures from its paragraph mark's em box, as in InDesign. It used to measure from its +/// baseline, so the empty line moved by the em box's offset and the line after it back by as +/// much. The other composers set lines baseline to baseline whatever the model. +#[test] +fn an_empty_paragraph_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::LeadingModel; + let text = "Aaa\n\nBbb\nCcc"; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + for para in [japanese(), ParaAttrs::default()] { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), para); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } + } +} + #[test] fn german_2006_text_gets_german_hyphenation() { let text = "Silbentrennung Fußgänger Bäcker Fenster Donaudampfschifffahrt Silbentrennung"; From eae0da1aee51486cbc0157b2484b85e053f7d542 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Thu, 29 Oct 2026 15:33:49 +0100 Subject: [PATCH 032/133] Leading: the empty line after a forced line break, and empty lines in vertical text Two cases the empty-line leading reference missed: - The empty line a trailing forced line break leaves takes its height and leading model from its paragraph mark's character format, like an empty paragraph. It took them from the paragraph style's characters, so text formatted with a leading model the style doesn't have moved that line by its em box's offset from the baseline, and the line after it back by as much. - In vertical text an empty line measures from the upright em box (the font's ideographic em box), as the upright characters around it do. It measured from the font's ascender and descender proportions, so it moved against the lines beside it. --- crates/compose/src/lib.rs | 36 ++++++++++++++++++-------- crates/compose/src/tests.rs | 50 +++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 22a26d212..3a35c65c6 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1458,7 +1458,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { Some(mark) if j + 1 == breaks.len() => next_lead.max(mark), _ => next_lead, }; - let (next_reference, next_model) = line_reference(next_glyphs, db, mark_chars, pp); + let (next_reference, next_model) = line_reference(next_glyphs, db, mark_chars, pp, f.vertical); down += prev_aki.unwrap_or(next_lead) + prev - next_reference; prev = next_reference; prev_aki = aki_below(next_model, next_lead); @@ -1979,7 +1979,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi Some(m) if k + 1 == breaks.len() => lead.max(m), _ => lead, }; - let (reference, model) = line_reference(line_glyphs, db, mark_chars, pp); + let (reference, model) = line_reference(line_glyphs, db, mark_chars, pp, f.vertical); let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead }; let position = position_line(PositionLineInput { frame: f, @@ -2458,8 +2458,15 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens); let base_size = base_chars.size; let spacing = spacing_for(pp, base_size, story); - // An empty paragraph takes its height from its paragraph mark's character format. - let mark_chars = if glyphs.is_empty() { doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) } else { base_chars.clone() }; + // An empty line takes its height from its paragraph mark's character format, the one character + // it holds: an empty paragraph's line, and the line a trailing forced line break leaves. + let mark_chars = if glyphs.is_empty() { + doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) + } else if glyphs.last().is_some_and(|g| g.ch == designcraft_doc::story::FORCED_LINE_BREAK) { + doc.styles.resolve_char(base_chars, story.char_format_of(prange.end)) + } else { + base_chars.clone() + }; let mark_leading = match mark_chars.leading { designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading, designcraft_doc::Leading::Points(v) => v, @@ -4162,16 +4169,18 @@ fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingMode (leading_reference(g.leading_model, cjk_em_box(g)), g.leading_model) } -/// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph) has no -/// character to measure from: it measures from its paragraph mark's em box under the mark's -/// leading model (`mark`: its font, size and model), as in InDesign, so it keeps the leading like -/// any other line instead of moving by the em box's offset from the baseline. Only the Japanese -/// composers use a leading model. +/// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph, or the +/// line a trailing forced line break leaves) has no character to measure from: it measures from +/// its paragraph mark's em box under the mark's leading model (`mark`: its font, size and model), +/// as in InDesign, so it keeps the leading like any other line instead of moving by the em box's +/// offset from the baseline. In `vertical` text that is the upright em box, as for the upright +/// characters around it. Only the Japanese composers use a leading model. fn line_reference( line: &[Glyph], db: &ScopedFonts<'_>, mark: &designcraft_doc::CharProps, pp: &ParaProps, + vertical: bool, ) -> (f64, designcraft_doc::cjk::LeadingModel) { use designcraft_doc::cjk::LeadingModel as L; if !line.is_empty() { @@ -4181,7 +4190,14 @@ fn line_reference( return (0.0, L::Roman); } let face = db.face(&mark.font_family, &mark.font_style); - (leading_reference(mark.leading_model, em_box(mark.size * mark.v_scale, face.ascent, face.descent)), mark.leading_model) + // Placed by the proportions the shaper gives the glyphs: upright ones fill the em box. + let (ascent, descent) = if vertical { + let (top, bottom) = face.em_box(); + (top, -bottom) + } else { + (face.ascent, face.descent) + }; + (leading_reference(mark.leading_model, em_box(mark.size * mark.v_scale, ascent, descent)), mark.leading_model) } /// Where `model` measures leading from, for an em box at `top..bottom` from the baseline. diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 8de242f65..0c591a991 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4566,6 +4566,56 @@ fn an_empty_paragraph_keeps_the_leading_under_a_leading_model() { } } +/// The empty line a trailing forced line break leaves measures from its paragraph mark's em box, +/// like an empty paragraph, so it keeps the leading too. It measured from the paragraph style's +/// characters: text formatted with a leading model the style doesn't have moved that line by the +/// em box's offset from the baseline, and the line after it back by as much. +#[test] +fn a_trailing_forced_line_breaks_empty_line_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::LeadingModel; + use designcraft_doc::story::FORCED_LINE_BREAK; + let text = format!("Aaa{FORCED_LINE_BREAK}\nBbb\nCcc"); + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + +/// In a vertical frame an empty paragraph measures from the upright em box (the font's +/// ideographic em box), as the upright characters around it do. It measured from the font's +/// ascender and descender, so it moved against the lines beside it. +#[test] +fn an_empty_paragraph_keeps_the_leading_under_a_leading_model_in_vertical_text() { + use designcraft_doc::cjk::LeadingModel; + let family = vertical_test_font(); + let text = "一\n\n二\n日"; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + d.story_mut(sid).unwrap().vertical = true; + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some(family.into()); + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(cs.frames[0].vertical); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + #[test] fn german_2006_text_gets_german_hyphenation() { let text = "Silbentrennung Fußgänger Bäcker Fenster Donaudampfschifffahrt Silbentrennung"; From 021bdad8b68aa57916b6887a58c5a25445793a33 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Sun, 1 Nov 2026 12:56:25 +0100 Subject: [PATCH 033/133] Empty-paragraph leading: test an empty line under a larger paragraph mark --- crates/compose/src/tests.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0c591a991..2eac271e2 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4590,6 +4590,26 @@ fn a_trailing_forced_line_breaks_empty_line_keeps_the_leading_under_a_leading_mo } } +/// An empty line whose paragraph mark is larger than the text around it takes its auto leading +/// from the mark: an empty paragraph's line, and the line a trailing forced line break leaves. +/// The line after it goes back to the text's own leading. +#[test] +fn an_empty_line_takes_its_auto_leading_from_a_larger_paragraph_mark() { + use designcraft_doc::story::FORCED_LINE_BREAK; + for text in ["Aaa\n\nBbb".to_string(), format!("Aaa{FORCED_LINE_BREAK}\nBbb")] { + let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let mark = text.find("\nB").unwrap(); + let story = d.story_mut(sid).unwrap(); + story.format_chars(0..text.len(), |f| f.over.size = Some(10.0)); + story.format_chars(mark..mark + 1, |f| f.over.size = Some(20.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 3, "{text:?}: {base:?}"); + assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{text:?}: {base:?}"); + assert!((base[2] - base[1] - 12.0).abs() < 1e-6, "{text:?}: {base:?}"); + } +} + /// In a vertical frame an empty paragraph measures from the upright em box (the font's /// ideographic em box), as the upright characters around it do. It measured from the font's /// ascender and descender, so it moved against the lines beside it. From 16bc2c47153a36eacddac36196fb2edf43e9f264 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 4 Nov 2026 21:32:42 +0100 Subject: [PATCH 034/133] Empty-paragraph leading: measure the mark at its shaped size and composite font entry --- crates/compose/src/lib.rs | 52 ++++++++++++++++++++++++------------- crates/compose/src/shape.rs | 17 ++++++++++++ crates/compose/src/tests.rs | 52 +++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 18 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 3a35c65c6..5770986a9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1315,6 +1315,7 @@ struct ParagraphLines<'a> { drop_cap: Option<&'a DropCap>, base_chars: &'a designcraft_doc::CharProps, mark_chars: &'a designcraft_doc::CharProps, + mark_em: &'a MarkEm, mark_leading: f64, base_leading: f64, last_line_mark: Option, @@ -1369,6 +1370,7 @@ struct PositionLineInput<'a, 'font> { db: &'a ScopedFonts<'font>, mark_leading: f64, mark_chars: &'a designcraft_doc::CharProps, + mark_em: &'a MarkEm, last_line_mark: Option, } @@ -1412,6 +1414,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { db, mark_leading, mark_chars, + mark_em, last_line_mark, } = input; let (mut x0, mut x1) = (col.x0, col.x1); @@ -1458,7 +1461,7 @@ fn position_line(input: PositionLineInput<'_, '_>) -> LinePosition { Some(mark) if j + 1 == breaks.len() => next_lead.max(mark), _ => next_lead, }; - let (next_reference, next_model) = line_reference(next_glyphs, db, mark_chars, pp, f.vertical); + let (next_reference, next_model) = line_reference(next_glyphs, mark_em, pp, f.vertical); down += prev_aki.unwrap_or(next_lead) + prev - next_reference; prev = next_reference; prev_aki = aki_below(next_model, next_lead); @@ -1872,6 +1875,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi drop_cap, base_chars, mark_chars, + mark_em, mark_leading, base_leading, last_line_mark, @@ -1979,7 +1983,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi Some(m) if k + 1 == breaks.len() => lead.max(m), _ => lead, }; - let (reference, model) = line_reference(line_glyphs, db, mark_chars, pp, f.vertical); + let (reference, model) = line_reference(line_glyphs, mark_em, pp, f.vertical); let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead }; let position = position_line(PositionLineInput { frame: f, @@ -2012,6 +2016,7 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi db, mark_leading, mark_chars, + mark_em, last_line_mark, }); let LinePosition { x0, x1, baseline, grid_end, continues } = position; @@ -2265,6 +2270,7 @@ struct ShapedParagraph { base_size: f64, spacing: Spacing, mark_chars: designcraft_doc::CharProps, + mark_em: MarkEm, mark_leading: f64, last_line_mark: Option, para_box: Option, @@ -2467,6 +2473,11 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { } else { base_chars.clone() }; + let mark_em = { + let mark = story.text.get(prange.end..).and_then(|t| t.chars().next()).unwrap_or('\n'); + let (face, height) = shape::em_face(db, &doc.styles, &mark_chars, mark, &doc.settings.advanced_type); + MarkEm { face, height, model: mark_chars.leading_model } + }; let mark_leading = match mark_chars.leading { designcraft_doc::Leading::Auto => mark_chars.size * pp.auto_leading, designcraft_doc::Leading::Points(v) => v, @@ -2498,6 +2509,7 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { base_size, spacing, mark_chars, + mark_em, mark_leading, last_line_mark, para_box, @@ -2887,6 +2899,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C base_size, spacing, mark_chars, + mark_em, mark_leading, last_line_mark, para_box: _, @@ -3055,6 +3068,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C drop_cap: drop_cap.as_ref(), base_chars: &base_chars, mark_chars: &mark_chars, + mark_em: &mark_em, mark_leading, base_leading, last_line_mark, @@ -4169,35 +4183,37 @@ fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingMode (leading_reference(g.leading_model, cjk_em_box(g)), g.leading_model) } +/// The paragraph mark's em box, which an empty line measures leading from: the face and em box +/// height the mark is shaped with (a composite font's entry, a superscript or subscript at its +/// Advanced Type size; see [`shape::em_face`]) and its leading model. +struct MarkEm { + face: std::sync::Arc, + height: f64, + model: designcraft_doc::cjk::LeadingModel, +} + /// [`cjk_line_reference`] of a line of paragraph `pp`. An empty line (an empty paragraph, or the /// line a trailing forced line break leaves) has no character to measure from: it measures from -/// its paragraph mark's em box under the mark's leading model (`mark`: its font, size and model), -/// as in InDesign, so it keeps the leading like any other line instead of moving by the em box's -/// offset from the baseline. In `vertical` text that is the upright em box, as for the upright -/// characters around it. Only the Japanese composers use a leading model. -fn line_reference( - line: &[Glyph], - db: &ScopedFonts<'_>, - mark: &designcraft_doc::CharProps, - pp: &ParaProps, - vertical: bool, -) -> (f64, designcraft_doc::cjk::LeadingModel) { +/// its paragraph mark's em box under the mark's leading model (`mark`), as in InDesign, so it +/// keeps the leading like any other line instead of moving by the em box's offset from the +/// baseline. In `vertical` text that is the upright em box, as for the upright characters around +/// it. Only the Japanese composers use a leading model. +fn line_reference(line: &[Glyph], mark: &MarkEm, pp: &ParaProps, vertical: bool) -> (f64, designcraft_doc::cjk::LeadingModel) { use designcraft_doc::cjk::LeadingModel as L; if !line.is_empty() { return cjk_line_reference(line); } - if !pp.composer.japanese() || mark.leading_model == L::Roman { + if !pp.composer.japanese() || mark.model == L::Roman { return (0.0, L::Roman); } - let face = db.face(&mark.font_family, &mark.font_style); // Placed by the proportions the shaper gives the glyphs: upright ones fill the em box. let (ascent, descent) = if vertical { - let (top, bottom) = face.em_box(); + let (top, bottom) = mark.face.em_box(); (top, -bottom) } else { - (face.ascent, face.descent) + (mark.face.ascent, mark.face.descent) }; - (leading_reference(mark.leading_model, em_box(mark.size * mark.v_scale, ascent, descent)), mark.leading_model) + (leading_reference(mark.model, em_box(mark.height, ascent, descent)), mark.model) } /// Where `model` measures leading from, for an em box at `top..bottom` from the baseline. diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..a301a9d26 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1094,6 +1094,23 @@ pub struct TypeEnv { pub glyph_fallback: bool, } +/// The face and em box height a character `c` with `p` is shaped with: a composite font +/// resolved to its entry for `c` (font, size and vertical scale), and a superscript or subscript +/// at its Advanced Type size, as [`shape_para`] shapes it. A shaped glyph's em box is +/// `units_per_em * sy`, which is this height. +pub(crate) fn em_face(db: &ScopedFonts<'_>, styles: &Styles, p: &CharProps, c: char, adv: &designcraft_doc::AdvancedType) -> (Arc, f64) { + let resolved; + let p = match styles.composite_font(&p.font_family) { + Some(font) => { + resolved = composite_props(db, p, font.entry(c)); + &resolved + } + None => p, + }; + let (size, _) = effective_size(p, adv); + (db.face(&p.font_family, &p.font_style), size * p.v_scale) +} + /// Synthesised super/subscript: size and shift from Advanced Type (percent of the font size). fn effective_size(p: &CharProps, adv: &designcraft_doc::AdvancedType) -> (f64, f64) { match p.position { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 2eac271e2..5b09800d7 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4610,6 +4610,58 @@ fn an_empty_line_takes_its_auto_leading_from_a_larger_paragraph_mark() { } } +/// Under a leading model the lines of `text` (all formatted by `format`, with a 16 pt leading) +/// are 16 pt apart, empty lines included. +fn assert_leading_kept(text: &str, mut d: Document, sid: StoryId, format: impl Fn(&mut designcraft_doc::CharFormat)) { + use designcraft_doc::cjk::LeadingModel; + for model in [LeadingModel::AkiBelow, LeadingModel::AkiAbove, LeadingModel::Center] { + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + format(f); + f.over.leading = Some(designcraft_doc::Leading::Points(16.0)); + f.over.leading_model = Some(model); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert_eq!(base.len(), 4, "{model:?}"); + for w in base.windows(2) { + assert!((w[1] - w[0] - 16.0).abs() < 1e-6, "{model:?}: {base:?}"); + } + } +} + +/// A superscript or subscript paragraph mark is shaped at the Advanced Type size, like the text +/// around it: an empty line measures from that em box, so it keeps the leading. It measured from +/// the em box at the full size, so it moved against the superscript lines beside it. +#[test] +fn an_empty_superscript_paragraph_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::Position; + let text = "Aaa\n\nBbb\nCcc"; + for position in [Position::Superscript, Position::Subscript] { + let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + assert_leading_kept(text, d, sid, |f| f.over.position = Some(position)); + } +} + +/// A paragraph mark in a composite font is measured with the composite font's entry (its font, +/// relative size and vertical scale), as shaping sets the text around it, so an empty line keeps +/// the leading. It measured the composite font's name, a substitute face, at the plain size. +#[test] +fn an_empty_paragraph_in_a_composite_font_keeps_the_leading_under_a_leading_model() { + use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry}; + let text = "Aaa\n\nBbb\nCcc"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), japanese()); + std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont { + name: "Scaled".into(), + entries: vec![CompositeFontEntry { + family: designcraft_fonts::DEFAULT_FAMILY.into(), + relative_size: 1.5, + vertical_scale: 1.2, + ..Default::default() + }], + }); + assert_leading_kept(text, d, sid, |f| f.over.font_family = Some("CompositeFont/Scaled".into())); +} + /// In a vertical frame an empty paragraph measures from the upright em box (the font's /// ideographic em box), as the upright characters around it do. It measured from the font's /// ascender and descender, so it moved against the lines beside it. From 550b681f73f25f457662741919ccea0ddbcb7109 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 4 Nov 2026 21:34:32 +0100 Subject: [PATCH 035/133] Tables: Space Before from the previous baseline InDesign measures a table's Space Before from the previous line's baseline, so descenders may hang into it, as it measures the text after the table from the table's bottom. --- crates/compose/src/table.rs | 4 +++- crates/compose/src/tests.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs index 5811887ae..9c4b6ebf9 100644 --- a/crates/compose/src/table.rs +++ b/crates/compose/src/table.rs @@ -289,8 +289,10 @@ pub(crate) fn place_table( let sum = |a: usize, b: usize| heights[a..b].iter().sum::(); let footer_h = sum(body_end, nr); let o = &table.options; + // InDesign measures Space Before from the previous line's baseline (the descenders may hang + // into it), as it measures text after the table from the table's bottom. let mut y = match cur.last_baseline { - Some(b) => b + cur.last_descent + cur.pending + o.space_before, + Some(b) => b + cur.pending + o.space_before, None => col.y0, }; let mut frag_rows: Vec<(usize, f64, bool)> = Vec::new(); // (row, y, repeated) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a47e27f45..feb95bf2a 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -1810,6 +1810,20 @@ fn table_rows_fit_their_content() { assert!(tf.strokes.len() >= 4 * 3 + 4); } +/// A table starts Space Before below the previous line's baseline, as in InDesign (not below its +/// descenders). +#[test] +fn table_starts_space_before_below_the_previous_baseline() { + let mut t = designcraft_doc::Table::new(77, 2, 2, 0, 0, 100.0); + t.options.space_before = 4.0; + let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 300.0, 600.0), t); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let f = &cs.frames[0]; + let above = f.lines.iter().filter(|l| l.baseline < f.tables[0].rect.y0).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max); + assert!(above.is_finite(), "a line above the table"); + assert!((f.tables[0].rect.y0 - (above + 4.0)).abs() < 1e-6, "{} vs {}", f.tables[0].rect.y0, above); +} + #[test] fn table_columns_scale_to_the_text_column() { let (d, sid, _) = table_doc(Rect::new(0.0, 0.0, 200.0, 1000.0), filled(2, 4, 0, 600.0)); From e8148461b5321cd75c61f4559ba21b98121ab927 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 4 Nov 2026 21:57:38 +0100 Subject: [PATCH 036/133] PDF export: state the empty .notdef contract and test that the next glyph keeps its place --- crates/fonts/src/fontdb/db.rs | 4 ++++ crates/pdf/src/tests.rs | 20 ++++++++++++-------- crates/pdf/src/text.rs | 5 ++++- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/crates/fonts/src/fontdb/db.rs b/crates/fonts/src/fontdb/db.rs index 224098a6a..ddc1e4c2e 100644 --- a/crates/fonts/src/fontdb/db.rs +++ b/crates/fonts/src/fontdb/db.rs @@ -207,6 +207,10 @@ impl FontDb { /// The box drawn for `face`'s missing glyph (.notdef) when the font's own has no outline, in /// font units, y-down: a hollow rectangle across the glyph's advance, cap height tall. `None` /// when the font draws its own. + /// + /// Contract: `Some` means exactly that the font's .notdef (glyph 0) has an empty outline, so + /// callers may test `missing_box(face).is_some()` for "this font's .notdef is empty" (PDF export + /// prints such a glyph as nothing, while [`FontDb::outline`] and the screen show this box). pub fn missing_box(&self, face: &FontFace) -> Option { if !font_outline(face, 0).elements().is_empty() { return None; diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 4f2e0a9ce..469778300 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -496,7 +496,7 @@ fn archival_exports_keep_placed_images_without_interpolation() { } /// What a page draws: each glyph (its text and outline bounds) and each filled path's bounds. -fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec) { +fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Point)>, Vec) { use hayro_interpret::font::Glyph; use hayro_interpret::{ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, @@ -504,7 +504,7 @@ fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec) { }; use kurbo::Shape as _; #[derive(Default)] - struct Rec(Vec<(String, kurbo::Rect)>, Vec); + struct Rec(Vec<(String, kurbo::Point)>, Vec); impl Device<'_> for Rec { fn set_soft_mask(&mut self, _: Option>) {} fn set_blend_mode(&mut self, _: BlendMode) {} @@ -513,17 +513,13 @@ fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec) { } fn push_clip_path(&mut self, _: &ClipPath) {} fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} - fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) { + fn draw_glyph(&mut self, g: &Glyph<'_>, xf: kurbo::Affine, glyph_xf: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) { let text = match g.as_unicode() { Some(hayro_cmap::BfString::Char(c)) => c.to_string(), Some(hayro_cmap::BfString::String(s)) => s, None => String::new(), }; - let bounds = match g { - Glyph::Outline(o) => o.outline().bounding_box(), - Glyph::Type3(_) => kurbo::Rect::ZERO, - }; - self.0.push((text, bounds)); + self.0.push((text, xf * glyph_xf * kurbo::Point::ORIGIN)); } fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {} fn pop_clip_path(&mut self) {} @@ -662,6 +658,14 @@ fn missing_glyphs_print_as_the_fonts_notdef() { let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap()); assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::>(), ["a", "b"], "{glyphs:?}"); assert_eq!(boxes(&paths), 0, "{paths:?}"); + // The empty .notdef still takes its advance: `b` stays where the layout puts it. + let cs = designcraft_compose::compose_story(&d, sid, &designcraft_compose::ComposeOptions::default()); + let line = &cs.frames[0].lines[0]; + let x = |c: char| line.glyphs.iter().find(|g| g.rendered_char == c).unwrap().x; + let notdef = line.glyphs.iter().find(|g| g.gid == 0).unwrap(); + assert!(notdef.adv > 0.0 && x('b') - x('a') > notdef.adv, "the .notdef has an advance"); + let pdf_gap = glyphs[1].1.x - glyphs[0].1.x; + assert!((pdf_gap - (x('b') - x('a'))).abs() < 0.01, "pdf {pdf_gap}, layout {}", x('b') - x('a')); } #[test] diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs index 1e9a1a5e2..3d4890feb 100644 --- a/crates/pdf/src/text.rs +++ b/crates/pdf/src/text.rs @@ -677,7 +677,10 @@ fn glyph_outlines(glyphs: &[PlacedGlyph], size: f64, tan: f64) -> BezPath { let k = size / g0.face.upem; for g in glyphs { // A .notdef the font leaves empty prints as nothing, as InDesign exports it (the screen - // shows a box, and Preflight lists the character). + // shows a box, and Preflight lists the character). `missing_box` is `Some` exactly when + // the font's .notdef is empty. Only PDF text painting calls this function: outline + // conversion and the screen still get the box from `FontDb::outline`. The glyphs after it + // keep their places: each is placed from its own position. if g.gid == 0 && db.missing_box(&g.face).is_some() { continue; } From c739606e1a791854954914515de85d0752be4a8c Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 4 Nov 2026 22:45:16 +0100 Subject: [PATCH 037/133] Text: an inline object is bidi-neutral An inline object's private-use mark is a strong left-to-right character, so in right-to-left text it joined the Latin run before it and was drawn on that run's far side. It now takes part in bidi as U+FFFC (the object replacement character) does, a neutral, and keeps its place in the reading order. --- crates/compose/src/shape.rs | 4 ++++ crates/compose/src/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..19085c786 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -929,6 +929,10 @@ fn shape_run_raw( } designcraft_doc::OBJECT_MARK => { let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c); + // Bidi-neutral like U+FFFC (the object replacement character), not a strong + // left-to-right character as its private-use mark is: an inline object in + // right-to-left text keeps its place in the reading order. + g.display_char = '\u{FFFC}'; if let Some(o) = sub.objects.get(&i).filter(|o| !o.custom) { let auto = matches!(p.leading, Leading::Auto); match o.y_offset { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a47e27f45..82fd3d9be 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3329,6 +3329,33 @@ fn inline_objects_still_clear_the_bottom_edge() { assert_eq!(cs.line_count(), 0); } +/// An inline object is bidi-neutral, as U+FFFC is: in a right-to-left paragraph it keeps its place +/// in the reading order between Latin text and the Arabic after it. Its private-use mark is a +/// strong left-to-right character, which joined it to the Latin run before it, so it was drawn on +/// the far side of that run. +#[test] +fn an_inline_object_keeps_its_place_in_right_to_left_text() { + let text = "ab \u{0628}"; + let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), para); + d.settings.glyph_fallback = true; + let it = designcraft_doc::Item::new( + ItemId(d.alloc()), + d.default_layer(), + designcraft_doc::Shape::Rectangle, + designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 6.0)), + ); + let at = 3; + d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(it, designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 })); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let line = &cs.frames[0].lines[0]; + let x = |byte: usize| line.glyphs.iter().find(|g| g.byte == byte).map(|g| g.x).unwrap(); + let beh = text.find('\u{0628}').unwrap() + designcraft_doc::OBJECT_MARK.len_utf8(); + let (latin, object, arabic) = (x(0), x(at), x(beh)); + // Read right to left: the Latin text, the object, then the Arabic letter. + assert!(arabic < object && object < latin, "arabic {arabic}, object {object}, latin {latin}"); +} + #[test] fn custom_anchors_do_not_change_bottom_baseline_fitting() { let (mut d, sid, _) = baseline_fit_doc("Text", 10.0); From 6978f3ff00444a9bf88326d298ac77694af4ef5a Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Wed, 4 Nov 2026 21:43:34 +0100 Subject: [PATCH 038/133] IDML import: an anchored text frame with an unknown story is threaded to its empty one A text frame whose ParentStory is unknown or missing gets an empty story, registered under an #orphan key, while the frame was later threaded by its ParentStory value. An anchored text frame, which isn't on a spread to be found another way, was then left out of its story's thread and the import failed ("embedded text frame ... not in its story's thread"). The frame now uses the key its story is registered under. --- crates/idml/src/import/item.rs | 6 +++-- crates/idml/src/tests.rs | 41 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/idml/src/import/item.rs b/crates/idml/src/import/item.rs index ac27a833e..941e237be 100644 --- a/crates/idml/src/import/item.rs +++ b/crates/idml/src/import/item.rs @@ -187,13 +187,15 @@ impl<'r> Importer<'r> { fn read_content(&mut self, e: &El, tag: &str, id: ItemId, item: &mut Item) { match tag { "TextFrame" => { - let story_self = e.get("ParentStory").unwrap_or("n").to_string(); + let mut story_self = e.get("ParentStory").unwrap_or("n").to_string(); let story = match self.story_ids.get(&story_self) { Some(s) => *s, None => { let sid = StoryId(self.alloc()); self.stories.insert(sid, Story::new(sid)); - self.story_ids.insert(format!("#orphan{}", sid.0), sid); + // Threaded by this key (an anchored frame isn't on a spread to find it by). + story_self = format!("#orphan{}", sid.0); + self.story_ids.insert(story_self.clone(), sid); sid } }; diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 24cec7141..5e8a64cbd 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -5044,3 +5044,44 @@ fn only_exactly_generated_cross_reference_text_is_regenerated() { let got: Vec> = s.xrefs.iter().map(|x| x.text.as_deref()).collect(); assert_eq!(got, [Some("Page , revised"), None, Some("Seite ")]); } + +/// A story part holding `before`, then the anchored text frame `a1` (120 × 40 pt) with +/// attributes `attrs` (its story reference), then `after`. +fn story_with_anchored_text_frame(before: &str, attrs: &str, after: &str) -> String { + format!( + r#" + + + + + {before} + + + + + + + {after} + + + +"# + ) +} + +/// An anchored text frame whose ParentStory is unknown or missing gets an empty story threaded to +/// it. The empty story was registered under one key and looked up under another when threading, +/// so the frame was left out of its thread and the import failed ("embedded text frame … not in +/// its story's thread"). +#[test] +fn anchored_text_frames_with_unknown_stories_import_with_empty_ones() { + for attrs in [r#"ParentStory="nope""#, ""] { + let d = import_idml_with(&fixture_with_story(&story_with_anchored_text_frame("Before ", attrs, " after")), &|_| None).unwrap(); + d.check().unwrap(); + let host = d.stories.values().find(|s| s.text.starts_with("Before")).unwrap(); + let frame = &host.objects[0].item; + let shown = d.story(frame.text_frame().unwrap().story).unwrap(); + assert!(shown.text.is_empty(), "{attrs}"); + assert_eq!(shown.frames, vec![frame.id], "{attrs}"); + } +} From 578697b3ac89f2ae8dd164671ea24295f4c690b4 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:04:57 +0000 Subject: [PATCH 039/133] Fix [Bug Report] [DesignCraft] Adding bleed to the document reset size of Fixes #2439. - crates/ui-egui/src/dialogs.rs - crates/ui-egui/src/dialogs/tests.rs - crates/engine/src/cmd/layout/registry.rs - crates/ui-egui/tests/autocraft_regression_2439.rs --- crates/ui-egui/src/dialogs.rs | 18 ++++++++-- crates/ui-egui/src/dialogs/tests.rs | 23 +++++++++++++ .../tests/autocraft_regression_2439.rs | 33 +++++++++++++++++++ 3 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/tests/autocraft_regression_2439.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a6400054d..b5e7cda4f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1956,6 +1956,9 @@ pub fn open_document_setup(app: &mut DesignApp) { } // The margins as shown: OK applies them to every page only when they were edited. f["marginsShown"] = json!(SETUP_EDGES.map(|e| f[format!("margin{e}")].clone())); + // The size as shown: OK sends it only when edited, so resized pages and parents keep theirs. + f["widthShown"] = f["width"].clone(); + f["heightShown"] = f["height"].clone(); let mut d = Dialog::new("documentSetup", f); d.unit = units; app.ui.dialog = Some(d); @@ -2358,17 +2361,26 @@ fn setup_link_follow(d: &mut Dialog, group: &str, changed: Option) { /// Document Setup's OK: `layout.documentSetup` with what was typed; a value that can't be read is /// refused before anything changes. The margins (the first page's, shown) go to every page only -/// when they were edited, so pages keep their own margins otherwise. +/// when they were edited, and so does the size, so pages keep their own margins and sizes otherwise. fn confirm_document_setup(app: &mut DesignApp, d: &Dialog) -> Result { let measure = |key: &str| setup_measure(d, key).ok_or_else(|| format!("{key}: not a measure")); let edges = |group: &str| -> Result, String> { SETUP_EDGES.iter().map(|e| measure(&format!("{group}{e}"))).collect() }; let count = |key: &str| d.n(key).filter(|n| n.is_finite() && *n >= 1.0).map(|n| n as u64).ok_or_else(|| format!("{key}: a whole number from 1")); + let size = |key: &str| -> Result, String> { + let v = measure(key)?; + Ok((d.fields.get(key) != d.fields.get(&format!("{key}Shown"))).then_some(v)) + }; let margins = edges("margin")?; let shown = d.fields.get("marginsShown").and_then(Value::as_array); let edited = SETUP_EDGES.iter().enumerate().any(|(i, e)| shown.and_then(|s| s.get(i)) != d.fields.get(&format!("margin{e}"))); let mut p = json!({"intent": d.s("intent"), "pages": count("pages")?, "startPage": count("startPage")?, "facingPages": d.b("facingPages"), - "binding": d.s("binding"), "width": measure("width")?, "height": measure("height")?, - "bleed": edges("bleed")?, "slug": edges("slug")?, "adjustLayout": d.b("adjustLayout")}); + "binding": d.s("binding"), "bleed": edges("bleed")?, "slug": edges("slug")?, "adjustLayout": d.b("adjustLayout")}); + if let Some(w) = size("width")? { + p["width"] = json!(w); + } + if let Some(h) = size("height")? { + p["height"] = json!(h); + } if edited { p["margins"] = json!({"top": margins[0], "bottom": margins[1], "inside": margins[2], "outside": margins[3]}); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 272165b08..f0091d4a9 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -347,6 +347,29 @@ fn document_setup_keeps_each_pages_margins_unless_they_are_edited() { assert_eq!(margins(&app), [12.0; 4]); } +#[test] +fn document_setup_keeps_resized_pages_unless_the_size_is_edited() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + app.run("layout.pageSize", json!({"pages": [2], "width": 300, "height": 400})).unwrap(); + let sizes = + |app: &DesignApp| app.session.active().unwrap().doc.spreads.iter().flat_map(|s| &s.pages).map(|p| (p.width, p.height)).collect::>(); + let before = sizes(&app); + assert_eq!(before[1], (300.0, 400.0)); + // Bleed only, then margins only: no page changes size. + for edit in [json!({"bleedTop": "9 pt", "bleedBottom": "9 pt", "bleedInside": "9 pt", "bleedOutside": "9 pt"}), json!({"marginTop": "1p0"})] { + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + setup_fields(&mut app, edit.clone()); + confirm(&mut app).unwrap(); + assert_eq!(sizes(&app), before, "{edit}"); + } + // An edited width still goes to every page. + crate::menus::activate(&mut app, "layout.documentSetup", &Value::Null); + setup_fields(&mut app, json!({"width": "500 pt"})); + confirm(&mut app).unwrap(); + assert!(sizes(&app).iter().all(|s| s.0 == 500.0)); +} + #[test] fn document_setup_keeps_a_value_it_cannot_read_and_changes_nothing() { for (key, value) in [("width", "wide"), ("marginTop", "-"), ("pages", "0"), ("bleedTop", "x")] { diff --git a/crates/ui-egui/tests/autocraft_regression_2439.rs b/crates/ui-egui/tests/autocraft_regression_2439.rs new file mode 100644 index 000000000..99fe8e2e4 --- /dev/null +++ b/crates/ui-egui/tests/autocraft_regression_2439.rs @@ -0,0 +1,33 @@ +use designcraft_engine::Session; +use designcraft_ui_egui::dialogs::{confirm, open_document_setup}; +use designcraft_ui_egui::{DesignApp, Services}; +use serde_json::json; + +fn sizes(app: &DesignApp) -> (Vec<(f64, f64)>, Vec<(f64, f64)>) { + let doc = &app.session.active().unwrap().doc; + let pages = doc.spreads.iter().flat_map(|s| &s.pages).map(|p| (p.width, p.height)).collect(); + let parents = doc.parents.iter().flat_map(|sp| sp.pages.iter()).map(|p| (p.width, p.height)).collect(); + (pages, parents) +} + +#[test] +fn document_setup_bleed_keeps_resized_pages_and_parents() { + let mut app = DesignApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"pages": 3})).unwrap(); + app.run("layout.pageSize", json!({"pages": [2], "width": 300, "height": 400})).unwrap(); + let parent = app.session.active().unwrap().doc.parents[0].id.0; + app.run("layout.parentPageSize", json!({"parent": parent, "page": 0, "width": 200, "height": 250})).unwrap(); + let before = sizes(&app); + assert_eq!(before.0[1], (300.0, 400.0)); + assert_eq!(before.1[0], (200.0, 250.0)); + + open_document_setup(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + for e in ["Top", "Bottom", "Inside", "Outside"] { + d.fields.insert(format!("bleed{e}"), json!("9 pt")); + } + confirm(&mut app).unwrap(); + + assert_eq!(app.session.active().unwrap().doc.settings.bleed, [9.0; 4]); + assert_eq!(sizes(&app), before, "bleed alone must not resize pages or parents"); +} From be0c62ddca1aabf9431baffa7f471469f5c2c7d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 02:30:50 +0000 Subject: [PATCH 040/133] Anchored objects: review fixes (#1195) - Delete and Backspace delete a selected anchored object, Escape deselects it; the arrows leave it (it flows with the text). - The Selection tool doesn't pick an object in a locked text frame (the command refuses it) or a hidden one (it isn't drawn). - Shift on a selected object's handle resizes it proportionally; a Shift-click on an unselected one doesn't select it. - An anchored selection follows its object through edits (by item id, the nearest when copies share it) and clears when the object is gone, so Delete or resize never act on another object. - Tests for each. --- crates/engine/src/cmd/anchored.rs | 43 ++++++++++++++++++++ crates/engine/src/lib.rs | 22 +++++++++++ crates/tools/src/anchored.rs | 8 ++-- crates/tools/src/select.rs | 16 +++++++- crates/tools/src/tests.rs | 65 +++++++++++++++++++++++++++++++ 5 files changed, 149 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index 7173068c9..aacf5ae77 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -379,6 +379,49 @@ mod tests { (s, sid) } + /// Review of #1195: an anchored selection follows its object through edits of the story. An + /// object inserted before it moves it along; resizing it keeps it selected; deleting its + /// text deletes it from the selection too, so Delete never takes another object. + #[test] + fn an_anchored_selection_follows_its_object() { + let (mut s, sid) = inline_box(); + let id = |s: &Session, k: usize| s.doc().unwrap().doc.story(sid).unwrap().objects[k].item.id; + s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).unwrap(); + let selected = id(&s, 0); + // Another object anchored at the start of the story, before the selected one. + let r = s.execute("frame.create", &json!({"rect": [450, 300, 470, 320]})).unwrap(); + s.execute("anchored.insert", &json!({"ids": [r["id"]], "story": sid.0, "pos": 0})).unwrap(); + // The selected object is now the second. + let st = s.doc_mut().unwrap(); + st.selection = designcraft_doc::Selection { anchored: Some(AnchoredSel { story: sid, index: 1 }), ..Default::default() }; + assert_eq!(id(&s, 1), selected); + // An edit that inserts an object before it: the selection moves with it. + s.edit(|d, _| { + let st = d.story_mut(sid).unwrap(); + let first = (*st.objects[0]).clone(); + let mut copy = first; + copy.item.id = ItemId(9_999); + st.insert_object(0, copy); + Ok(()) + }) + .unwrap(); + let a = s.doc().unwrap().selection.anchored.unwrap(); + assert_eq!((a.index, id(&s, a.index)), (2, selected), "follows its object"); + // Resizing keeps it selected. + s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 30, 40]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.anchored.map(|a| a.index), Some(2)); + // Its text deleted with the object: nothing stays selected, rather than another object. + let pos = s.doc().unwrap().doc.story(sid).unwrap().text.match_indices(designcraft_doc::OBJECT_MARK).nth(2).unwrap().0; + s.edit(|d, _| { + d.story_mut(sid).unwrap().delete(pos..pos + designcraft_doc::OBJECT_MARK.len_utf8()); + Ok(()) + }) + .unwrap(); + assert_eq!(s.doc().unwrap().selection.anchored, None); + let _ = s.execute("edit.clear", &json!({})); + assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().objects.len(), 2, "Delete took nothing"); + } + /// A locked anchored object, one on a locked layer, or one in a locked frame or a frame on a /// locked layer can't be selected, resized or deleted: it stays in the text with its marker. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1c585aa4f..b67e4fd05 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -803,7 +803,17 @@ impl Session { let st = self.doc_mut()?; let mut doc = (*st.doc).clone(); let mut sel = st.selection.clone(); + let anchored = sel.anchored; + let anchored_id = anchored.and_then(|a| doc.story(a.story)?.objects.get(a.index)).map(|o| o.item.id); let r = f(&mut doc, &mut sel)?; + // An anchored selection names its object by place in the story: an edit that inserts or + // removes objects before it would leave it naming another. Follow the object instead (a + // command that chose a new selection keeps its choice). + if sel.anchored == anchored + && let Some(a) = anchored + { + sel.anchored = anchored_id.and_then(|id| follow_anchored(&doc, a, id)); + } crate::cmd::sync_placeholders(&mut doc); crate::cmd::flex::sync(&mut doc); doc.sync_endnote_story(); @@ -815,6 +825,18 @@ impl Session { } } +/// Where the anchored object `a` named before an edit is now: the object of its story with item +/// `id`, the one nearest its old place when copies share the id (pasted text); `None` when it is +/// gone. +fn follow_anchored(doc: &Document, a: designcraft_doc::AnchoredSel, id: designcraft_doc::ItemId) -> Option { + let objects = &doc.story(a.story)?.objects; + if objects.get(a.index).is_some_and(|o| o.item.id == id) { + return Some(a); + } + let index = objects.iter().enumerate().filter(|(_, o)| o.item.id == id).map(|(k, _)| k).min_by_key(|k| k.abs_diff(a.index))?; + Some(designcraft_doc::AnchoredSel { index, ..a }) +} + fn push_undo(st: &mut DocState, e: HistoryEntry) { st.history.undo.push(e); st.history.redo.clear(); diff --git a/crates/tools/src/anchored.rs b/crates/tools/src/anchored.rs index d0febac0b..877d803aa 100644 --- a/crates/tools/src/anchored.rs +++ b/crates/tools/src/anchored.rs @@ -37,7 +37,8 @@ pub fn placed(doc: &Document, cache: &Cache, layout: &CanvasLayout, story: Optio } let (Some(loc), Some(frame)) = (doc.find(ft.frame), doc.item(ft.frame)) else { continue }; let layer = doc.layer(frame.layer); - if frame.hidden || layer.is_some_and(|l| !l.visible || l.locked) { + // A locked frame's objects are locked too (`anchored.select` refuses them). + if frame.hidden || frame.locked || layer.is_some_and(|l| !l.visible || l.locked) { continue; } let Some(slot) = layout.slot(loc.spread) else { continue }; @@ -45,9 +46,10 @@ pub fn placed(doc: &Document, cache: &Cache, layout: &CanvasLayout, story: Optio let [a, b, c, d, _, _] = xf.as_coeffs(); let turned = b.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0; for o in &ft.objects { - // A locked object (or one on a locked layer) can't be selected, as other items. + // A locked object (or one on a locked layer) can't be selected, as other items; a + // hidden one isn't drawn, so it can't be clicked. let it = &o.object.item; - if it.locked || doc.layer(it.layer).is_some_and(|l| l.locked) { + if it.hidden || it.locked || doc.layer(it.layer).is_some_and(|l| l.locked) { continue; } let r = o.object.item.bounds(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1d315c7d3..1eb2d7742 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1307,7 +1307,8 @@ impl Tool for SelectionTool { // Anchored objects (inline graphics and the like): a press on a selected one's handle // resizes it, a press on one selects it. They flow with the text, so a drag doesn't move // them, and a double click selects rather than editing the text around them. - if !self.direct && !ev.mods.shift && matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) { + if !self.direct && matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) { + // A handle resizes, with Shift too (proportionally, as other frames). if let Some((pl, h)) = anchored_handle_at(cx, p) && let Some(o) = cx.doc.story(pl.sel.story).and_then(|s| s.objects.get(pl.sel.index)) { @@ -1316,7 +1317,9 @@ impl Tool for SelectionTool { self.drag = Drag::AnchoredResize { sel: pl.sel, handle, from: pl.spread_rect, local: o.item.bounds(), spread: pl.spread, to: None }; return vec![Action::Handled]; } - if handle_at(cx, p).is_none() + // Shift-click adds to an item selection, which an anchored object can't join. + if !ev.mods.shift + && handle_at(cx, p).is_none() && let Some(pl) = crate::anchored::at(cx.doc, cx.cache, cx.layout, p) { self.drag = Drag::None; @@ -1472,6 +1475,15 @@ impl Tool for SelectionTool { if direct_points && matches!(key, ToolKey::Delete | ToolKey::Backspace) { return vec![Action::Exec("path.deletePoints".into(), json!({}))]; } + // A selected anchored object: Delete and Backspace delete it (with its place in the + // text), Escape deselects it. It flows with the text, so the arrows don't move it. + if cx.selection.anchored.is_some() && cx.selection.items.is_empty() { + return match key { + ToolKey::Delete | ToolKey::Backspace => vec![Action::Exec("edit.clear".into(), json!({}))], + ToolKey::Escape => vec![Action::Exec("selection.set".into(), json!({"ids": []}))], + _ => vec![], + }; + } if cx.selection.items.is_empty() { // Selected ruler guides: the arrows nudge them, Delete deletes them. if cx.selection.guides.is_empty() { diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 1d95a6807..cb1cb3d4f 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2316,6 +2316,71 @@ fn selection_tool_selects_an_inline_object_and_resizes_it_by_a_handle() { assert!(matches!(a.as_slice(), [Action::Exec(c, _)] if c == "selection.set"), "{a:?}"); } +/// Review of #1195: a selected anchored object takes Delete and Backspace (`edit.clear`) and +/// Escape (deselect) from the Selection tool; the arrows don't move it (it flows with the text). +#[test] +fn keys_act_on_a_selected_anchored_object() { + let (d, sid) = inline_box_doc(); + let (c, l) = (Cache::new(), CanvasLayout::new(&d, false)); + let s = Selection { anchored: Some(designcraft_doc::AnchoredSel { story: sid, index: 0 }), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let mut t = create("selection"); + for key in [ToolKey::Delete, ToolKey::Backspace] { + assert_eq!(t.key(&cx, key, Mods::default()), vec![Action::Exec("edit.clear".into(), serde_json::json!({}))], "{key:?}"); + } + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]); + assert!(t.key(&cx, ToolKey::Left, Mods::default()).is_empty()); +} + +/// Review of #1195: the Selection tool doesn't pick an anchored object it can't select: one in a +/// locked text frame (`anchored.select` refuses it), or a hidden one (it isn't drawn). +#[test] +fn locked_frames_and_hidden_anchored_objects_are_not_picked() { + let (d, sid) = inline_box_doc(); + let c = Cache::new(); + let r = crate::anchored::placed(&d, &c, &CanvasLayout::new(&d, false), None)[0].canvas_rect; + let mut locked = d.clone(); + let frame = locked.story(sid).unwrap().frames[0]; + locked.item_mut(frame).unwrap().locked = true; + let mut hidden = d.clone(); + std::sync::Arc::make_mut(&mut hidden.story_mut(sid).unwrap().objects[0]).item.hidden = true; + for (what, d) in [("locked frame", &locked), ("hidden object", &hidden)] { + let l = CanvasLayout::new(d, false); + assert!(crate::anchored::placed(d, &c, &l, None).is_empty(), "{what}"); + assert!(crate::anchored::at(d, &c, &l, r.center()).is_none(), "{what}"); + } +} + +/// Review of #1195: Shift on a selected anchored object's handle resizes it proportionally, as +/// other frames; a Shift-click on an unselected one doesn't select it. +#[test] +fn shift_on_an_anchored_handle_resizes_proportionally() { + let (d, sid) = inline_box_doc(); + let (c, l) = (Cache::new(), CanvasLayout::new(&d, false)); + let r = crate::anchored::placed(&d, &c, &l, None)[0].canvas_rect; + let shift = Mods { shift: true, ..Default::default() }; + let s = Selection { anchored: Some(designcraft_doc::AnchoredSel { story: sid, index: 0 }), ..Default::default() }; + let cx = ctx(&d, &s, &c, &l); + let mut t = create("selection"); + // The bottom-right corner, dragged 12 to the right with Shift: 24 × 40 becomes 36 × 60. + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, r.x1, r.y1).with_mods(shift)), vec![Action::Handled]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, r.x1 + 12.0, r.y1).with_mods(shift)); + match t.pointer(&cx, &PointerEvent::new(PointerKind::Up, r.x1 + 12.0, r.y1).with_mods(shift)).as_slice() { + [Action::Exec(cmd, p)] => { + assert_eq!(cmd, "anchored.resize"); + let to: Vec = serde_json::from_value(p["to"].clone()).unwrap(); + assert!(((to[2] - to[0]) / (to[3] - to[1]) - 24.0 / 40.0).abs() < 1e-6, "proportional: {to:?}"); + } + other => panic!("{other:?}"), + } + // Unselected, a Shift-click on it doesn't select it on its own. + let none = Selection::default(); + let cx = ctx(&d, &none, &c, &l); + let mut t = create("selection"); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, r.center().x, r.center().y).with_mods(shift)); + assert!(!a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "anchored.select")), "{a:?}"); +} + #[test] fn parent_resize_page_tool_targets_the_visible_parent() { let d = Document::new(&NewDocument { width: 400.0, height: 600.0, pages: 3, facing_pages: true, ..Default::default() }); From 2f6cce6dc1640d69cf49c3c702dd3c59319fdcc9 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:54:42 -0600 Subject: [PATCH 041/133] Small Caps: draw them when the font has none MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A run set to Small Caps asked the font for its smcp feature and nothing else, so on a font without one — most of them — the setting did nothing while All Caps worked, which uppercases the text itself. The run is now uppercased and each lowercase glyph scaled to 70% when the face has no smcp, as InDesign draws them; capitals already in the run keep their size, All Small Caps scales every letter, and the line box, leading and first baseline are measured from the unscaled size so turning it on cannot reflow the page in height. Whether a face has the feature is read once from its GSUB and cached by face id. Tests use Inter (no smcp) and Source Sans 3 (has it). --- crates/compose/src/shape.rs | 46 ++++++++++++++++++++++++++++++++----- crates/compose/src/tests.rs | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..a7f0c1199 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1074,6 +1074,28 @@ fn shape_cached( out } +/// Size of a small capital drawn by us, as a fraction of the type size, close to InDesign's own. +const SMALL_CAPS_SIZE: f64 = 0.7; + +/// Faces whose small caps we must draw, by face id. Reading a font's feature list parses its GSUB, +/// which is not something to do once per run per line. +static SMALL_CAPS_MISSING: RwLock> = RwLock::new(Vec::new()); + +/// Whether this run's small caps have to be drawn instead of taken from the font: the font's own +/// `smcp` is used whenever it has one. +fn small_caps_drawn_by_us(face: &FontFace, p: &CharProps) -> bool { + if !matches!(p.capitalization, Capitalization::SmallCaps | Capitalization::OpenTypeAllSmallCaps) { + return false; + } + let id = face.id(); + if let Some((_, missing)) = SMALL_CAPS_MISSING.read().unwrap_or_else(std::sync::PoisonError::into_inner).iter().find(|e| e.0 == id) { + return *missing; + } + let missing = !designcraft_fonts::font_features(face).tags.contains("smcp"); + SMALL_CAPS_MISSING.write().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, missing)); + missing +} + fn metrics(face: &FontFace, p: &CharProps, auto_leading: TypeEnv) -> (f64, f64, f64, f64, f64, f64, f64, f64) { let (size, shift) = effective_size(p, &auto_leading.adv); let k = size / face.upem; @@ -1199,7 +1221,11 @@ fn shape_segment( let tracking = p.tracking / 1000.0 * p.size; let manual = if let Kerning::Manual(v) = p.kerning { v / 1000.0 * p.size } else { 0.0 }; let src = replacement.unwrap_or(&text[range.clone()]); - let caps = p.capitalization == Capitalization::AllCaps; + // A font with no small caps of its own gets them drawn: the letter is uppercased and set + // smaller, the way InDesign does it, which is why All Caps worked on such a font and Small + // Caps looked like nothing happened (#2438). + let small = small_caps_drawn_by_us(face, p); + let caps = p.capitalization == Capitalization::AllCaps || small; let feats = features_for(p); // Upright in vertical text, Horizontal Kana takes the vertical kana alternates instead. let mut upright_feats = feats.clone(); @@ -1253,12 +1279,20 @@ fn shape_segment( let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len()); Box::from(src.get(sg.cluster..end).unwrap_or("")) }); + // Small caps drawn by us shrink the lowercase letters (all of them for All Small Caps); + // the capitals of a Small Caps run keep their size. Only the glyph and its advance change: + // the line box above is measured from the unscaled size, so leading never moves. + let shrink = match small { + true if p.capitalization == Capitalization::OpenTypeAllSmallCaps => SMALL_CAPS_SIZE, + true if ch.is_lowercase() => SMALL_CAPS_SIZE, + _ => 1.0, + }; // Upright: down the line is the shaper's -y, across it (text space -y) its x. - let mut adv = if up { -(sg.y_advance as f64) * k_v } else { sg.x_advance as f64 * k * hs }; + let mut adv = if up { -(sg.y_advance as f64) * k_v * shrink } else { sg.x_advance as f64 * k * hs * shrink }; let (dx, dy) = if up { - (-(sg.y_offset as f64) * k_v, -(sg.x_offset as f64) * k * hs) + (-(sg.y_offset as f64) * k_v * shrink, -(sg.x_offset as f64) * k * hs * shrink) } else { - (sg.x_offset as f64 * k * hs, -(sg.y_offset as f64) * k * p.v_scale) + (sg.x_offset as f64 * k * hs * shrink, -(sg.y_offset as f64) * k * p.v_scale * shrink) }; let (ascent, descent) = if up { (em_top * k_v, -em_bottom * k_v) } else { (ascent, descent) }; let body = adv; @@ -1280,8 +1314,8 @@ fn shape_segment( adv, dx: dx + mark_x, dy: dy - mark_y, - sx: k * hs, - sy: k * p.v_scale, + sx: k * hs * shrink, + sy: k * p.v_scale * shrink, shift, ascent, typo_ascent: face.typo_ascent * k, diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a47e27f45..41f98d16a 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8647,3 +8647,46 @@ fn cross_reference_text_breaks_at_its_spaces() { } } } + +/// A font with small caps of its own keeps them (Source Sans 3 has `smcp`), and one without gets +/// them drawn: the lowercase letters are set as capitals at 70%, while a capital already in the run +/// keeps its size. That is the case the report hit, where All Caps worked and Small Caps did nothing. +#[test] +fn small_caps_come_from_the_font_or_are_drawn_when_it_has_none() { + use designcraft_doc::Capitalization; + let text = "ab A"; + + let composed = |family: &str, caps: Capitalization| { + let (mut d, sid, _) = doc_with(text, Rect::new(72.0, 36.0, 372.0, 136.0), ParaAttrs::default()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some(family.into()); + f.over.size = Some(20.0); + f.over.capitalization = Some(caps); + }); + let cs = compose_story(&d, sid, &Default::default()); + cs.frames[0].lines[0].glyphs.iter().map(|g| (g.byte, g.gid, g.adv, g.sx, g.rendered_char)).collect::>() + }; + + // Inter ships without `smcp`; Source Sans 3 has it. + let plain = composed("Inter", Capitalization::Normal); + let small = composed("Inter", Capitalization::SmallCaps); + let at = |gs: &[(usize, u32, f64, f64, char)], byte: usize| gs.iter().find(|g| g.0 == byte).cloned().unwrap(); + let (_, a_plain, adv_plain, _, _) = at(&plain, 0); + let (_, cap_plain, adv_cap, _, _) = at(&plain, 3); + let (_, a_small, adv_a, sx_a, ch_a) = at(&small, 0); + let (_, cap_small, adv_A, sx_cap, _) = at(&small, 3); + assert_eq!(ch_a, 'a', "the run still reads a"); + assert_eq!(a_small, cap_plain, "the a is drawn with the glyph of an A"); + assert_eq!(a_small, cap_small, "the same glyph the run's own A uses"); + assert!((adv_a / adv_cap - 0.7).abs() < 1e-6, "the small a takes 70%: {} / {}", adv_a, adv_cap); + assert!((adv_A - adv_cap).abs() < 1e-9, "the capital keeps its advance: {} vs {}", adv_A, adv_cap); + assert!((sx_a / sx_cap - 0.7).abs() < 1e-6, "and its drawing is scaled by the same 0.7"); + assert_ne!(a_plain, cap_plain, "in the plain run the two letters differ"); + + // With Source Sans 3 the font sets them: its `smcp` gives a small-capital glyph of its own, + // not the uppercased A we would draw. + let named = composed("Source Sans 3", Capitalization::SmallCaps); + let (_, a_named, _, _, _) = at(&named, 0); + assert_ne!(a_named, cap_plain, "the a takes the font's small capital, not an uppercased A"); + assert_ne!(a_named, a_plain, "and it is not the plain a either"); +} From 8fe575d5c9d9ec88e725ad1ff4622345782318cf Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:55:58 -0600 Subject: [PATCH 042/133] Small Caps: keep the test identifiers snake case clippy refuses adv_A under -D warnings; the assertions read the same. --- crates/compose/src/tests.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 41f98d16a..60d8d1f22 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8673,13 +8673,13 @@ fn small_caps_come_from_the_font_or_are_drawn_when_it_has_none() { let at = |gs: &[(usize, u32, f64, f64, char)], byte: usize| gs.iter().find(|g| g.0 == byte).cloned().unwrap(); let (_, a_plain, adv_plain, _, _) = at(&plain, 0); let (_, cap_plain, adv_cap, _, _) = at(&plain, 3); - let (_, a_small, adv_a, sx_a, ch_a) = at(&small, 0); - let (_, cap_small, adv_A, sx_cap, _) = at(&small, 3); + let (_, small_a, adv_a, sx_a, ch_a) = at(&small, 0); + let (_, small_cap, adv_upper, sx_cap, _) = at(&small, 3); assert_eq!(ch_a, 'a', "the run still reads a"); - assert_eq!(a_small, cap_plain, "the a is drawn with the glyph of an A"); - assert_eq!(a_small, cap_small, "the same glyph the run's own A uses"); + assert_eq!(small_a, cap_plain, "the a is drawn with the glyph of an A"); + assert_eq!(small_a, small_cap, "the same glyph the run's own A uses"); assert!((adv_a / adv_cap - 0.7).abs() < 1e-6, "the small a takes 70%: {} / {}", adv_a, adv_cap); - assert!((adv_A - adv_cap).abs() < 1e-9, "the capital keeps its advance: {} vs {}", adv_A, adv_cap); + assert!((adv_upper - adv_cap).abs() < 1e-9, "the capital keeps its advance: {} vs {}", adv_upper, adv_cap); assert!((sx_a / sx_cap - 0.7).abs() < 1e-6, "and its drawing is scaled by the same 0.7"); assert_ne!(a_plain, cap_plain, "in the plain run the two letters differ"); From 376abaa4b0fd38053ec3d8c4ae40dd66b6277670 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:56:38 -0600 Subject: [PATCH 043/133] Small Caps: the plain advance is only there for the record --- 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 60d8d1f22..c6709e25b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -8671,7 +8671,7 @@ fn small_caps_come_from_the_font_or_are_drawn_when_it_has_none() { let plain = composed("Inter", Capitalization::Normal); let small = composed("Inter", Capitalization::SmallCaps); let at = |gs: &[(usize, u32, f64, f64, char)], byte: usize| gs.iter().find(|g| g.0 == byte).cloned().unwrap(); - let (_, a_plain, adv_plain, _, _) = at(&plain, 0); + let (_, a_plain, _adv_plain, _, _) = at(&plain, 0); let (_, cap_plain, adv_cap, _, _) = at(&plain, 3); let (_, small_a, adv_a, sx_a, ch_a) = at(&small, 0); let (_, small_cap, adv_upper, sx_cap, _) = at(&small, 3); From d457d412bf4a652a5e2fab4833d124f15fe06442 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:57:13 -0600 Subject: [PATCH 044/133] Small Caps: the shrink is its own decision, not a branch in the loop clippy measures cognitive complexity on shape_run_raw and a match inside the glyph loop pushed it over the limit; the rule of which glyphs shrink now lives in a function that says it once. --- crates/compose/src/shape.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index a7f0c1199..6932b4de2 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1081,6 +1081,13 @@ const SMALL_CAPS_SIZE: f64 = 0.7; /// which is not something to do once per run per line. static SMALL_CAPS_MISSING: RwLock> = RwLock::new(Vec::new()); +/// How much a glyph shrinks when we draw its small caps: the lowercase letters of a Small Caps run, +/// every letter of All Small Caps, and nothing else. Only the glyph and its advance change — the +/// line box is measured from the unscaled size, so turning it on never moves the leading. +fn small_caps_shrink(small: bool, all_small_caps: bool, ch: char) -> f64 { + if small && (all_small_caps || ch.is_lowercase()) { SMALL_CAPS_SIZE } else { 1.0 } +} + /// Whether this run's small caps have to be drawn instead of taken from the font: the font's own /// `smcp` is used whenever it has one. fn small_caps_drawn_by_us(face: &FontFace, p: &CharProps) -> bool { @@ -1279,14 +1286,7 @@ fn shape_segment( let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len()); Box::from(src.get(sg.cluster..end).unwrap_or("")) }); - // Small caps drawn by us shrink the lowercase letters (all of them for All Small Caps); - // the capitals of a Small Caps run keep their size. Only the glyph and its advance change: - // the line box above is measured from the unscaled size, so leading never moves. - let shrink = match small { - true if p.capitalization == Capitalization::OpenTypeAllSmallCaps => SMALL_CAPS_SIZE, - true if ch.is_lowercase() => SMALL_CAPS_SIZE, - _ => 1.0, - }; + let shrink = small_caps_shrink(small, p.capitalization == Capitalization::OpenTypeAllSmallCaps, ch); // Upright: down the line is the shaper's -y, across it (text space -y) its x. let mut adv = if up { -(sg.y_advance as f64) * k_v * shrink } else { sg.x_advance as f64 * k * hs * shrink }; let (dx, dy) = if up { From 8fcdfef802691125173115ce515855a14b182e1f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 8 Nov 2026 05:07:35 +0000 Subject: [PATCH 045/133] Anchored objects: second review (#1195) - An item stacked above an anchored object's text frame keeps a click on it: the object is only picked where its own frame is the top item. - Anchored Object Options and Release refuse locked objects, as select, resize and Delete do; their parameter docs say they act on the selected object first. - object_ref's doc comment is back on object_ref. - The parity doc no longer presents the ignored drag as reference behaviour: moving an anchored object by dragging is not implemented yet. - Tests: the stacked item, and Options and Release in the lock test. --- crates/engine/src/cmd/anchored.rs | 16 ++++++++++++---- crates/tools/src/anchored.rs | 3 +++ crates/tools/src/select.rs | 12 +++++++++--- crates/tools/src/tests.rs | 27 +++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 5 files changed, 52 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/anchored.rs b/crates/engine/src/cmd/anchored.rs index aacf5ae77..b9d89fcf6 100644 --- a/crates/engine/src/cmd/anchored.rs +++ b/crates/engine/src/cmd/anchored.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Anchored Object Options…", ["Object", "Anchored Object"], None, - "{story?, index? (default: the object at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}", + "{story?, index? (default: the selected anchored object, else the one at the insertion point), position?: inline|aboveLine|custom, yOffset?, align?: left|center|right, spaceBefore?, spaceAfter?, xRelative? | yRelative?: anchor|textFrame|columnEdge|pageMargin|pageEdge, xOffset?, objectPoint? | refPoint?: 0..8, keepWithinColumn?, spineRelative? (custom: the settings describe a left-hand page and mirror on a right-hand page)}", has_doc, options ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Release", ["Object", "Anchored Object"], None, - "{story?, index? (default: the object at the insertion point)} — puts the object back on the page where it is now and removes it from the text", + "{story?, index? (default: the selected anchored object, else the one at the insertion point)} — puts the object back on the page where it is now and removes it from the text", has_doc, release ), @@ -187,7 +187,6 @@ fn insert(s: &mut Session, p: &Value) -> Result { }) } -/// `{story, index}`, or the anchored object at (or just before) the text insertion point. /// Whether the `k`-th anchored object of story `sid` can't be selected or changed: it, or the text /// frame holding it, is locked or on a locked layer (as for other page items). fn is_locked(s: &Session, sid: StoryId, k: usize) -> Result { @@ -215,6 +214,8 @@ fn check_unlocked(s: &Session, sid: StoryId, k: usize, cmd: &str) -> Result<()> Ok(()) } +/// `{story, index}`, else the selected anchored object, else the one at (or just before) the text +/// insertion point. fn object_ref(s: &Session, p: &Value, cmd: &str) -> Result<(StoryId, usize)> { if let (Some(sid), Some(k)) = (p.get("story").and_then(Value::as_u64), p.get("index").and_then(Value::as_u64)) { return Ok((StoryId(sid), usize::try_from(k).map_err(|_| bad(cmd, "index out of range"))?)); @@ -321,6 +322,7 @@ pub(crate) fn delete(s: &mut Session, a: AnchoredSel) -> Result { fn options(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.options")?; + check_unlocked(s, sid, k, "anchored.options")?; let cur = s.doc()?.doc.story(sid).and_then(|st| st.objects.get(k).cloned()).ok_or_else(|| bad("anchored.options", "no such anchored object"))?; let position = position_param(p, &cur.position)?; s.edit(|d, _| { @@ -334,6 +336,7 @@ fn options(s: &mut Session, p: &Value) -> Result { fn release(s: &mut Session, p: &Value) -> Result { let (sid, k) = object_ref(s, p, "anchored.release")?; + check_unlocked(s, sid, k, "anchored.release")?; let d0 = s.doc()?.doc.clone(); let st = d0.story(sid).ok_or_else(|| bad("anchored.release", "no such story"))?; let obj = st.objects.get(k).cloned().ok_or_else(|| bad("anchored.release", "no such anchored object"))?; @@ -423,7 +426,8 @@ mod tests { } /// A locked anchored object, one on a locked layer, or one in a locked frame or a frame on a - /// locked layer can't be selected, resized or deleted: it stays in the text with its marker. + /// locked layer can't be selected, resized, deleted, changed in Anchored Object Options or + /// released: it stays in the text with its marker. #[test] fn locked_anchored_objects_are_left_alone() { type Lock = fn(&mut designcraft_doc::Document, StoryId); @@ -455,10 +459,14 @@ mod tests { assert!(s.execute("anchored.select", &json!({"story": sid.0, "index": 0})).is_err(), "{what}: select"); assert!(s.execute("anchored.resize", &json!({"from": [0, 0, 24, 40], "to": [0, 0, 24, 60]})).is_err(), "{what}: resize"); assert!(s.execute("edit.clear", &json!({})).is_err(), "{what}: delete"); + // Anchored Object Options and Release (on the selected object, as from the menu). + assert!(s.execute("anchored.options", &json!({"position": "aboveLine"})).is_err(), "{what}: options"); + assert!(s.execute("anchored.release", &json!({})).is_err(), "{what}: release"); let st = s.doc().unwrap().doc.story(sid).unwrap().clone(); assert_eq!(st.objects.len(), 1, "{what}: the object stays"); assert_eq!(st.text.matches(OBJECT_MARK).count(), 1, "{what}: and its marker"); assert_eq!(st.objects[0].size(), (24.0, 40.0), "{what}: at its size"); + assert!(matches!(st.objects[0].position, AnchorPosition::Inline { .. }), "{what}: inline still"); } } diff --git a/crates/tools/src/anchored.rs b/crates/tools/src/anchored.rs index 877d803aa..de83c7d85 100644 --- a/crates/tools/src/anchored.rs +++ b/crates/tools/src/anchored.rs @@ -16,6 +16,8 @@ pub struct Placed { pub spread_rect: Rect, pub canvas_rect: Rect, pub turned: bool, + /// The text frame it was composed in. + pub frame: designcraft_doc::ItemId, } /// The anchored objects of `story` (every story's when `None`) composed in frames on the @@ -64,6 +66,7 @@ pub fn placed(doc: &Document, cache: &Cache, layout: &CanvasLayout, story: Optio spread_rect, canvas_rect: slot.xf.transform_rect_bbox(spread_rect), turned, + frame: ft.frame, }); } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1eb2d7742..210d394a4 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1305,8 +1305,8 @@ impl Tool for SelectionTool { return actions; } // Anchored objects (inline graphics and the like): a press on a selected one's handle - // resizes it, a press on one selects it. They flow with the text, so a drag doesn't move - // them, and a double click selects rather than editing the text around them. + // resizes it, a press on one selects it. Dragging one to move it isn't implemented yet (the + // drag is ignored), and a double click selects rather than editing the text around them. if !self.direct && matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick) { // A handle resizes, with Shift too (proportionally, as other frames). if let Some((pl, h)) = anchored_handle_at(cx, p) @@ -1317,10 +1317,16 @@ impl Tool for SelectionTool { self.drag = Drag::AnchoredResize { sel: pl.sel, handle, from: pl.spread_rect, local: o.item.bounds(), spread: pl.spread, to: None }; return vec![Action::Handled]; } - // Shift-click adds to an item selection, which an anchored object can't join. + // Shift-click adds to an item selection, which an anchored object can't join. An item + // stacked above the object's text frame keeps the click: the object is only picked + // where its own frame is the top item. if !ev.mods.shift && handle_at(cx, p).is_none() && let Some(pl) = crate::anchored::at(cx.doc, cx.cache, cx.layout, p) + && cx.hit(p).is_none_or(|(_, id)| { + let top = |id| cx.doc.top_level_of(id).unwrap_or(id); + top(id) == top(pl.frame) + }) { self.drag = Drag::None; if cx.selection.anchored == Some(pl.sel) { diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index cb1cb3d4f..cfbc02bf1 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2316,6 +2316,33 @@ fn selection_tool_selects_an_inline_object_and_resizes_it_by_a_handle() { assert!(matches!(a.as_slice(), [Action::Exec(c, _)] if c == "selection.set"), "{a:?}"); } +/// Review of #1195: an item stacked above an anchored object's text frame keeps a click on it; +/// the object is only picked where its own frame is the top item. +#[test] +fn an_item_above_the_text_frame_keeps_a_click_on_an_anchored_object() { + let (mut d, _) = inline_box_doc(); + let c = Cache::new(); + let r = crate::anchored::placed(&d, &c, &CanvasLayout::new(&d, false), None)[0].canvas_rect; + let (s, l) = (Selection::default(), CanvasLayout::new(&d, false)); + let p = r.center(); + let mut t = create("selection"); + let a = t.pointer(&ctx(&d, &s, &c, &l), &PointerEvent::new(PointerKind::Down, p.x, p.y)); + assert!(matches!(a.as_slice(), [Action::Exec(c, _)] if c == "anchored.select"), "{a:?}"); + // A filled rectangle over the object, above the text frame. + let lid = d.default_layer(); + let spread = l.xf(SpreadRef::Doc(0)).inverse() * p; + let box_id = ItemId(d.alloc()); + let mut cover = + Item::new(box_id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(spread.x - 30.0, spread.y - 30.0, spread.x + 30.0, spread.y + 30.0))); + cover.fill = designcraft_doc::Fill::swatch("Black"); + d.insert_item(SpreadRef::Doc(0), cover, None).unwrap(); + let l = CanvasLayout::new(&d, false); + let mut t = create("selection"); + let a = t.pointer(&ctx(&d, &s, &c, &l), &PointerEvent::new(PointerKind::Down, p.x, p.y)); + assert!(!a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "anchored.select")), "the item above wins: {a:?}"); + assert!(a.iter().any(|a| matches!(a, Action::Exec(c, p) if c == "selection.set" && p["ids"] == serde_json::json!([box_id.0]))), "{a:?}"); +} + /// Review of #1195: a selected anchored object takes Delete and Backspace (`edit.clear`) and /// Escape (deselect) from the Selection tool; the arrows don't move it (it flows with the text). #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9c4ecf6d2..088f2226c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -288,7 +288,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level - 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. -- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); the Selection tool selects one where it sits in the text (a click; a drag doesn't move it) and resizes it by its handles (an outline follows the pointer with the size; on release the frame takes it, cropping the picture from the sides that moved, or with Cmd scaling it, Shift proportional, and the text reflows), and Delete removes it (`anchored.select`, `anchored.resize`); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. +- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); the Selection tool selects one where it sits in the text (a click, unless an item stacked above its frame is there; dragging it to move it is not implemented yet) and resizes it by its handles (an outline follows the pointer with the size; on release the frame takes it, cropping the picture from the sides that moved, or with Cmd scaling it, Shift proportional, and the text reflows), and Delete removes it (`anchored.select`, `anchored.resize`); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands. - Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; a dragged guide snaps along its axis to other guides, margins, columns, bleed, page and object edges and centers and the document grid (Shift: the ruler's ticks; Cmd suspends snapping); selected like objects with the Selection tools (click, Shift-click, a marquee that touches no object, Edit › Select All Guides ⌥⌘G), drawn highlighted, moved together by dragging or the arrow keys, deleted with Delete, and placed exactly with the X or Y field of the Control and Properties panels; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands. - Column guides: with the Selection tool, drag an interior column guide to move its gutter (both guides together, keeping its width, stopped by the neighbouring guides and the margins), snapping to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels; one undo step. Refused while Lock Column Guides is on (the default). A document page takes the result as its own columns; on a parent page it reaches the pages that follow it. Objects stay where they are (there is no persistent Layout Adjustment setting yet). `layout.moveColumnGuide`. - Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands. From 1ea786881eb433a27bace2a823e49d802acdb9f6 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:26:18 +0000 Subject: [PATCH 046/133] Apply review fixes - crates/compose/src/shape.rs --- crates/compose/src/shape.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 6932b4de2..cd7d42f60 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1082,16 +1082,16 @@ const SMALL_CAPS_SIZE: f64 = 0.7; static SMALL_CAPS_MISSING: RwLock> = RwLock::new(Vec::new()); /// How much a glyph shrinks when we draw its small caps: the lowercase letters of a Small Caps run, -/// every letter of All Small Caps, and nothing else. Only the glyph and its advance change — the +/// and nothing else. Only the glyph and its advance change — the /// line box is measured from the unscaled size, so turning it on never moves the leading. -fn small_caps_shrink(small: bool, all_small_caps: bool, ch: char) -> f64 { - if small && (all_small_caps || ch.is_lowercase()) { SMALL_CAPS_SIZE } else { 1.0 } +fn small_caps_shrink(small: bool, ch: char) -> f64 { + if small && ch.is_lowercase() { SMALL_CAPS_SIZE } else { 1.0 } } -/// Whether this run's small caps have to be drawn instead of taken from the font: the font's own -/// `smcp` is used whenever it has one. +/// Whether this run's Small Caps have to be drawn instead of taken from the font: the font's own +/// `smcp` is used whenever it has one. OpenType All Small Caps only applies a font's own small caps. fn small_caps_drawn_by_us(face: &FontFace, p: &CharProps) -> bool { - if !matches!(p.capitalization, Capitalization::SmallCaps | Capitalization::OpenTypeAllSmallCaps) { + if p.capitalization != Capitalization::SmallCaps { return false; } let id = face.id(); @@ -1286,7 +1286,7 @@ fn shape_segment( let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len()); Box::from(src.get(sg.cluster..end).unwrap_or("")) }); - let shrink = small_caps_shrink(small, p.capitalization == Capitalization::OpenTypeAllSmallCaps, ch); + let shrink = small_caps_shrink(small, src.get(sg.cluster..).and_then(|s| s.chars().next()).unwrap_or(ch)); // Upright: down the line is the shaper's -y, across it (text space -y) its x. let mut adv = if up { -(sg.y_advance as f64) * k_v * shrink } else { sg.x_advance as f64 * k * hs * shrink }; let (dx, dy) = if up { From 2a256668305bdc2e04dda58385723d5b3b3f56a8 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:31:50 -0600 Subject: [PATCH 047/133] Step and Repeat: a selected guide repeats along its own axis The command only knew about objects, so selecting a ruler guide left Edit > Step and Repeat greyed out. A guide selection now takes the same command: each copy moves along the axis the guide runs on, taking `dx` for a vertical guide and `dy` for a horizontal one, and the offset across it is ignored. Copies keep the guide's spread, page, layer, lock and liquid flags. A cell of the grid that only moves across the guide is skipped rather than dropped on top of the original, and a call whose offsets never move the guide is refused. Naming objects with `ids` still takes the object path, so a guide selected beside them is left untouched. --- crates/engine/src/cmd.rs | 6 ++ crates/engine/src/cmd/object.rs | 112 ++++++++++++++++++++++++++++++-- 2 files changed, 113 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index ed77b3319..38c13038c 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -142,6 +142,12 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; if s.active().is_some_and(|d| !d.selection.items.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) } } +/// Objects or ruler guides: Step and Repeat copies either, so a page with only a guide selected +/// keeps the command awake. +pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.active().is_some_and(|d| !d.selection.items.is_empty() || !d.selection.guides.is_empty()) { Ok(()) } else { Err(NOTHING_SELECTED.into()) } +} pub fn has_text(s: &Session) -> std::result::Result<(), String> { has_doc(s)?; if s.active().is_some_and(|d| d.selection.text.is_some()) { Ok(()) } else { Err("no text insertion point".into()) } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 634c90a61..a43c4245f 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -6,13 +6,15 @@ use std::sync::Arc; use designcraft_color::BlendMode; use designcraft_doc::{ - AssetId, Content, Document, Effects, Fill, Item, ItemId, ItemLoc, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, - TextFrameOptions, TextSel, + AssetId, Content, Document, Effects, Fill, Guide, GuideSel, Item, ItemId, ItemLoc, Orientation, ParaFormat, Selection, Shape, SpreadRef, Story, + StoryId, Stroke, TextFrame, TextFrameOptions, TextSel, }; use designcraft_geom::{Affine, Point, Rect, Vec2, shapes}; use serde_json::{Value, json}; -use super::{CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection, ok, point_param, rect_param, spread_param, str_param, targets}; +use super::{ + CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection_or_guides, ok, point_param, rect_param, spread_param, str_param, targets, +}; use crate::{Result, Session}; /// `name` must be a swatch of the document: an unknown name would paint nothing. The error names @@ -668,8 +670,8 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", - has_selection, + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied along its own axis and the offset across it is ignored; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + has_selection_or_guides, step_and_repeat ), cmd!("path.create", "Create Path", [], None, "{spread?, anchors: [{p:[x,y], in?:[x,y], out?:[x,y]}], closed?: bool}", has_doc, path_create), @@ -3668,6 +3670,57 @@ fn checked_step_offset(dx: f64, dy: f64, x: u64, y: u64) -> Result { Ok(Vec2::new(x, y)) } +/// Copies the selected ruler guides by `offsets`, moving each along its own axis and ignoring the +/// offset across it. `None` when nothing is selected but objects, so the object path reports it. +fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result> { + let picked = s.doc()?.selection.guides.clone(); + if picked.is_empty() { + return Ok(None); + } + picked + .len() + .checked_mul(offsets.len()) + .filter(|work| *work <= MAX_STEP_REPEAT_WORK) + .ok_or_else(|| bad("edit.stepAndRepeat", format!("a single command may create at most {MAX_STEP_REPEAT_WORK} guides")))?; + let src = s.doc()?.doc.clone(); + let mut plan = Vec::with_capacity(picked.len()); + for g in &picked { + let page = src.spread(g.spread).and_then(|sp| sp.pages.get(g.page)).ok_or_else(|| bad("edit.stepAndRepeat", "a selected guide is gone"))?; + let guide = page.guides.get(g.index).ok_or_else(|| bad("edit.stepAndRepeat", "a selected guide is gone"))?.clone(); + plan.push((*g, guide)); + } + s.edit(|d, sel| { + let mut made = Vec::new(); + for (at, guide) in &plan { + let sp = d.spread_mut(at.spread).ok_or_else(|| bad("edit.stepAndRepeat", "no such spread"))?; + let pg = sp.pages.get_mut(at.page).ok_or_else(|| bad("edit.stepAndRepeat", "no such page"))?; + for off in offsets { + let shift = match guide.orientation { + Orientation::Horizontal => off.y, + Orientation::Vertical => off.x, + }; + if shift == 0.0 { + continue; + } + let index = pg.guides.len(); + pg.guides.push(Guide { position: guide.position + shift, ..guide.clone() }); + made.push(GuideSel { spread: at.spread, page: at.page, index }); + } + } + if made.is_empty() { + return Err(bad( + "edit.stepAndRepeat", + "the offsets do not move the guide along its own axis: a horizontal guide takes `dy`, a vertical one `dx`", + )); + } + let mut all = picked.clone(); + all.extend(made.iter().copied()); + *sel = Selection { guides: all, ..Default::default() }; + let out: Vec = made.iter().map(|g| json!({"page": g.page, "index": g.index})).collect(); + Ok(json!({"created": out.len(), "guides": out})) + }) +} + fn step_repeat_offsets(p: &Value) -> Result> { let (dx, dy) = (step_repeat_delta(p, "dx", 12.0)?, step_repeat_delta(p, "dy", 12.0)?); match (p.get("rows"), p.get("columns")) { @@ -3744,6 +3797,15 @@ fn checked_step_repeat_targets(d: &Document, ids: &[ItemId], copies: usize, max_ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { let ids = targets(s, p)?; let offsets = step_repeat_offsets(p)?; + // No object was named and none is selected: a ruler guide may be, and it repeats along the + // axis it runs on — a horizontal guide only takes `dy`, a vertical one only `dx`. + if ids.is_empty() + && p.get("id").is_none() + && p.get("ids").is_none() + && let Some(out) = step_and_repeat_guides(s, &offsets)? + { + return Ok(out); + } let ids = checked_step_repeat_targets(&s.doc()?.doc, &ids, offsets.len(), MAX_STEP_REPEAT_WORK)?; s.edit(|d, sel| { let src = d.clone(); @@ -3998,6 +4060,46 @@ mod step_repeat_tests { assert!(s.execute("object.swapFillStroke", &json!({})).is_err(), "nothing unlocked to change"); } + #[test] + fn a_selected_guide_repeats_along_its_own_axis() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let positions = |s: &Session, o: Orientation| -> Vec { + s.doc().unwrap().doc.spreads[0].pages[0].guides.iter().filter(|g| g.orientation == o).map(|g| g.position).collect() + }; + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100.0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "a new guide is selected, as in InDesign"); + let r = s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 30.0, "dy": 999.0})).unwrap(); + assert_eq!(r["created"], 2); + assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 130.0, 160.0], "a vertical guide takes `dx` and ignores `dy`"); + assert_eq!(s.doc().unwrap().selection.guides.len(), 3, "the guide and its copies stay selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(positions(&s, Orientation::Vertical), vec![100.0], "one undo step"); + + s.execute("guide.add", &json!({"orientation": "horizontal", "position": 50.0})).unwrap(); + let r = s.execute("edit.stepAndRepeat", &json!({"rows": 2, "columns": 2, "dx": 99.0, "dy": 25.0})).unwrap(); + assert_eq!(r["created"], 2, "the cell that only moves across the guide is skipped"); + assert_eq!(positions(&s, Orientation::Horizontal), vec![50.0, 75.0, 75.0], "a horizontal guide takes `dy`"); + + // An offset that does not move the guide at all is refused rather than stacking a copy on it. + s.execute("guide.add", &json!({"orientation": "vertical", "position": 7.0})).unwrap(); + assert!(s.execute("edit.stepAndRepeat", &json!({"count": 3, "dy": 10.0})).is_err()); + assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 7.0]); + + // A copy of a spread guide stays a spread guide. + s.execute("guide.add", &json!({"orientation": "vertical", "position": 5.0, "spreadGuide": true})).unwrap(); + s.execute("edit.stepAndRepeat", &json!({"count": 1, "dx": 5.0})).unwrap(); + let copies: Vec = + s.doc().unwrap().doc.spreads[0].pages[0].guides.iter().filter(|g| g.position == 5.0 || g.position == 10.0).map(|g| g.spread).collect(); + assert_eq!(copies, vec![true, true]); + + // Naming objects keeps the object path: a guide selected beside them is left where it is. + let frame = s.execute("frame.create", &json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap(); + let before = s.doc().unwrap().doc.spreads[0].pages[0].guides.len(); + assert_eq!(s.execute("edit.stepAndRepeat", &json!({"ids": [frame], "count": 1, "dx": 20.0})).unwrap()["created"], 1); + assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].guides.len(), before, "the selected guide is untouched"); + } + #[test] fn step_repeat_validates_counts_and_offsets() { assert_eq!(step_repeat_offsets(&json!({"count": MAX_STEP_REPEAT_COPIES})).unwrap().len(), MAX_STEP_REPEAT_COPIES as usize); From 86c33e19d799937411f9d1ff1001900d3b596291 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:33:08 -0600 Subject: [PATCH 048/133] Step and Repeat: the object commands keep their own gate --- crates/engine/src/cmd/object.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a43c4245f..193df5365 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -13,7 +13,8 @@ use designcraft_geom::{Affine, Point, Rect, Vec2, shapes}; use serde_json::{Value, json}; use super::{ - CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection_or_guides, ok, point_param, rect_param, spread_param, str_param, targets, + CommandSpec, bad, bool_or, cmd, f64_or, has_doc, has_selection, has_selection_or_guides, ok, point_param, rect_param, spread_param, str_param, + targets, }; use crate::{Result, Session}; From 2e7d96f3fc7d32796d3abd8db34a1f9b4f468a53 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:33:44 -0600 Subject: [PATCH 049/133] Step and Repeat: the guide path returns what it made --- crates/engine/src/cmd/object.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 193df5365..5f1a5e208 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3720,6 +3720,7 @@ fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result = made.iter().map(|g| json!({"page": g.page, "index": g.index})).collect(); Ok(json!({"created": out.len(), "guides": out})) }) + .map(Some) } fn step_repeat_offsets(p: &Value) -> Result> { From 837afff2c07fce584b48a63b39848d0e155fadde Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 12:34:41 -0600 Subject: [PATCH 050/133] Step and Repeat: a vertical guide needs `dx: 0` to stand still, not an absent `dx` --- crates/engine/src/cmd/object.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 5f1a5e208..ab0b30e3d 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4085,7 +4085,7 @@ mod step_repeat_tests { // An offset that does not move the guide at all is refused rather than stacking a copy on it. s.execute("guide.add", &json!({"orientation": "vertical", "position": 7.0})).unwrap(); - assert!(s.execute("edit.stepAndRepeat", &json!({"count": 3, "dy": 10.0})).is_err()); + assert!(s.execute("edit.stepAndRepeat", &json!({"count": 3, "dx": 0.0, "dy": 10.0})).is_err()); assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 7.0]); // A copy of a spread guide stays a spread guide. From f3fbc26ce7a77d5a0dd4dc3b191a7a175d588753 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:53:35 +0000 Subject: [PATCH 051/133] Apply review fixes - crates/engine/src/cmd/guides.rs - crates/engine/src/cmd/object.rs --- crates/engine/src/cmd/guides.rs | 2 +- crates/engine/src/cmd/object.rs | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index 18826fb18..47b981013 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -165,7 +165,7 @@ fn finite_number(p: &Value, key: &str, command: &str) -> Result> { } /// `position` as a guide position: finite and within [`MAX_GUIDE_POSITION`] of the origin. -fn guide_position(position: f64, command: &str) -> Result { +pub(crate) fn guide_position(position: f64, command: &str) -> Result { if !position.is_finite() || position.abs() > MAX_GUIDE_POSITION { return Err(bad(command, format!("a guide position must be between -{MAX_GUIDE_POSITION} and {MAX_GUIDE_POSITION}"))); } diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index ab0b30e3d..0d8c82684 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -671,7 +671,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied along its own axis and the offset across it is ignored; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied along its own axis (the offset across it is ignored, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", has_selection_or_guides, step_and_repeat ), @@ -3704,7 +3704,8 @@ fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result Date: Sun, 8 Nov 2026 20:31:28 +0000 Subject: [PATCH 052/133] Fix kashidas: pick the join by Arabic typographic rules, not "after Fixes #2486. - crates/compose/src/lib.rs - crates/compose/tests/autocraft_regression_2486.rs --- crates/compose/src/lib.rs | 47 +++++++++++-- .../tests/autocraft_regression_2486.rs | 68 +++++++++++++++++++ 2 files changed, 109 insertions(+), 6 deletions(-) create mode 100644 crates/compose/tests/autocraft_regression_2486.rs diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index abac72985..b6d72db92 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4788,11 +4788,43 @@ fn joins_prev(c: char) -> bool { | 0x06C0 | 0x06C3..=0x06CB | 0x06CD | 0x06CF | 0x06D2 | 0x06D3) } -/// Where kashidas go on a line: one join per word, after a seen or sad when there is one, else the -/// word's last join (indices of the glyph before the join). +/// Arabic combining marks, which sit on a letter and never take part in a join. +fn is_arabic_mark(c: char) -> bool { + matches!(c as u32, 0x064B..=0x065F | 0x0670) +} + +/// Letters whose initial and medial forms are a tooth (ب ت ث ن ي ئ). +fn is_tooth(c: char) -> bool { + matches!(c as u32, 0x0626 | 0x0628 | 0x062A | 0x062B | 0x0646 | 0x064A) +} + +/// How well Arabic typography takes a kashida at the join of `g` and `n`, from 0 (best) to 4, or +/// `None` where one must not go. `prev` is the letter before `g` and `next` the one after `n`. +fn kashida_rank(prev: Option, g: char, n: char, next: Option) -> Option { + let medial = prev.is_some_and(joins_next); + let last = !(joins_next(n) && next.is_some_and(joins_prev)); + let forbidden = n == '\u{0648}' + || (last && matches!(n as u32, 0x0649 | 0x064A | 0x0646)) + || (is_tooth(g) && matches!(n as u32, 0x0635 | 0x0636 | 0x0639 | 0x063A | 0x0641 | 0x0642)) + || g == '\u{0643}' + || (g == '\u{0644}' && (!medial || matches!(n as u32, 0x0644 | 0x062F))); + if forbidden { + return None; + } + Some(match n as u32 { + 0x0629 | 0x0647 if last => 0, + 0x0627 if last => 1, + 0x0631 | 0x0632 => 2, + _ if !last && is_tooth(g) && is_tooth(n) => 3, + _ => 4, + }) +} + +/// Where kashidas go on a line: one join per word, the best by [`kashida_rank`] and the later in +/// the word among equals (indices of the glyph before the join). fn kashida_points(line: &[Glyph]) -> Vec { let mut out = Vec::new(); - let mut best: Option<(bool, usize)> = None; + let mut best: Option<(u8, usize)> = None; for (i, g) in line.iter().enumerate() { if g.is_space() { if let Some((_, k)) = best.take() { @@ -4812,9 +4844,12 @@ fn kashida_points(line: &[Glyph]) -> Vec { if !joins_next(g.ch) || !joins_prev(n.ch) || (g.ch == '\u{0644}' && matches!(n.ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}')) { continue; } - let seen = matches!(g.ch as u32, 0x0633..=0x0636); - if best.is_none_or(|(s, _)| !s || seen) { - best = Some((seen, i)); + let letter = |p: &&Glyph, cluster: &Glyph| p.byte != cluster.byte && !is_arabic_mark(p.ch); + let prev = line.get(..i).and_then(|l| l.iter().rev().find(|p| letter(p, g))).map(|p| p.ch); + let next = line.get(i + 2..).and_then(|l| l.iter().find(|p| letter(p, n))).map(|p| p.ch); + let Some(rank) = kashida_rank(prev, g.ch, n.ch, next) else { continue }; + if best.is_none_or(|(r, _)| rank <= r) { + best = Some((rank, i)); } } out.extend(best.map(|b| b.1)); diff --git a/crates/compose/tests/autocraft_regression_2486.rs b/crates/compose/tests/autocraft_regression_2486.rs new file mode 100644 index 000000000..8eedaf3a4 --- /dev/null +++ b/crates/compose/tests/autocraft_regression_2486.rs @@ -0,0 +1,68 @@ +//! Justified Arabic puts its one kashida per word at the join typography prefers, and none where +//! every join is forbidden (#2486). + +use std::collections::BTreeSet; + +use designcraft_compose::{ComposeOptions, compose_story}; +use designcraft_doc::build::NewDocument; +use designcraft_doc::{Align, Document, ParaAttrs, ParaFormat, SpreadRef, TextDirection}; +use designcraft_fonts::FontDb; +use designcraft_fonts::testing::font_mapping; +use designcraft_geom::Rect; + +const FAMILY: &str = "DC Kashida Rules"; + +/// Installs a font that draws every Arabic letter used below as a Latin letter, and the tatweel as +/// an underscore, so the test does not depend on the fonts of the machine. +fn install_font() { + let letters = "ابتثحدرزسصضعغفقكلمنهةوىي"; + let mut glyphs: Vec<(char, char)> = letters.chars().zip('a'..='z').collect(); + glyphs.extend([('\u{0640}', '_'), (' ', ' ')]); + FontDb::global().add_font(font_mapping(FAMILY, &glyphs).unwrap()); +} + +/// The positions (in letters) of the letters before which kashidas are drawn when `word`, repeated +/// on justified lines of several widths, is stretched. +fn kashida_letters(word: &str) -> BTreeSet { + let text = vec![word; 40].join(" "); + let mut found = BTreeSet::new(); + for width in (60..=140).step_by(4) { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + let para = ParaAttrs { align: Some(Align::RightJustified), direction: Some(TextDirection::RightToLeft), ..Default::default() }; + let rect = Rect::new(0.0, 0.0, f64::from(width), 800.0); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), rect, lid, &text, ParaFormat { para, ..Default::default() }).unwrap(); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + assert!(cs.frames[0].lines.len() > 2, "{word} at {width}"); + for g in cs.frames[0].lines.iter().flat_map(|l| &l.glyphs) { + if g.len == 0 && g.gid == g.face.glyph_for('\u{0640}') { + let start = text[..g.byte].rfind(' ').map_or(0, |s| s + 1); + found.insert(text[start..g.byte].chars().count()); + } + } + } + found +} + +#[test] +fn kashidas_follow_the_typographic_rules() { + install_font(); + let words = [ + ("تصوم", None), + ("نقود", None), + ("يوم", None), + ("لبني", Some(1)), + ("هين", Some(0)), + ("الكتاب", Some(3)), + ("مدرسة", Some(3)), + ("بكر", Some(0)), + ("بلد", Some(0)), + ("بتم", Some(0)), + ("بيت", Some(0)), + ("بنت", Some(0)), + ]; + for (word, expected) in words { + assert_eq!(kashida_letters(word), expected.into_iter().collect::>(), "{word}"); + } +} From 258b6d4a707e51f8b2025a0f2c1353678d463513 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:46:03 +0000 Subject: [PATCH 053/133] Apply review fixes - crates/compose/src/lib.rs --- crates/compose/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b6d72db92..44e04fff6 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4826,7 +4826,7 @@ fn kashida_points(line: &[Glyph]) -> Vec { let mut out = Vec::new(); let mut best: Option<(u8, usize)> = None; for (i, g) in line.iter().enumerate() { - if g.is_space() { + if g.is_space() || g.ch == '\t' || g.ch == story::RIGHT_INDENT_TAB { if let Some((_, k)) = best.take() { out.push(k); } From 8c8c7464b8ba15824ddbe1353a6d4a145b665eca Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:04:38 +0000 Subject: [PATCH 054/133] Apply review fixes - crates/compose/src/lib.rs - crates/compose/tests/autocraft_regression_2486.rs --- crates/compose/src/lib.rs | 2 +- crates/compose/tests/autocraft_regression_2486.rs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 44e04fff6..1e9f22a98 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4805,7 +4805,7 @@ fn kashida_rank(prev: Option, g: char, n: char, next: Option) -> Opt let last = !(joins_next(n) && next.is_some_and(joins_prev)); let forbidden = n == '\u{0648}' || (last && matches!(n as u32, 0x0649 | 0x064A | 0x0646)) - || (is_tooth(g) && matches!(n as u32, 0x0635 | 0x0636 | 0x0639 | 0x063A | 0x0641 | 0x0642)) + || (is_tooth(g) && matches!(n as u32, 0x0631 | 0x0632 | 0x0635 | 0x0636 | 0x0639 | 0x063A | 0x0641 | 0x0642)) || g == '\u{0643}' || (g == '\u{0644}' && (!medial || matches!(n as u32, 0x0644 | 0x062F))); if forbidden { diff --git a/crates/compose/tests/autocraft_regression_2486.rs b/crates/compose/tests/autocraft_regression_2486.rs index 8eedaf3a4..01ab607d7 100644 --- a/crates/compose/tests/autocraft_regression_2486.rs +++ b/crates/compose/tests/autocraft_regression_2486.rs @@ -61,6 +61,9 @@ fn kashidas_follow_the_typographic_rules() { ("بتم", Some(0)), ("بيت", Some(0)), ("بنت", Some(0)), + ("كبير", Some(1)), + ("تبر", Some(0)), + ("سير", Some(0)), ]; for (word, expected) in words { assert_eq!(kashida_letters(word), expected.into_iter().collect::>(), "{word}"); From a1eb160aac520d864286c6ed1f5f5e1f0044250f Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:46:50 -0600 Subject: [PATCH 055/133] Step and Repeat: a refused guide copy leaves nothing behind The position check refuses a copy that would land a guide past the guide range. Two copies are asked for where the first fits and the second does not; `Session::edit` only stores the document on success, so nothing of the first should remain either. The test now says so. --- crates/engine/src/cmd/object.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 0d8c82684..479873042 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4102,7 +4102,9 @@ mod step_repeat_tests { assert_eq!(s.execute("edit.stepAndRepeat", &json!({"ids": [frame], "count": 1, "dx": 20.0})).unwrap()["created"], 1); assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].guides.len(), before, "the selected guide is untouched"); s.execute("guide.add", &json!({"orientation": "vertical", "position": 999_990.0})).unwrap(); - assert!(s.execute("edit.stepAndRepeat", &json!({"count": 1, "dx": 20.0})).is_err(), "a copy past the guide range is refused"); + let antes = positions(&s, Orientation::Vertical); + assert!(s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 10.0})).is_err(), "a copy past the guide range is refused"); + assert_eq!(positions(&s, Orientation::Vertical), antes, "the first copy fitted and the second did not: neither is left behind"); } #[test] From c8dcc53b333ce30a4884b5a8501fa6ecc0919639 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 03:59:44 +0000 Subject: [PATCH 056/133] Apply review fixes - crates/engine/src/cmd/object.rs --- crates/engine/src/cmd/object.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 479873042..23dc1ab56 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -671,7 +671,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied along its own axis (the offset across it is ignored, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", has_selection_or_guides, step_and_repeat ), @@ -3671,8 +3671,9 @@ fn checked_step_offset(dx: f64, dy: f64, x: u64, y: u64) -> Result { Ok(Vec2::new(x, y)) } -/// Copies the selected ruler guides by `offsets`, moving each along its own axis and ignoring the -/// offset across it. `None` when nothing is selected but objects, so the object path reports it. +/// Copies the selected ruler guides by `offsets`, moving a vertical guide by the offsets' x and a +/// horizontal one by their y, ignoring the other. `None` when nothing is selected but objects, so +/// the object path reports it. fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result> { let picked = s.doc()?.selection.guides.clone(); if picked.is_empty() { @@ -3800,8 +3801,8 @@ fn checked_step_repeat_targets(d: &Document, ids: &[ItemId], copies: usize, max_ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { let ids = targets(s, p)?; let offsets = step_repeat_offsets(p)?; - // No object was named and none is selected: a ruler guide may be, and it repeats along the - // axis it runs on — a horizontal guide only takes `dy`, a vertical one only `dx`. + // No object was named and none is selected: a ruler guide may be, and it repeats across + // its own line — a horizontal guide only takes `dy`, a vertical one only `dx`. if ids.is_empty() && p.get("id").is_none() && p.get("ids").is_none() From 60e5e8192504ab207fd61808d6ecb803147026cc Mon Sep 17 00:00:00 2001 From: con3code Date: Wed, 11 Nov 2026 09:23:01 +0900 Subject: [PATCH 057/133] =?UTF-8?q?i18n:=20Japanese=20names=20Inches=20Dec?= =?UTF-8?q?imal=20=E3=83=87=E3=82=B7=E3=83=9E=E3=83=AB=E3=82=A4=E3=83=B3?= =?UTF-8?q?=E3=83=81,=20as=20InDesign=20does=20(#1363)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/table.rs | 2 +- crates/ui-egui/src/i18n/tests.rs | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ae2dd653f..1e758c31d 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -95,7 +95,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Corners:", "角:"), ("Sharp", "シャープ"), ("Diffused", "拡散"), - ("Inches Decimal", "インチ(10 進)"), + ("Inches Decimal", "デシマルインチ"), ("Back", "戻る"), ("Warning", "警告"), ("Don't show again", "今後表示しない"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index ebde2b629..209c0426a 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -213,7 +213,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Join", ["Join", "Joindre", "Unir", "Join", "连接"]), ("Convert Point", ["Convert Point", "Convertir le point", "Convertir punto", "Convert Point", "转换点"]), ("Hide Rulers", ["Lineale ausblenden", "Masquer les règles", "Ocultar reglas", "定規を隠す", "隐藏标尺"]), - ("Inches Decimal", ["Zoll dezimal", "Pouces décimaux", "Pulgadas decimales", "インチ(10 進)", "十进制英寸"]), + ("Inches Decimal", ["Zoll dezimal", "Pouces décimaux", "Pulgadas decimales", "デシマルインチ", "十进制英寸"]), ( "Paste Vector Art", ["Vektorgrafik einfügen", "Coller l’illustration vectorielle", "Pegar ilustración vectorial", "ベクトルアートをペースト", "粘贴矢量图稿"], diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f873e5b8a..ca7323bcf 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -604,3 +604,9 @@ fn czech_counts_use_the_plural_form_for_the_number() { // A noun without plural forms keeps the plain translation. assert_eq!(count_label("cs", "a new noun", 3), "3 a new noun"); } + +#[test] +fn japanese_names_decimal_inches_as_indesign_does() { + // InDesign's Japanese unit lists (Preferences › Units & Increments) read デシマルインチ. + assert_eq!(tr("ja", designcraft_geom::units::Unit::InchesDecimal.label()), "デシマルインチ"); +} From 368315bdb05898bbd6599b73ba32e7f9a7b20bbd Mon Sep 17 00:00:00 2001 From: con3code Date: Wed, 11 Nov 2026 23:23:55 +0900 Subject: [PATCH 058/133] i18n: record the Japanese unit names InDesign shows (#1363) --- docs/localization-parity.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index b1b55d2fa..5a29ebb0a 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-04 · **Change:** minor (pt-BR catalog filled; Russian listed; Esperanto text language; Hungarian interface catalog, bundled-font coverage and flyout regression checks; Swedish interface) · **Target:** Adobe InDesign 2026 (21.6) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-11 · **Change:** minor (pt-BR catalog filled; Russian listed; Esperanto text language; Hungarian interface catalog, bundled-font coverage and flyout regression checks; Swedish interface) · **Target:** Adobe InDesign 2026 (21.6) Per-language status of the DesignCraft interface and of document typesetting in each script. Script-specific typesetting detail: [cjk.md](cjk.md), [cjk-typography.md](cjk-typography.md), @@ -54,6 +54,11 @@ caption, table row/column movement and row-height distribution now use the exist catalog. Print, import options and an active table were rendered in Japanese and English with craft-fonts. The language totals above retain their dated measurement; this is a targeted fix. +Japanese unit names (2026-11-11): InDesign 2025's Japanese Preferences › Units & Increments lists +the ruler units as ポイント, パイカ, インチ, デシマルインチ, ミリメートル, センチメートル, シセロ, +アゲート, ピクセル and 歯, and offers 級 for text size (observed in the app). Inches Decimal now reads +デシマルインチ (#1363); the other names are in #1507. + Hungarian interface (2026-11-01): `hu.rs` contains **1,906 entries and four context-specific captions**, including all 37 tool names. The initial catalog was prepared with AI assistance and personally reviewed in the app by **Veress Róbert**, a native Hungarian speaker with over @@ -127,6 +132,7 @@ German variants have no automatic hyphenation; their German shaping and quotes a | Date | Change | Summary | |---|---|---| +| 2026-11-11 | trivial | Japanese unit names as InDesign's Japanese interface shows them; Inches Decimal is デシマルインチ | | 2026-11-04 | minor | pt-BR catalog filled (996 strings and the unit names; path is "demarcador"): 2,936 of 2,939 strings by `i18n-report`, pt-BR to full 8–12 → 1–2 h; Russian (1,855) listed, eight languages beyond the twelve | | 2026-11-01 | minor | Initial Hungarian interface: 1,906 entries, four context captions, native review, bundled-font glyph coverage and wide/narrow flyout regressions | | 2026-10-11 | minor | Localized Japanese print, import and table controls; checked Japanese and English renders | From a9796a69c0414e36ff26e0a24a3792a85809938e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 23:43:37 +0000 Subject: [PATCH 059/133] Fonts: a glyph outline is capped at 262,144 path elements --- crates/fonts/src/fontdb.rs | 29 ++++++++++++++++++++++++----- crates/fonts/src/fontdb/outline.rs | 11 ++++++++++- crates/fonts/src/fontdb/tests.rs | 15 +++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index 6e145ade0..e67307010 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -150,21 +150,40 @@ use system::unix_font_dirs; use system::{CatalogEntry, FileStamp}; pub use system::{ReloadedFonts, system_font_dirs}; +impl FlipPen { + /// Room for one more path element. A glyph that expands past [`outline::MAX_OUTLINE_ELEMENTS`] + /// (a variable-font composite repeating a complex base) stops growing here, and + /// [`outline::font_outline`] then returns no outline rather than a truncated one. + fn has_room(&self) -> bool { + self.0.elements().len() < outline::MAX_OUTLINE_ELEMENTS + } +} + impl OutlinePen for FlipPen { fn move_to(&mut self, x: f32, y: f32) { - self.0.move_to((x as f64, -y as f64)); + if self.has_room() { + self.0.move_to((x as f64, -y as f64)); + } } fn line_to(&mut self, x: f32, y: f32) { - self.0.line_to((x as f64, -y as f64)); + if self.has_room() { + self.0.line_to((x as f64, -y as f64)); + } } fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) { - self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); + if self.has_room() { + self.0.quad_to((cx0 as f64, -cy0 as f64), (x as f64, -y as f64)); + } } fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) { - self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); + if self.has_room() { + self.0.curve_to((cx0 as f64, -cy0 as f64), (cx1 as f64, -cy1 as f64), (x as f64, -y as f64)); + } } fn close(&mut self) { - self.0.close_path(); + if self.has_room() { + self.0.close_path(); + } } } diff --git a/crates/fonts/src/fontdb/outline.rs b/crates/fonts/src/fontdb/outline.rs index 30e328be4..e6ed7a68d 100644 --- a/crates/fonts/src/fontdb/outline.rs +++ b/crates/fonts/src/fontdb/outline.rs @@ -48,7 +48,12 @@ pub(super) fn has_serifs(face: &FontFace) -> Option { Some(foot > stem * 1.6) } -/// Glyph `gid`'s outline as the font draws it, in font units, y-down (flipped). +/// Most path elements one glyph's outline may hold: ten times what the largest real glyphs use, +/// so only a font that repeats a complex base component past all reason reaches it. +pub(super) const MAX_OUTLINE_ELEMENTS: usize = 1 << 18; + +/// Glyph `gid`'s outline as the font draws it, in font units, y-down (flipped). A glyph past +/// [`MAX_OUTLINE_ELEMENTS`] has no outline (a truncated one would be a wrong glyph). pub(super) fn font_outline(face: &FontFace, gid: u32) -> BezPath { let mut pen = FlipPen(BezPath::new()); if let Some(f) = face.skrifa() @@ -56,6 +61,10 @@ pub(super) fn font_outline(face: &FontFace, gid: u32) -> BezPath { { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen); } + if !pen.has_room() { + log::warn!("glyph {gid} has more than {MAX_OUTLINE_ELEMENTS} path elements: drawn empty"); + return BezPath::new(); + } pen.0 } diff --git a/crates/fonts/src/fontdb/tests.rs b/crates/fonts/src/fontdb/tests.rs index 6417b340a..d3e5b4865 100644 --- a/crates/fonts/src/fontdb/tests.rs +++ b/crates/fonts/src/fontdb/tests.rs @@ -8,3 +8,18 @@ mod fallback; mod docfonts; mod vertical; + +/// A glyph that keeps drawing past the element cap stops growing the path, and says so. +#[test] +fn the_outline_pen_stops_at_the_element_cap() { + use super::outline::MAX_OUTLINE_ELEMENTS; + use super::{BezPath, FlipPen, OutlinePen}; + let mut pen = FlipPen(BezPath::new()); + pen.move_to(0.0, 0.0); + for i in 0..MAX_OUTLINE_ELEMENTS + 10 { + pen.line_to(i as f32, 0.0); + } + pen.close(); + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS); + assert!(!pen.has_room()); +} From 93155fce49b91ec7f1d8e13de66e50b60b278e02 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 12 Nov 2026 11:51:43 +0500 Subject: [PATCH 060/133] Fonts: a legacy family name that finds another face is a style substitute font.list called "Source Serif 4 Semibold" "Regular" exact while the text drew in Source Serif 4 Regular: the face lookup takes a face's legacy family name (name ID 1) to its typographic family and looks the style up there, and has_style only compared the style names. It now also asks that the face found be one the family name names (its family, a family alias, its WWS family, or an alternate spelling such as "(OTF)"), so font.list, preflight and the text-format warnings report the substitute. The typographic names stay exact. Fixes #2618 --- crates/engine/src/cmd/fonts.rs | 34 +++++++++++++++++++++++++++++++ crates/fonts/src/fontdb/scoped.rs | 8 ++++++++ 2 files changed, 42 insertions(+) diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index 8d78e4b4a..f759fd5d1 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -554,4 +554,38 @@ mod resolution_tests { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(before, s.execute("font.list", &json!({})).unwrap()); } + + /// #2618: a face's legacy family name with a style it doesn't have (`Source Serif 4 + /// Semibold` `Regular`, which the lookup takes to Source Serif 4 Regular) is a substitute, + /// not exact; the typographic name and an alternate spelling of it stay exact. + #[test] + fn a_legacy_family_name_resolving_to_another_face_is_a_style_substitute() { + let status = |family: &str, style: &str| { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("frame.create", &json!({"rect":[20,20,300,400],"content":"text","text":"Body"})).unwrap(); + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let sid = *d.stories.keys().next().unwrap(); + d.story_mut(sid).unwrap().format_chars(0..4, |f| { + f.over.font_family = Some(family.into()); + f.over.font_style = Some(style.into()); + }); + let list = s.execute("font.list", &json!({})).unwrap(); + let font = list.as_array().unwrap().iter().find(|f| f["family"] == family).cloned().unwrap(); + let preflight = s.execute("preflight.run", &json!({})).unwrap(); + let flagged = preflight["issues"].as_array().unwrap().iter().any(|i| i["kind"] == "missingFontStyle"); + (font, flagged) + }; + let (font, flagged) = status("Source Serif 4 Semibold", "Regular"); + assert_eq!((font["resolvedFamily"].as_str(), font["resolvedStyle"].as_str()), (Some("Source Serif 4"), Some("Regular")), "{font}"); + assert_eq!(font["matchStatus"], "styleSubstitute", "{font}"); + assert_eq!(font["styleMissing"], true); + assert_eq!(font["missing"], false); + assert!(flagged, "preflight reports the substituted style"); + for (family, style) in [("Source Serif 4", "Semibold"), ("Source Serif 4 (OTF)", "Semibold"), ("Source Serif 4", "Regular")] { + let (font, flagged) = status(family, style); + assert_eq!(font["matchStatus"], "exact", "{family} {style}: {font}"); + assert!(!flagged, "{family} {style}"); + } + } } diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index 358189186..17b9c63a3 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -62,6 +62,14 @@ impl ScopedFonts<'_> { return false; } let face = self.face(family, style); + // The face found must be one `family` names. `face` takes a face's legacy family name + // (`Source Serif 4 Semibold`, name ID 1) to its typographic family and looks the style up + // there, so `Source Serif 4 Semibold` `Regular` finds Source Serif 4 Regular: another + // face, which Find Font and preflight called exact (#2618). + let names = |f: &str| f.eq_ignore_ascii_case(&face.family) || face.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(f)); + if !std::iter::once(family).chain(alternate_names(family)).any(names) { + return face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == norm(style)); + } norm(&face.style) == norm(style) || (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == norm(style))) // An optical-size face asked for by its WWS names. From 8a5e8b1c1400cac540fbb4dec6ad4ca5ab76ad25 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:21:56 +0000 Subject: [PATCH 061/133] Apply review fixes - crates/fonts/src/fontdb/scoped.rs --- crates/fonts/src/fontdb/scoped.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index 17b9c63a3..e83e96a1e 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -67,13 +67,16 @@ impl ScopedFonts<'_> { // there, so `Source Serif 4 Semibold` `Regular` finds Source Serif 4 Regular: another // face, which Find Font and preflight called exact (#2618). let names = |f: &str| f.eq_ignore_ascii_case(&face.family) || face.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(f)); + let wws_named = |w: &(String, String)| { + std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f)) && norm(&w.1) == norm(style) + }; if !std::iter::once(family).chain(alternate_names(family)).any(names) { - return face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == norm(style)); + return face.wws.as_ref().is_some_and(wws_named); } norm(&face.style) == norm(style) || (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == norm(style))) // An optical-size face asked for by its WWS names. - || face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == norm(style)) + || face.wws.as_ref().is_some_and(wws_named) } /// Prefer known metric-compatible substitutes, then an appropriate script family. This From d5c302401e28851a9e875958b23c857a3a635c55 Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:44:35 +0000 Subject: [PATCH 062/133] Apply review fixes - crates/fonts/src/fontdb/scoped.rs --- crates/fonts/src/fontdb/scoped.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index e83e96a1e..5cb414298 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -68,7 +68,7 @@ impl ScopedFonts<'_> { // face, which Find Font and preflight called exact (#2618). let names = |f: &str| f.eq_ignore_ascii_case(&face.family) || face.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(f)); let wws_named = |w: &(String, String)| { - std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f)) && norm(&w.1) == norm(style) + std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f)) && norm(&w.1) == norm(base_style(style)) }; if !std::iter::once(family).chain(alternate_names(family)).any(names) { return face.wws.as_ref().is_some_and(wws_named); From 85098772b110362ae4623fa6a23b092e15795f41 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 12 Nov 2026 14:50:39 +0500 Subject: [PATCH 063/133] Fonts: a style with axis settings matches a WWS style by name only on an instance The WWS comparison now takes the style's base name (Regular of Regular {wght:650}), so a variable face's instance matches; on a static face, which draws without the settings, that style is not there. --- crates/fonts/src/fontdb/scoped.rs | 7 ++++++- crates/fonts/src/fontdb/tests/docfonts.rs | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index 5cb414298..086f80b3f 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -67,8 +67,13 @@ impl ScopedFonts<'_> { // there, so `Source Serif 4 Semibold` `Regular` finds Source Serif 4 Regular: another // face, which Find Font and preflight called exact (#2618). let names = |f: &str| f.eq_ignore_ascii_case(&face.family) || face.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(f)); + // A style with axis settings (`Regular {wght:650}`) matches by its base name only on a + // face those settings apply to (an instance); a static face draws without them. + let axes_apply = !style.contains('{') || !face.coords.is_empty(); let wws_named = |w: &(String, String)| { - std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f)) && norm(&w.1) == norm(base_style(style)) + std::iter::once(family).chain(alternate_names(family)).any(|f| w.0.eq_ignore_ascii_case(f)) + && norm(&w.1) == norm(base_style(style)) + && axes_apply }; if !std::iter::once(family).chain(alternate_names(family)).any(names) { return face.wws.as_ref().is_some_and(wws_named); diff --git a/crates/fonts/src/fontdb/tests/docfonts.rs b/crates/fonts/src/fontdb/tests/docfonts.rs index 0b7886f44..14e698f72 100644 --- a/crates/fonts/src/fontdb/tests/docfonts.rs +++ b/crates/fonts/src/fontdb/tests/docfonts.rs @@ -227,6 +227,8 @@ fn a_wws_family_that_is_also_the_legacy_family_finds_the_optical_size_face() { assert_eq!(fonts.face("DocFont Kepler Display", "Light").style, "Light Display", "the display face, not the text size"); assert_eq!(fonts.styles("DocFont Kepler Display"), ["Light"]); assert!(fonts.has_style("DocFont Kepler Display", "Light")); + // Axis settings on a static face aren't applied, so that style isn't there (#2672 review). + assert!(!fonts.has_style("DocFont Kepler Display", "Light {wght:650}")); assert_eq!(fonts.face("DocFont Kepler", "Light").style, "Light"); let _ = std::fs::remove_dir_all(&folder); } From 788bb42c566f97ff38dd00adbf19aa8810da8164 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:27:55 +0100 Subject: [PATCH 064/133] Styles: test what a character Running Header shows after its style is deleted for [None] (#1794) --- crates/engine/src/cmd/style/paragraph.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/cmd/style/paragraph.rs b/crates/engine/src/cmd/style/paragraph.rs index 034515048..2c56c9d9a 100644 --- a/crates/engine/src/cmd/style/paragraph.rs +++ b/crates/engine/src/cmd/style/paragraph.rs @@ -1128,6 +1128,13 @@ mod delete_tests { } } + /// What the Running Header variable `name` shows on the first page. + fn header_text(s: &Session, name: &str) -> String { + let d = s.doc().unwrap().doc.clone(); + let values = designcraft_compose::vars::values(&d, Some(0), Some(&s.cache.running_index(&d))); + values[d.variable(name).unwrap()].clone() + } + /// A document whose character style `Emphasis` is used everywhere one can be: as a based-on /// parent, on text, in a paragraph style's and a paragraph's nested, nested line, GREP, drop /// cap, bullet and number styles, as the footnote reference style, the default character @@ -1193,10 +1200,18 @@ mod delete_tests { assert_eq!(s.doc().unwrap().doc.styles.para("Lead").unwrap().para.bullet_char_style.as_deref(), Some("Emphasis")); } + /// Deleting with no replacement points every use at `[None]`, a character Running Header too, + /// as InDesign does. Such a header then picks up text with no character style, as one defined + /// with `[None]` does in InDesign: a Last on Page header that showed the styled `Hi` now shows + /// the unstyled `there` after it. #[test] fn deleting_a_character_style_for_none_unsets_based_on() { let (mut s, _) = char_doc(); + let last = json!({"name": "Last", "type": "runningHeader", "style": "Emphasis", "character": true, "use": "lastOnPage"}); + s.execute("variables.define", &last).unwrap(); + assert_eq!((header_text(&s, "Term"), header_text(&s, "Last")), ("Hi".into(), "Hi".into())); s.execute("style.character.delete", &json!({"name": "Emphasis"})).unwrap(); + assert_eq!(header_text(&s, "Last"), "there", "the header shows the last unstyled text on the page"); assert!(!named(&s, "Emphasis"), "no dangling reference"); let d = s.doc().unwrap().doc.clone(); assert_eq!(d.styles.char_style("Child").unwrap().based_on, None); From 9d885c9bf6fd59b25f5cd5bf2520fe5263519a0c Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 12 Nov 2026 21:14:23 +0000 Subject: [PATCH 065/133] Fonts: Reload Fonts finds a style installed after its family was loaded (#2617) A family already in use resolved a newly installed style to its closest loaded style, because the catalog was only read when no face of the family was loaded. When only another style is loaded, the installed files with the asked style are now loaded, once per scan of the font folders. --- crates/fonts/src/fontdb.rs | 5 ++++ crates/fonts/src/fontdb/db.rs | 2 ++ crates/fonts/src/fontdb/scoped.rs | 16 +++++++++++ crates/fonts/src/fontdb/system.rs | 35 +++++++++++++++++++++++ crates/fonts/src/fontdb/tests/sysfonts.rs | 21 ++++++++++++++ 5 files changed, 79 insertions(+) diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs index 6e145ade0..4bcda5390 100644 --- a/crates/fonts/src/fontdb.rs +++ b/crates/fonts/src/fontdb.rs @@ -92,6 +92,11 @@ pub struct FontDb { /// when it was read: [`FontDb::reload_fonts`] reads again the files that changed since. #[cfg(not(target_arch = "wasm32"))] installed_files: Mutex>, + /// The (family, style) pairs, lowercased, looked for in the catalog because the loaded faces + /// lack that style: each is looked for once per scan of the font folders (see + /// [`FontDb::load_cataloged_style`]). + #[cfg(not(target_arch = "wasm32"))] + styles_tried: Mutex>, /// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] font_dirs: Vec, diff --git a/crates/fonts/src/fontdb/db.rs b/crates/fonts/src/fontdb/db.rs index 224098a6a..4c98d7b96 100644 --- a/crates/fonts/src/fontdb/db.rs +++ b/crates/fonts/src/fontdb/db.rs @@ -56,6 +56,8 @@ impl FontDb { catalog: RwLock::new(Vec::new()), #[cfg(not(target_arch = "wasm32"))] installed_files: Mutex::new(HashMap::new()), + #[cfg(not(target_arch = "wasm32"))] + styles_tried: Mutex::new(std::collections::HashSet::new()), font_dirs, font_files: Vec::new, #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/fonts/src/fontdb/scoped.rs b/crates/fonts/src/fontdb/scoped.rs index 358189186..dc9c3d53b 100644 --- a/crates/fonts/src/fontdb/scoped.rs +++ b/crates/fonts/src/fontdb/scoped.rs @@ -258,6 +258,12 @@ impl ScopedFonts<'_> { fn find_or_load(&self, family: &str, style: &str) -> Option> { if let Some(f) = self.find(family, style) { + // Only another style of the family is loaded: the asked one may have been installed + // since the family was loaded (#2617). + #[cfg(not(target_arch = "wasm32"))] + if !style.contains('{') && !Self::is_style(&f, family, style) && self.db.load_cataloged_style(family, style) { + return self.find(family, style); + } return Some(f); } #[cfg(not(target_arch = "wasm32"))] @@ -267,6 +273,16 @@ impl ScopedFonts<'_> { None } + /// Is `face`, found for `family`, the `style` asked for (by its own, a localized or its WWS + /// style name), not the closest of another style? + #[cfg(not(target_arch = "wasm32"))] + fn is_style(face: &FontFace, family: &str, style: &str) -> bool { + let ns = norm(style); + norm(&face.style) == ns + || (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == ns)) + || face.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == ns) + } + /// The family and style of the face whose PostScript name is `name`, ignoring case (the /// document's, loaded, or installed on the system, not loading it). SVGs exported from /// Illustrator name fonts this way (`font-family="'MyriadPro-Regular'"`). diff --git a/crates/fonts/src/fontdb/system.rs b/crates/fonts/src/fontdb/system.rs index 84916807e..5f501e63f 100644 --- a/crates/fonts/src/fontdb/system.rs +++ b/crates/fonts/src/fontdb/system.rs @@ -328,6 +328,9 @@ impl FontDb { sys.chain_tried.clear(); sys.coverage.clear(); sys.coverage_ranges = 0; + drop(sys); + // Styles installed since their family was loaded can now be found (#2617). + self.styles_tried.lock().unwrap_or_else(PoisonError::into_inner).clear(); count } @@ -461,6 +464,38 @@ impl FontDb { self.insert_faces(faces) > 0 } + /// Load the installed files that hold `style` of `family` (by its typographic or WWS names), + /// for a family loaded before that style was installed (#2617). Each family and style is + /// looked for once per scan of the font folders, so a style that isn't installed costs one + /// catalog search. Returns whether any face was added. + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn load_cataloged_style(&self, family: &str, style: &str) -> bool { + let ns = norm(style); + let paths: Vec = { + // Held while the catalog is read: a rescan clears it only after its catalog is in. + let mut tried = self.styles_tried.lock().unwrap_or_else(PoisonError::into_inner); + if !tried.insert((family.to_lowercase(), ns.clone())) { + return false; + } + let cat = self.read_catalog(); + let named = |c: &CatalogEntry| { + (c.family.eq_ignore_ascii_case(family) && norm(&c.style) == ns) + || c.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family) && norm(&w.1) == ns) + }; + let mut p: Vec<_> = cat.iter().filter(|c| named(c)).map(|c| c.path.clone()).collect(); + p.sort(); + p.dedup(); + p + }; + let mut faces = Vec::new(); + for p in paths { + if let Some(data) = self.read_installed(&p) { + faces.extend(self.new_faces(data, FontSource::Installed(p))); + } + } + self.insert_faces(faces) > 0 + } + /// Load the font files (.ttf, .otf, .ttc, .otc; not in subfolders) of a document's `Document /// Fonts` folder under a new scope, for that document alone: looked up through /// [`FontDb::scoped`], they come before the shared faces of the same family and style, until diff --git a/crates/fonts/src/fontdb/tests/sysfonts.rs b/crates/fonts/src/fontdb/tests/sysfonts.rs index 0485ac7aa..2824f6464 100644 --- a/crates/fonts/src/fontdb/tests/sysfonts.rs +++ b/crates/fonts/src/fontdb/tests/sysfonts.rs @@ -165,6 +165,27 @@ fn rescanning_finds_fonts_installed_since() { assert!(db.has_family(FAMILY) && has(&db.families(), FAMILY)); } +#[test] +fn reloading_finds_a_style_installed_since_its_family_was_loaded() { + // #2617: the family's Regular is in use; its Bold is installed while the app runs. + let dir = font_dir("new-style"); + let later = dir.join("Later"); + std::fs::create_dir_all(&later).unwrap(); + std::fs::copy(dir.join("Sysfont-Regular.ttf"), later.join("Sysfont-Regular.ttf")).unwrap(); + let db = FontDb::with_font_dirs(vec![later.clone()]); + assert_eq!(db.face(FAMILY, "Regular").style, "Regular"); + assert!(db.is_loaded(FAMILY)); + assert!(!db.scoped(0).has_style(FAMILY, "Bold")); + std::fs::copy(dir.join("Sub/Sysfont-Bold.TTF"), later.join("Sysfont-Bold.ttf")).unwrap(); + assert_eq!(db.reload_fonts().cataloged, 2); + assert_eq!(db.face(FAMILY, "Bold").style, "Bold"); + assert!(db.scoped(0).has_style(FAMILY, "Bold")); + assert_eq!(db.face(FAMILY, "Regular").style, "Regular"); + // A style still missing is the closest one, as before. + assert_eq!(db.face(FAMILY, "Light").style, "Regular"); + assert!(!db.scoped(0).has_style(FAMILY, "Light")); +} + #[test] fn a_background_scan_serves_the_first_lookup() { let dir = font_dir("background"); From 62df51ccfc54114e8351e9635a91911c89817414 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Fri, 13 Nov 2026 11:27:24 +0000 Subject: [PATCH 066/133] PDF/X-1a: an RGB colour converts with black point compensation when the colour settings have it on (#2570) The flattener converts the RGB left in the PDF/X-4 print file without black point compensation, so the Color Settings checkbox changed nothing in PDF/X-1a. With it on, the exporter now converts RGB process colours into the output intent's CMYK itself, relative colorimetric with black point compensation; the flattener leaves DeviceCMYK as it is. --- crates/pdf/src/export.rs | 4 +++ crates/pdf/src/export/booklet.rs | 1 + crates/pdf/src/export/common.rs | 15 +++++++++-- crates/pdf/src/export/images.rs | 1 + crates/pdf/src/export/pipeline.rs | 19 +++++++++++--- crates/pdf/src/pdfx.rs | 10 +++++++ crates/pdf/src/pdfx1a.rs | 31 ++++++++++++++++++++++ crates/pdf/src/x1a_tests.rs | 43 +++++++++++++++++++++++++++++++ 8 files changed, 119 insertions(+), 5 deletions(-) diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index e4fa19e5c..5e9c204d4 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -45,6 +45,8 @@ use images::ConstantImageHasher; pub(crate) use images::SRGB_ICC; use images::{CmykImage, GreyImage, ImageContentCache, RasterMode, SrgbImage, embedded_icc, is_grey, is_grey_icc}; pub(crate) use metadata::civil; +#[cfg(test)] +pub(crate) use pipeline::export_pdf_with_cms; pub(crate) use pipeline::{MARK_LEN, Sheet, exported_items, mark_start}; pub use pipeline::{ drawn_children, export_pdf, export_pdf_with_report, item_exported, layer_exported, print_color, sheet_spreads, shown_parent_items, @@ -93,6 +95,8 @@ pub(crate) struct Exporter<'a> { pub reverse_cmaps: HashMap>>, /// Convert CMYK to RGB (PDF/A: krilla needs a CMYK output profile we don't ship yet). pub rgb_only: bool, + /// PDF/X-1a: RGB process colours converted here with black point compensation. + pub(crate) x1a_process: Option, /// Tagged PDF: the structure in reading order (stories gather their frames' content). tags: Vec, story_tags: HashMap>, diff --git a/crates/pdf/src/export/booklet.rs b/crates/pdf/src/export/booklet.rs index bc2138623..d72d3e9a1 100644 --- a/crates/pdf/src/export/booklet.rs +++ b/crates/pdf/src/export/booklet.rs @@ -119,6 +119,7 @@ fn export_booklet_inner(doc: &Document, cache: &Cache, opts: &BookletOptions) -> fonts: HashMap::new(), reverse_cmaps: HashMap::new(), rgb_only: false, + x1a_process: None, tags: Vec::new(), story_tags: HashMap::new(), tag_story: None, diff --git a/crates/pdf/src/export/common.rs b/crates/pdf/src/export/common.rs index 53bcf8165..fd90415a4 100644 --- a/crates/pdf/src/export/common.rs +++ b/crates/pdf/src/export/common.rs @@ -153,7 +153,7 @@ impl Exporter<'_> { self.doc.swatch(ink).filter(|w| matches!(w.value, SwatchValue::Color { color_type: ColorType::Spot, .. })).unwrap_or(sw); let SwatchValue::Color { color, .. } = &target.value else { break }; if process { - return Some(device(&designcraft_color::swatch::apply_tint(*color, t), self.rgb_only)); + return Some(self.process(&designcraft_color::swatch::apply_tint(*color, t))); } let space = SeparationSpace::new(SeparationColorant::Custom(target.name.clone()), regular(color, self.rgb_only)); return Some(SepColor::new(q(t), space).into()); @@ -161,6 +161,17 @@ impl Exporter<'_> { _ => break, } } - self.doc.resolve_color(name, tint).map(|c| device(&c, self.rgb_only)) + self.doc.resolve_color(name, tint).map(|c| self.process(&c)) + } + + /// A process colour in its own device space, except RGB in PDF/X-1a with black point + /// compensation: converted here into CMYK with it, as the flattener would convert it without. + fn process(&self, c: &Color) -> krilla::color::Color { + if let (Some(conversion), Color::Rgb { r, g, b }) = (&self.x1a_process, *c) + && let Some([c, m, y, k]) = conversion.cmyk([q(r), q(g), q(b)]) + { + return device(&Color::cmyk(c, m, y, k), self.rgb_only); + } + device(c, self.rgb_only) } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index b50c6b20a..2b6452de6 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -241,6 +241,7 @@ mod image_content_cache_tests { fonts: HashMap::new(), reverse_cmaps: HashMap::new(), rgb_only: false, + x1a_process: None, tags: Vec::new(), story_tags: HashMap::new(), tag_story: None, diff --git a/crates/pdf/src/export/pipeline.rs b/crates/pdf/src/export/pipeline.rs index 85d39c2e9..79f9627b1 100644 --- a/crates/pdf/src/export/pipeline.rs +++ b/crates/pdf/src/export/pipeline.rs @@ -153,7 +153,14 @@ pub fn print_color(doc: &Document, opts: &PdfOptions) -> bool { /// Like [`export_pdf`], also returning warnings about approximated or dropped features. pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result { - write::guard(|| export_pdf_with_report_inner(doc, cache, opts)) + write::guard(|| export_pdf_with_report_inner(doc, cache, opts, &designcraft_color::cms::active())) +} + +/// [`export_pdf_with_report`] with the colour settings of `cms` for the print output, rather than +/// the process-wide ones other tests share. +#[cfg(test)] +pub(crate) fn export_pdf_with_cms(doc: &Document, cache: &Cache, opts: &PdfOptions, cms: &designcraft_color::cms::Cms) -> Result { + write::guard(|| export_pdf_with_report_inner(doc, cache, opts, cms)) } /// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X @@ -176,7 +183,7 @@ fn add_form_fields(bytes: &mut Vec, warnings: &mut Vec, doc: &Docume } } -fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result { +fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions, cms: &designcraft_color::cms::Cms) -> Result { let sheets = sheets(doc, opts)?; let (version, archival) = match opts.standard { Standard::None => (PdfVersion::Pdf17, None), @@ -186,9 +193,14 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions }; let configuration = write::configuration(version, archival)?; let mut warnings = Vec::new(); + let mut x1a_process = None; let base = if print_color(doc, opts) { // An output intent only for PDF/X, as in InDesign. - let (settings, warning) = crate::pdfx::print_settings(opts.standard.is_pdfx())?; + let (settings, warning) = crate::pdfx::print_settings_with(cms, opts.standard.is_pdfx())?; + if opts.standard == Standard::PdfX1a { + let profile = crate::pdfx::output_profile(cms, warning.is_some()); + x1a_process = crate::pdfx1a::ProcessConversion::new(&profile, cms.settings().bpc); + } warnings.extend(warning); let pdfx_version = (opts.standard == Standard::PdfX4).then(|| "PDF/X-4".to_string()); krilla::SerializeSettings { pdfx_version, ..settings } @@ -227,6 +239,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions fonts: HashMap::new(), reverse_cmaps: HashMap::new(), rgb_only: archival.is_some(), + x1a_process, tags: Vec::new(), story_tags: HashMap::new(), tag_story: None, diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 731a5989d..d69e420a1 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -48,6 +48,16 @@ pub(crate) fn print_settings_with(cms: &designcraft_color::cms::Cms, intent: boo } } +/// The CMYK profile [`print_settings_with`] writes as the output intent for `cms`: the working +/// space's, else Coated FOGRA39 (also when `replaced`: its warning said the working space's +/// profile couldn't be written). +pub(crate) fn output_profile(cms: &designcraft_color::cms::Cms, replaced: bool) -> std::borrow::Cow<'static, [u8]> { + match cms.output_intent() { + Ok(space) if !replaced => space.icc, + _ => std::borrow::Cow::Borrowed(craft_cms::builtin::COATED_FOGRA39_ICC), + } +} + /// Finish krilla's PDF/X-4 output with the XMP entries PDF/X-4 requires and krilla doesn't write: /// `xmp:MetadataDate` and `xmpMM:VersionID`, as an incremental update. `date` (Unix seconds, UTC) /// is the metadata date; `None` (no clock, as on wasm) writes the epoch. `None` back when the diff --git a/crates/pdf/src/pdfx1a.rs b/crates/pdf/src/pdfx1a.rs index aa8873083..79a9a579e 100644 --- a/crates/pdf/src/pdfx1a.rs +++ b/crates/pdf/src/pdfx1a.rs @@ -27,6 +27,37 @@ const CONFORMANCE: &str = "PDF/X-1a:2003"; /// naming one of them needs no `/DestOutputProfile` in PDF/X. const ICC_REGISTRY: &str = "http://www.color.org"; +/// RGB process colour into the output intent's CMYK with black point compensation, for PDF/X-1a +/// when the colour settings ask for it. The flattener converts the RGB left in the print file +/// without black point compensation, so this is made only when it is on: otherwise the export +/// stays the flattener's. Relative colorimetric, as the flattener converts. +pub(crate) struct ProcessConversion(std::sync::Arc); + +impl ProcessConversion { + /// Into CMYK profile `icc` with black point compensation `bpc`; `None` without it, or when + /// the profile isn't a CMYK profile craft-cms converts into (the flattener then converts). + pub(crate) fn new(icc: &[u8], bpc: bool) -> Option { + if !bpc { + return None; + } + let profile = craft_cms::Profile::parse(icc).ok()?; + if profile.color_space != craft_cms::ColorSpace::Cmyk { + return None; + } + let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc, precise_float: false }; + craft_cms::cached(craft_cms::builtin::srgb(), &profile, opts).ok().map(Self) + } + + /// The CMYK of 8-bit sRGB `rgb` (as the flattener reads DeviceRGB); `None` when it can't + /// convert. + pub(crate) fn cmyk(&self, rgb: [u8; 3]) -> Option<[f32; 4]> { + let src = rgb.map(|v| f32::from(v) / 255.0); + let mut out = [0.0f32; 4]; + self.0.convert_f32(&src, 3, &mut out, 4, false).ok()?; + Some(out.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 })) + } +} + /// The graphics placed on one output page, to name in errors: the page's name and the graphics' /// names. #[derive(Clone, Debug, Default)] diff --git a/crates/pdf/src/x1a_tests.rs b/crates/pdf/src/x1a_tests.rs index c79aaa172..86e5346c2 100644 --- a/crates/pdf/src/x1a_tests.rs +++ b/crates/pdf/src/x1a_tests.rs @@ -319,6 +319,49 @@ fn x1a_dropped_inks_warning_says_they_wont_print() { assert!(warnings.iter().all(|w| !w.contains("converted to process")), "{warnings:?}"); } +/// The `k` (DeviceCMYK fill) operands of the first page's content, in order. +fn cmyk_fills(bytes: &[u8]) -> Vec> { + let pdf = Pdf::new(bytes.to_vec()).unwrap(); + let pages = pdf.pages(); + let content = pages.iter().next().unwrap().page_stream().unwrap().to_vec(); + let text = String::from_utf8_lossy(&content); + let tokens: Vec<&str> = text.split_whitespace().collect(); + tokens + .iter() + .enumerate() + .filter(|(i, t)| **t == "k" && *i >= 4) + .map(|(i, _)| tokens[i - 4..i].iter().map(|s| s.parse().unwrap()).collect()) + .collect() +} + +/// An RGB fill converts into the output intent's CMYK with black point compensation when the +/// colour settings ask for it (#2570): the issue's blue and a dark grey print with less ink than +/// without it. +#[test] +fn x1a_converts_rgb_fills_with_black_point_compensation() { + use designcraft_color::cms::{Cms, ColorSettings}; + let mut d = Document::new(&NewDocument::default()); + d.swatches.push(Swatch::color("Blue", Color::rgb(40.0 / 255.0, 60.0 / 255.0, 180.0 / 255.0))); + d.swatches.push(Swatch::color("Shadow", Color::rgb(30.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0))); + add(&mut d, Rect::new(72.0, 72.0, 172.0, 172.0), "Blue", |_| {}); + add(&mut d, Rect::new(272.0, 72.0, 372.0, 172.0), "Shadow", |_| {}); + let opts = PdfOptions { standard: Standard::PdfX1a, ..PdfOptions::default() }; + let fills = |bpc: bool| { + let cms = Cms::new(&ColorSettings { bpc, ..ColorSettings::default() }).unwrap(); + let r = crate::export::export_pdf_with_cms(&d, &Cache::new(), &opts, &cms).unwrap(); + assert_eq!(check_pdfx1a(&r.bytes), Vec::::new(), "bpc {bpc}"); + let fills = cmyk_fills(&r.bytes); + assert_eq!(fills.len(), 2, "bpc {bpc}: {fills:?}"); + fills + }; + let (with, without) = (fills(true), fills(false)); + for (with, without) in with.iter().zip(&without) { + assert_ne!(with, without, "black point compensation changed nothing"); + let ink = |c: &Vec| c.iter().sum::(); + assert!(ink(with) < ink(without), "with {with:?}, without {without:?}"); + } +} + /// The output intent and the identification are read as objects: whitespace between tokens (as /// qpdf and Ghostscript write them) doesn't hide them. #[test] From 7f6aeddf6200f08d574d1664c12ce3cbb67e7155 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Fri, 13 Nov 2026 20:47:02 +0100 Subject: [PATCH 067/133] IDML import: a rule inherits through an indented BasedOn A paragraph style's BasedOn written on lines of its own (an indented file) kept its line breaks and indentation in the rule-setting chain lookup, so the base style was not found and its rule weight and offset were lost. Strip them the same way the style's own BasedOn is read. --- crates/idml/src/import/styles.rs | 7 ++++++- crates/idml/src/tests.rs | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 0cf411d20..8162da2f1 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -343,7 +343,12 @@ impl<'r> Importer<'r> { if let Some(v) = e.prop(k) { return Some(v); } - let style_ref = |r: String| if r.starts_with("ParagraphStyle/") { r } else { format!("ParagraphStyle/{}", names::escape_id(&r)) }; + // An indented file puts line breaks and indentation around a `BasedOn` written on lines + // of its own; a name's own trailing spaces stay. + let style_ref = |r: String| { + let r = unindented(&r); + if r.starts_with("ParagraphStyle/") { r.to_string() } else { format!("ParagraphStyle/{}", names::escape_id(r)) } + }; let mut next = if e.local() == "ParagraphStyle" { e.prop("BasedOn") } else { e.get("AppliedParagraphStyle").map(str::to_string) }.map(style_ref); for _ in 0..16 { diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index d97cdeb73..85e473b75 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -4506,6 +4506,28 @@ fn style_names_ending_in_a_space_and_partial_rule_overrides_import() { assert_ne!(black.color, white.color, "only the colour is overridden"); } +/// A paragraph style whose `BasedOn` sits on lines of its own (an indented file) takes the +/// rule settings it doesn't set from the style it is based on. +#[test] +fn a_rule_inherits_through_a_based_on_on_lines_of_its_own() { + let styles = STYLES.replace( + r#" "#, + " + $ID/[No paragraph style] + + + + ParagraphStyle/Base + Color/Black + + ", + ); + let d = import_idml(&fixture_with_table_styles(&styles, STORY)).unwrap(); + let rule = d.styles.paragraph.iter().find(|s| s.name == "Derived").unwrap().para.rule_above.clone().unwrap(); + assert!(rule.on, "the rule stays on"); + assert_eq!((rule.weight, rule.offset), (16.0, -3.0), "weight and offset come from the base style"); +} + #[test] fn a_style_setting_only_a_rules_type_gap_or_keep_in_frame_overrides_it() { let styles = STYLES.replace( From cafa4abe6450b7448e05fe84c2a0ceef8bee42d8 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Fri, 13 Nov 2026 20:57:21 +0100 Subject: [PATCH 068/133] IDML import: the rule chain reads BasedOn as the style chain does Try the reference as written, then without the indentation around it, and fall back to the trimmed reference, so a space before the line break no longer hides the base style when no style id has that space. --- crates/idml/src/import/styles.rs | 11 +++++------ crates/idml/src/tests.rs | 14 +++++++++++--- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index 8162da2f1..fd5874e62 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -343,12 +343,11 @@ impl<'r> Importer<'r> { if let Some(v) = e.prop(k) { return Some(v); } - // An indented file puts line breaks and indentation around a `BasedOn` written on lines - // of its own; a name's own trailing spaces stay. - let style_ref = |r: String| { - let r = unindented(&r); - if r.starts_with("ParagraphStyle/") { r.to_string() } else { format!("ParagraphStyle/{}", names::escape_id(r)) } - }; + // As `based_on` reads it: the reference as written, or without the line breaks and + // indentation an indented file puts around it, when that names a style; else trimmed. + let id = |r: &str| if r.starts_with("ParagraphStyle/") { r.to_string() } else { format!("ParagraphStyle/{}", names::escape_id(r)) }; + let style_ref = + |r: String| [r.as_str(), unindented(&r)].into_iter().map(id).find(|i| self.para_els.contains_key(i)).unwrap_or_else(|| id(r.trim())); let mut next = if e.local() == "ParagraphStyle" { e.prop("BasedOn") } else { e.get("AppliedParagraphStyle").map(str::to_string) }.map(style_ref); for _ in 0..16 { diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 85e473b75..19ba9ec4f 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -4520,12 +4520,20 @@ fn a_rule_inherits_through_a_based_on_on_lines_of_its_own() { ParagraphStyle/Base Color/Black + + + ParagraphStyle/Base + Color/Black + ", ); let d = import_idml(&fixture_with_table_styles(&styles, STORY)).unwrap(); - let rule = d.styles.paragraph.iter().find(|s| s.name == "Derived").unwrap().para.rule_above.clone().unwrap(); - assert!(rule.on, "the rule stays on"); - assert_eq!((rule.weight, rule.offset), (16.0, -3.0), "weight and offset come from the base style"); + // "Spaced" has a space before the line break, and no style is named with that space. + for name in ["Derived", "Spaced"] { + let rule = d.styles.paragraph.iter().find(|s| s.name == name).unwrap().para.rule_above.clone().unwrap(); + assert!(rule.on, "{name}: the rule stays on"); + assert_eq!((rule.weight, rule.offset), (16.0, -3.0), "{name}: weight and offset come from the base style"); + } } #[test] From 27c6473a9d47cd36637f26632ac207bc648753e6 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:40:32 -0600 Subject: [PATCH 069/133] Step and Repeat: a grid makes one guide copy per distance, not two on one spot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A horizontal guide takes `dy` from every row of a grid, so a 2 x 2 grid at dy 25 moved it twice by 25 and put two copies in the same place — and the test said vec![50.0, 75.0, 75.0], which is the defect written down as the expectation. Dedupe the shifts per guide. Removing the guard makes the test fail on created returning 2. --- crates/engine/src/cmd/object.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 23dc1ab56..35b7973e3 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -671,7 +671,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", has_selection_or_guides, step_and_repeat ), @@ -3672,8 +3672,9 @@ fn checked_step_offset(dx: f64, dy: f64, x: u64, y: u64) -> Result { } /// Copies the selected ruler guides by `offsets`, moving a vertical guide by the offsets' x and a -/// horizontal one by their y, ignoring the other. `None` when nothing is selected but objects, so -/// the object path reports it. +/// horizontal one by their y, ignoring the other. A shift already made for a guide is not made again, +/// so grid cells never stack copies. `None` when nothing is selected but objects, so the object path +/// reports it. fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result> { let picked = s.doc()?.selection.guides.clone(); if picked.is_empty() { @@ -3696,14 +3697,16 @@ fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result = Vec::new(); for off in offsets { let shift = match guide.orientation { Orientation::Horizontal => off.y, Orientation::Vertical => off.x, }; - if shift == 0.0 { + if shift == 0.0 || shifts.contains(&shift) { continue; } + shifts.push(shift); let index = pg.guides.len(); let position = super::guides::guide_position(guide.position + shift, "edit.stepAndRepeat")?; pg.guides.push(Guide { position, ..guide.clone() }); @@ -4082,8 +4085,8 @@ mod step_repeat_tests { s.execute("guide.add", &json!({"orientation": "horizontal", "position": 50.0})).unwrap(); let r = s.execute("edit.stepAndRepeat", &json!({"rows": 2, "columns": 2, "dx": 99.0, "dy": 25.0})).unwrap(); - assert_eq!(r["created"], 2, "the cell that only moves across the guide is skipped"); - assert_eq!(positions(&s, Orientation::Horizontal), vec![50.0, 75.0, 75.0], "a horizontal guide takes `dy`"); + assert_eq!(r["created"], 1, "cells that only move across the guide, or repeat a shift already made, are skipped"); + assert_eq!(positions(&s, Orientation::Horizontal), vec![50.0, 75.0], "a horizontal guide takes `dy`, each distance once"); // An offset that does not move the guide at all is refused rather than stacking a copy on it. s.execute("guide.add", &json!({"orientation": "vertical", "position": 7.0})).unwrap(); From 4e54cce89ef5ed318f928b8db5260c70a89eab5e Mon Sep 17 00:00:00 2001 From: "autocraft-bot[bot]" <354215646+autocraft-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:05:04 +0000 Subject: [PATCH 070/133] Apply review fixes - crates/engine/src/cmd/object.rs --- crates/engine/src/cmd/object.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 35b7973e3..faa971cce 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -3722,7 +3722,7 @@ fn step_and_repeat_guides(s: &mut Session, offsets: &[Vec2]) -> Result = made.iter().map(|g| json!({"page": g.page, "index": g.index})).collect(); + let out: Vec = made.iter().map(|g| json!({"spread": g.spread, "page": g.page, "index": g.index})).collect(); Ok(json!({"created": out.len(), "guides": out})) }) .map(Some) From c3a254464accaa90b7f931b3c6c74ece3bd16600 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:30:33 -0600 Subject: [PATCH 071/133] Step and Repeat: the returned guide names its spread, and the description says so The review commit added `spread` to each guide in the reply; the command's description still promised {page, index}, which is now wrong, and a shape nothing asserts is how the earlier `ids` mistake happened. The test pins the whole object, so the description cannot drift from the reply again. --- crates/engine/src/cmd/object.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index faa971cce..49706914f 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -671,7 +671,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{spread, page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", has_selection_or_guides, step_and_repeat ), @@ -4078,6 +4078,7 @@ mod step_repeat_tests { assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "a new guide is selected, as in InDesign"); let r = s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 30.0, "dy": 999.0})).unwrap(); assert_eq!(r["created"], 2); + assert_eq!(r["guides"][0], json!({"spread": 0, "page": 0, "index": 1}), "a copy says which spread, page and index it went into"); assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 130.0, 160.0], "a vertical guide takes `dx` and ignores `dy`"); assert_eq!(s.doc().unwrap().selection.guides.len(), 3, "the guide and its copies stay selected"); s.execute("edit.undo", &json!({})).unwrap(); From f898496c5522eb57db4c51b8d726c64e5ea2c135 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:32:01 -0600 Subject: [PATCH 072/133] Step and Repeat: the reply's guide names its spread, and the test pins the shape The review commit added `spread` to each guide in the reply; the description still promised {page, index}, and a shape nothing asserts is how the earlier `ids` mistake reached the thread. The assertion holds the whole object, and it caught my own guess at it: the spread in the reply is a reference ({kind, index}), not a number, so the description says that too. --- crates/engine/src/cmd/object.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 49706914f..6012be194 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -671,7 +671,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Edit"], Some("Cmd+Alt+U"), - "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{spread, page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", + "{count?: 1..1000, dx?, dy?, rows?, columns?, ids?} — copies of the selection (or ids) offset by (dx, dy); a selected ruler guide is copied by `dx` when vertical and by `dy` when horizontal (the other offset is ignored, each distance once so a grid never stacks two copies on one spot, copies stay within 1000000 pt of the spread origin) → {created, guides: [{spread: {kind, index}, page, index}]}; with rows/columns, a grid of at most 1000 cells, and at most 1000 item copies including group contents → {created, ids: the copies}", has_selection_or_guides, step_and_repeat ), @@ -4078,7 +4078,7 @@ mod step_repeat_tests { assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "a new guide is selected, as in InDesign"); let r = s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 30.0, "dy": 999.0})).unwrap(); assert_eq!(r["created"], 2); - assert_eq!(r["guides"][0], json!({"spread": 0, "page": 0, "index": 1}), "a copy says which spread, page and index it went into"); + assert_eq!(r["guides"][0], json!({"spread": {"kind": "doc", "index": 0}, "page": 0, "index": 1}), "a copy says which spread, page and index it went into"); assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 130.0, 160.0], "a vertical guide takes `dx` and ignores `dy`"); assert_eq!(s.doc().unwrap().selection.guides.len(), 3, "the guide and its copies stay selected"); s.execute("edit.undo", &json!({})).unwrap(); From 78badf90a22bf559cf7ef7c2793374c921e968b9 Mon Sep 17 00:00:00 2001 From: Diego Valadez <49816124+kuseidos@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:32:45 -0600 Subject: [PATCH 073/133] rustfmt: the assertion the formatter wanted on three lines --- crates/engine/src/cmd/object.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 6012be194..31b476067 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4078,7 +4078,11 @@ mod step_repeat_tests { assert_eq!(s.doc().unwrap().selection.guides.len(), 1, "a new guide is selected, as in InDesign"); let r = s.execute("edit.stepAndRepeat", &json!({"count": 2, "dx": 30.0, "dy": 999.0})).unwrap(); assert_eq!(r["created"], 2); - assert_eq!(r["guides"][0], json!({"spread": {"kind": "doc", "index": 0}, "page": 0, "index": 1}), "a copy says which spread, page and index it went into"); + assert_eq!( + r["guides"][0], + json!({"spread": {"kind": "doc", "index": 0}, "page": 0, "index": 1}), + "a copy says which spread, page and index it went into" + ); assert_eq!(positions(&s, Orientation::Vertical), vec![100.0, 130.0, 160.0], "a vertical guide takes `dx` and ignores `dy`"); assert_eq!(s.doc().unwrap().selection.guides.len(), 3, "the guide and its copies stay selected"); s.execute("edit.undo", &json!({})).unwrap(); From 7a5c4262892b8a7a67566415e18d9f979dd1a949 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Fri, 13 Nov 2026 22:56:53 +0000 Subject: [PATCH 074/133] IDML import: a slightly slanted text frame keeps its slant in its transform, so its text starts at the column edge (#2615) A text frame whose path is a parallelogram within 1 in 20 of axis-aligned is imported as its rectangle with the slant in the item transform. Before, the composer treated it as a shaped frame and the sloped top edge cut the first lines: the first line started far right of the column edge and one-line headings wrapped. --- crates/idml/src/import/item.rs | 58 ++++++++++++++++++++++++++++++++++ crates/idml/src/tests.rs | 37 ++++++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/crates/idml/src/import/item.rs b/crates/idml/src/import/item.rs index ac27a833e..758d99d8a 100644 --- a/crates/idml/src/import/item.rs +++ b/crates/idml/src/import/item.rs @@ -181,6 +181,19 @@ impl<'r> Importer<'r> { } } self.read_content(e, tag, id, &mut it); + // A text frame drawn as a slightly slanted rectangle carries the slant in its transform: + // its text is set in the rectangle and slants with the frame, instead of being cut by + // the sloped edges as in a shaped frame (#2615). + if tag == "TextFrame" + && let Some((rect, slant)) = unslant_text_frame_path(&it.path) + { + let back = slant.inverse(); + it.path = rect; + it.xf *= slant; + if let Some(p) = &mut it.wrap.path { + p.transform(back); + } + } Some(it) } @@ -419,6 +432,51 @@ fn clipping_path(g: &El, to_graphic: Affine) -> Option Option<(PathData, Affine)> { + let [sp] = path.subpaths.as_slice() else { return None }; + let [p0, p1, p2, p3] = sp.anchors.as_slice() else { return None }; + let pts = [p0, p1, p2, p3]; + if !sp.closed || pts.iter().any(|a| a.h_in != a.p || a.h_out != a.p || !(a.p.x.is_finite() && a.p.y.is_finite())) { + return None; + } + let (e1, e2) = (p1.p - p0.p, p3.p - p0.p); + // A parallelogram: the fourth corner is where the two edges from the first one lead. + let size = e1.hypot().max(e2.hypot()); + if !size.is_finite() || ((p0.p + e1 + e2) - p2.p).hypot() > size * 1e-9 { + return None; + } + let (h, v) = if e1.x.abs() >= e1.y.abs() { (e1, e2) } else { (e2, e1) }; + // Edge directions with positive width and height. + let h = if h.x < 0.0 { -h } else { h }; + let v = if v.y < 0.0 { -v } else { v }; + let (w, ht) = (h.x, v.y); + let (sy, sx) = (h.y / w, v.x / ht); + if !(w > 0.0 && ht > 0.0 && sy.abs() <= MAX_FRAME_SLANT && sx.abs() <= MAX_FRAME_SLANT) || (sy == 0.0 && sx == 0.0) { + return None; + } + let c = p0.p.midpoint(p2.p).to_vec2(); + let slant = Affine::translate(c) * Affine::new([1.0, sy, sx, 1.0, 0.0, 0.0]) * Affine::translate(-c); + // Unslanted corners, snapped to the rectangle's edges so it is exactly axis-aligned. + let mut rect = path.transformed(slant.inverse()); + for sp in &mut rect.subpaths { + for a in &mut sp.anchors { + let x = if a.p.x < c.x { c.x - w / 2.0 } else { c.x + w / 2.0 }; + let y = if a.p.y < c.y { c.y - ht / 2.0 } else { c.y + ht / 2.0 }; + a.p = Point::new(x, y); + (a.h_in, a.h_out) = (a.p, a.p); + } + } + Some((rect, slant)) +} + fn path_of(pg: &El) -> PathData { path_capped(pg, usize::MAX) } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 1b09e6ec1..01bb25f92 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -660,6 +660,43 @@ fn absent_item_and_document_attributes_take_indesign_defaults() { } } +/// #2615: a text frame whose path is a slightly slanted rectangle (here its top and bottom drop +/// 2.09 pt across 207.75 pt) is imported as a rectangle with the slant in its transform. Its text +/// starts at the column edge and a heading that fits stays on one line, instead of the sloped top +/// edge cutting the first lines as in a shaped frame. +#[test] +fn slightly_slanted_text_frame_sets_its_text_in_the_rectangle() { + let corners = [(-136.5, -74.69600535168195), (-136.5, 93.6875), (71.24999999999999, 91.6022553516819), (71.24999999999999, -76.78125000000001)]; + let pts: String = + corners.iter().map(|(x, y)| format!(r#""#)).collect(); + let body = "Body text follows the heading and fills a few more lines of the frame so that the story has more than one paragraph."; + let designmap = format!( + r#" + +Results at a glance
{body}
+ +{pts} + +
"# + ); + let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap(); + let it = &d.spreads[0].items[0]; + // The frame is where InDesign drew it: its corners on the spread are unchanged. + let anchors = &it.path.subpaths[0].anchors; + for (a, &(x, y)) in anchors.iter().zip(&corners) { + let p = it.xf * a.p; + assert!((p.x - (x + 300.0)).abs() < 1e-9 && (p.y - (y + 300.0)).abs() < 1e-9, "{p:?} vs {x} {y}"); + } + let sid = it.text_frame().unwrap().story; + let cs = designcraft_compose::compose_story(&d, sid, &Default::default()); + let lines: Vec<_> = cs.frames[0].lines.iter().collect(); + assert!(lines.len() >= 3, "{} lines", lines.len()); + let area = it.text_area(); + assert!((lines[0].x0 - area.x0).abs() < 1e-9 && (lines[0].x1 - area.x1).abs() < 1e-9, "first line {}..{} in {area:?}", lines[0].x0, lines[0].x1); + assert_eq!(lines.iter().filter(|l| l.para == 0).count(), 1, "the heading fits on one line"); + assert!(lines.iter().all(|l| (l.x0 - area.x0).abs() < 1e-9), "every line starts at the column edge"); +} + /// InDesign: a break character ends its paragraph (`
` with a ParagraphBreakType closes the /// range); the text after it is a paragraph with its own style, set on the next page of the /// break's parity. From 391886dd173f497114dd4e4f77d4b8e3b4abb8bc Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 00:59:44 +0000 Subject: [PATCH 075/133] Address review: map explicit gradient vectors with the unslanted text frame path (#2615) --- crates/idml/src/import/item.rs | 7 +++++++ crates/idml/src/tests.rs | 8 +++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/idml/src/import/item.rs b/crates/idml/src/import/item.rs index 758d99d8a..ed2306c2b 100644 --- a/crates/idml/src/import/item.rs +++ b/crates/idml/src/import/item.rs @@ -193,6 +193,13 @@ impl<'r> Importer<'r> { if let Some(p) = &mut it.wrap.path { p.transform(back); } + // Explicit gradient vectors are in the inner space too, so they move with the path. + for v in [&mut it.fill.gradient_vector, &mut it.stroke.gradient_vector] { + if let Some([x0, y0, x1, y1]) = *v { + let (a, b) = (back * Point::new(x0, y0), back * Point::new(x1, y1)); + *v = Some([a.x, a.y, b.x, b.y]); + } + } } Some(it) } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 01bb25f92..b0fd5230c 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -675,7 +675,7 @@ fn slightly_slanted_text_frame_sets_its_text_in_the_rectangle() { Results at a glance
{body}
-{pts} +{pts}
"# ); @@ -687,6 +687,12 @@ fn slightly_slanted_text_frame_sets_its_text_in_the_rectangle() { let p = it.xf * a.p; assert!((p.x - (x + 300.0)).abs() < 1e-9 && (p.y - (y + 300.0)).abs() < 1e-9, "{p:?} vs {x} {y}"); } + // An explicit gradient vector moves with the path: it is still where InDesign put it. + let [x0, y0, x1, y1] = it.fill.gradient_vector.expect("gradient vector"); + for ((x, y), (ex, ey)) in [(x0, y0), (x1, y1)].into_iter().zip([(-100.0, 0.0), (0.0, 0.0)]) { + let p = it.xf * designcraft_geom::Point::new(x, y); + assert!((p.x - (ex + 300.0)).abs() < 1e-9 && (p.y - (ey + 300.0)).abs() < 1e-9, "{p:?} vs {ex} {ey}"); + } let sid = it.text_frame().unwrap().story; let cs = designcraft_compose::compose_story(&d, sid, &Default::default()); let lines: Vec<_> = cs.frames[0].lines.iter().collect(); From 6b9e9b43c9fb4da8fe9df31757ad90c40c3e452c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:11:31 -0800 Subject: [PATCH 076/133] Tools: a failed preview keeps the revision of the document it shows A preview put back the gesture's starting document but kept the revision of the preview before it. When the next preview failed or changed nothing, caches keyed by revision (page thumbnails and separations) showed the earlier preview's contents. --- crates/engine/src/tests.rs | 17 +++++++++++++++++ crates/engine/src/tooling.rs | 3 +++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 10b42ee68..4ed6f47b0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2537,3 +2537,20 @@ fn deleting_the_active_layer_moves_to_a_usable_layer() { s.execute("layer.delete", &json!({"id": bottom.0})).unwrap(); assert_eq!(s.doc().unwrap().active_layer, artwork); } + +/// A preview that fails leaves the gesture's starting document with the revision it began at, +/// so a cache keyed by revision does not show the previous preview's contents. +#[test] +fn a_failed_preview_puts_back_the_revision_the_gesture_began_at() { + let mut s = session(); + let id = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap(); + let (start, before) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().revision); + s.begin_interaction("Move").unwrap(); + s.preview("transform.move", json!({"ids": [id], "dx": 30, "dy": 0})).unwrap(); + let moved = s.doc().unwrap().revision; + assert_ne!(moved, before); + assert!(s.preview("transform.move", json!({"ids": [9999], "dx": 60, "dy": 0})).is_err()); + let st = s.doc().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &start), "the document is the one the gesture began with"); + assert_eq!(st.revision, before, "not {moved}, the revision of the previous preview"); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 2badc3a17..27ce0d301 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -291,6 +291,9 @@ impl Session { let Some(it) = st.interaction.clone() else { return Err(EngineError::Other("no interaction".into())) }; st.doc = it.doc.clone(); st.selection = it.selection.clone(); + // A preview that fails or changes nothing shows the snapshot under the snapshot's + // revision, not under the revision of the preview before it. + st.revision = it.revision; // Not through `execute`: a preview is part of the gesture (an IME composition included), // not a command that ends it. let r = self.guarded(cmd, |s| s.execute_unguarded(cmd, ¶ms)); From da29b9e340c34cd28c194cc374fe1d618fa9f3ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:09:03 -0800 Subject: [PATCH 077/133] IDML: object style fill, stroke and paragraph style follow the based-on chain An object style without an EnableFill, EnableStroke or EnableParagraphStyle flag or value of its own now takes that category from the style it is based on, and a style that turns one on takes the values it leaves out from the styles it is based on. Value lookup for these categories, Text Frame General Options and corners stops at the first based-on style that turns the category off, and at a based-on [None]. --- crates/idml/src/import/object_style.rs | 15 +++-- crates/idml/src/import/styles.rs | 52 +++++++++------ crates/idml/src/tests/object_styles.rs | 87 ++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 22 deletions(-) diff --git a/crates/idml/src/import/object_style.rs b/crates/idml/src/import/object_style.rs index d7ded1ef8..206bcccfb 100644 --- a/crates/idml/src/import/object_style.rs +++ b/crates/idml/src/import/object_style.rs @@ -120,11 +120,18 @@ impl<'r> Importer<'r> { } pub(super) fn stroke_from(&mut self, e: &El, item: Option<&El>) -> Stroke { - let model_elements = if item.is_some() { - std::iter::once(e).chain(self.object_style_chain(e).iter()).map(crate::xml::to_craft).collect::>() + if item.is_some() { + let chain = self.object_style_chain(e); + let levels: Vec<&El> = std::iter::once(e).chain(chain.iter()).collect(); + self.stroke_in(&levels) } else { - vec![crate::xml::to_craft(e)] - }; + self.stroke_in(&[e]) + } + } + + /// The stroke that `levels` give, nearest first: each setting from the first level that has it. + pub(super) fn stroke_in(&mut self, levels: &[&El]) -> Stroke { + let model_elements: Vec<_> = levels.iter().map(|l| crate::xml::to_craft(l)).collect(); let model_refs: Vec<_> = model_elements.iter().collect(); let model = craft_idml::model::StrokeValues::from_elements(&model_refs); let mut s = Stroke::none(); diff --git a/crates/idml/src/import/styles.rs b/crates/idml/src/import/styles.rs index dba8b8cec..03dcd92bf 100644 --- a/crates/idml/src/import/styles.rs +++ b/crates/idml/src/import/styles.rs @@ -184,26 +184,31 @@ impl<'r> Importer<'r> { .unwrap_or_else(|| names::style_name_in(OBJECT_BUILTINS, &unescape_id(b.trim_start_matches("ObjectStyle/")))) }); let based_on = based_on.filter(|b| *b != designcraft_doc::NO_OBJECT_STYLE && *b != name); - let fill = values.fill_enabled.then(|| { - let sw = values.fill_color.as_deref().map(|r| self.swatch_ref(r)).unwrap_or_else(|| swatch::NONE.into()); - Fill { swatch: sw, tint: tint(values.fill_tint).unwrap_or(1.0), ..Fill::none() } - }); - let stroke = values.stroke_enabled.then(|| self.stroke_from(e, None)); - let paragraph_style = values.paragraph_style_enabled.then(|| values.paragraph_style.as_deref().map(|r| self.para_style_ref(r))).flatten(); let levels = based_on_levels(e, &objects_by_self); + // Fill, stroke and paragraph style: each category as the nearest style that gives its + // flag (or, without one, its value) sets it, and each value from the nearest style that + // gives it, up to the first style that turns the category off. + let fill = category_on(&levels, "EnableFill", |l| l.get("FillColor").is_some()).then(|| { + let on = category_levels(&levels, "EnableFill"); + let sw = on.iter().find_map(|l| l.get("FillColor")).map(|r| self.swatch_ref(r)).unwrap_or_else(|| swatch::NONE.into()); + Fill { swatch: sw, tint: tint(on.iter().find_map(|l| l.num("FillTint"))).unwrap_or(1.0), ..Fill::none() } + }); + let stroke = category_on(&levels, "EnableStroke", |l| l.get("StrokeColor").is_some()) + .then(|| self.stroke_in(&category_levels(&levels, "EnableStroke"))); + let para_levels = category_levels(&levels, "EnableParagraphStyle"); + let paragraph_style = category_on(&levels, "EnableParagraphStyle", |l| l.get("AppliedParagraphStyle").is_some()) + .then(|| para_levels.iter().find_map(|l| l.get("AppliedParagraphStyle")).map(|r| self.para_style_ref(r))) + .flatten(); let text_frame = if category_on(&levels, "EnableTextFrameGeneralOptions", |_| false) { - let prefs: Vec<&El> = levels - .iter() - .filter(|l| l.get("EnableTextFrameGeneralOptions") != Some("false")) - .filter_map(|l| l.find("TextFramePreference")) - .collect(); + let prefs: Vec<&El> = + category_levels(&levels, "EnableTextFrameGeneralOptions").into_iter().filter_map(|l| l.find("TextFramePreference")).collect(); (!prefs.is_empty()).then(|| self.frame_options(&prefs)) } else { None }; let effects = self.style_effects(e); let corners = style_corners(&levels); - let apply_next_style = paragraph_style.is_some() && e.get("ApplyNextParagraphStyle") == Some("true"); + let apply_next_style = paragraph_style.is_some() && para_levels.iter().find_map(|l| l.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, @@ -408,22 +413,20 @@ impl<'r> Importer<'r> { /// 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. +/// others from the styles in `levels` before the first one that turns 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 }) + corners_in(&category_levels(levels, "EnableStrokeAndCornerOptions"), "").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. +/// ends the chain ([`chain`]). 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))) { + for l in chain(levels) { match l.get(flag) { Some(v) => return v == "true", None if own(l) => return true, @@ -433,6 +436,19 @@ fn category_on(levels: &[&El], flag: &str, own: impl Fn(&El) -> bool) -> bool { false } +/// The styles in `levels` (a style, then the styles it is based on) that give the values of the +/// category whose flag is `flag`, nearest first: those before the first one that turns it off, and +/// before a `[None]` after the first style. +fn category_levels<'e>(levels: &[&'e El], flag: &str) -> Vec<&'e El> { + chain(levels).take_while(|l| l.get(flag) != Some("false")).collect() +} + +/// `levels` up to a `[None]` after the first style, as a `BasedOn` of `[None]` names no style. +fn chain<'a, 'e>(levels: &'a [&'e El]) -> impl Iterator + 'a { + let more = levels.iter().skip(1).take_while(|l| l.get("Self") != Some("ObjectStyle/$ID/[None]")); + levels.iter().take(1).chain(more).copied() +} + /// 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 719936f40..d9ddd1db7 100644 --- a/crates/idml/src/tests/object_styles.rs +++ b/crates/idml/src/tests/object_styles.rs @@ -414,6 +414,93 @@ fn a_style_without_category_flags_takes_them_from_its_based_on_style() { assert!(style(designcraft_doc::NO_OBJECT_STYLE).corners.is_some(), "[None] keeps the corners it sets itself"); } +/// A style without a Fill, Stroke or Paragraph Styles flag or value of its own takes each category +/// from the style it is based on, and a style turning a category on takes the values it leaves out +/// from there; a based-on style that turns a category off gives nothing. +#[test] +fn fill_stroke_and_paragraph_style_categories_come_through_the_based_on_chain() { + let styles = r#" + $ID/[None] + + + ObjectStyle/Brand + + + ObjectStyle/Brand + + + ObjectStyle/Brand + + + ObjectStyle/Off + "#; + let d = fixture(styles, &[]); + let style = |n: &str| d.styles.object_style(n).cloned().unwrap(); + let brand = style("Brand"); + let (brand_fill, brand_stroke) = (brand.fill.clone().expect("Brand sets a fill"), brand.stroke.clone().expect("Brand sets a stroke")); + let kid = style("Kid"); + assert_eq!((kid.fill.as_ref(), kid.stroke.as_ref()), (Some(&brand_fill), Some(&brand_stroke)), "Kid inherits Brand's fill and stroke"); + assert_eq!((kid.paragraph_style.as_deref(), kid.apply_next_style), (Some("Opener"), true), "Kid inherits Brand's paragraph style"); + let t = style("Tint"); + let (fill, stroke) = (t.fill.expect("Tint sets a fill"), t.stroke.expect("Tint sets a stroke")); + assert_eq!(fill.swatch, brand_fill.swatch, "Tint takes Brand's fill color"); + assert!((fill.tint - 0.7).abs() < 1e-6 && (brand_fill.tint - 0.4).abs() < 1e-6, "{fill:?} {brand_fill:?}"); + assert_eq!((stroke.swatch, stroke.weight), (brand_stroke.swatch.clone(), 5.0), "Tint takes Brand's stroke color"); + for n in ["Off", "OffKid"] { + let s = style(n); + assert!(s.fill.is_none() && s.stroke.is_none() && s.paragraph_style.is_none(), "{n}: {s:?}"); + } +} + +/// A style that turns a category on takes none of its values from beyond a based-on style that +/// turns the category off. +#[test] +fn category_values_stop_at_a_based_on_style_that_turns_the_category_off() { + let styles = r#" + $ID/[None] + + + + ObjectStyle/Full + + + ObjectStyle/Off + "#; + let d = fixture(styles, &[]); + let gap = d.styles.object_style("Gap").cloned().unwrap(); + assert_eq!(gap.fill.as_ref().map(|f| f.swatch.as_str()), Some(designcraft_color::swatch::NONE), "{:?}", gap.fill); + assert_ne!(gap.text_frame.as_ref().map(|t| t.columns), Some(3), "{:?}", gap.text_frame); + assert!(gap.corners.is_none(), "{:?}", gap.corners); +} + +/// A style based on `[None]` that turns a category on takes none of that category's values from +/// `[None]`, which keeps its own. +#[test] +fn category_values_stop_at_none() { + let designmap = r#" + + + + $ID/[None] + + + + "#; + let spread = r#" + + "#; + let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap(); + let plain = d.styles.object_style("Plain").cloned().unwrap(); + assert_eq!(plain.fill.as_ref().map(|f| f.swatch.as_str()), Some(designcraft_color::swatch::NONE), "{:?}", plain.fill); + assert_eq!(plain.stroke.as_ref().map(|s| s.weight), Some(designcraft_doc::Stroke::none().weight), "{:?}", plain.stroke); + let none = d.styles.object_style(designcraft_doc::NO_OBJECT_STYLE).cloned().unwrap(); + assert_eq!(none.stroke.map(|s| s.weight), Some(0.0), "[None] keeps its own stroke weight"); +} + /// 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 766f21850617445695708480cd33d0214455d65c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:17:32 -0800 Subject: [PATCH 078/133] Data merge: objects anchored in nested endnotes get their own ids in each record A record's copy of a text frame gave fresh ids to the objects anchored in its story, table cells, footnotes and top-level endnotes, but not to objects anchored in an endnote inside a table cell or a footnote. Those copies kept the template's ids and were missing from the record's id map, so a placeholder on such an object did not follow the copy. The copy now walks every cell and note at any depth with a stack instead of recursion. --- crates/engine/src/cmd/datamerge/fill.rs | 18 +++++---- crates/engine/src/cmd/datamerge/tests.rs | 47 ++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 9d94da7d9..028e1c259 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -129,16 +129,20 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } -/// 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, and +/// the cells and notes inside those at any depth (#1522). The texts are walked with a stack, so a deeply +/// nested file can't exhaust the call stack. fn renumber_anchored(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Document, st: &mut Story, maps: &mut Maps) { - let mut fresh = |t: &mut Story| { - for o in &mut t.objects { + let mut texts = vec![st]; + while let Some(t) = texts.pop() { + let Story { objects, tables, notes, endnotes, .. } = t; + for o in objects.iter_mut() { renumber_in(dst, src, &mut Arc::make_mut(o).item, maps, false); } - }; - 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 table in tables.values_mut() { + texts.extend(Arc::make_mut(table).cells.iter_mut().map(|c| &mut c.text)); + } + texts.extend(notes.iter_mut().chain(endnotes.iter_mut()).map(|n| &mut Arc::make_mut(n).text)); } } diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index e631b69ea..b8a6abe1a 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1536,6 +1536,53 @@ fn merged_records_give_anchored_objects_their_own_ids() { designcraft_format::load(&designcraft_format::save(doc).unwrap()).unwrap(); } +/// A record's copy gives the objects anchored in an endnote of a table cell or of a footnote ids of +/// their own, and maps them, so placeholders on them follow the copy. +#[test] +fn record_copies_renumber_objects_anchored_in_nested_endnotes() { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let a = exec(&mut s, "frame.create", json!({"rect": [450, 450, 474, 490]}))["id"].as_u64().unwrap(); + let b = exec(&mut s, "frame.create", json!({"rect": [480, 450, 504, 490]}))["id"].as_u64().unwrap(); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_cell = take(d, a); + let in_footnote = take(d, b); + 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(), "Cell endnote", Default::default()).unwrap(); + Arc::make_mut(&mut cell.endnotes[0]).text.insert_object(0, in_cell); + let st = d.story_mut(sid).unwrap(); + st.insert_note(st.len(), "Footnote", Default::default()).unwrap(); + let note = &mut Arc::make_mut(&mut st.notes[0]).text; + note.insert_endnote(note.len(), "Footnote endnote", Default::default()).unwrap(); + Arc::make_mut(&mut note.endnotes[0]).text.insert_object(0, in_footnote); + st.insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let ids: Vec = dst.anchored_items().into_iter().map(|(_, i)| i.id.0).collect(); + let unique: std::collections::BTreeSet<_> = ids.iter().collect(); + assert_eq!((ids.len(), unique.len()), (4, 4), "the copies have ids of their own: {ids:?}"); + for old in [a, b] { + assert!(maps.items.contains_key(&ItemId(old)), "object {old} is mapped to its copy"); + } + dst.check().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] From 414941886d3b919b902121a722195d434a779f8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:58:44 -0800 Subject: [PATCH 079/133] Dialogs: number fields are named from their captions The number fields of Insert Table, Convert Text to Table, Cell Options, Paragraph Style Options and Character Style Options (their CJK sections included), and the Paragraph Rules, Paragraph Borders and Shading, Span Columns, Hyphenation and Justification dialogs had no accessible name, so a screen reader read the field's internal key (`bodyRows`, `cell_fill_tint`, `psleftIndent`). Each field now takes the caption shown beside it, without the trailing colon, as the Text Frame Options fields do since #2733. A border's stroke weights and offsets add their group ("Stroke Top", "Offsets Top"), and the justification fields add their column ("Word Spacing Minimum"). --- crates/ui-egui/src/dialogs.rs | 237 ++++++++++++++++-------- crates/ui-egui/src/dialogs/style_cjk.rs | 75 ++++---- crates/ui-egui/src/dialogs/tests.rs | 61 ++++++ 3 files changed, 262 insertions(+), 111 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b4e0fa310..6e550d6b2 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -286,7 +286,8 @@ fn convert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let same = same_separators(d); label(ui, "Number of Columns", same); let max = designcraft_engine::cmd::table::MAX_COLUMNS as f64; - let field = crate::widgets::NumField::number("columns", d.n("columns"), "", 0).width(70.0).range(1.0, max).spinner().enabled(same); + let name = crate::i18n::tr(lang, "Number of Columns"); + let field = crate::widgets::NumField::number("columns", d.n("columns"), "", 0).name(name).width(70.0).range(1.0, max).spinner().enabled(same); if let Some(v) = field.show(ui) { d.fields.insert("columns".into(), json!(v.round())); } @@ -341,7 +342,7 @@ fn insert_table_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { egui::Grid::new(("ins_table", g)).num_columns(2).min_col_width(100.0).spacing([8.0, 6.0]).show(ui, |ui| { for (key, label, min, max) in pair { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| crate::rtl::label(ui, format!("{label}:"))); - let field = crate::widgets::NumField::number(key, d.n(key), "", 0).width(70.0).range(*min, *max as f64).spinner(); + let field = crate::widgets::NumField::number(key, d.n(key), "", 0).name(label).width(70.0).range(*min, *max as f64).spinner(); if let Some(v) = field.show(ui) { d.fields.insert((*key).into(), json!(v.round())); } @@ -4307,9 +4308,11 @@ fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("fill".into(), json!(n)); } ui.end_row(); - crate::rtl::label(ui, crate::i18n::tr(&lang, "Tint:")); + let caption = crate::i18n::tr(&lang, "Tint:"); + crate::rtl::label(ui, caption); let tint = values["fillTint"].as_f64().map(|t| (t * 100.0).round()); - if let Some(t) = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).width(60.0).range(0.0, 100.0).show(ui) { + let field = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).name(caption.trim_end_matches(':')); + if let Some(t) = field.width(60.0).range(0.0, 100.0).show(ui) { d.fields.insert("fillTint".into(), json!(t / 100.0)); } ui.end_row(); @@ -5915,9 +5918,11 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo ("Space Before:", "spaceBefore"), ("Space After:", "spaceAfter"), ] { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label)); + let caption = crate::i18n::tr(&app.ui.language, label); + crate::rtl::label(ui, caption); let v = cur(d, &format!("p.{key}"), &pv[key]).as_f64(); - if let Some(n) = crate::widgets::measure(ui, &format!("ps{key}"), v, units, 80.0) { + let id = format!("ps{key}"); + if let Some(n) = crate::widgets::NumField::measure(&id, v, units).name(caption.trim_end_matches(':')).width(80.0).show(ui) { d.fields.insert(format!("p.{key}"), json!(n)); } ui.end_row(); @@ -6190,8 +6195,10 @@ fn style_tabs(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &d } } ui.add_space(6.0); - crate::rtl::label(ui, crate::i18n::tr(lang, "X:")); - if let Some(x) = crate::widgets::measure(ui, "pstabx", stop.as_ref().map(|s| s.position), unit, 72.0) { + let x_caption = crate::i18n::tr(lang, "X:"); + crate::rtl::label(ui, x_caption); + let x_field = crate::widgets::NumField::measure("pstabx", stop.as_ref().map(|s| s.position), unit).name(x_caption.trim_end_matches(':')); + if let Some(x) = x_field.width(72.0).show(ui) { result = Some(match sel { Some(i) => tabs::move_to(&mut list, i, x), None => tabs::add(&mut list, designcraft_doc::TabStop { position: x, align, leader: String::new(), align_on: String::new() }), @@ -6258,10 +6265,11 @@ fn para_set(d: &mut Dialog, key: &str, v: Value) { d.fields.insert(format!("p.{key}"), v); } -/// A count attribute (lines, columns), rounded and kept in `range`. -fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, range: (u32, u32)) { +/// A count attribute (lines, columns), rounded and kept in `range`, named from `caption`. +fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, range: (u32, u32)) { let v = para_value(d, pv, key).as_f64(); - if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 50.0, 0) { + let id = format!("ps{key}"); + if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches(':')).width(50.0).show(ui) { let n = if n.is_finite() { n.round().clamp(f64::from(range.0), f64::from(range.1)) as u32 } else { range.0 }; para_set(d, key, json!(n)); } @@ -6274,9 +6282,11 @@ fn para_check(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, label: & } } -fn para_measure(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, unit: Unit) { +/// A measure attribute in `unit`, named from `caption`. +fn para_measure(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, unit: Unit) { let v = para_value(d, pv, key).as_f64(); - if let Some(n) = crate::widgets::measure(ui, &format!("ps{key}"), v, unit, 80.0) { + let id = format!("ps{key}"); + if let Some(n) = crate::widgets::NumField::measure(&id, v, unit).name(caption.trim_end_matches(':')).width(80.0).show(ui) { para_set(d, key, json!(n)); } } @@ -6300,16 +6310,27 @@ fn para_choice_width(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, } /// Four per-side values in the order the attribute holds them: top, left, bottom, right. An -/// edited side stores the whole array. -fn para_sides(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, field: &dyn Fn(&mut egui::Ui, &str, Option) -> Option) { +/// edited side stores the whole array. `field` draws one side's field: its id, its name (`group` +/// and the side's caption, as "Offsets Top") and its value. +fn para_sides( + lang: &str, + ui: &mut egui::Ui, + d: &mut Dialog, + pv: &Value, + key: &str, + group: &str, + field: &dyn Fn(&mut egui::Ui, &str, &str, Option) -> Option, +) { let mut sides: [f64; 4] = serde_json::from_value(para_value(d, pv, key)).unwrap_or_default(); let linked = linked(d, key, sides.iter().all(|v| (v - sides[0]).abs() < 1e-9)); let mut changed = false; // As InDesign's: Top and Bottom, the link, Left and Right. egui::Grid::new(("pssides", key)).num_columns(5).spacing([8.0, 6.0]).show(ui, |ui| { for (i, label) in ["Top:", "Left:", "Bottom:", "Right:"].into_iter().enumerate() { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - if let Some(v) = field(ui, &format!("ps{key}{i}"), sides.get(i).copied()) { + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + let name = format!("{group} {}", caption.trim_end_matches(':')); + if let Some(v) = field(ui, &format!("ps{key}{i}"), &name, sides.get(i).copied()) { // Linked, a side typed in sets all four. if linked { sides = [v; 4]; @@ -6443,7 +6464,7 @@ fn para_corners(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tip)); resp.on_hover_text(tip); let id = format!("ps{key}{i}"); - if let Some(v) = crate::widgets::NumField::measure(&id, Some(c.size), units).width(84.0).spinner().range(0.0, 10_000.0).show(ui) { + if let Some(v) = crate::widgets::NumField::measure(&id, Some(c.size), units).name(tip).width(84.0).spinner().range(0.0, 10_000.0).show(ui) { c.size = if v.is_finite() { v.clamp(0.0, 10_000.0) } else { 0.0 }; *changed = Some(i); } @@ -6526,7 +6547,8 @@ fn para_color_tint( ui.add_enabled_ui(enabled, |ui| { ui.horizontal(|ui| { let id = format!("ps{tint_key}"); - let field = crate::widgets::NumField::number(&id, tint, "%", 0).width(96.0).spinner().presets(TINTS).step(10.0).range(0.0, 100.0); + let field = crate::widgets::NumField::number(&id, tint, "%", 0).name(labels.1.trim_end_matches(':')); + let field = field.width(96.0).spinner().presets(TINTS).step(10.0).range(0.0, 100.0); if let Some(v) = field.show(ui) { para_set(d, tint_key, json!(if v.is_finite() { (v / 100.0).clamp(0.0, 1.0) } else { 1.0 })); } @@ -6555,8 +6577,10 @@ fn border_shading(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc ui.add_enabled_ui(on, |ui| { if border { head(ui, "Stroke"); - para_sides(lang, ui, d, pv, &key("Weights"), &|ui: &mut egui::Ui, id: &str, v: Option| { + let group = crate::i18n::tr(lang, "Stroke"); + para_sides(lang, ui, d, pv, &key("Weights"), group, &|ui: &mut egui::Ui, id: &str, name: &str, v: Option| { crate::widgets::NumField::number(id, v, " pt", 2) + .name(name) .width(84.0) .spinner() .range(0.0, 1000.0) @@ -6594,8 +6618,9 @@ fn border_shading(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc ui.horizontal_top(|ui| { ui.vertical(|ui| { head(ui, "Offsets"); - para_sides(lang, ui, d, pv, &key("Offsets"), &|ui: &mut egui::Ui, id: &str, v: Option| { - crate::widgets::spin_measure(ui, id, v, units, 72.0) + let group = crate::i18n::tr(lang, "Offsets"); + para_sides(lang, ui, d, pv, &key("Offsets"), group, &|ui: &mut egui::Ui, id: &str, name: &str, v: Option| { + crate::widgets::NumField::measure(id, v, units).name(name).width(72.0).spinner().show(ui) }); }); ui.add_space(12.0); @@ -6664,9 +6689,11 @@ fn drop_cap_fields(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, cn ("Lines:", "dropCapLines", designcraft_compose::MAX_DROP_CAP_LINES), ("Characters:", "dropCapChars", designcraft_compose::MAX_DROP_CAP_CHARS), ] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); let v = field_or(d, &format!("p.{key}"), &pv[key]).as_f64(); - if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 60.0, 0) { + let id = format!("ps{key}"); + if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches(':')).width(60.0).show(ui) { d.fields.insert(format!("p.{key}"), json!((n.max(0.0) as u64).min(max as u64))); } ui.end_row(); @@ -6917,8 +6944,9 @@ fn grep_styles(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, cnames /// lines kept together (all of them, or its first and last lines), and where it starts. fn keep_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { ui.horizontal(|ui| { - crate::rtl::label(ui, crate::i18n::tr(lang, "Keep with Next:")); - para_count(ui, d, pv, "keepWithNext", (0, 5)); + let caption = crate::i18n::tr(lang, "Keep with Next:"); + crate::rtl::label(ui, caption); + para_count(ui, d, pv, "keepWithNext", caption, (0, 5)); crate::rtl::label(ui, crate::i18n::tr(lang, "lines")); }); ui.add_space(4.0); @@ -6936,8 +6964,9 @@ fn keep_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { ui.add_enabled_ui(!all, |ui| { egui::Grid::new("pskeepends").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| { for (label, key) in [("Start:", "keepFirst"), ("End:", "keepLast")] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - para_count(ui, d, pv, key, (1, 50)); + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + para_count(ui, d, pv, key, caption, (1, 50)); crate::rtl::label(ui, crate::i18n::tr(lang, "lines")); ui.end_row(); } @@ -7007,8 +7036,10 @@ fn span_columns(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: ui.end_row(); } SpanColumns::Split(n) => { - crate::rtl::label(ui, crate::i18n::tr(lang, "Columns:")); - if let Some(c) = crate::widgets::number(ui, "pssplitn", Some(f64::from(n)), "", 50.0, 0) { + let caption = crate::i18n::tr(lang, "Columns:"); + crate::rtl::label(ui, caption); + let field = crate::widgets::NumField::number("pssplitn", Some(f64::from(n)), "", 0).name(caption.trim_end_matches(':')); + if let Some(c) = field.width(50.0).show(ui) { next = Some(SpanColumns::Split(if c.is_finite() { c.round().clamp(2.0, 20.0) as u32 } else { 2 })); } ui.end_row(); @@ -7022,15 +7053,17 @@ fn span_columns(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: }; if let Some((before, after)) = spaces { for (label, key) in [(before, "spanSpaceBefore"), (after, "spanSpaceAfter")] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - para_measure(ui, d, pv, key, v_units); + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + para_measure(ui, d, pv, key, caption, v_units); ui.end_row(); } } if matches!(cur, SpanColumns::Split(_)) { for (label, key) in [("Inside Gutter:", "splitInsideGutter"), ("Outside Gutter:", "splitOutsideGutter")] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - para_measure(ui, d, pv, key, units); + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + para_measure(ui, d, pv, key, caption, units); ui.end_row(); } } @@ -7201,8 +7234,9 @@ fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Val para_choice(lang, ui, d, pv, "listType", &[("none", "None"), ("bullets", "Bullets"), ("numbers", "Numbers")]); ui.end_row(); if kind != "none" { - crate::rtl::label(ui, crate::i18n::tr(lang, "Level:")); - para_count(ui, d, pv, "listLevel", (1, designcraft_doc::LIST_LEVELS as u32)); + let caption = crate::i18n::tr(lang, "Level:"); + crate::rtl::label(ui, caption); + para_count(ui, d, pv, "listLevel", caption, (1, designcraft_doc::LIST_LEVELS as u32)); ui.end_row(); } match kind.as_str() { @@ -7251,8 +7285,9 @@ fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Val para_set(d, "startAt", json!(1)); } }); + let start_at = crate::i18n::tr(lang, "Start At"); if let Some(n) = start - && let Some(v) = crate::widgets::number(ui, "psstartat", Some(n as f64), "", 60.0, 0) + && let Some(v) = crate::widgets::NumField::number("psstartat", Some(n as f64), "", 0).name(start_at).width(60.0).show(ui) { para_set(d, "startAt", json!(if v.is_finite() { v.round().clamp(0.0, 1_000_000.0) as u32 } else { 1 })); } @@ -7287,12 +7322,14 @@ fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Val para_choice(lang, ui, d, pv, key, &[("left", "Left"), ("center", "Center"), ("right", "Right")]); ui.end_row(); for (label, key) in [("Left Indent:", "leftIndent"), ("First Line Indent:", "firstLineIndent")] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - para_measure(ui, d, pv, key, units); + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + para_measure(ui, d, pv, key, caption, units); ui.end_row(); } // Tab Position: none, or a stop for the text after the label. - crate::rtl::label(ui, crate::i18n::tr(lang, "Tab Position:")); + let tab_caption = crate::i18n::tr(lang, "Tab Position:"); + crate::rtl::label(ui, tab_caption); ui.horizontal(|ui| { let tab = para_value(d, pv, "listTab").as_f64(); let mut on = tab.is_some(); @@ -7301,7 +7338,10 @@ fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Val para_set(d, "listTab", if on { json!(left) } else { Value::Null }); } if let Some(t) = tab - && let Some(v) = crate::widgets::measure(ui, "pslisttab", Some(t), units, 80.0) + && let Some(v) = crate::widgets::NumField::measure("pslisttab", Some(t), units) + .name(tab_caption.trim_end_matches(':')) + .width(80.0) + .show(ui) { para_set(d, "listTab", json!(if v.is_finite() { v.max(0.0) } else { 0.0 })); } @@ -7615,10 +7655,12 @@ impl CharFields<'_> { } } -/// A number attribute shown multiplied by `scale` (100 for a fraction shown as a percentage). -fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, suffix: &str, scale: f64, range: (f64, f64)) { +/// A number attribute shown multiplied by `scale` (100 for a fraction shown as a percentage), +/// named from `caption`. +#[allow(clippy::too_many_arguments)] +fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, suffix: &str, scale: f64, range: (f64, f64)) { let v = cf.get(d, key).as_f64().map(|x| x * scale); - let field = crate::widgets::NumField::number(key, v, suffix, 2).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale))); @@ -7725,13 +7767,16 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo }); egui::Grid::new("psc2").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Size:")); - char_number(ui, d, cf, "size", " pt", 1.0, (0.1, 1296.0)); + char_number(ui, d, cf, "size", crate::i18n::tr(lang, "Size:"), " pt", 1.0, (0.1, 1296.0)); crate::rtl::label(ui, crate::i18n::tr(lang, "Leading:")); let lv = match cf.get(d, "leading") { v if v["kind"] == "points" => v["value"].as_f64(), _ => None, }; - let field = crate::widgets::NumField::points("pslead", lv, 2).width(80.0).range(0.0, 5000.0); + let field = crate::widgets::NumField::points("pslead", lv, 2) + .name(crate::i18n::tr(lang, "Leading:").trim_end_matches(':')) + .width(80.0) + .range(0.0, 5000.0); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, "leading", n.map_or(Value::Null, |n| json!({"kind": "points", "value": n}))); @@ -7747,7 +7792,7 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo &[(json!({"kind": "metrics"}), "Metrics"), (json!({"kind": "optical"}), "Optical"), (json!({"kind": "none"}), "0")], ); crate::rtl::label(ui, crate::i18n::tr(lang, "Tracking:")); - char_number(ui, d, cf, "tracking", "", 1.0, (-1000.0, 10000.0)); + char_number(ui, d, cf, "tracking", crate::i18n::tr(lang, "Tracking:"), "", 1.0, (-1000.0, 10000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Case:")); char_choice( @@ -7797,16 +7842,16 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo fn advanced_character_formats(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { egui::Grid::new("csa").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Horizontal Scale:")); - char_number(ui, d, cf, "hScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "hScale", crate::i18n::tr(lang, "Horizontal Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Vertical Scale:")); - char_number(ui, d, cf, "vScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "vScale", crate::i18n::tr(lang, "Vertical Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Baseline Shift:")); - char_number(ui, d, cf, "baselineShift", " pt", 1.0, (-5000.0, 5000.0)); + char_number(ui, d, cf, "baselineShift", crate::i18n::tr(lang, "Baseline Shift:"), " pt", 1.0, (-5000.0, 5000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Skew:")); - char_number(ui, d, cf, "skew", "°", 1.0, (-85.0, 85.0)); + char_number(ui, d, cf, "skew", crate::i18n::tr(lang, "Skew:"), "°", 1.0, (-85.0, 85.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Language:")); let opts: Vec<(Value, &str)> = crate::panels::properties::LANGUAGES.iter().map(|l| (json!(l), *l)).collect(); @@ -7858,10 +7903,10 @@ fn character_color(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharField }); egui::Grid::new("cscg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:")); - char_number(ui, d, cf, if stroke { "strokeTint" } else { "fillTint" }, "%", 100.0, (0.0, 100.0)); + char_number(ui, d, cf, if stroke { "strokeTint" } else { "fillTint" }, crate::i18n::tr(lang, "Tint:"), "%", 100.0, (0.0, 100.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:")); - char_number(ui, d, cf, "strokeWeight", " pt", 1.0, (0.0, 800.0)); + char_number(ui, d, cf, "strokeWeight", crate::i18n::tr(lang, "Weight:"), " pt", 1.0, (0.0, 800.0)); ui.end_row(); ui.label(""); char_check(ui, d, cf, "strokeBehindFill", crate::i18n::tr(lang, "Stroke Behind Fill")); @@ -7932,16 +7977,16 @@ fn line_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, ui.add_space(4.0); egui::Grid::new(("csline", key)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:")); - char_number(ui, d, cf, &format!("{key}Weight"), " pt", 1.0, (0.0, 800.0)); + char_number(ui, d, cf, &format!("{key}Weight"), crate::i18n::tr(lang, "Weight:"), " pt", 1.0, (0.0, 800.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:")); - char_number(ui, d, cf, &format!("{key}Offset"), " pt", 1.0, (-800.0, 800.0)); + char_number(ui, d, cf, &format!("{key}Offset"), crate::i18n::tr(lang, "Offset:"), " pt", 1.0, (-800.0, 800.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Color:")); char_swatch(lang, ui, d, cf, doc, &format!("{key}Color"), Some("(Text Color)")); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:")); - char_number(ui, d, cf, &format!("{key}Tint"), "%", 100.0, (0.0, 100.0)); + char_number(ui, d, cf, &format!("{key}Tint"), crate::i18n::tr(lang, "Tint:"), "%", 100.0, (0.0, 100.0)); ui.end_row(); }); } @@ -8179,16 +8224,22 @@ fn hyphenation(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, curr ("Before Last:", "hyphBeforeLast", "letters", 15.0), ("Hyphen Limit:", "hyphLimit", "hyphens", 25.0), ] { - label_right(ui, &tr(label)); + let caption = tr(label); + label_right(ui, &caption); let min = if key == "hyphLimit" { 0.0 } else { 1.0 }; - if let Some(n) = crate::widgets::spin_number(ui, &format!("hy{prefix}{key}"), cur(d, key).as_f64(), "", 60.0, 0) { + let id = format!("hy{prefix}{key}"); + let field = crate::widgets::NumField::number(&id, cur(d, key).as_f64(), "", 0).name(caption.trim_end_matches(':')); + if let Some(n) = field.width(60.0).spinner().show(ui) { d.fields.insert(format!("{prefix}{key}"), json!(n.round().clamp(min, max) as u64)); } crate::rtl::label(ui, tr(unit)); ui.end_row(); } - label_right(ui, &tr("Hyphenation Zone:")); - if let Some(n) = crate::widgets::spin_measure(ui, &format!("hy{prefix}zone"), cur(d, "hyphZone").as_f64(), units, 60.0) { + let zone = tr("Hyphenation Zone:"); + label_right(ui, &zone); + let id = format!("hy{prefix}zone"); + let field = crate::widgets::NumField::measure(&id, cur(d, "hyphZone").as_f64(), units).name(zone.trim_end_matches(':')); + if let Some(n) = field.width(60.0).spinner().show(ui) { d.fields.insert(format!("{prefix}hyphZone"), json!(if n.is_finite() { n.clamp(0.0, 8640.0) } else { 36.0 })); } ui.end_row(); @@ -8297,19 +8348,26 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu crate::rtl::label(ui, crate::i18n::tr(lang, "Maximum")); ui.end_row(); for (label, base, _) in JUSTIFY_ROWS { - crate::rtl::label(ui, crate::i18n::tr(lang, &format!("{label}:"))); - for suffix in ["Min", "Desired", "Max"] { + let row = format!("{label}:"); + let caption = crate::i18n::tr(lang, &row); + crate::rtl::label(ui, caption); + // Each field is named by its row and column ("Word Spacing Minimum"). + for (suffix, column) in [("Min", "Minimum"), ("Desired", "Desired"), ("Max", "Maximum")] { let key = format!("{base}{suffix}"); let v = cur(d, &key).as_f64().map(|x| x * 100.0); - if let Some(n) = ui.scope(|ui| crate::widgets::number(ui, &format!("ps{key}"), v, "%", 60.0, 0)).inner { + let (id, name) = (format!("ps{key}"), format!("{} {}", caption.trim_end_matches(':'), crate::i18n::tr(lang, column))); + if let Some(n) = ui.scope(|ui| crate::widgets::NumField::number(&id, v, "%", 0).name(&name).width(60.0).show(ui)).inner { d.fields.insert(format!("{prefix}{key}"), json!(n / 100.0)); } } ui.end_row(); } - crate::rtl::label(ui, crate::i18n::tr(lang, "Auto Leading:")); + let auto_caption = crate::i18n::tr(lang, "Auto Leading:"); + crate::rtl::label(ui, auto_caption); 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 { + let id = format!("ps{prefix}autoLeading"); + let name = auto_caption.trim_end_matches(':'); + if let Some(n) = ui.scope(|ui| crate::widgets::NumField::number(&id, auto, "%", 0).name(name).width(60.0).show(ui)).inner { d.fields.insert(format!("{prefix}autoLeading"), json!(auto_leading_typed(n))); } ui.end_row(); @@ -8420,9 +8478,12 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & // Left and Right Indent, then Keep In Frame (rule above). ui.add_enabled_ui(on, |ui| { egui::Grid::new(("rules", which)).num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { - crate::rtl::label(ui, crate::i18n::tr(lang, "Weight:")); + let weight = crate::i18n::tr(lang, "Weight:"); + crate::rtl::label(ui, weight); if let Some(v) = sized(ui, &mut |ui| { - crate::widgets::NumField::number(&key("weight"), rule["weight"].as_f64(), " pt", 2).width(80.0).spinner().range(0.0, 1000.0).show(ui) + let id = key("weight"); + let field = crate::widgets::NumField::number(&id, rule["weight"].as_f64(), " pt", 2).name(weight.trim_end_matches(':')); + field.width(80.0).spinner().range(0.0, 1000.0).show(ui) }) { d.fields.insert(key("weight"), json!(v.clamp(0.0, 1000.0))); } @@ -8450,8 +8511,13 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & if let Some(w) = doc.and_then(|doc| swatch_menu_with(ui, doc, ("rule_color", which), &color, 130.0, Some(text_color))) { d.fields.insert(key("color"), json!(w)); } - crate::rtl::label(ui, crate::i18n::tr(lang, "Tint:")); - if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("tint"), rule["tint"].as_f64().map(|t| t * 100.0), "%", 80.0, 0)) { + let tint = crate::i18n::tr(lang, "Tint:"); + crate::rtl::label(ui, tint); + if let Some(v) = sized(ui, &mut |ui| { + let id = key("tint"); + let field = crate::widgets::NumField::number(&id, rule["tint"].as_f64().map(|t| t * 100.0), "%", 0).name(tint.trim_end_matches(':')); + field.width(80.0).show(ui) + }) { d.fields.insert(key("tint"), json!((v / 100.0).clamp(0.0, 1.0))); } ui.end_row(); @@ -8464,11 +8530,16 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & d.fields.insert(key("gapColor"), json!(w)); } }); - crate::rtl::label(ui, crate::i18n::tr(lang, "Gap Tint:")); + let gap_tint_caption = crate::i18n::tr(lang, "Gap Tint:"); + crate::rtl::label(ui, gap_tint_caption); ui.add_enabled_ui(gaps && gap != designcraft_color::swatch::NONE, |ui| { // A full gap tint is left out of the rule's JSON: it reads 100%. let gap_tint = rule["gapTint"].as_f64().unwrap_or(1.0) * 100.0; - if let Some(v) = sized(ui, &mut |ui| crate::widgets::number(ui, &key("gapTint"), Some(gap_tint), "%", 80.0, 0)) { + if let Some(v) = sized(ui, &mut |ui| { + let id = key("gapTint"); + let field = crate::widgets::NumField::number(&id, Some(gap_tint), "%", 0).name(gap_tint_caption.trim_end_matches(':')); + field.width(80.0).show(ui) + }) { d.fields.insert(key("gapTint"), json!((v / 100.0).clamp(0.0, 1.0))); } }); @@ -8485,18 +8556,30 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & } } }); - crate::rtl::label(ui, crate::i18n::tr(lang, "Offset:")); + let offset = crate::i18n::tr(lang, "Offset:"); + crate::rtl::label(ui, offset); if let Some(v) = sized(ui, &mut |ui| { - crate::widgets::NumField::measure(&key("offset"), rule["offset"].as_f64(), v_units).width(80.0).spinner().show(ui) + let id = key("offset"); + crate::widgets::NumField::measure(&id, rule["offset"].as_f64(), v_units) + .name(offset.trim_end_matches(':')) + .width(80.0) + .spinner() + .show(ui) }) { d.fields.insert(key("offset"), json!(v)); } ui.end_row(); for (label, field) in [("Left Indent:", "leftIndent"), ("Right Indent:", "rightIndent")] { - crate::rtl::label(ui, crate::i18n::tr(lang, label)); - if let Some(v) = - sized(ui, &mut |ui| crate::widgets::NumField::measure(&key(field), rule[field].as_f64(), h_units).width(80.0).spinner().show(ui)) - { + let caption = crate::i18n::tr(lang, label); + crate::rtl::label(ui, caption); + if let Some(v) = sized(ui, &mut |ui| { + let id = key(field); + crate::widgets::NumField::measure(&id, rule[field].as_f64(), h_units) + .name(caption.trim_end_matches(':')) + .width(80.0) + .spinner() + .show(ui) + }) { d.fields.insert(key(field), json!(v)); } } diff --git a/crates/ui-egui/src/dialogs/style_cjk.rs b/crates/ui-egui/src/dialogs/style_cjk.rs index acb6a6bc7..ba3525344 100644 --- a/crates/ui-egui/src/dialogs/style_cjk.rs +++ b/crates/ui-egui/src/dialogs/style_cjk.rs @@ -117,10 +117,11 @@ fn grid(id: &str) -> egui::Grid { } /// A number attribute that may be automatic (`null`: half the text size, the text's tint...): -/// emptying the field makes it automatic again. -fn char_auto_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, suffix: &str, scale: f64, range: (f64, f64)) { +/// emptying the field makes it automatic again. The field is named from `caption`. +#[allow(clippy::too_many_arguments)] +fn char_auto_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, suffix: &str, scale: f64, range: (f64, f64)) { let v = cf.get(d, key).as_f64().map(|x| x * scale); - let field = crate::widgets::NumField::number(key, v, suffix, 2).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); if let Some(n) = field.show_or_clear(ui) { cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale))); } @@ -210,10 +211,10 @@ fn tate_chu_yoko(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) ui.add_space(4.0); egui::Grid::new("cjktcy").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Up/Down Position:")); - char_number(ui, d, cf, "tateChuYokoYOffset", " pt", 1.0, (-1000.0, 1000.0)); + char_number(ui, d, cf, "tateChuYokoYOffset", crate::i18n::tr(lang, "Up/Down Position:"), " pt", 1.0, (-1000.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Left/Right Position:")); - char_number(ui, d, cf, "tateChuYokoXOffset", " pt", 1.0, (-1000.0, 1000.0)); + char_number(ui, d, cf, "tateChuYokoXOffset", crate::i18n::tr(lang, "Left/Right Position:"), " pt", 1.0, (-1000.0, 1000.0)); ui.end_row(); }); } @@ -250,10 +251,10 @@ fn ruby_placement(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields crate::rtl::label(ui, egui::RichText::new(tr(lang, "Offset from Parent")).font(crate::theme::semibold(12.0))); grid("cjkrubyoffset").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Across the Line:")); - char_number(ui, d, cf, "rubyYOffset", " pt", 1.0, (-1000.0, 1000.0)); + char_number(ui, d, cf, "rubyYOffset", tr(lang, "Across the Line:"), " pt", 1.0, (-1000.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Along the Line:")); - char_number(ui, d, cf, "rubyXOffset", " pt", 1.0, (-1000.0, 1000.0)); + char_number(ui, d, cf, "rubyXOffset", tr(lang, "Along the Line:"), " pt", 1.0, (-1000.0, 1000.0)); ui.end_row(); }); } @@ -266,20 +267,20 @@ fn ruby_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFi grid("cjkrubyfont").show(ui, |ui| { font_fields(app, ui, d, cf, ("rubyFont", "rubyFontStyle"), true); crate::rtl::label(ui, tr(lang, "Size:")); - char_auto_number(ui, d, cf, "rubyFontSize", " pt", 1.0, (0.1, 1296.0)); + char_auto_number(ui, d, cf, "rubyFontSize", tr(lang, "Size:"), " pt", 1.0, (0.1, 1296.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Horizontal Scale:")); - char_number(ui, d, cf, "rubyXScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "rubyXScale", tr(lang, "Horizontal Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Vertical Scale:")); - char_number(ui, d, cf, "rubyYScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "rubyYScale", tr(lang, "Vertical Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); }); char_check(ui, d, cf, "rubyOpenTypePro", tr(lang, "Use OpenType Pro Ruby Glyphs")); ui.add_space(4.0); grid("cjkrubytcy").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Tate-chu-yoko Digits:")); - char_count(ui, d, cf, "rubyAutoTcyDigits", (0.0, 9.0)); + char_count(ui, d, cf, "rubyAutoTcyDigits", tr(lang, "Tate-chu-yoko Digits:"), (0.0, 9.0)); ui.end_row(); }); char_check(ui, d, cf, "rubyAutoTcyIncludeRoman", tr(lang, "Include Roman Characters")); @@ -329,7 +330,7 @@ fn ruby_longer(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { grid("cjkrubyscale").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Minimum Scale:")); let on = cf.get(d, "rubyAutoScaling").as_bool() == Some(true); - ui.add_enabled_ui(on, |ui| char_number(ui, d, cf, "rubyScalingMin", "%", 100.0, (10.0, 100.0))); + ui.add_enabled_ui(on, |ui| char_number(ui, d, cf, "rubyScalingMin", tr(lang, "Minimum Scale:"), "%", 100.0, (10.0, 100.0))); ui.end_row(); }); char_check(ui, d, cf, "rubyAutoAlign", tr(lang, "Auto Align at Line Start/End")); @@ -377,10 +378,10 @@ fn adornment_color(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharField } grid(&format!("cjkcolorg{prefix}")).show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Tint:")); - char_auto_number(ui, d, cf, &format!("{prefix}{part}Tint"), "%", 100.0, (0.0, 100.0)); + char_auto_number(ui, d, cf, &format!("{prefix}{part}Tint"), tr(lang, "Tint:"), "%", 100.0, (0.0, 100.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Weight:")); - char_auto_number(ui, d, cf, &format!("{prefix}StrokeWeight"), " pt", 1.0, (0.0, 800.0)); + char_auto_number(ui, d, cf, &format!("{prefix}StrokeWeight"), tr(lang, "Weight:"), " pt", 1.0, (0.0, 800.0)); ui.end_row(); }); overprint_check(ui, d, cf, &format!("{prefix}OverprintFill"), tr(lang, "Overprint Fill")); @@ -511,22 +512,22 @@ fn kenten(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharField let custom = on == Some(true) && kind == KentenKind::Custom; grid("cjkkenten").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Distance from Parent:")); - char_number(ui, d, cf, "kentenDistance", " pt", 1.0, (-1296.0, 1296.0)); + char_number(ui, d, cf, "kentenDistance", tr(lang, "Distance from Parent:"), " pt", 1.0, (-1296.0, 1296.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Position:")); char_choice(lang, ui, d, cf, "kentenPosition", &[(json!("aboveRight"), "Above/Right"), (json!("belowLeft"), "Below/Left")]); ui.end_row(); crate::rtl::label(ui, tr(lang, "Size:")); - char_auto_number(ui, d, cf, "kentenSize", " pt", 1.0, (0.1, 1296.0)); + char_auto_number(ui, d, cf, "kentenSize", tr(lang, "Size:"), " pt", 1.0, (0.1, 1296.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Alignment:")); char_choice(lang, ui, d, cf, "kentenAlignment", &[(json!("center"), "Centered"), (json!("start"), "Left/Top")]); ui.end_row(); crate::rtl::label(ui, tr(lang, "Horizontal Scale:")); - char_number(ui, d, cf, "kentenXScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "kentenXScale", tr(lang, "Horizontal Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Vertical Scale:")); - char_number(ui, d, cf, "kentenYScale", "%", 100.0, (1.0, 1000.0)); + char_number(ui, d, cf, "kentenYScale", tr(lang, "Vertical Scale:"), "%", 100.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, tr(lang, "Kenten Type:")); let shown = match on { @@ -566,11 +567,13 @@ fn kenten(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharField fn shatai(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { grid("cjkshatai").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Magnification:")); - char_number(ui, d, cf, "shataiMagnification", "%", 1.0, (0.0, 90.0)); + char_number(ui, d, cf, "shataiMagnification", tr(lang, "Magnification:"), "%", 1.0, (0.0, 90.0)); ui.end_row(); - crate::rtl::label(ui, tr(lang, "Angle:")); + let angle = tr(lang, "Angle:"); + crate::rtl::label(ui, angle); let v = cf.get(d, "shataiAngle").as_f64(); - let field = crate::widgets::NumField::number("shataiAngle", v, "°", 2).width(80.0).range(0.0, 180.0).presets(&[30.0, 45.0, 60.0]); + let field = crate::widgets::NumField::number("shataiAngle", v, "°", 2).name(angle.trim_end_matches(':')); + let field = field.width(80.0).range(0.0, 180.0).presets(&[30.0, 45.0, 60.0]); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, "shataiAngle", n.map_or(Value::Null, |n| json!(n))); @@ -586,24 +589,26 @@ fn shatai(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { fn auto_tate_chu_yoko(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { grid("cjkautotcy").show(ui, |ui| { crate::rtl::label(ui, tr(lang, "Tate-chu-yoko Digits:")); - para_count(ui, d, pv, "autoTcy", (0.0, f64::from(designcraft_compose::shape::AUTO_TCY_MAX))); + para_count(ui, d, pv, "autoTcy", tr(lang, "Tate-chu-yoko Digits:"), (0.0, f64::from(designcraft_compose::shape::AUTO_TCY_MAX))); ui.end_row(); }); para_check(ui, d, pv, "autoTcyIncludeRoman", tr(lang, "Include Roman Characters")); } -/// A whole-number paragraph attribute. -fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, range: (f64, f64)) { +/// A whole-number paragraph attribute, named from `caption`. +fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, range: (f64, f64)) { let v = para_value(d, pv, key).as_f64(); - if let Some(n) = crate::widgets::NumField::number(key, v, "", 0).width(80.0).range(range.0, range.1).show(ui) { + let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches(':')); + if let Some(n) = field.width(80.0).range(range.0, range.1).show(ui) { d.fields.insert(format!("p.{key}"), json!(n.round().max(range.0).min(range.1) as u64)); } } -/// A whole-number attribute (stored as an integer: the model's fields are `u32`). -fn char_count(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, range: (f64, f64)) { +/// A whole-number attribute (stored as an integer: the model's fields are `u32`), named from +/// `caption`. +fn char_count(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, range: (f64, f64)) { let v = cf.get(d, key).as_f64(); - let field = crate::widgets::NumField::number(key, v, "", 0).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, key, n.map_or(Value::Null, |n| json!(n.round().max(range.0).min(range.1) as u64))); @@ -616,13 +621,13 @@ fn warichu(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { ui.add_space(4.0); egui::Grid::new("cjkwarichu").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Lines:")); - char_count(ui, d, cf, "warichuLines", (2.0, 16.0)); + char_count(ui, d, cf, "warichuLines", crate::i18n::tr(lang, "Lines:"), (2.0, 16.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Warichu Size:")); - char_number(ui, d, cf, "warichuSize", "%", 1.0, (1.0, 1000.0)); + char_number(ui, d, cf, "warichuSize", crate::i18n::tr(lang, "Warichu Size:"), "%", 1.0, (1.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Line Spacing:")); - char_number(ui, d, cf, "warichuLineSpacing", " pt", 1.0, (-1000.0, 1000.0)); + char_number(ui, d, cf, "warichuLineSpacing", crate::i18n::tr(lang, "Line Spacing:"), " pt", 1.0, (-1000.0, 1000.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Alignment:")); char_choice( @@ -645,10 +650,10 @@ fn warichu(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, "Line Break Options")).font(crate::theme::semibold(12.0))); egui::Grid::new("cjkwarichubreak").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { crate::rtl::label(ui, crate::i18n::tr(lang, "Characters Before Break:")); - char_count(ui, d, cf, "warichuCharsBeforeBreak", (0.0, 100.0)); + char_count(ui, d, cf, "warichuCharsBeforeBreak", crate::i18n::tr(lang, "Characters Before Break:"), (0.0, 100.0)); ui.end_row(); crate::rtl::label(ui, crate::i18n::tr(lang, "Characters After Break:")); - char_count(ui, d, cf, "warichuCharsAfterBreak", (0.0, 100.0)); + char_count(ui, d, cf, "warichuCharsAfterBreak", crate::i18n::tr(lang, "Characters After Break:"), (0.0, 100.0)); ui.end_row(); }); } @@ -866,10 +871,12 @@ fn grid_settings(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { ui.add_space(4.0); let lines = para_value(d, pv, "gridGyoudori").as_u64().unwrap_or(0); grid("cjkgyoudori").show(ui, |ui| { - crate::rtl::label(ui, tr(lang, "Gyoudori:")); + let gyoudori = tr(lang, "Gyoudori:"); + crate::rtl::label(ui, gyoudori); ui.horizontal(|ui| { // Empty or 0: automatic (as many grid lines as the leading needs). let field = crate::widgets::NumField::number("gridGyoudori", (lines > 0).then_some(lines as f64), "", 0) + .name(gyoudori.trim_end_matches(':')) .width(80.0) .range(0.0, 100.0) .presets(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index f5c6403e8..2dfa38c29 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1796,6 +1796,67 @@ fn text_frame_options_dims_the_sides_for_a_non_rectangular_frame() { } } +/// The number fields of Insert Table and of Paragraph Style Options' sections are named from the +/// captions beside them, not from their internal keys; each name listed is found exactly once. +#[test] +fn dialog_number_fields_are_named_from_their_captions() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + let para = |section: &str, extra: Value| { + let mut fields = json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": section}); + if let (Some(f), Value::Object(extra)) = (fields.as_object_mut(), extra) { + f.extend(extra); + } + Dialog::new("paragraphStyleOptions", fields) + }; + let cases: Vec<(Dialog, &[&str])> = vec![ + (Dialog::new("insertTable", Value::Null), &["Body Rows", "Columns", "Header Rows", "Footer Rows"]), + (para("chars", json!({})), &["Size", "Leading", "Tracking"]), + (para("advanced", json!({})), &["Horizontal Scale", "Vertical Scale", "Baseline Shift", "Skew"]), + (para("indents", json!({})), &["Left Indent", "First Line Indent", "Right Indent", "Space Before", "Space After"]), + (para("tabs", json!({})), &["X"]), + (para("rules", json!({})), &["Weight", "Tint", "Gap Tint", "Offset", "Left Indent", "Right Indent"]), + ( + para("border", json!({})), + &["Stroke Top", "Stroke Right", "Tint", "Gap Tint", "Top Left Corner", "Bottom Right Corner", "Offsets Top", "Offsets Right"], + ), + (para("shading", json!({})), &["Tint", "Top Left Corner", "Offsets Top"]), + (para("keep", json!({})), &["Keep with Next", "Start", "End"]), + (para("hyph", json!({})), &["Words with at Least", "After First", "Before Last", "Hyphen Limit", "Hyphenation Zone"]), + (para("justify", json!({})), &["Word Spacing Minimum", "Letter Spacing Desired", "Glyph Scaling Maximum", "Auto Leading"]), + (para("nested", json!({})), &["Lines", "Characters"]), + ( + para("bullets", json!({"p.listType": "numbers", "p.startAt": 1, "p.listTab": 18})), + &["Level", "Start At", "Left Indent", "First Line Indent", "Tab Position"], + ), + (para("color", json!({})), &["Tint", "Weight"]), + (para("underline", json!({})), &["Weight", "Offset", "Tint"]), + ]; + for (dialog, names) in cases { + let what = format!("{} {}", dialog.id, dialog.s("section")); + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.ui.dialog = Some(dialog); + // The check covers the number fields only: some dropdowns in these views have no name yet. + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("dialog_field_names_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 name in names { + assert_eq!(h.query_all_by_role_and_label(Role::TextInput, name).count(), 1, "{what}: the {name} field"); + } + } +} + /// Text Frame Options shows the insets (or a non-rectangular frame's one Inset), the gutter and /// the other measures in the document's ruler unit, not always in picas, and reads a bare number /// typed there in that unit (#2739). From 4b72a3f6f826117034af124604852d64cc8431e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:38:19 -0800 Subject: [PATCH 080/133] Tools: a drag no longer replaces a dialog's open preview A tool's Begin replaced any open interaction, taking the previewed document as its starting state. A drag while a dialog's preview was shown left the preview in the document with no undo step, whether the drag was kept or canceled. A dialog that opened its preview during a tool's drag or an IME composition replaced that gesture the same way. Session::begin_interaction now fails while another interaction is open, after keeping an IME composition's marked text as typed. A tool's drag that begins while a dialog's preview is open is refused, and its previews, commit and cancel leave the preview alone. A drag whose release never came is kept as its own undo step when the tool's next one begins. --- crates/engine/src/lib.rs | 8 +++++ crates/engine/src/tests.rs | 57 ++++++++++++++++++++++++++++++++++ crates/engine/src/tests/ime.rs | 16 ++++++++++ crates/engine/src/tooling.rs | 42 ++++++++++++++++++++++++- 4 files changed, 122 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ac899412e..8fe91bddd 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -404,6 +404,12 @@ pub struct Session { /// The selection tool a Cmd-held press borrows for one gesture while another tool stays /// chosen (#919). Dropped on release. pub(crate) temp_tool: Option>, + /// The tool's gesture began while another interaction (a dialog's preview) was open, so its + /// Begin was refused: its previews, commit and cancel are dropped until it ends. + pub(crate) refused_gesture: bool, + /// The document uid and starting revision of the interaction the tool's gesture opened, while + /// it is open. + pub(crate) tool_interaction: Option<(u64, u64)>, /// The selection tool (`selection` or `directSelection`) chosen last: the one Cmd borrows. pub(crate) last_selection_tool: &'static str, pub journal: Vec<(String, Value)>, @@ -477,6 +483,8 @@ impl Session { cache: Arc::new(Cache::new()), tool: designcraft_tools::create("selection"), temp_tool: None, + refused_gesture: false, + tool_interaction: None, last_selection_tool: "selection", journal: vec![], find_context: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 10b42ee68..7eff53e7c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -160,6 +160,63 @@ fn tool_gesture_creates_one_undo_step() { assert!((it.visible_bounds().x0 - 36.0).abs() < 1e-6, "visible {:?} path {:?}", it.visible_bounds(), it.bounds()); } +/// A tool's drag while a dialog's preview is open is refused: the preview stays for the dialog to +/// keep or cancel, and the drag leaves no change without an undo step. +#[test] +fn a_tool_drag_leaves_a_dialogs_preview_alone() { + use designcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::at_zoom(1.0); + let before = s.doc().unwrap().doc.clone(); + s.begin_interaction("Create Guides").unwrap(); + s.preview("layout.createGuides", json!({"rows": 2, "columns": 2})).unwrap(); + let previewed = s.doc().unwrap().doc.clone(); + assert_ne!(previewed, before, "previewed"); + s.set_tool("rectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + let err = s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap_err().to_string(); + assert!(err.contains("Create Guides is in progress"), "{err}"); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 200.0), v).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.interaction.as_ref().map(|it| it.label.as_str()), Some("Create Guides")); + assert_eq!(st.doc, previewed, "the drag drew nothing"); + assert!(st.history.undo.is_empty()); + s.cancel_interaction(); + assert_eq!(s.doc().unwrap().doc, before, "Cancel takes the guides away"); + // With the preview gone, the next drag draws as before. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + let st = s.doc().unwrap(); + assert_eq!(st.doc.spreads[0].items.len(), 1); + assert_eq!(st.history.undo.len(), 1); +} + +/// A dialog's preview does not start while a tool's drag is open, and a drag whose release never +/// came is kept as its own undo step when the tool's next one begins. +#[test] +fn an_open_tool_drag_is_not_replaced() { + use designcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::at_zoom(1.0); + s.set_tool("rectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap(); + let label = s.doc().unwrap().interaction.as_ref().map(|it| it.label.clone()).expect("the drag is open"); + let err = s.begin_interaction("Create Guides").unwrap_err().to_string(); + assert_eq!(err, format!("{label} is in progress")); + assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.clone()), Some(label)); + // No release: the next press starts another drag. + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let st = s.doc().unwrap(); + assert!(st.interaction.is_none()); + assert_eq!(st.doc.spreads[0].items.len(), 2); + assert_eq!(st.history.undo.len(), 2, "one undo step for each drag"); +} + /// A command that runs another one (Cut runs Clear) recorded an undo step for each, so the /// second Undo did nothing. One command is one step, whatever it runs inside. #[test] diff --git a/crates/engine/src/tests/ime.rs b/crates/engine/src/tests/ime.rs index 222142c80..bbe12ab6a 100644 --- a/crates/engine/src/tests/ime.rs +++ b/crates/engine/src/tests/ime.rs @@ -222,3 +222,19 @@ fn a_cancelled_gesture_puts_back_the_revision_and_leaves_a_saved_document_saved( assert!(!seen.contains(&after), "{after} in {seen:?}"); assert!(s.doc().unwrap().is_dirty()); } + +/// A dialog's preview that opens during a composition keeps the marked text as typed first, as +/// one undo step, and then opens on that document. +#[test] +fn a_dialog_preview_ends_the_composition_first() { + let mut s = session(); + let sid = typing_into(&mut s, "a"); + s.tool_preedit("が", None, ViewInfo::default()).unwrap(); + let before = steps(&s); + s.begin_interaction("Hyphenation").unwrap(); + assert!(!s.tool_composing()); + assert_eq!(s.doc().unwrap().interaction.as_ref().map(|it| it.label.as_str()), Some("Hyphenation")); + assert_eq!(steps(&s), before + 1); + s.cancel_interaction(); + assert_eq!(text(&mut s, sid), "aが"); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 2badc3a17..c8ffe4799 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -68,6 +68,7 @@ impl Session { } self.tool = designcraft_tools::create(id); self.temp_tool = None; + self.refused_gesture = false; if matches!(self.tool.id(), "selection" | "directSelection") { self.last_selection_tool = self.tool.id(); } @@ -262,7 +263,10 @@ impl Session { pub fn run_actions(&mut self, actions: Vec) -> Result<()> { for a in actions { match a { - Action::Begin(label) => self.begin_interaction(&label)?, + Action::Begin(label) => self.begin_gesture(&label)?, + // A refused gesture leaves the open interaction alone until it ends. + Action::Preview(..) if self.refused_gesture => {} + Action::Commit | Action::Cancel if self.refused_gesture => self.refused_gesture = false, Action::Preview(cmd, p) => self.preview(&cmd, p)?, Action::Commit => self.commit_interaction()?, Action::Cancel => self.cancel_interaction(), @@ -278,13 +282,46 @@ impl Session { Ok(()) } + /// Open an interaction (a dialog's preview) on the active document. Marked text of an IME + /// composition is kept as typed first. Fails while another interaction is open. pub fn begin_interaction(&mut self, label: &str) -> Result<()> { + self.end_composition()?; + self.open_interaction(label) + } + + /// A tool's Begin. The tool's own gesture that never got its end (a release lost to a tool + /// switch) is kept as its own undo step first. While another interaction is open (a dialog's + /// preview) the gesture is refused, and its previews, commit and cancel are dropped. + fn begin_gesture(&mut self, label: &str) -> Result<()> { + if self.active().is_some_and(|st| st.interaction.as_ref().is_some_and(|it| self.tool_interaction == Some((st.uid, it.revision)))) { + self.commit_interaction()?; + } + let r = self.open_interaction(label); + self.refused_gesture = r.is_err(); + if r.is_ok() { + self.tool_interaction = self.active().and_then(|st| st.interaction.as_ref().map(|it| (st.uid, it.revision))); + } + r + } + + fn open_interaction(&mut self, label: &str) -> Result<()> { let st = self.doc_mut()?; + // Replacing an open interaction would leave its preview in the document with no undo step. + if let Some(open) = &st.interaction { + return Err(EngineError::Other(format!("{} is in progress", open.label))); + } st.interaction = Some(Interaction { label: label.into(), doc: st.doc.clone(), selection: st.selection.clone(), preview: None, revision: st.revision }); Ok(()) } + /// The interaction of the document with `uid` ended: it is no longer the tool's. + fn end_tool_interaction(&mut self, uid: Option) { + if self.tool_interaction.is_some_and(|(u, _)| Some(u) == uid) { + self.tool_interaction = None; + } + } + /// Apply `cmd` on top of the interaction's snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: Value) -> Result<()> { let st = self.doc_mut()?; @@ -307,6 +344,7 @@ impl Session { } pub fn commit_interaction(&mut self) -> Result<()> { + self.end_tool_interaction(self.active().map(|st| st.uid)); let st = self.doc_mut()?; let Some(it) = st.interaction.take() else { return Ok(()) }; if !Arc::ptr_eq(&it.doc, &st.doc) { @@ -321,6 +359,7 @@ impl Session { } pub fn cancel_interaction(&mut self) { + self.end_tool_interaction(self.active().map(|st| st.uid)); if let Some(st) = self.active_mut() && let Some(it) = st.interaction.take() { @@ -346,6 +385,7 @@ impl Session { st.doc = it.doc; st.selection = it.selection; st.revision = it.revision; + self.end_tool_interaction(Some(uid)); } } } From 3c15887fd99c86b6c957a930588aa89f6a575c16 Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Sat, 14 Nov 2026 22:58:57 +0000 Subject: [PATCH 081/133] fix(tools): select the point Direct Selection presses on an unselected path Pressing an anchor of a path that wasn't selected selected only the path, so the point stayed hollow while it was dragged. It is now selected too and draws solid, as when the path was already selected. Fixes #2564 --- crates/engine/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ crates/tools/src/select.rs | 4 +++- crates/tools/src/tests.rs | 5 ++++- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 08c30cdef..98b19fad5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2317,6 +2317,39 @@ fn direct_selection_pulls_one_corner_of_an_unselected_frame() { assert!(corners(&s).iter().zip(&before).all(|(p, q)| (p.y - q.y - 50.0).abs() < 1e-6), "{:?}", corners(&s)); } +/// Issue #2564: with Direct Selection, pressing a point of a path that isn't selected selects +/// that point (drawn solid), whether the press is a click or a drag. +#[test] +fn direct_selection_press_on_an_unselected_path_selects_the_point() { + use designcraft_tools::{PointerEvent, PointerKind, SnapView}; + let mut s = session(); + let id = s.execute("path.create", &json!({"anchors": [{"p": [100, 300]}, {"p": [300, 400]}]})).unwrap()["id"].as_u64().unwrap(); + s.set_tool("directSelection"); + let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) }; + let layout = s.layout(); + let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y)); + let item = designcraft_doc::ItemId(id); + // A click on the end point. + s.execute("edit.deselectAll", &json!({})).unwrap(); + let p = at(300.0, 400.0); + s.pointer(&PointerEvent::new(PointerKind::Down, p.x, p.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, p.x, p.y), v).unwrap(); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.items, [item]); + assert_eq!(sel.anchors, [(item, 0, 1)], "the clicked point is selected"); + // A drag from the start point: it moves and stays selected. + s.execute("edit.deselectAll", &json!({})).unwrap(); + let (a, b) = (at(100.0, 300.0), at(100.0, 250.0)); + s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, a.x, a.y - 20.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap(); + let st = s.doc().unwrap(); + let it = st.doc.item(item).unwrap(); + assert!((it.xf * it.path.subpaths[0].anchors[0].p - designcraft_geom::Point::new(100.0, 250.0)).hypot() < 1e-6); + assert_eq!(st.selection.anchors, [(item, 0, 0)], "the dragged point is selected"); +} + #[test] fn direct_selection_on_a_selected_frame_deletes_only_its_image() { use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 1fb30e6f7..895c57224 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -848,7 +848,9 @@ impl SelectionTool { { let at = anchor_spread_point(cx, id, si, ai); self.drag = Drag::Anchor { id, si, ai, handle: None, start: p, at, others: vec![] }; - return vec![Action::Exec("selection.set".into(), json!({"ids": [id], "content": false})), Action::Begin("Move Anchor".into())]; + // The point pressed is selected too, so it draws solid like any selected point. + let points = json!({"ids": [id], "content": false, "anchors": [[id, si, ai]]}); + return vec![Action::Exec("selection.set".into(), points), Action::Begin("Move Anchor".into())]; } // A selected placed graphic's own handles resize it inside its frame (the // frame's anchors, under Direct Selection, come first). diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index acbef71fa..ec55a4d27 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2306,7 +2306,10 @@ fn pulling_a_corner_of_an_unselected_frame_selects_the_frame_not_its_content() { let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)); assert_eq!( acts, - vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [a.0], "content": false})), Action::Begin("Move Anchor".into())] + vec![ + Action::Exec("selection.set".into(), serde_json::json!({"ids": [a.0], "content": false, "anchors": [[a.0, 0, 1]]})), + Action::Begin("Move Anchor".into()) + ] ); } From c008d24d0f88a125296f2cd0096dc3e3cc3ece0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:03:05 -0800 Subject: [PATCH 082/133] Tools: an open drag stays with its document The interaction a tool's drag opens now carries its own mark, so a finished drag in another document no longer clears it. Returning to the first document and dragging again keeps the open drag as its own undo step instead of refusing the new one. --- crates/engine/src/lib.rs | 6 ++---- crates/engine/src/tests.rs | 32 ++++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 38 +++++++++++++++--------------------- 3 files changed, 50 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1c1a9b18..f9c5e8f71 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -84,6 +84,8 @@ pub struct Interaction { pub preview: Option<(String, Value)>, /// The document's revision when the gesture began: a cancel puts it back. pub revision: u64, + /// A tool's gesture opened it, not a dialog's preview. + pub tool: bool, } #[derive(Clone, Debug)] @@ -411,9 +413,6 @@ pub struct Session { /// The tool's gesture began while another interaction (a dialog's preview) was open, so its /// Begin was refused: its previews, commit and cancel are dropped until it ends. pub(crate) refused_gesture: bool, - /// The document uid and starting revision of the interaction the tool's gesture opened, while - /// it is open. - pub(crate) tool_interaction: Option<(u64, u64)>, /// The selection tool (`selection` or `directSelection`) chosen last: the one Cmd borrows. pub(crate) last_selection_tool: &'static str, pub journal: Vec<(String, Value)>, @@ -491,7 +490,6 @@ impl Session { tool: designcraft_tools::create("selection"), temp_tool: None, refused_gesture: false, - tool_interaction: None, last_selection_tool: "selection", journal: vec![], find_context: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index aed42b671..9e4fb95fa 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -217,6 +217,38 @@ fn an_open_tool_drag_is_not_replaced() { assert_eq!(st.history.undo.len(), 2, "one undo step for each drag"); } +/// A drag left open in one document stays that document's: a finished drag in another document +/// does not take it over, and the next drag back in the first one keeps it as its own undo step. +#[test] +fn an_open_tool_drag_stays_with_its_document() { + use designcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::at_zoom(1.0); + s.execute("file.new", &json!({})).unwrap(); + s.set_active(0); + s.set_tool("rectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap(); + // No release: the other document's drag begins and ends. + s.set_active(1); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 55.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 55.0), v).unwrap(); + s.set_active(0); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let st = s.doc().unwrap(); + assert!(st.interaction.is_none()); + assert_eq!(st.doc.spreads[0].items.len(), 2); + assert_eq!(st.history.undo.len(), 2, "one undo step for each drag"); + s.set_active(1); + let st = s.doc().unwrap(); + assert!(st.interaction.is_none()); + assert_eq!(st.doc.spreads[0].items.len(), 1); + assert_eq!(st.history.undo.len(), 1); +} + /// A command that runs another one (Cut runs Clear) recorded an undo step for each, so the /// second Undo did nothing. One command is one step, whatever it runs inside. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 06f520d27..11838e074 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -297,42 +297,39 @@ impl Session { /// composition is kept as typed first. Fails while another interaction is open. pub fn begin_interaction(&mut self, label: &str) -> Result<()> { self.end_composition()?; - self.open_interaction(label) + self.open_interaction(label, false) } - /// A tool's Begin. The tool's own gesture that never got its end (a release lost to a tool - /// switch) is kept as its own undo step first. While another interaction is open (a dialog's - /// preview) the gesture is refused, and its previews, commit and cancel are dropped. + /// A tool's Begin. The tool's own gesture on this document that never got its end (a release + /// lost to a tool or document switch) is kept as its own undo step first. While another + /// interaction is open (a dialog's preview) the gesture is refused, and its previews, commit and + /// cancel are dropped. fn begin_gesture(&mut self, label: &str) -> Result<()> { - if self.active().is_some_and(|st| st.interaction.as_ref().is_some_and(|it| self.tool_interaction == Some((st.uid, it.revision)))) { + if self.active().is_some_and(|st| st.interaction.as_ref().is_some_and(|it| it.tool)) { self.commit_interaction()?; } - let r = self.open_interaction(label); + let r = self.open_interaction(label, true); self.refused_gesture = r.is_err(); - if r.is_ok() { - self.tool_interaction = self.active().and_then(|st| st.interaction.as_ref().map(|it| (st.uid, it.revision))); - } r } - fn open_interaction(&mut self, label: &str) -> Result<()> { + fn open_interaction(&mut self, label: &str, tool: bool) -> Result<()> { let st = self.doc_mut()?; // Replacing an open interaction would leave its preview in the document with no undo step. if let Some(open) = &st.interaction { return Err(EngineError::Other(format!("{} is in progress", open.label))); } - st.interaction = - Some(Interaction { label: label.into(), doc: st.doc.clone(), selection: st.selection.clone(), preview: None, revision: st.revision }); + st.interaction = Some(Interaction { + label: label.into(), + doc: st.doc.clone(), + selection: st.selection.clone(), + preview: None, + revision: st.revision, + tool, + }); Ok(()) } - /// The interaction of the document with `uid` ended: it is no longer the tool's. - fn end_tool_interaction(&mut self, uid: Option) { - if self.tool_interaction.is_some_and(|(u, _)| Some(u) == uid) { - self.tool_interaction = None; - } - } - /// Apply `cmd` on top of the interaction's snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: Value) -> Result<()> { let st = self.doc_mut()?; @@ -355,7 +352,6 @@ impl Session { } pub fn commit_interaction(&mut self) -> Result<()> { - self.end_tool_interaction(self.active().map(|st| st.uid)); let st = self.doc_mut()?; let Some(it) = st.interaction.take() else { return Ok(()) }; if !Arc::ptr_eq(&it.doc, &st.doc) { @@ -370,7 +366,6 @@ impl Session { } pub fn cancel_interaction(&mut self) { - self.end_tool_interaction(self.active().map(|st| st.uid)); if let Some(st) = self.active_mut() && let Some(it) = st.interaction.take() { @@ -396,7 +391,6 @@ impl Session { st.doc = it.doc; st.selection = it.selection; st.revision = it.revision; - self.end_tool_interaction(Some(uid)); } } } From 52e3e8b7bb3d2e7e915eb4110e02642ceea50ded Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:06:13 -0800 Subject: [PATCH 083/133] Dialogs: number field names drop a full-width colon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Chinese catalog ends captions with a full-width colon, so a field named from its caption kept it ("大小:" for Size). Every name trimmed from a caption in the dialogs now drops both colon forms, as setting_label already does. --- crates/ui-egui/src/dialogs.rs | 56 +++++++++++++------------ crates/ui-egui/src/dialogs/style_cjk.rs | 10 ++--- crates/ui-egui/src/dialogs/tests.rs | 33 +++++++++++++++ 3 files changed, 68 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 41fc9eb16..fdb88528d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1361,7 +1361,7 @@ fn text_frame_options_dialog(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) /// named from its `caption`. fn spin_measure(ui: &mut egui::Ui, d: &mut Dialog, key: &str, caption: &str, w: f32, enabled: bool) { let id = format!("tfo_{key}"); - let field = crate::widgets::NumField::measure(&id, d.m(key), d.unit).name(caption.trim_end_matches(':')); + let field = crate::widgets::NumField::measure(&id, d.m(key), d.unit).name(caption.trim_end_matches([':', ':'])); if let Some(v) = field.width(w).spinner().range(0.0, 15552.0).enabled(enabled).show(ui) { d.fields.insert(key.into(), json!(format_measure(v, d.unit))); } @@ -1461,7 +1461,7 @@ pub(crate) fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { let number = crate::i18n::tr_context(lang, "Number:", "count"); caption_at(ui, number, cap); let n = d.n("columns"); - let columns = crate::widgets::NumField::number("tfo_columns", n, "", 0).name(number.trim_end_matches(':')); + let columns = crate::widgets::NumField::number("tfo_columns", n, "", 0).name(number.trim_end_matches([':', ':'])); if let Some(v) = columns.width(field).spinner().range(1.0, 40.0).show(ui) { d.fields.insert("columns".into(), json!(v.round().to_string())); } @@ -1479,7 +1479,7 @@ pub(crate) fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { 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 auto = crate::widgets::NumField::measure("tfo_auto_width", width, d.unit).name(tr("Width:").trim_end_matches(':')); + let auto = crate::widgets::NumField::measure("tfo_auto_width", width, d.unit).name(tr("Width:").trim_end_matches([':', ':'])); let _ = auto.width(field).spinner().enabled(false).show(ui); } }); @@ -1489,7 +1489,7 @@ pub(crate) fn general(lang: &str, ui: &mut egui::Ui, d: &mut Dialog) { // Maximum is for Flexible Width columns, which aren't in the document model yet. caption_at(ui, tr("Maximum:"), cap2); ui.add_enabled_ui(false, |ui| { - let max = crate::widgets::NumField::number("tfo_max", None, "", 0).name(tr("Maximum:").trim_end_matches(':')); + let max = crate::widgets::NumField::number("tfo_max", None, "", 0).name(tr("Maximum:").trim_end_matches([':', ':'])); let _ = max.width(field).spinner().enabled(false).show(ui); }); }); @@ -4343,7 +4343,7 @@ fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let caption = crate::i18n::tr(&lang, "Tint:"); crate::rtl::label(ui, caption); let tint = values["fillTint"].as_f64().map(|t| (t * 100.0).round()); - let field = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).name(caption.trim_end_matches(':')); + let field = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).name(caption.trim_end_matches([':', ':'])); if let Some(t) = field.width(60.0).range(0.0, 100.0).show(ui) { d.fields.insert("fillTint".into(), json!(t / 100.0)); } @@ -5986,7 +5986,9 @@ fn paragraph_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo crate::rtl::label(ui, caption); let v = cur(d, &format!("p.{key}"), &pv[key]).as_f64(); let id = format!("ps{key}"); - if let Some(n) = crate::widgets::NumField::measure(&id, v, units).name(caption.trim_end_matches(':')).width(80.0).show(ui) { + if let Some(n) = + crate::widgets::NumField::measure(&id, v, units).name(caption.trim_end_matches([':', ':'])).width(80.0).show(ui) + { d.fields.insert(format!("p.{key}"), json!(n)); } ui.end_row(); @@ -6261,7 +6263,8 @@ fn style_tabs(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &d ui.add_space(6.0); let x_caption = crate::i18n::tr(lang, "X:"); crate::rtl::label(ui, x_caption); - let x_field = crate::widgets::NumField::measure("pstabx", stop.as_ref().map(|s| s.position), unit).name(x_caption.trim_end_matches(':')); + let x_field = + crate::widgets::NumField::measure("pstabx", stop.as_ref().map(|s| s.position), unit).name(x_caption.trim_end_matches([':', ':'])); if let Some(x) = x_field.width(72.0).show(ui) { result = Some(match sel { Some(i) => tabs::move_to(&mut list, i, x), @@ -6333,7 +6336,7 @@ fn para_set(d: &mut Dialog, key: &str, v: Value) { fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, range: (u32, u32)) { let v = para_value(d, pv, key).as_f64(); let id = format!("ps{key}"); - if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches(':')).width(50.0).show(ui) { + if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches([':', ':'])).width(50.0).show(ui) { let n = if n.is_finite() { n.round().clamp(f64::from(range.0), f64::from(range.1)) as u32 } else { range.0 }; para_set(d, key, json!(n)); } @@ -6350,7 +6353,7 @@ fn para_check(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, label: & fn para_measure(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, unit: Unit) { let v = para_value(d, pv, key).as_f64(); let id = format!("ps{key}"); - if let Some(n) = crate::widgets::NumField::measure(&id, v, unit).name(caption.trim_end_matches(':')).width(80.0).show(ui) { + if let Some(n) = crate::widgets::NumField::measure(&id, v, unit).name(caption.trim_end_matches([':', ':'])).width(80.0).show(ui) { para_set(d, key, json!(n)); } } @@ -6393,7 +6396,7 @@ fn para_sides( for (i, label) in ["Top:", "Left:", "Bottom:", "Right:"].into_iter().enumerate() { let caption = crate::i18n::tr(lang, label); crate::rtl::label(ui, caption); - let name = format!("{group} {}", caption.trim_end_matches(':')); + let name = format!("{group} {}", caption.trim_end_matches([':', ':'])); if let Some(v) = field(ui, &format!("ps{key}{i}"), &name, sides.get(i).copied()) { // Linked, a side typed in sets all four. if linked { @@ -6611,7 +6614,7 @@ fn para_color_tint( ui.add_enabled_ui(enabled, |ui| { ui.horizontal(|ui| { let id = format!("ps{tint_key}"); - let field = crate::widgets::NumField::number(&id, tint, "%", 0).name(labels.1.trim_end_matches(':')); + let field = crate::widgets::NumField::number(&id, tint, "%", 0).name(labels.1.trim_end_matches([':', ':'])); let field = field.width(96.0).spinner().presets(TINTS).step(10.0).range(0.0, 100.0); if let Some(v) = field.show(ui) { para_set(d, tint_key, json!(if v.is_finite() { (v / 100.0).clamp(0.0, 1.0) } else { 1.0 })); @@ -6757,7 +6760,7 @@ fn drop_cap_fields(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, cn crate::rtl::label(ui, caption); let v = field_or(d, &format!("p.{key}"), &pv[key]).as_f64(); let id = format!("ps{key}"); - if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches(':')).width(60.0).show(ui) { + if let Some(n) = crate::widgets::NumField::number(&id, v, "", 0).name(caption.trim_end_matches([':', ':'])).width(60.0).show(ui) { d.fields.insert(format!("p.{key}"), json!((n.max(0.0) as u64).min(max as u64))); } ui.end_row(); @@ -7102,7 +7105,7 @@ fn span_columns(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: SpanColumns::Split(n) => { let caption = crate::i18n::tr(lang, "Columns:"); crate::rtl::label(ui, caption); - let field = crate::widgets::NumField::number("pssplitn", Some(f64::from(n)), "", 0).name(caption.trim_end_matches(':')); + let field = crate::widgets::NumField::number("pssplitn", Some(f64::from(n)), "", 0).name(caption.trim_end_matches([':', ':'])); if let Some(c) = field.width(50.0).show(ui) { next = Some(SpanColumns::Split(if c.is_finite() { c.round().clamp(2.0, 20.0) as u32 } else { 2 })); } @@ -7403,7 +7406,7 @@ fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Val } if let Some(t) = tab && let Some(v) = crate::widgets::NumField::measure("pslisttab", Some(t), units) - .name(tab_caption.trim_end_matches(':')) + .name(tab_caption.trim_end_matches([':', ':'])) .width(80.0) .show(ui) { @@ -7724,7 +7727,7 @@ impl CharFields<'_> { #[allow(clippy::too_many_arguments)] fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, suffix: &str, scale: f64, range: (f64, f64)) { let v = cf.get(d, key).as_f64().map(|x| x * scale); - let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches([':', ':'])).width(80.0).range(range.0, range.1); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale))); @@ -7838,7 +7841,7 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo _ => None, }; let field = crate::widgets::NumField::points("pslead", lv, 2) - .name(crate::i18n::tr(lang, "Leading:").trim_end_matches(':')) + .name(crate::i18n::tr(lang, "Leading:").trim_end_matches([':', ':'])) .width(80.0) .range(0.0, 5000.0); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; @@ -8292,7 +8295,7 @@ fn hyphenation(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, curr label_right(ui, &caption); let min = if key == "hyphLimit" { 0.0 } else { 1.0 }; let id = format!("hy{prefix}{key}"); - let field = crate::widgets::NumField::number(&id, cur(d, key).as_f64(), "", 0).name(caption.trim_end_matches(':')); + let field = crate::widgets::NumField::number(&id, cur(d, key).as_f64(), "", 0).name(caption.trim_end_matches([':', ':'])); if let Some(n) = field.width(60.0).spinner().show(ui) { d.fields.insert(format!("{prefix}{key}"), json!(n.round().clamp(min, max) as u64)); } @@ -8302,7 +8305,7 @@ fn hyphenation(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, curr let zone = tr("Hyphenation Zone:"); label_right(ui, &zone); let id = format!("hy{prefix}zone"); - let field = crate::widgets::NumField::measure(&id, cur(d, "hyphZone").as_f64(), units).name(zone.trim_end_matches(':')); + let field = crate::widgets::NumField::measure(&id, cur(d, "hyphZone").as_f64(), units).name(zone.trim_end_matches([':', ':'])); if let Some(n) = field.width(60.0).spinner().show(ui) { d.fields.insert(format!("{prefix}hyphZone"), json!(if n.is_finite() { n.clamp(0.0, 8640.0) } else { 36.0 })); } @@ -8419,7 +8422,7 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu for (suffix, column) in [("Min", "Minimum"), ("Desired", "Desired"), ("Max", "Maximum")] { let key = format!("{base}{suffix}"); let v = cur(d, &key).as_f64().map(|x| x * 100.0); - let (id, name) = (format!("ps{key}"), format!("{} {}", caption.trim_end_matches(':'), crate::i18n::tr(lang, column))); + let (id, name) = (format!("ps{key}"), format!("{} {}", caption.trim_end_matches([':', ':']), crate::i18n::tr(lang, column))); if let Some(n) = ui.scope(|ui| crate::widgets::NumField::number(&id, v, "%", 0).name(&name).width(60.0).show(ui)).inner { d.fields.insert(format!("{prefix}{key}"), json!(n / 100.0)); } @@ -8430,7 +8433,7 @@ fn justification(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, prefix: &str, cu crate::rtl::label(ui, auto_caption); let auto = cur(d, "autoLeading").as_f64().map(|x| x * 100.0); let id = format!("ps{prefix}autoLeading"); - let name = auto_caption.trim_end_matches(':'); + let name = auto_caption.trim_end_matches([':', ':']); if let Some(n) = ui.scope(|ui| crate::widgets::NumField::number(&id, auto, "%", 0).name(name).width(60.0).show(ui)).inner { d.fields.insert(format!("{prefix}autoLeading"), json!(auto_leading_typed(n))); } @@ -8546,7 +8549,7 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & crate::rtl::label(ui, weight); if let Some(v) = sized(ui, &mut |ui| { let id = key("weight"); - let field = crate::widgets::NumField::number(&id, rule["weight"].as_f64(), " pt", 2).name(weight.trim_end_matches(':')); + let field = crate::widgets::NumField::number(&id, rule["weight"].as_f64(), " pt", 2).name(weight.trim_end_matches([':', ':'])); field.width(80.0).spinner().range(0.0, 1000.0).show(ui) }) { d.fields.insert(key("weight"), json!(v.clamp(0.0, 1000.0))); @@ -8579,7 +8582,8 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & crate::rtl::label(ui, tint); if let Some(v) = sized(ui, &mut |ui| { let id = key("tint"); - let field = crate::widgets::NumField::number(&id, rule["tint"].as_f64().map(|t| t * 100.0), "%", 0).name(tint.trim_end_matches(':')); + let field = + crate::widgets::NumField::number(&id, rule["tint"].as_f64().map(|t| t * 100.0), "%", 0).name(tint.trim_end_matches([':', ':'])); field.width(80.0).show(ui) }) { d.fields.insert(key("tint"), json!((v / 100.0).clamp(0.0, 1.0))); @@ -8601,7 +8605,7 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & let gap_tint = rule["gapTint"].as_f64().unwrap_or(1.0) * 100.0; if let Some(v) = sized(ui, &mut |ui| { let id = key("gapTint"); - let field = crate::widgets::NumField::number(&id, Some(gap_tint), "%", 0).name(gap_tint_caption.trim_end_matches(':')); + let field = crate::widgets::NumField::number(&id, Some(gap_tint), "%", 0).name(gap_tint_caption.trim_end_matches([':', ':'])); field.width(80.0).show(ui) }) { d.fields.insert(key("gapTint"), json!((v / 100.0).clamp(0.0, 1.0))); @@ -8625,7 +8629,7 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & if let Some(v) = sized(ui, &mut |ui| { let id = key("offset"); crate::widgets::NumField::measure(&id, rule["offset"].as_f64(), v_units) - .name(offset.trim_end_matches(':')) + .name(offset.trim_end_matches([':', ':'])) .width(80.0) .spinner() .show(ui) @@ -8639,7 +8643,7 @@ fn paragraph_rules(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, prefix: & if let Some(v) = sized(ui, &mut |ui| { let id = key(field); crate::widgets::NumField::measure(&id, rule[field].as_f64(), h_units) - .name(caption.trim_end_matches(':')) + .name(caption.trim_end_matches([':', ':'])) .width(80.0) .spinner() .show(ui) @@ -9914,7 +9918,7 @@ fn color_picker(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { None => text(ui, egui::pos2(x + 28.0, cy), egui::Align2::RIGHT_CENTER, label), } let fr = egui::Rect::from_min_size(egui::pos2(x + 35.0, cy - 10.5), egui::vec2(44.0, 21.0)); - if let Some(v) = picker_field(ui, d, fr, key, label.trim_end_matches(':'), value, range) { + if let Some(v) = picker_field(ui, d, fr, key, label.trim_end_matches([':', ':']), value, range) { if matches!(key, "r" | "g" | "bl") { d.fields.insert("model".into(), json!("rgb")); } diff --git a/crates/ui-egui/src/dialogs/style_cjk.rs b/crates/ui-egui/src/dialogs/style_cjk.rs index ba3525344..4bb923bb3 100644 --- a/crates/ui-egui/src/dialogs/style_cjk.rs +++ b/crates/ui-egui/src/dialogs/style_cjk.rs @@ -121,7 +121,7 @@ fn grid(id: &str) -> egui::Grid { #[allow(clippy::too_many_arguments)] fn char_auto_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, suffix: &str, scale: f64, range: (f64, f64)) { let v = cf.get(d, key).as_f64().map(|x| x * scale); - let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, suffix, 2).name(caption.trim_end_matches([':', ':'])).width(80.0).range(range.0, range.1); if let Some(n) = field.show_or_clear(ui) { cf.set(d, key, n.map_or(Value::Null, |n| json!(n / scale))); } @@ -572,7 +572,7 @@ fn shatai(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) { let angle = tr(lang, "Angle:"); crate::rtl::label(ui, angle); let v = cf.get(d, "shataiAngle").as_f64(); - let field = crate::widgets::NumField::number("shataiAngle", v, "°", 2).name(angle.trim_end_matches(':')); + let field = crate::widgets::NumField::number("shataiAngle", v, "°", 2).name(angle.trim_end_matches([':', ':'])); let field = field.width(80.0).range(0.0, 180.0).presets(&[30.0, 45.0, 60.0]); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { @@ -598,7 +598,7 @@ fn auto_tate_chu_yoko(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) /// A whole-number paragraph attribute, named from `caption`. fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: &str, range: (f64, f64)) { let v = para_value(d, pv, key).as_f64(); - let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches(':')); + let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches([':', ':'])); if let Some(n) = field.width(80.0).range(range.0, range.1).show(ui) { d.fields.insert(format!("p.{key}"), json!(n.round().max(range.0).min(range.1) as u64)); } @@ -608,7 +608,7 @@ fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, caption: /// `caption`. fn char_count(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, caption: &str, range: (f64, f64)) { let v = cf.get(d, key).as_f64(); - let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches(':')).width(80.0).range(range.0, range.1); + let field = crate::widgets::NumField::number(key, v, "", 0).name(caption.trim_end_matches([':', ':'])).width(80.0).range(range.0, range.1); let edit = if cf.sparse { field.show_or_clear(ui) } else { field.show(ui).map(Some) }; if let Some(n) = edit { cf.set(d, key, n.map_or(Value::Null, |n| json!(n.round().max(range.0).min(range.1) as u64))); @@ -876,7 +876,7 @@ fn grid_settings(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) { ui.horizontal(|ui| { // Empty or 0: automatic (as many grid lines as the leading needs). let field = crate::widgets::NumField::number("gridGyoudori", (lines > 0).then_some(lines as f64), "", 0) - .name(gyoudori.trim_end_matches(':')) + .name(gyoudori.trim_end_matches([':', ':'])) .width(80.0) .range(0.0, 100.0) .presets(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 2dfa38c29..4001d9780 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1857,6 +1857,39 @@ fn dialog_number_fields_are_named_from_their_captions() { } } +/// A caption that ends in a full-width colon, as the Chinese catalog writes them, names its number +/// field without that colon. +#[test] +fn dialog_number_field_names_drop_a_full_width_colon() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + let cases: [(&str, &[&str]); 2] = [("chars", &["大小", "行距", "字距调整"]), ("advanced", &["基线偏移", "倾斜"])]; + for (section, names) in cases { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.ui.language = "zh".into(); + app.ui.dialog = Some(Dialog::new("paragraphStyleOptions", json!({"name": designcraft_doc::story::BASIC_PARAGRAPH, "section": section}))); + // The check reads accessible names only, so captions may draw without a CJK face installed. + let builder = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_accessibility_check(false).allow_missing_glyphs(); + let mut h = builder.build_ui_state( + |ui, app: &mut DesignApp| { + let key = egui::Id::unique("dialog_field_names_zh_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 name in names { + assert_eq!(h.query_all_by_role_and_label(Role::TextInput, name).count(), 1, "{section}: the {name} field"); + } + } +} + /// Text Frame Options shows the insets (or a non-rectangular frame's one Inset), the gutter and /// the other measures in the document's ruler unit, not always in picas, and reads a bare number /// typed there in that unit (#2739). From c581a19953f6a3c3f45aaac269a7248bdd99c079 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:09:49 -0800 Subject: [PATCH 084/133] Data merge: a record's copy keeps the thread order of anchored frames Frames were added to the copied story in the order the copy reached them, which for frames anchored in table cells and notes can differ from the source thread, so text flowed through the copied frames out of order. Each copy now goes where its source frame is in the source story's thread. --- crates/engine/src/cmd/datamerge/fill.rs | 12 +++++- crates/engine/src/cmd/datamerge/tests.rs | 50 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/datamerge/fill.rs b/crates/engine/src/cmd/datamerge/fill.rs index 9d03986e0..2f4e9aa1f 100644 --- a/crates/engine/src/cmd/datamerge/fill.rs +++ b/crates/engine/src/cmd/datamerge/fill.rs @@ -20,6 +20,10 @@ use crate::EngineError; pub struct Maps { pub items: HashMap, pub stories: HashMap, + /// Each source text frame's place in its story's thread, for the stories copied so far. + source_ranks: HashMap, + /// The same place, by the id of the frame's copy. + frame_ranks: HashMap, } #[derive(Clone, Debug, PartialEq)] @@ -103,6 +107,7 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum } } designcraft_doc::remap_story_assets(&mut st, &assets); + maps.source_ranks.extend(st.frames.iter().enumerate().map(|(i, f)| (*f, i))); st.frames.clear(); // Mapped first: the map is the seen-set that stops story recursion. maps.stories.insert(tf.story, n); @@ -111,8 +116,13 @@ fn renumber_in(dst: &mut designcraft_doc::Document, src: &designcraft_doc::Docum n }; tf.story = new_sid; + // Frames are copied in page and nesting order, which can differ from the thread order: + // each copy goes where its source frame is in the source story's thread. + let rank = maps.source_ranks.get(&old).copied().unwrap_or(usize::MAX); + maps.frame_ranks.insert(new_id, rank); if let Some(st) = dst.story_mut(new_sid) { - st.frames.push(new_id); + let at = st.frames.partition_point(|f| maps.frame_ranks.get(f).is_some_and(|r| *r <= rank)); + st.frames.insert(at, new_id); } } Content::Graphic(g) => { diff --git a/crates/engine/src/cmd/datamerge/tests.rs b/crates/engine/src/cmd/datamerge/tests.rs index b8a6abe1a..b14089a34 100644 --- a/crates/engine/src/cmd/datamerge/tests.rs +++ b/crates/engine/src/cmd/datamerge/tests.rs @@ -1583,6 +1583,56 @@ fn record_copies_renumber_objects_anchored_in_nested_endnotes() { dst.check().unwrap(); } +/// A story threaded through anchored text frames in two table cells keeps its thread order in a +/// record's copy, so its text flows through the copied frames in the same order, whichever cell +/// holds the first frame. +#[test] +fn record_copies_keep_the_thread_order_of_frames_anchored_in_cells() { + for first_in_first_cell in [true, false] { + thread_order_of_frames_anchored_in_cells(first_in_first_cell); + } +} + +fn thread_order_of_frames_anchored_in_cells(first_in_first_cell: bool) { + use designcraft_doc::{AnchoredObject, ItemId, SpreadRef}; + use std::sync::Arc; + + let mut s = Session::new(); + new_doc(&mut s, 1); + let made = text_frame(&mut s, [36.0, 36.0, 400.0, 300.0], "Body", None); + let (frame, sid) = (ItemId(made["id"].as_u64().unwrap()), StoryId(made["story"].as_u64().unwrap())); + let first = text_frame(&mut s, [450.0, 450.0, 500.0, 490.0], "Threaded text", None); + let second = text_frame(&mut s, [450.0, 500.0, 500.0, 540.0], "", None); + exec(&mut s, "text.thread", json!({"from": first["id"], "to": second["id"]})); + let (a, b) = (first["id"].as_u64().unwrap(), second["id"].as_u64().unwrap()); + let thread = StoryId(first["story"].as_u64().unwrap()); + let mut src = s.doc().unwrap().doc.as_ref().clone(); + assert_eq!(src.story(thread).unwrap().frames, vec![ItemId(a), ItemId(b)]); + let d = &mut src; + let take = |d: &mut designcraft_doc::Document, id: u64| { + let it = d.item(ItemId(id)).cloned().unwrap(); + Arc::make_mut(&mut d.spreads[0]).items.retain(|i| i.id.0 != id); + AnchoredObject::new(it, Default::default()) + }; + let in_first = take(d, a); + let in_second = take(d, b); + let mut table = designcraft_doc::Table::new(d.alloc(), 1, 2, 0, 0, 80.0); + let (left, right) = if first_in_first_cell { (in_first, in_second) } else { (in_second, in_first) }; + table.cells[0].text.insert_object(0, left); + table.cells[1].text.insert_object(0, right); + d.story_mut(sid).unwrap().insert_table(0, table); + src.check().unwrap(); + + let mut dst = src.clone(); + let it = src.item(frame).cloned().unwrap(); + let mut maps = super::fill::Maps::default(); + super::fill::copy_item(&mut dst, &src, &it, SpreadRef::Doc(0), designcraft_geom::Vec2::new(0.0, 0.0), &mut maps).unwrap(); + let copy = maps.stories[&thread]; + let expected = vec![maps.items[&ItemId(a)], maps.items[&ItemId(b)]]; + assert_eq!(dst.story(copy).unwrap().frames, expected, "the copy's frames keep the thread order ({first_in_first_cell})"); + dst.check().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] From c113bd0d57789fb9ea75ca85faef74f37630b595 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Mon, 16 Nov 2026 17:24:48 +0100 Subject: [PATCH 085/133] Leading: a paragraph that holds only a drop cap takes its empty line's format from the paragraph mark --- crates/compose/src/lib.rs | 7 +++---- crates/compose/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9d9ea9025..00c5bd51d 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2957,10 +2957,9 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph { let base_size = base_chars.size; let spacing = spacing_for(pp, base_size, story, cjk); // An empty line takes its height from its paragraph mark's character format, the one character - // it holds: an empty paragraph's line, and the line a trailing forced line break leaves. - let mark_chars = if glyphs.is_empty() { - doc.styles.resolve_char(base_chars, story.char_format_of(prange.start)) - } else if glyphs.last().is_some_and(|g| g.ch == designcraft_doc::story::FORCED_LINE_BREAK) { + // it holds: an empty paragraph's line, the line left once a drop cap that is the whole + // paragraph is split off, and the line a trailing forced line break leaves. + let mark_chars = if glyphs.is_empty() || glyphs.last().is_some_and(|g| g.ch == designcraft_doc::story::FORCED_LINE_BREAK) { doc.styles.resolve_char(base_chars, story.char_format_of(prange.end)) } else { base_chars.clone() diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 13d7d8834..e53a2ffd0 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5641,6 +5641,27 @@ fn an_empty_line_takes_its_auto_leading_from_a_larger_paragraph_mark() { } } +/// A paragraph that holds only a drop cap is left with an empty line once the drop cap is split +/// off: that line takes its auto leading from the paragraph mark, as an empty paragraph's does. It +/// read the format of the paragraph's first character, the drop cap. +#[test] +fn a_drop_cap_only_paragraph_takes_its_leading_from_the_mark() { + let text = "Aaa\nW\nBbb"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default()); + let cap = text.find('W').unwrap(); + let story = d.story_mut(sid).unwrap(); + story.format_chars(0..text.len(), |f| f.over.size = Some(10.0)); + story.format_chars(cap..cap + 1, |f| f.over.size = Some(40.0)); + story.format_chars(cap + 1..cap + 2, |f| f.over.size = Some(20.0)); + story.paras[1].para.drop_cap_lines = Some(2); + story.paras[1].para.drop_cap_chars = Some(1); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let base: Vec = all_lines(&cs).iter().map(|l| l.baseline).collect(); + assert!(base.len() >= 2, "{base:?}"); + // The 20 pt mark's auto leading (24 pt), not the 40 pt drop cap's (48 pt). + assert!((base[1] - base[0] - 24.0).abs() < 1e-6, "{base:?}"); +} + /// Under a leading model the lines of `text` (all formatted by `format`, with a 16 pt leading) /// are 16 pt apart, empty lines included. fn assert_leading_kept(text: &str, mut d: Document, sid: StoryId, format: impl Fn(&mut designcraft_doc::CharFormat)) { From be10efd762e67a82a5f0dc0b5fbd1c601f26c119 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 17 Nov 2026 19:15:25 +0500 Subject: [PATCH 086/133] Tracking in right-to-left text: the space follows the character in reading order Tracking (and manual kerning) on a character is space after it in reading order. The shaper adds it to the glyph's advance, at its right, which is after the character left to right but before it right to left: tracking on bet opened a gap between alef and bet instead of between bet and gimel. The bidi reorder now moves a right-to-left cluster's tracking to its left: out of its own advance and into the advance of whatever is drawn left of it (at the start of a line, nothing), so advances stay end to end for carets, selections and rules. Glyphs record the tracking they carry, scaled with glyph scaling and drop caps; a synthesized hyphen carries none. Fixes #2884 --- crates/compose/src/lib.rs | 23 +++++++++++++++-- crates/compose/src/shape.rs | 10 +++++++- crates/compose/src/tests.rs | 50 +++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 3c468b0bf..30af4491c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -4069,6 +4069,7 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) { g.adv += g.space * (ws - 1.0); } else if !g.is_space() && g.adv > 0.0 { g.adv = g.adv * gs + ls * g.space; + g.track *= gs; g.sx *= gs; g.dx *= gs; } @@ -5442,13 +5443,30 @@ fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: let width = |u: &std::ops::Range| pens[u.end] - pens[u.start]; let mut cur = start; let mut shifts = vec![0.0; line.len()]; + // The glyph whose advance ends at `cur`: the last one of the cluster drawn there. + let mut left: Option = None; for &k in &order { let u = &units[k]; + let rtl = levels[k].is_rtl(); + // Tracking is space after the character in reading order (#2884): right-to-left, that + // is at its left. The space leaves the cluster's advance for the advance of whatever is + // drawn left of it (at the start of the line, nothing), so advances stay end to end. + let track: f64 = if rtl { line[u.clone()].iter().map(|g| g.track).sum() } else { 0.0 }; + if track != 0.0 { + if let Some(o) = left.and_then(|l| out.get_mut(l)) { + o.adv += track; + } + for i in u.clone() { + out[i].adv -= line[i].track; + } + cur += track; + } for i in u.clone() { shifts[i] = cur - pens[u.start]; - out[i].rtl = levels[k].is_rtl(); + out[i].rtl = rtl; } - cur += width(u); + cur += width(u) - track; + left = u.end.checked_sub(1); } for (p, d) in out.iter_mut().zip(shifts) { p.x += d; @@ -5733,6 +5751,7 @@ fn split_drop_cap( let k = if k.is_finite() && k > 0.0 { k.min(1000.0) } else { 1.0 }; for g in dc.iter_mut().chain(after.iter_mut()) { g.adv *= k; + g.track *= k; g.dx *= k; g.dy *= k; g.sx *= k; diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..dbc1a9f7e 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -71,6 +71,9 @@ pub struct Glyph { pub allow_kashidas: bool, pub safe_tatweel_before: bool, pub shaping_rtl: bool, + /// Tracking and manual kerning included in `adv`, the space after the character in reading + /// order. Right-to-left, that is at the glyph's left (see `reorder_visual`). + pub track: f64, /// The character's language as a BCP 47 tag ([`designcraft_doc::language_tag`]). pub lang: Option<&'static str>, /// Upright in a vertical frame: shaped top to bottom (`adv` is its vertical advance) and hung @@ -1145,6 +1148,7 @@ fn control_glyph(face: &Arc, p: &CharProps, auto_leading: TypeEnv, sty allow_kashidas: p.allow_kashidas, safe_tatweel_before: false, shaping_rtl: false, + track: 0.0, lang: designcraft_doc::language_tag(&p.language), upright: false, list_label: false, @@ -1262,10 +1266,12 @@ fn shape_segment( }; let (ascent, descent) = if up { (em_top * k_v, -em_bottom * k_v) } else { (ascent, descent) }; let body = adv; + let mut track = 0.0; if ch == SOFT_HYPHEN { adv = 0.0; } else if last_in_cluster { - adv += tracking + manual; + track = tracking + manual; + adv += track; } let mark = face.glyph_is_mark(sg.gid); let mark_x = if mark { p.diacritic_x_offset.clamp(-1000.0, 1000.0) / 1000.0 * p.size * hs } else { 0.0 }; @@ -1319,6 +1325,7 @@ fn shape_segment( allow_kashidas: p.allow_kashidas, safe_tatweel_before: sg.safe_tatweel_before, shaping_rtl: sg.rtl, + track, lang, upright: up, list_label: false, @@ -1433,6 +1440,7 @@ pub(crate) fn hyphen_after(g: &Glyph) -> Glyph { let mut h = g.clone(); h.gid = gid; h.adv = g.face.advance(gid) * g.sx; + h.track = 0.0; h.dx = 0.0; h.dy = 0.0; h.byte = g.byte + g.len; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 8e03b35d0..a23aeb051 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3571,6 +3571,56 @@ fn right_to_left_runs_are_ordered_visually() { assert!(g.windows(2).all(|w| w[0].cluster <= w[1].cluster), "{:?}", g.iter().map(|g| g.cluster).collect::>()); } +/// #2884: tracking is space after the character in reading order. Right to left that is at its +/// left, between it and the character read after it, mirroring left to right. +#[test] +fn tracking_in_right_to_left_text_follows_the_character_in_reading_order() { + use designcraft_doc::TextDirection; + let lines = |text: &str, direction: TextDirection, align: Align, tracked: std::ops::Range| { + let para = ParaAttrs { direction: Some(direction), align: Some(align), ..Default::default() }; + let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 500.0, 200.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap(); + let width = |l: &Line| l.glyphs.iter().map(|g| g.adv).sum::(); + // Alef, bet, gimel, dalet, he (two bytes each); tracking on bet. + let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}"; + let bytes = [0, 2, 4, 6, 8]; + for align in [Align::Right, Align::Left] { + let plain = lines(text, TextDirection::RightToLeft, align, 0..0); + let tracked = lines(text, TextDirection::RightToLeft, align, 2..4); + // Tracking 1000 is one em: what it adds to the line. + let em = width(&tracked) - width(&plain); + assert!(em > 1.0, "{align:?}: the tracking widens the line by {em}"); + // The space opens between bet and gimel (read after it); every other pair keeps its gap. + for w in bytes.windows(2) { + let gap = |l: &Line| x_of(l, w[0]) - x_of(l, w[1]); + let want = if w[0] == 2 { gap(&plain) + em } else { gap(&plain) }; + assert!((gap(&tracked) - want).abs() < 0.01, "{align:?}: bytes {w:?} are {} apart, not {want}", gap(&tracked)); + } + // Advances stay end to end on the line, so carets, selections and rules have no gap. + let mut drawn: Vec<&PlacedGlyph> = tracked.glyphs.iter().filter(|g| g.len > 0).collect(); + drawn.sort_by(|a, b| a.x.total_cmp(&b.x)); + for w in drawn.windows(2) { + assert!((w[0].x + w[0].adv - w[1].x).abs() < 0.01, "{align:?}: advances of bytes {} and {} don't meet", w[0].byte, w[1].byte); + } + // The caret after bet is at bet's left edge, the one before it at its right edge. + assert!((crate::caret_x(&tracked, 4) - x_of(&tracked, 2)).abs() < 0.01, "{align:?}: caret after bet"); + assert!((crate::caret_x(&tracked, 2) - x_of(&tracked, 0)).abs() < 0.01, "{align:?}: caret before bet"); + } + // Left to right, the same: the space opens between b and c. + let plain = lines("abcde", TextDirection::LeftToRight, Align::Left, 0..0); + let tracked = lines("abcde", TextDirection::LeftToRight, Align::Left, 1..2); + let em = width(&tracked) - width(&plain); + for (a, b) in [(0, 1), (1, 2), (2, 3), (3, 4)] { + let gap = |l: &Line| x_of(l, b) - x_of(l, a); + let want = if a == 1 { gap(&plain) + em } else { gap(&plain) }; + assert!((gap(&tracked) - want).abs() < 0.01, "left to right: bytes {a}, {b}"); + } +} + #[test] fn bidi_matches_the_reference_order() { use unicode_bidi::{BidiInfo, Level}; From b4ab777f747bc7b44264992d6eed4deb19965678 Mon Sep 17 00:00:00 2001 From: Hamza Date: Tue, 17 Nov 2026 19:46:30 +0500 Subject: [PATCH 087/133] Right-to-left tracking: move it as scaled, and at a drop cap's letters too Review fixes. A justified line that scales its glyphs scales each advance, tracking included, so the space moved to a cluster's left is the scaled tracking, not the shaped one. A right-to-left drop cap places its letters from the right edge; a letter's tracking now goes to its left there too, into the advance of the letter drawn left of it, as in a line. --- crates/compose/src/lib.rs | 29 +++++++++++++++----- crates/compose/src/tests.rs | 54 +++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 30af4491c..3171dba0f 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5337,9 +5337,12 @@ fn layout_line( let mut x = x0 + offset; let bidi = bidi_info.has_rtl(); let mut pens = Vec::with_capacity(if bidi { line.len() } else { 0 }); + // The tracking each placed advance carries, scaled with it. + let mut tracks = Vec::with_capacity(if bidi { line.len() } else { 0 }); for (i, g) in line.iter().enumerate() { if bidi { pens.push(x); + tracks.push(g.track * scale[i]); } let mut p = place(g, x); if scale[i] != 1.0 { @@ -5362,7 +5365,7 @@ fn layout_line( } if bidi { pens.push(x); - reorder_visual(&line, &mut out, &pens, x0 + offset, bidi_info); + reorder_visual(&line, &mut out, &pens, &tracks, x0 + offset, bidi_info); } for (i, leader) in &leaders { if let Some((g, p)) = line.get(*i).zip(out.get(*i)) { @@ -5422,9 +5425,9 @@ fn kashida_points(line: &[Glyph]) -> Vec { } /// Bidi: put a laid-out line (glyphs in text order, `pens` their pen positions and then the end -/// position) into visual order from `start`, cluster by cluster (Unicode Bidirectional -/// Algorithm, rule L2). -fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) { +/// position, `tracks` the tracking in their placed advances) into visual order from `start`, +/// cluster by cluster (Unicode Bidirectional Algorithm, rule L2). +fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], tracks: &[f64], start: f64, info: &unicode_bidi::BidiInfo<'_>) { use unicode_bidi::{BidiInfo, Level}; // Clusters: runs of glyphs from the same source character. let mut units: Vec> = Vec::new(); @@ -5451,13 +5454,13 @@ fn reorder_visual(line: &[Glyph], out: &mut [PlacedGlyph], pens: &[f64], start: // Tracking is space after the character in reading order (#2884): right-to-left, that // is at its left. The space leaves the cluster's advance for the advance of whatever is // drawn left of it (at the start of the line, nothing), so advances stay end to end. - let track: f64 = if rtl { line[u.clone()].iter().map(|g| g.track).sum() } else { 0.0 }; + let track: f64 = if rtl { u.clone().filter_map(|i| tracks.get(i)).sum() } else { 0.0 }; if track != 0.0 { if let Some(o) = left.and_then(|l| out.get_mut(l)) { o.adv += track; } for i in u.clone() { - out[i].adv -= line[i].track; + out[i].adv -= tracks.get(i).copied().unwrap_or(0.0); } cur += track; } @@ -5802,10 +5805,22 @@ impl DropCap { /// The drop cap's glyphs set from `at` (right to left: mirrored, its first character on the right). fn place_drop_cap(dc: &DropCap, at: f64, rtl: bool) -> Vec { let mut x = at; + // Right to left, the edge the next letter ends at and the tracking of the letter before it in + // reading order: that space is at its left (#2884), so in the advance of the letter drawn there. + let mut right = at + dc.width; + let mut carried = 0.0; let mut out = Vec::with_capacity(dc.glyphs.len()); for g in &dc.glyphs { - let pen = if rtl { at + at + dc.width - x - g.adv } else { x }; + let (pen, adv) = if rtl { + let adv = g.adv - g.track + carried; + carried = g.track; + right -= adv; + (right, adv) + } else { + (x, g.adv) + }; let mut p = place(g, pen); + p.adv = adv; p.y += dc.drop; p.rtl = rtl; out.push(p); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index a23aeb051..07967ffa6 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3621,6 +3621,60 @@ fn tracking_in_right_to_left_text_follows_the_character_in_reading_order() { } } +/// #2884 review: a justified line whose glyphs are scaled moves the tracking as scaled, so every +/// advance keeps the glyph's own share; and a right-to-left drop cap puts a letter's tracking at +/// its left, as the line does. +#[test] +fn right_to_left_tracking_follows_glyph_scaling_and_drop_caps() { + use designcraft_doc::TextDirection; + let rtl = |align: Align| ParaAttrs { direction: Some(TextDirection::RightToLeft), align: Some(align), ..Default::default() }; + let text = "\u{5D0}\u{5D1}\u{5D2}\u{5D3}\u{5D4}"; + // Two words, then a third the measure leaves for the next line. + let words = format!("{text} \u{5D5}\u{5D6} {text}"); + let line = |para: ParaAttrs, width: f64, tracked: std::ops::Range| { + let (mut d, sid, _) = doc_with(&words, Rect::new(0.0, 0.0, width, 200.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let glyph = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).cloned().unwrap(); + // The first two words on a line of their own, justified by scaling their glyphs about a third + // (the word space is fixed). + let plain = line(rtl(Align::Right), 500.0, 2..4); + let two: f64 = plain.glyphs.iter().filter(|g| g.byte < 15).map(|g| g.adv).sum(); + let scaled = ParaAttrs { + glyph_scale_min: Some(1.0), + glyph_scale_max: Some(2.0), + word_space_max: Some(1.0), + word_space_min: Some(1.0), + ..rtl(Align::RightJustified) + }; + let just = line(scaled, two * 1.3, 2..4); + assert!(just.range.end <= 16, "the first two words are a line of their own: {:?}", just.range); + for byte in [0, 2, 4, 6, 8, 11, 13] { + let (p, j) = (glyph(&plain, byte), glyph(&just, byte)); + let k = j.sx / p.sx; + assert!(k > 1.05, "byte {byte}: the glyph is scaled by {k}"); + assert!((j.adv - p.adv * k).abs() < 0.01, "byte {byte}: advance {} is not {} scaled by {k}", j.adv, p.adv); + } + // A two-letter drop cap with tracking on its first letter (alef): the space opens between alef + // and bet, read after it, and their advances still meet. + let cap = |tracked: std::ops::Range| { + let para = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(2), ..rtl(Align::Right) }; + let (mut d, sid, _) = doc_with(&format!("{text} {}", "\u{5D5}".repeat(200)), Rect::new(0.0, 0.0, 300.0, 400.0), para); + d.story_mut(sid).unwrap().format_chars(tracked, |f| f.over.tracking = Some(1000.0)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs)[0].clone() + }; + let (untracked, tracked) = (cap(0..0), cap(0..2)); + let (a0, b0, a1, b1) = (glyph(&untracked, 0), glyph(&untracked, 2), glyph(&tracked, 0), glyph(&tracked, 2)); + assert!(a1.x > b1.x, "alef is right of bet"); + let em = (a1.x - b1.x) - (a0.x - b0.x); + assert!(em > 1.0, "the tracking opens a space between alef and bet: {em}"); + assert!((b1.x + b1.adv - a1.x).abs() < 0.01, "bet's advance meets alef: {} vs {}", b1.x + b1.adv, a1.x); + assert!((a1.adv - a0.adv).abs() < 0.01, "alef's advance is its own: {} vs {}", a1.adv, a0.adv); +} + #[test] fn bidi_matches_the_reference_order() { use unicode_bidi::{BidiInfo, Level}; From d28f479e7e1c8d4d2d8bdb92f934ecc46ac0928f Mon Sep 17 00:00:00 2001 From: jayzed80 Date: Thu, 19 Nov 2026 18:15:23 +0000 Subject: [PATCH 088/133] IDML import: keep a slanted frame's gradient parameter (#2615) A linear gradient's colour is its parameter along the axis, and the slant moved into the item transform changes that parameter for points off the axis, so mapping only the vector's two endpoints back to the unslanted inner space moved the colours. The axis now takes the shear's inverse transpose, scaled to span the same parameter range, for linear fills and strokes; a radial vector is a centre and a radius point, so it is still only mapped back. The new test imports a frame whose sides lean 8 pt over its height with a linear gradient fill and stroke, and checks the parameter at off-axis spread points: 0.21 and 0.46 without the compensation, 0.25 and 0.5 with it. --- crates/idml/src/import/item.rs | 38 ++++++++++++++++++++---- crates/idml/src/tests.rs | 53 ++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 6 deletions(-) diff --git a/crates/idml/src/import/item.rs b/crates/idml/src/import/item.rs index eb9300ff6..6d194c7fc 100644 --- a/crates/idml/src/import/item.rs +++ b/crates/idml/src/import/item.rs @@ -196,12 +196,18 @@ impl<'r> Importer<'r> { if let Some(p) = &mut it.wrap.path { p.transform(back); } - // Explicit gradient vectors are in the inner space too, so they move with the path. - for v in [&mut it.fill.gradient_vector, &mut it.stroke.gradient_vector] { - if let Some([x0, y0, x1, y1]) = *v { - let (a, b) = (back * Point::new(x0, y0), back * Point::new(x1, y1)); - *v = Some([a.x, a.y, b.x, b.y]); - } + // Explicit gradient vectors are in the inner space too, so they move with the path. A + // linear gradient's colour is its parameter along the axis, which the slant changes + // for points off the axis, so its axis is compensated; a radial vector is a centre + // and a radius point, so both just move back. + let linear = |name: &str| { + designcraft_color::swatch::resolve_gradient(&self.swatches, name).is_some_and(|g| g.kind == designcraft_color::GradientKind::Linear) + }; + if let Some(v) = it.fill.gradient_vector { + it.fill.gradient_vector = Some(unslant_gradient_vector(v, back, linear(&it.fill.swatch))); + } + if let Some(v) = it.stroke.gradient_vector { + it.stroke.gradient_vector = Some(unslant_gradient_vector(v, back, linear(&it.stroke.swatch))); } } Some(it) @@ -481,6 +487,26 @@ fn unslant_text_frame_path(path: &PathData) -> Option<(PathData, Affine)> { Some((rect, slant)) } +/// A gradient vector in a text frame's inner space, moved into the unslanted space that `back` +/// maps the path back to. A radial vector is a centre and a radius point, so both move back. A +/// linear gradient's colour is its parameter along the axis, and the slant changes that parameter +/// for points off the axis, so its axis takes the shear's inverse transpose, scaled to span the +/// same parameter range: every point then keeps the colour it had in the original space. +fn unslant_gradient_vector([x0, y0, x1, y1]: [f64; 4], back: Affine, linear: bool) -> [f64; 4] { + let (a, b) = (back * Point::new(x0, y0), back * Point::new(x1, y1)); + let [m11, m12, m21, m22, _, _] = back.as_coeffs(); + let det = m11 * m22 - m12 * m21; + let (dx, dy) = (x1 - x0, y1 - y0); + // The axis's image under the shear's inverse transpose, and the factor that keeps the + // parameter the one it had in the original space. + let (ex, ey) = ((m22 * dx - m12 * dy) / det, (m11 * dy - m21 * dx) / det); + let k = (dx * dx + dy * dy) / (ex * ex + ey * ey); + if !linear || !(k.is_finite() && k > 0.0) { + return [a.x, a.y, b.x, b.y]; + } + [a.x, a.y, a.x + k * ex, a.y + k * ey] +} + fn path_from_model(geometry: craft_idml::model::PathGeometry) -> PathData { let subpaths = geometry .paths diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 0325d492e..909e9a593 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -703,6 +703,59 @@ fn slightly_slanted_text_frame_sets_its_text_in_the_rectangle() { assert!(lines.iter().all(|l| (l.x0 - area.x0).abs() < 1e-9), "every line starts at the column edge"); } +/// #2615: a linear gradient (fill and stroke) on a slanted text frame keeps the colour it had in +/// the frame's original space at points off its axis. Mapping only the vector's endpoints back +/// would tilt the parameter field: here the frame's sides lean 8 pt over its 300 pt height, and +/// the spread point (300, 300) is half-way along the gradient. +#[test] +fn a_slanted_text_frames_gradient_keeps_its_parameter_off_the_axis() { + let corners = [(246.0, 0.0), (254.0, 300.0), (354.0, 300.0), (346.0, 0.0)]; + let pts: String = + corners.iter().map(|(x, y)| format!(r#""#)).collect(); + let graphic = r#" + + + + + + + +"#; + let designmap = format!( + r#" + + + +{pts} + +"# + ); + let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap), ("Resources/Graphic.xml", graphic)]), &|_| None).unwrap(); + let it = &d.spreads[0].items[0]; + // The frame is unslanted: its path is the rectangle, the slant is in its transform, and its + // corners on the spread are where InDesign drew them. + let rect = [(250.0, 0.0), (250.0, 300.0), (350.0, 300.0), (350.0, 0.0)]; + for (a, (&(x, y), &(ex, ey))) in it.path.subpaths[0].anchors.iter().zip(rect.iter().zip(&corners)) { + assert!((a.p.x - x).abs() < 1e-9 && (a.p.y - y).abs() < 1e-9, "path {:?} vs {x} {y}", a.p); + let p = it.xf * a.p; + assert!((p.x - ex).abs() < 1e-9 && (p.y - ey).abs() < 1e-9, "corner {p:?} vs {ex} {ey}"); + } + // The parameter along each gradient at an off-axis spread point is the one it had before the + // frame was unslanted: (250, 150) to (350, 150), so x = 275 is a quarter and x = 300 a half. + let param = |v: [f64; 4], p: designcraft_geom::Point| { + let d = designcraft_geom::Point::new(v[2], v[3]) - designcraft_geom::Point::new(v[0], v[1]); + (p - designcraft_geom::Point::new(v[0], v[1])).dot(d) / d.hypot2() + }; + for (x, want) in [(275.0, 0.25), (300.0, 0.5)] { + let p = it.xf.inverse() * designcraft_geom::Point::new(x, 300.0); + for (what, v) in [("fill", it.fill.gradient_vector), ("stroke", it.stroke.gradient_vector)] { + let v = v.unwrap_or_else(|| panic!("{what} gradient vector")); + let got = param(v, p); + assert!((got - want).abs() < 1e-9, "{what} at x = {x}: {got} instead of {want}"); + } + } +} + /// InDesign: a break character ends its paragraph (`
` with a ParagraphBreakType closes the /// range); the text after it is a paragraph with its own style, set on the next page of the /// break's parity. From 5b2507b4b6929c7cdff638b8378d38806914c4a2 Mon Sep 17 00:00:00 2001 From: Youssef Azriouil Date: Sun, 22 Nov 2026 22:32:41 +0100 Subject: [PATCH 089/133] Empty-paragraph leading: test Hangul text under Aki Below An empty paragraph between two Hangul lines keeps the leading under the Japanese composer with Aki Below. Test contributed in review. --- crates/compose/src/tests.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index e53a2ffd0..c700930dd 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5597,6 +5597,35 @@ fn an_empty_paragraph_keeps_the_leading_under_a_leading_model() { } } +/// Baselines of `text` set in a Hangul test font under the Japanese composer with Aki Below and +/// 20 pt leading. +fn hangul_lines(text: &str) -> Vec { + let chars: Vec = "가나".chars().collect(); + let font = designcraft_fonts::testing::font_with("DC Test Korean Lines", &chars).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 500.0), japanese()); + d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| { + f.over.font_family = Some("DC Test Korean Lines".into()); + f.over.language = Some("Korean".into()); + f.over.leading = Some(designcraft_doc::Leading::Points(20.0)); + f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::AkiBelow); + }); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + all_lines(&cs).iter().map(|l| l.baseline).collect() +} + +/// Hangul text under Aki Below: an empty paragraph between two lines keeps the leading, so the +/// baselines match those of three lines of text. The empty paragraph rose and the line after it +/// dropped back by as much. +#[test] +fn an_empty_hangul_paragraph_keeps_the_leading_under_aki_below() { + let (text, empty) = (hangul_lines("가나\n가나\n가나"), hangul_lines("가나\n\n가나")); + assert_eq!(empty.len(), 3); + for (a, b) in text.iter().zip(&empty) { + assert!((a - b).abs() < 1e-6, "{text:?} vs {empty:?}"); + } +} + /// The empty line a trailing forced line break leaves measures from its paragraph mark's em box, /// like an empty paragraph, so it keeps the leading too. It measured from the paragraph style's /// characters: text formatted with a leading model the style doesn't have moved that line by the From d94dde8cf349175b9f7195958f78ecd8b6f1528b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:09:25 -0800 Subject: [PATCH 090/133] Effects: the dialog shows why its preview did not start While a tool's drag is open, turning on Preview in the Effects dialog now shows " is in progress" in the dialog's status line, as the other dialogs do. Before, the refusal was dropped and the dialog gave no sign that nothing was previewed. --- crates/ui-egui/src/effects_dialog.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/effects_dialog.rs b/crates/ui-egui/src/effects_dialog.rs index a09b87498..1e84cb545 100644 --- a/crates/ui-egui/src/effects_dialog.rs +++ b/crates/ui-egui/src/effects_dialog.rs @@ -149,7 +149,10 @@ fn preview(app: &mut DesignApp, d: &mut Dialog) { if shown.as_ref() == Some(&p) { return; } - if shown.is_none() && app.session.begin_interaction("Effects").is_err() { + if shown.is_none() + && let Err(e) = app.session.begin_interaction("Effects") + { + d.fields.insert("status".into(), json!(e.to_string())); return; } match app.session.preview("object.effects", p.clone()) { @@ -935,6 +938,26 @@ mod tests { assert_eq!(fx.outer_glow.mode, designcraft_color::BlendMode::Normal); } + /// While a tool's drag is open the preview does not start, and the dialog shows why. + #[test] + fn the_preview_shows_the_refusal_while_a_tool_drag_is_open() { + use designcraft_tools::{PointerEvent, PointerKind}; + let (mut app, id) = app_with_frame(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + let v = designcraft_engine::ViewInfo::at_zoom(1.0); + app.session.set_tool("rectangle"); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 400.0, 400.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 450.0, 450.0), v).unwrap(); + let label = app.session.doc().unwrap().interaction.as_ref().map(|it| it.label.clone()).expect("the drag is open"); + open(&mut app, "dropShadow"); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields.get("status"), Some(&json!(format!("{label} is in progress")))); + assert!(!d.fields.contains_key(PREVIEWED)); + assert!(!app.session.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().effects.drop_shadow.on); + } + #[test] fn offsets_follow_distance_and_angle_as_in_indesign() { let (mut app, _) = app_with_frame(); From fb0c111b3ef0fe9fa9455b3ca5ea647cfb05ba17 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:28:49 +0700 Subject: [PATCH 091/133] rustfmt the dashed-stroke port after merging main --- crates/pptx/src/slide.rs | 1 - crates/pptx/src/table.rs | 7 ++----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/crates/pptx/src/slide.rs b/crates/pptx/src/slide.rs index a15282c37..1aaef29b9 100644 --- a/crates/pptx/src/slide.rs +++ b/crates/pptx/src/slide.rs @@ -732,4 +732,3 @@ fn encode_png(rgba: Vec, w: u32, h: u32) -> Option> { let image = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, rgba).ok()?; craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).ok() } - diff --git a/crates/pptx/src/table.rs b/crates/pptx/src/table.rs index 875b7e944..a32f1156b 100644 --- a/crates/pptx/src/table.rs +++ b/crates/pptx/src/table.rs @@ -93,11 +93,8 @@ fn model_border(ex: &Exporter, s: Option<&StrokeSeg>, k: f64, opacity: f32) -> c if pattern.len() % 2 == 1 { pattern.extend(pattern.clone()); } - let pairs = pattern - .chunks(2) - .filter_map(|pair| pair.first().zip(pair.get(1))) - .map(|(dash, gap)| (*dash / st.weight, *gap / st.weight)) - .collect(); + let pairs = + pattern.chunks(2).filter_map(|pair| pair.first().zip(pair.get(1))).map(|(dash, gap)| (*dash / st.weight, *gap / st.weight)).collect(); Some(craft_pptx::style::Dash::Custom { pattern: pairs }) } else if matches!(st.kind, StrokeType::Dotted) { Some(craft_pptx::style::Dash::Preset { name: "sysDot".into() }) From 5031840ff9f2828386eb58f24f2d35b17d505108 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 06:17:53 +0700 Subject: [PATCH 092/133] Remove unused MAX_DASH_ENTRIES import from pptx slides The dash cap still uses the qualified designcraft_doc::MAX_DASH_ENTRIES path, so the import failed clippy -D warnings on CI. --- crates/pptx/src/slide.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/pptx/src/slide.rs b/crates/pptx/src/slide.rs index 1aaef29b9..78f002eb2 100644 --- a/crates/pptx/src/slide.rs +++ b/crates/pptx/src/slide.rs @@ -5,7 +5,7 @@ use std::collections::HashMap; use designcraft_color::swatch::resolve_gradient; use designcraft_color::{BlendMode, GradientKind}; use designcraft_compose::Cache; -use designcraft_doc::{Arrowhead, AssetId, Cap, Content, Document, Graphic, Item, Join, MAX_DASH_ENTRIES, Shape, Stroke, StrokeAlign, StrokeType}; +use designcraft_doc::{Arrowhead, AssetId, Cap, Content, Document, Graphic, Item, Join, Shape, Stroke, StrokeAlign, StrokeType}; use designcraft_geom::kurbo::{PathEl, Shape as _}; use designcraft_geom::{Affine, BezPath, Rect, Vec2, corners}; From abd40399574a1a279c516440b42f5695b8890e6e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 11:32:43 -0500 Subject: [PATCH 093/133] nightly: update signing pin, macOS docs layout, and profile reopen (#3298) --- .github/nightly-signing-policy.json | 6 +- .github/workflows/nightly-sign.yml | 18 ++++- .github/workflows/nightly.yml | 4 +- apps/designcraft/src/profile_root.rs | 83 ++++++++++++++++++++++- packaging/macos/nightly.sh | 5 +- packaging/macos/nightly_sign_tests.py | 84 +++++++++++++++++++++++- packaging/nightly-release-tests.py | 94 ++++++++++++++++++++++++++- 7 files changed, 279 insertions(+), 15 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index a5d253325..dba507f38 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1400018213, "producer_workflow_id": 429745945, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 406a64f0f..1af5b46f1 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 app-name: designcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index d9a8e0f37..c1e022947 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 app-name: designcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/apps/designcraft/src/profile_root.rs b/apps/designcraft/src/profile_root.rs index 1522d0070..93b8ee77d 100644 --- a/apps/designcraft/src/profile_root.rs +++ b/apps/designcraft/src/profile_root.rs @@ -142,7 +142,14 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; + let joined = chosen.join(name); + match std::fs::symlink_metadata(&joined) { + Ok(meta) if !meta.is_dir() => return Err(format!("the nightly {label} must be a directory")), + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), + } + let child = canonical_future(&joined)?; if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } @@ -159,11 +166,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(windows)] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + /// Recognise the shared portable data namespace in both the supplied and resolved path. /// This is not an inventory of arbitrary custom stable overrides or a Launcher ownership proof. fn is_portable_layout(path: &Path, platform: Platform) -> bool { @@ -244,6 +296,8 @@ fn validate_for( Ok(confirmed) } +const PROFILE_FOLDERS: [&str; 2] = ["Recovery", "logs"]; + #[cfg(test)] mod tests { use super::*; @@ -489,4 +543,29 @@ mod tests { assert_eq!(resolved, std::fs::canonicalize(&chosen).unwrap()); assert!(resolved.is_dir()); } + + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } } diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh index c5547d2b5..9210f4c6f 100755 --- a/packaging/macos/nightly.sh +++ b/packaging/macos/nightly.sh @@ -33,11 +33,12 @@ OUTPUT="$DIST/designcraft-$VERSION-macos-aarch64-nightly.zip" nightly_compile_gui APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" -mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs" cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/DesignCraft" chmod 755 "$APP/Contents/MacOS/DesignCraft" cp "$ROOT/assets/app-icon/designcraft-nightly.icns" "$APP/Contents/Resources/designcraft-nightly.icns" -nightly_copy_notices "$APP/Contents/Resources" +# Launcher admits notices under Resources/docs, not beside the icon. +nightly_copy_notices "$APP/Contents/Resources/docs" # The private mktemp cwd is the helper authority root: stage the template inside it. cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" (cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py index 33cf5cfbf..c78066e3e 100644 --- a/packaging/macos/nightly_sign_tests.py +++ b/packaging/macos/nightly_sign_tests.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """The macOS Nightly signing and verification scripts, run on any POSIX host against generated fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, -lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a -real signature, notarization or Mac run.""" +lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These +check the scripts and bundle layout, not native signing, notarization or Mac execution.""" import base64 import importlib.util import json @@ -27,6 +27,8 @@ COMMIT = "b" * 40 VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12] ASSET = f"designcraft-{VERSION}-macos-aarch64-nightly.zip" APP = "DesignCraft Nightly.app" +APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE") +OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT") TEAM = "ABCDE12345" IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567" SECRETS = { @@ -183,6 +185,50 @@ class Fixture: z.writestr(info, b"" if path.is_dir() else path.read_bytes()) return self.input + def package(self, font_licences): + """Drive the real producer from a clean fixture checkout, without Cargo or Apple tools.""" + source = HERE.parents[1] + checkout = self.root / "source" + checkout.mkdir() + notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file()) + for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py", + "packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh", + "packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py", + "assets/app-icon/designcraft-nightly.icns"): + target = checkout / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / relative, target) + env = self.env(**dict.fromkeys(SECRETS)) + + def git(*args): + return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args], + cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout + + git("init", "-q") + git("add", "--", ".") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture") + commit = git("rev-parse", "HEAD").strip() + version = VERSION[:-12] + commit[:12] + # Generated licence text exercises the copier without depending on a font checkout. + fonts = self.root / "craft-fonts" + for family, data in font_licences.items(): + licence = fonts / "fonts" / family / "OFL.txt" + licence.parent.mkdir(parents=True) + licence.write_bytes(data) + # The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI. + (self.bin / "cargo").write_text( + '#!/bin/sh\nset -eu\n' + 'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/designcraft"\n' + 'mkdir -p "$(dirname "$gui")"\n' + "printf \"#!/bin/sh\\necho 'DesignCraft %s (nightly-v1)'\\n\" \"$DESIGNCRAFT_VERSION\" >\"$gui\"\n", + ) + result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS), + DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts), + DESIGNCRAFT_BUILD_CHANNEL="nightly-v1", DESIGNCRAFT_VERSION=version, + DESIGNCRAFT_BUILD_SHA=commit, DESIGNCRAFT_BUILD_DATE="2026-11-23") + assert result.returncode == 0, result.stdout + return self.dist / ASSET.replace(VERSION, version) + def env(self, **changes): env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} @@ -447,6 +493,40 @@ class Verify(unittest.TestCase): class Build(unittest.TestCase): + def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self): + f = Fixture(self) + fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"} + archive = f.package(fonts) + source = HERE.parents[1] + resources = f"{APP}/Contents/Resources" + icon = "designcraft-nightly.icns" + notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES} + notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()}) + notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()}) + # Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon. + expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()} + expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes() + contents = f"{APP}/Contents" + gui = f"{contents}/MacOS/DesignCraft" + with zipfile.ZipFile(archive) as zipped: + entries = zipped.infolist() + names = {entry.filename for entry in entries} + self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case") + self.assertEqual({entry.filename for entry in entries if not entry.is_dir()}, + set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"}) + self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= { + f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"}) + for path, data in expected_files.items(): + with self.subTest(path=path): + self.assertEqual(zipped.read(path), data) + mode = zipped.getinfo(path).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode)) + self.assertFalse(mode & 0o111) + mode = zipped.getinfo(gui).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR) + result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS)) + self.assertEqual(result.returncode, 0, result.stdout) + def test_compilation_refuses_signing_material_before_building(self): f = Fixture(self) for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"): diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 8cb5e9a37..60ad396aa 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -13,6 +13,12 @@ INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" SIGNER_BRANCH = "nightly-signer" NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# The pinned shared registry enables Windows, Linux and macOS for DesignCraft. +SIGNER_SECRETS = { + "AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT", + "AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE", + "APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD", +} NIGHTLY_TRUST = { "windows-x86_64": ( "publisher_subject", @@ -50,6 +56,49 @@ def assert_nightly_serialization(source): raise ValueError("nightly serialization must use its stable group and no cancellation") +def caller_entries(lines, indent): + """Split the callers' plain YAML block entries; refuse other forms at checked levels.""" + entries = {} + children = None + for line in lines: + if children is not None and line.startswith(" " * (indent + 1)): + children.append(line) + continue + row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line) + if row is None or row[1] in entries: + raise ValueError("malformed or duplicate caller mapping entry") + children = [] + entries[row[1]] = row[2], children + return entries + + +def assert_caller_secrets(source, job_name, names): + """Check the actual caller's root, job and secret blocks without a YAML dependency.""" + lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")] + root = caller_entries(lines, 0) + job_marker, job_lines = root.pop("jobs", (None, [])) + jobs = caller_entries(job_lines, 2) + if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None: + raise ValueError("the caller must have one plain job block") + job = caller_entries(jobs[job_name][1], 4) + if "environment" in job or "environment" in root or "secrets" in root: + raise ValueError("only the native callee may bind the environment") + if names: + if "secrets" not in job: + raise ValueError("signer requires an explicit target-specific secret map") + mode, secret_lines = job.pop("secrets") + expected = {name: ("${{ secrets." + name + " }}", []) for name in names} + if mode is not None or caller_entries(secret_lines, 6) != expected: + raise ValueError("signer must forward exactly the reviewed same-name secret references") + elif "secrets" in job: + raise ValueError("unsigned caller must not pass secrets") + for value, children in (*root.values(), *job.values()): + outside_map = "\n".join([value or "", *children]) + # Scan all remaining text: quoted braces can appear before a secret reference. + if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map): + raise ValueError("secret bindings belong only in the signer map") + + def job_conditions(jobs): """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" lines = jobs.splitlines() @@ -197,8 +246,49 @@ class TrustedSourcePreparation(unittest.TestCase): with self.subTest(workflow=name): self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") - self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") - self.assertNotIn("secrets.", executable) + + def test_signer_forwards_exactly_the_reviewed_secret_names(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + assert_caller_secrets(signer, "release", SIGNER_SECRETS) + + def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + header = " secrets:\n" + linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n" + self.assertIn(linux, signer) + mutations = { + "missing name": signer.replace(linux, ""), + "extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n", + "renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")), + "duplicate name": signer.replace(linux, linux + linux), + "duplicate map": signer + header + linux, + "quoted duplicate map": signer + ' "secrets": inherit\n', + "inherit": signer.split(header)[0] + " secrets: inherit\n", + "yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"), + "yaml merge": signer + " <<: *other\n", + "environment": signer + " environment: release\n", + "secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"), + } + for change, source in mutations.items(): + with self.subTest(change=change), self.assertRaises(ValueError): + assert_caller_secrets(source, "release", SIGNER_SECRETS) + + def test_unsigned_caller_has_no_secrets(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + assert_caller_secrets(producer, "unsigned", set()) + for suffix in (" secrets: {}\n", " secrets: inherit\n", + " secrets:\n EXTRA: ${{ secrets.EXTRA }}\n", + " extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"): + with self.subTest(suffix=suffix), self.assertRaises(ValueError): + assert_caller_secrets(producer + suffix, "unsigned", set()) + + def test_unsigned_caller_refuses_secret_after_format_brace(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + # This inert fixture is never dispatched; the brace is part of the format string. + env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n" + source = producer.replace("jobs:\n", env + "jobs:\n", 1) + with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"): + assert_caller_secrets(source, "unsigned", set()) class NightlyTrustAnchors(unittest.TestCase): From 9babbf460b420c17e0acd57e9588989c92835445 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:57:46 +0100 Subject: [PATCH 094/133] Release: bump designcraft to v0.22.0 --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b4a802771..b77607498 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1769,7 +1769,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.21.1" +version = "0.22.0" dependencies = [ "arboard", "craft-update", @@ -1795,7 +1795,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-image-codecs", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-cms", "kurbo", @@ -1826,7 +1826,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1846,7 +1846,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "designcraft-color", @@ -1859,7 +1859,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.21.1" +version = "0.22.0" dependencies = [ "caseless", "craft-atomic", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-epub", "craft-mime", @@ -1915,7 +1915,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.21.1" +version = "0.22.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-designcraft-format", "designcraft-doc", @@ -1938,7 +1938,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.21.1" +version = "0.22.0" dependencies = [ "flo_curves", "kurbo", @@ -1951,7 +1951,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-idml", @@ -1968,7 +1968,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-cms", "craft-eps", @@ -1990,7 +1990,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-file-formats", "craft-mcp-server", @@ -2005,7 +2005,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "craft-cms", @@ -2031,7 +2031,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.21.1" +version = "0.22.0" dependencies = [ "chrono", "craft-image-codecs", @@ -2052,7 +2052,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.21.1" +version = "0.22.0" dependencies = [ "bytemuck", "craft-image-codecs", @@ -2073,7 +2073,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-docx", "craft-file-formats", @@ -2087,7 +2087,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -2099,7 +2099,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.21.1" +version = "0.22.0" dependencies = [ "craft-dialogs", "craft-file-formats", @@ -2134,7 +2134,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.21.1" +version = "0.22.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -8388,7 +8388,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.21.1" +version = "0.22.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 1dcb6d332..c54020126 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.21.1" +version = "0.22.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From ffecf35cd447dddaba9c1dcb5ea52d70a3cb1e33 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:12:38 +0100 Subject: [PATCH 095/133] Point CRAFT_FONTS_DIR at ../craft-fonts in .cargo/config.toml (#3301) A plain local build embeds no craft-fonts unless CRAFT_FONTS_DIR is passed by hand. The entry mirrors deckcraft and pdfcraft; an environment value still wins and a missing checkout builds as before. Co-authored-by: Fredrik Hallin Co-authored-by: Claude Sonnet 5.5 --- .cargo/config.toml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.cargo/config.toml b/.cargo/config.toml index 35049cbcb..9c41044f8 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,7 @@ +# Local builds pick up the optional craft-fonts checkout next to this repo (Inter etc.). When the +# directory is missing the build warns and carries on with egui's bundled fonts and system fonts. +[env] +CRAFT_FONTS_DIR = { value = "../craft-fonts", relative = true } + [alias] xtask = "run --package xtask --" From c8b076b12614aa4cd2b5bfe16eef245ec22e14cf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 15:25:08 -0500 Subject: [PATCH 096/133] ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#3304) --- .github/workflows/nightly.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index c1e022947..6a0eb7bca 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' From a3c3f6856799308503425b608a501dd045a3f4e4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 16:05:48 -0500 Subject: [PATCH 097/133] ci: pin storytold/craft-common-actions to @main universally (#3305) --- .github/nightly-signing-policy.json | 6 +++--- .github/workflows/nightly-sign.yml | 4 ++-- .github/workflows/nightly.yml | 4 ++-- packaging/nightly-release-tests.py | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index dba507f38..6f4e663bf 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1400018213, "producer_workflow_id": 429745945, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 1af5b46f1..e5d9c3824 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: designcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 6a0eb7bca..97135ace3 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: designcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 60ad396aa..61405638a 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -156,7 +156,7 @@ def reviewed_manual_actors(caller_source, policy): def caller_pin(name): return re.findall( - r"(?m)^ tooling-revision: ([0-9a-f]{40})$", + r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text(), )[0] @@ -332,7 +332,7 @@ class NightlyTrustAnchors(unittest.TestCase): self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") pins.update(uses) self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") - self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main") class NightlyEnabledCallers(unittest.TestCase): @@ -742,7 +742,7 @@ def trust_closure_problems(workflows): if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): if name == "nightly-sign.yml": signer_calls += 1 - if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + if name != "nightly-sign.yml" or ref != "main": problems.append(name + " calls nightly-release.yml@" + ref) if workflow.lower() in ("release.yml", "release.yaml"): stable_callers.add(name) @@ -792,7 +792,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase): "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, - "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")}, "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, } From 336b668377512e57d52362d8c0ed37ec3920e61e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 28 Nov 2026 22:41:08 -0500 Subject: [PATCH 098/133] fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#3314) --- .github/nightly-signing-policy.json | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 6f4e663bf..f29c9c1cf 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -95,7 +95,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", From 7f2e348396e948add2100be3a5959458d3ac3097 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:55:40 +0000 Subject: [PATCH 099/133] Text: select an empty line's return on double- and triple-click (#3321) --- crates/engine/src/cmd/text/caret.rs | 113 +++++++++++++++++++++++++--- 1 file changed, 104 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/text/caret.rs b/crates/engine/src/cmd/text/caret.rs index 7b2aeb5ce..a4f7dcff4 100644 --- a/crates/engine/src/cmd/text/caret.rs +++ b/crates/engine/src/cmd/text/caret.rs @@ -131,7 +131,7 @@ fn unit_at(s: &Session, sid: StoryId, cell: Option, b: usize, unit: &s "word" => word_or_spaces_at(text, b), "line" => { let cs = s.cache.get(&st.doc, sid, None); - line_at(&text_composition(cs, cell), b).unwrap_or((b, b)) + line_at(&text_composition(cs, cell), text, b).unwrap_or((b, b)) } // The paragraph with its return (the last paragraph has none). "paragraph" => story.para_ranges().get(story.para_at(b)).map_or((b, b), |r| (r.start, (r.end + 1).min(text.len()))), @@ -141,8 +141,9 @@ fn unit_at(s: &Session, sid: StoryId, cell: Option, b: usize, unit: &s } /// The word at byte `i`; on spaces the run of spaces; on anything else that one character -/// (grapheme cluster). At the end of a paragraph, what ends it. Grapheme clusters are never split: -/// combining marks, viramas, variation selectors and emoji ZWJ sequences stay with their base. +/// (grapheme cluster). At the end of a paragraph, what ends it; on an empty paragraph, its +/// return if it has one. Grapheme clusters are never split: combining marks, viramas, variation +/// selectors and emoji ZWJ sequences stay with their base. fn word_or_spaces_at(s: &str, i: usize) -> (usize, usize) { use unicode_segmentation::UnicodeSegmentation; let i = floor_char_boundary(s, i.min(s.len())); @@ -150,7 +151,10 @@ fn word_or_spaces_at(s: &str, i: usize) -> (usize, usize) { let ps = s[..i].rfind('\n').map_or(0, |k| k + 1); let pe = s[i..].find('\n').map_or(s.len(), |k| i + k); let g: Vec<(usize, &str)> = s[ps..pe].grapheme_indices(true).collect(); - let Some(k) = g.iter().rposition(|(o, _)| ps + o <= i) else { return (i, i) }; + let Some(k) = g.iter().rposition(|(o, _)| ps + o <= i) else { + // An empty paragraph has only its return; select it so double-clicking selects the line. + return if s.as_bytes().get(i) == Some(&b'\n') { (i, i + 1) } else { (i, i) }; + }; let kind = |c: &str| match c.chars().next() { Some(c) if is_word(c) => 1, Some(c) if c.is_whitespace() => 2, @@ -181,10 +185,11 @@ fn text_composition(cs: std::sync::Arc, cell: Option Option<(usize, usize)> { +/// The composed line holding the character at byte `pos`, or an empty line's return if it has one. +fn line_at(cs: &compose::ComposedStory, text: &str, pos: usize) -> Option<(usize, usize)> { let lines = || cs.frames.iter().flat_map(|f| f.lines.iter()); - lines().find(|l| l.range.contains(&pos)).map(|l| (l.range.start, l.range.end)).or_else(|| line_of(cs, pos)) + let (a, e) = lines().find(|l| l.range.contains(&pos)).map(|l| (l.range.start, l.range.end)).or_else(|| line_of(cs, pos))?; + Some(if a == e && text.as_bytes().get(e) == Some(&b'\n') { (a, e + 1) } else { (a, e) }) } pub(super) fn place(s: &mut Session, p: &Value, extend: bool) -> Result { @@ -545,8 +550,10 @@ mod multi_click_tests { assert_eq!(word(s, 2), e); assert_eq!(word(s, 6), e, "on the joiner"); assert_eq!(word(s, s.len() - 1), (s.len() - 6, s.len()), "at the end: the last character whole"); - // Empty paragraphs select nothing. - assert_eq!(word("a\n\nb", 2), (2, 2)); + // Empty paragraphs select their return when one is present, otherwise nothing. + assert_eq!(word("a\n\nb", 2), (2, 3)); + assert_eq!(word("a\n", 2), (2, 2)); + assert_eq!(word("", 0), (0, 0)); } /// Issue #981: holding the button after a double, triple or quadruple click and moving extends @@ -638,6 +645,94 @@ mod multi_click_tests { assert!(s.execute("text.selectAt", &json!({"frame": fid, "point": p, "unit": "sentence"})).is_err()); assert!(s.execute("text.selectAt", &json!({"frame": fid, "unit": "word"})).is_err(), "no point"); } + + /// Issue #3321: double- or triple-clicking an empty line selects its paragraph return so the + /// selection is visible and character formatting such as leading applies to that line. + #[test] + fn double_and_triple_clicking_an_empty_line_selects_its_return_and_applies_leading() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text = "First\n\nSecond"; + let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 300], "content": "text", "text": text})).unwrap(); + let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap()); + let line_pt = |s: &Session, idx: usize| { + let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None); + let l = &cs.frames[0].lines[idx]; + json!([l.x0 + 4.0, l.baseline - l.ascent * 0.5]) + }; + let sel = |s: &Session| s.doc().unwrap().selection.text.map(|t| (t.anchor, t.focus)).unwrap(); + let baselines = |s: &Session| -> Vec { + let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None); + cs.frames[0].lines.iter().map(|l| l.baseline).collect() + }; + + let base = baselines(&s); + assert_eq!(base.len(), 3); + let default_gap = base[2] - base[0]; + + // Double-click ("word"), triple-click ("line") and text.selectWord on the empty middle + // line all select its paragraph return (byte 6..7). + let empty_pt = line_pt(&s, 1); + for unit in ["word", "line"] { + s.execute("text.selectAt", &json!({"frame": fid, "point": empty_pt, "unit": unit})).unwrap(); + assert_eq!(sel(&s), (6, 7), "unit={unit}"); + } + s.execute("text.selectWord", &json!({"frame": fid, "point": empty_pt})).unwrap(); + assert_eq!(sel(&s), (6, 7)); + + // The selected paragraph return produces a visible highlight quad on the empty line. + { + let cs = s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), None); + let l = &cs.frames[0].lines[1]; + let range = s.doc().unwrap().selection.text.unwrap().range(); + let (a, e) = (range.start.max(l.range.start), range.end.min(l.range.end)); + let past = e == l.range.end && range.end > l.range.end; + assert!(past); + let quads = crate::compose::highlight_quads(l, a, e, past); + assert_eq!(quads.len(), 1); + assert!(quads[0][1].x > quads[0][0].x && quads[0][2].y > quads[0][0].y); + } + + // Dragging after double- or triple-clicking an empty line extends across it in both directions. + for unit in ["word", "line"] { + s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 1), "unit": unit})).unwrap(); + s.execute("text.extendTo", &json!({"frame": fid, "point": line_pt(&s, 2), "unit": unit})).unwrap(); + assert_eq!(sel(&s), (6, text.len()), "extend forward unit={unit}"); + s.execute("text.extendTo", &json!({"frame": fid, "point": line_pt(&s, 0), "unit": unit})).unwrap(); + assert_eq!(sel(&s), (7, 0), "extend backward unit={unit}"); + } + + // Changing leading with the empty line selected updates the empty line's height. + s.execute("text.selectAt", &json!({"frame": fid, "point": empty_pt, "unit": "word"})).unwrap(); + assert_eq!(sel(&s), (6, 7)); + s.execute("type.char", &json!({"attrs": {"leading": {"kind": "points", "value": 30.0}}})).unwrap(); + let wider = baselines(&s); + assert!(wider[2] - wider[0] > default_gap, "wider leading must expand the gap: {wider:?} vs {base:?}"); + assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["leading"], json!({"kind": "points", "value": 30.0})); + + s.execute("type.char", &json!({"attrs": {"leading": {"kind": "points", "value": 6.0}}})).unwrap(); + let tighter = baselines(&s); + assert!(tighter[2] - tighter[0] < default_gap, "tighter leading must shrink the gap: {tighter:?} vs {base:?}"); + + // Empty first line, consecutive empty lines, trailing empty line, and empty story bounds. + s.execute("story.setText", &json!({"story": sid, "text": "\n\nTail\n"})).unwrap(); + for unit in ["word", "line"] { + s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 0), "unit": unit})).unwrap(); + assert_eq!(sel(&s), (0, 1), "leading empty line unit={unit}"); + s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 1), "unit": unit})).unwrap(); + assert_eq!(sel(&s), (1, 2), "second empty line unit={unit}"); + // Trailing empty paragraph has no return after it: stays safely collapsed at story end. + s.execute("text.selectAt", &json!({"frame": fid, "point": line_pt(&s, 3), "unit": unit})).unwrap(); + assert_eq!(sel(&s), (7, 7), "trailing empty line unit={unit}"); + } + + // Empty story: stays safely collapsed at byte 0. + s.execute("story.setText", &json!({"story": sid, "text": ""})).unwrap(); + for unit in ["word", "line"] { + s.execute("text.selectAt", &json!({"frame": fid, "point": [80, 80], "unit": unit})).unwrap(); + assert_eq!(sel(&s), (0, 0), "empty story unit={unit}"); + } + } } #[cfg(test)] From 613aaab8365dce3002c4c5a9b66fe41afb9bcfa5 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:04:26 +0000 Subject: [PATCH 100/133] Update File Name text variable when saving under a new name (#3258) --- crates/compose/src/cache.rs | 6 +- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/file.rs | 1 + crates/engine/src/cmd/file/bytes.rs | 19 ++++++ crates/engine/src/cmd/file/open.rs | 3 + crates/engine/src/cmd/file/save.rs | 27 +++++++- crates/engine/src/cmd/variables/tests.rs | 81 ++++++++++++++++++++++++ crates/render/src/damage.rs | 13 ++++ 8 files changed, 147 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index 5c662028e..ec84d6bd9 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -114,6 +114,7 @@ fn doc_signature(doc: &Document) -> u64 { (Arc::as_ptr(sp) as usize).hash(&mut h); } (Arc::as_ptr(&doc.styles) as usize).hash(&mut h); + doc.title.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`). @@ -302,11 +303,12 @@ impl Cache { let with_vars = crate::vars::has_vars(story); let running = with_vars && crate::vars::has_running(doc, story); if with_vars { - // Variables depend on the page count, sections and definitions (and running headers on - // the whole document). + // Variables depend on the page count, title, sections and definitions (and running + // headers on the whole document). use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); format!("{:?}", doc.text_variables).hash(&mut h); + doc.title.hash(&mut h); sig.extend([doc.page_count(), h.finish() as usize]); if running { sig.push(doc_signature(doc) as usize); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 8331c4be9..f8683c670 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -277,6 +277,7 @@ pub fn specs() -> Vec { st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }); let mut doc = e.doc; super::rulers::keep_zero_point(&st.doc, &mut doc); + super::file::keep_title(&st.doc, &mut doc); st.doc = doc; st.selection = e.selection; st.bump_revision(); @@ -290,6 +291,7 @@ pub fn specs() -> Vec { st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() }); let mut doc = e.doc; super::rulers::keep_zero_point(&st.doc, &mut doc); + super::file::keep_title(&st.doc, &mut doc); st.doc = doc; st.selection = e.selection; st.bump_revision(); diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 5271e729d..7722ed067 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -25,6 +25,7 @@ pub use open::{ReadDocument, read_document}; pub use open::{RecentPreview, recent_preview}; pub(crate) use place::{crop_pdf, crop_pdf_from, document_of, prepare_placed, read_source, validate_placement}; pub use registry::specs; +pub(crate) use save::keep_title; pub(crate) use snippets::{snippet_bytes, snippet_place}; #[cfg(test)] diff --git a/crates/engine/src/cmd/file/bytes.rs b/crates/engine/src/cmd/file/bytes.rs index b1985dd7b..77aaa9a82 100644 --- a/crates/engine/src/cmd/file/bytes.rs +++ b/crates/engine/src/cmd/file/bytes.rs @@ -37,6 +37,25 @@ pub(super) fn without_native_extension(name: &str) -> &str { } } +/// The document title for a saved file at `path`: its file name without a trailing `.designcraft` +/// or `.idml` extension (any case). `None` when `path` has no file name. +pub(super) fn title_from_path(path: &std::path::Path) -> Option { + let name = path.file_name()?.to_string_lossy(); + let stem = match name.rsplit_once('.') { + Some((stem, ext)) + if !stem.is_empty() + && matches!( + craft_file_formats::from_extension(ext), + Some(craft_file_formats::Format::DesignCraft | craft_file_formats::Format::Idml) + ) => + { + stem + } + _ => &name, + }; + (!stem.is_empty()).then(|| stem.to_string()) +} + /// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package. /// The first [`DOCUMENT_SNIFF_BYTES`] of a file are enough for packages that start with their /// `mimetype` entry, as both formats write them. diff --git a/crates/engine/src/cmd/file/open.rs b/crates/engine/src/cmd/file/open.rs index 506a8639c..b295acb3c 100644 --- a/crates/engine/src/cmd/file/open.rs +++ b/crates/engine/src/cmd/file/open.rs @@ -144,6 +144,9 @@ pub fn read_document(path: &str, cancel: &std::sync::atomic::AtomicBool) -> Resu return Err(e); } let file = std::path::Path::new(path); + if let Some(title) = file.file_name().map(|n| without_native_extension(&n.to_string_lossy()).to_string()).filter(|t| !t.is_empty()) { + d.title = title; + } crate::cmd::interchange::resolve_packaged_links(&mut d, Some(file)); crate::cmd::datamerge::resolve_sources_on_open(&mut d, Some(file)); let links = crate::cmd::native_links::resolve(&mut d, Some(file), true); diff --git a/crates/engine/src/cmd/file/save.rs b/crates/engine/src/cmd/file/save.rs index d70c5ce7a..8b7601267 100644 --- a/crates/engine/src/cmd/file/save.rs +++ b/crates/engine/src/cmd/file/save.rs @@ -2,12 +2,19 @@ use super::DocState; #[cfg(not(target_arch = "wasm32"))] use super::bytes::from_bytes; -use super::bytes::{bytes_for_path, with_save_extension}; +use super::bytes::{bytes_for_path, title_from_path, with_save_extension}; #[cfg(not(target_arch = "wasm32"))] use super::open::load_document_fonts; #[cfg(test)] use super::place::image_place_tests; -use super::{Arc, EngineError, Result, Session, Value, bad, json, str_param}; +use super::{Arc, Document, EngineError, Result, Session, Value, bad, json, str_param}; + +/// Undo and redo swap whole documents; the saved file's title stays as it is now. +pub(crate) fn keep_title(now: &Document, to: &mut Arc) { + if to.title != now.title { + Arc::make_mut(to).title.clone_from(&now.title); + } +} pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { let st = s.doc_mut()?; @@ -24,13 +31,21 @@ pub(super) fn file_save(s: &mut Session, p: &Value) -> Result { let linked = crate::cmd::native_links::for_destination(&st.doc, from, destination); let links_changed = linked.is_some(); let mut saved = linked.unwrap_or_else(|| (*st.doc).clone()); + let title_changed = title_from_path(destination).is_some_and(|title| { + if saved.title != title { + saved.title = title; + true + } else { + false + } + }); crate::cmd::datamerge::refresh_relative_paths(&mut saved, destination); // Proxies the background job hasn't made yet are made here, on this thread: the save is // synchronous. The document keeps them. let proxied = crate::cmd::native_links::with_proxies(&saved, || false); let proxies_made = proxied.is_some(); let saved = proxied.unwrap_or(saved); - let changed = links_changed || proxies_made || saved.data_merge != st.doc.data_merge; + let changed = links_changed || proxies_made || title_changed || saved.data_merge != st.doc.data_merge; let saved = if changed { Arc::new(saved) } else { st.doc.clone() }; let mut warnings = crate::cmd::native_links::web_save_warnings(&saved); let allow_loss = p.get("allowLoss").and_then(Value::as_bool).unwrap_or(false); @@ -72,6 +87,9 @@ pub(super) fn file_save_a_copy(s: &mut Session, p: &Value) -> Result { let destination = std::path::Path::new(&path); let from = st.path.as_deref().map(std::path::Path::new); let mut copy = crate::cmd::native_links::for_destination(&st.doc, from, destination).unwrap_or_else(|| (*st.doc).clone()); + if let Some(title) = title_from_path(destination) { + copy.title = title; + } crate::cmd::datamerge::refresh_relative_paths(&mut copy, destination); if embed { crate::cmd::native_links::embed_linked(&mut copy, "file.saveACopy")?; @@ -139,6 +157,9 @@ pub(super) fn file_revert(s: &mut Session, _: &Value) -> Result { } else { from_bytes(&bytes)? }; + if let Some(title) = title_from_path(std::path::Path::new(&path)) { + d.title = title; + } // As opened again: the fonts beside it now (unchanged files are shared, not read again), // its linked files found again. let (fonts, _, _) = load_document_fonts(&mut d, &path); diff --git a/crates/engine/src/cmd/variables/tests.rs b/crates/engine/src/cmd/variables/tests.rs index 726f8d6a8..143db1884 100644 --- a/crates/engine/src/cmd/variables/tests.rs +++ b/crates/engine/src/cmd/variables/tests.rs @@ -485,3 +485,84 @@ fn a_custom_variable_defined_with_a_number_shows_its_digits() { let d = s.doc().unwrap().doc.clone(); assert_eq!(shown_on_parent(&s, &d, sid), 4, "2026 shows"); } + +/// #3258: saving under a new name updates the `File Name` text variable (and its cached +/// composition) on both document pages and parent pages, keeps it across undo, leaves it alone +/// when Save As fails, and picks up a renamed file on open. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn file_name_variable_updates_on_save_as_including_parent_pages() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.title, "Untitled-1"); + + let parent_frame = s + .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": ""})) + .unwrap(); + let parent_sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(parent_frame["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": parent_sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("variables.insert", &json!({"name": "File Name"})).unwrap(); + + let doc_frame = s.execute("frame.create", &json!({"rect": [72, 100, 500, 140], "content": "text", "text": ""})).unwrap(); + let doc_sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(doc_frame["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + s.execute("text.select", &json!({"story": doc_sid.0, "anchor": 0, "focus": 0})).unwrap(); + s.execute("variables.insert", &json!({"name": "File Name"})).unwrap(); + + let visible_glyphs = |s: &Session, sid, page: Option| -> usize { + let d = s.doc().unwrap().doc.clone(); + let cs = s.cache.get(&d, sid, page); + cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum() + }; + let listed = |s: &mut Session| -> String { + let list = s.execute("variables.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().find(|v| v["name"] == "File Name").unwrap()["value"].as_str().unwrap().to_string() + }; + + // Warm the composition cache before Save As on document, parent-on-page, and parent spread. + assert_eq!(listed(&mut s), "Untitled-1"); + assert_eq!(visible_glyphs(&s, doc_sid, None), "Untitled-1".len()); + assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "Untitled-1".len()); + assert_eq!(visible_glyphs(&s, parent_sid, None), "Untitled-1".len()); + + // Save As updates the title, bumps revision, and invalidates cached compositions. + let rev_before = s.doc().unwrap().revision; + let saved_path = dir.path().join("CatalogEdition.designcraft"); + s.execute("file.saveAs", &json!({"path": saved_path.to_string_lossy()})).unwrap(); + assert_eq!(s.doc().unwrap().doc.title, "CatalogEdition"); + assert!(!s.doc().unwrap().is_dirty()); + assert_ne!(s.doc().unwrap().revision, rev_before, "canvas and thumbnails must redraw"); + assert_eq!(listed(&mut s), "CatalogEdition"); + assert_eq!(visible_glyphs(&s, doc_sid, None), "CatalogEdition".len()); + assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "CatalogEdition".len()); + assert_eq!(visible_glyphs(&s, parent_sid, None), "CatalogEdition".len()); + + // A failed Save As leaves the current title and File Name variable intact. + let missing = dir.path().join("missing/Other.designcraft"); + assert!(s.execute("file.saveAs", &json!({"path": missing.to_string_lossy()})).is_err()); + assert_eq!(s.doc().unwrap().doc.title, "CatalogEdition"); + assert_eq!(listed(&mut s), "CatalogEdition"); + + // Save As under another name (including .idml) updates it again. + let idml_path = dir.path().join("Issue.idml"); + s.execute("file.saveAs", &json!({"path": idml_path.to_string_lossy()})).unwrap(); + assert_eq!(s.doc().unwrap().doc.title, "Issue"); + assert_eq!(listed(&mut s), "Issue"); + assert_eq!(visible_glyphs(&s, doc_sid, None), "Issue".len()); + assert_eq!(visible_glyphs(&s, parent_sid, Some(0)), "Issue".len()); + + // Undoing an edit made before Save As keeps the saved file name instead of reverting to Untitled-1. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.title, "Issue"); + assert_eq!(listed(&mut s), "Issue"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.title, "Issue"); + + // Reopening a file renamed on disk reflects its current file name. + let renamed = dir.path().join("RenamedBook.designcraft"); + std::fs::rename(&saved_path, &renamed).unwrap(); + let mut reopened = Session::new(); + reopened.execute("file.open", &json!({"path": renamed.to_string_lossy()})).unwrap(); + assert_eq!(reopened.doc().unwrap().doc.title, "RenamedBook"); + assert_eq!(listed(&mut reopened), "RenamedBook"); +} diff --git a/crates/render/src/damage.rs b/crates/render/src/damage.rs index 44ee418f5..22698953c 100644 --- a/crates/render/src/damage.rs +++ b/crates/render/src/damage.rs @@ -29,6 +29,7 @@ pub fn damage_with(old: &Document, new: &Document, cache: Option<&designcraft_co || old.layers != new.layers || old.settings != new.settings || old.sections != new.sections + || old.title != new.title || old.text_variables != new.text_variables || old.footnote_options != new.footnote_options || old.xref_formats != new.xref_formats @@ -582,4 +583,16 @@ mod tests { } changed } + + /// #3258: saving under a new name changes `doc.title` without touching spreads or stories; + /// damage reports a full repaint so File Name variables on document and parent pages redraw. + #[test] + fn renaming_document_damages_canvas() { + let mut d = Document::new(&NewDocument { pages: 1, title: "Untitled-1".into(), ..Default::default() }); + let old = d.clone(); + let cache = designcraft_compose::Cache::new(); + d.title = "CatalogEdition".into(); + assert!(damage(&old, &d).is_none()); + assert!(damage_with(&old, &d, Some(&cache)).is_none()); + } } From b5328dbde00da7c93578685188b108ec49f98c89 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:16:52 +0000 Subject: [PATCH 101/133] Include variable signature for wrapping neighbours in composition cache --- crates/compose/src/cache.rs | 18 +++++++++++++----- crates/compose/src/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs index ec84d6bd9..f1c8aff28 100644 --- a/crates/compose/src/cache.rs +++ b/crates/compose/src/cache.rs @@ -170,6 +170,15 @@ fn numbering_signature(starts: &NumberStarts, story: &Story) -> Vec { sig } +/// Document-level state a story's text variables depend on. +fn vars_signature(doc: &Document) -> usize { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + format!("{:?}", doc.text_variables).hash(&mut h); + doc.title.hash(&mut h); + h.finish() as usize +} + /// Everything page names and section markers are made from. fn sections_hash(doc: &Document) -> u64 { use std::hash::{Hash, Hasher}; @@ -256,6 +265,9 @@ impl Cache { if let Some(starts) = &starts { sig.push(hash_of(&numbering_signature(starts, ns))); } + if crate::vars::has_vars(ns) { + sig.extend([doc.page_count(), vars_signature(doc)]); + } keep_items.extend(k.into_iter().filter(|it| kept.insert(Arc::as_ptr(it)))); keep_stories.push(ns.clone()); } @@ -305,11 +317,7 @@ impl Cache { if with_vars { // Variables depend on the page count, title, sections and definitions (and running // headers on the whole document). - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - format!("{:?}", doc.text_variables).hash(&mut h); - doc.title.hash(&mut h); - sig.extend([doc.page_count(), h.finish() as usize]); + sig.extend([doc.page_count(), vars_signature(doc)]); if running { sig.push(doc_signature(doc) as usize); } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0a1f67184..b68b16963 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -10575,6 +10575,31 @@ fn a_neighbours_numbering_moves_the_text_its_objects_wrap() { assert_eq!(line_layout(&cache.get(&d, b, None)), fresh); } +#[test] +fn a_neighbours_file_name_variable_moves_the_text_its_objects_wrap() { + // Regression: a variable-free story wrapped by a neighbour's anchored object kept its cached + // lines when the document title changed, though a longer File Name pushed the object's anchor + // onto the next line. + let long = [LOREM; 3].join(" "); + let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, title: "A".into(), ..Default::default() }); + let lid = d.default_layer(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap(); + let (fa, a) = + d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 400.0), lid, &format!("{var} Anchor"), ParaFormat::default()).unwrap(); + 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(); + let end = d.story(a).unwrap().len(); + anchor_box(&mut d, a, end, left - area.x0, 20.0, true, WrapMode::BoundingBox); + let cache = Cache::new(); + let before = line_layout(&cache.get(&d, b, None)); + assert_eq!(before, line_layout(&compose_story(&d, b, &ComposeOptions::default()))); + d.title = "A Much Longer Document File Name".into(); + let fresh = line_layout(&compose_story(&d, b, &ComposeOptions::default())); + assert_ne!(fresh, before, "the longer file name moves the wrapping object"); + assert_eq!(line_layout(&cache.get(&d, b, None)), fresh); +} + #[test] fn many_stories_in_continuing_lists_compose_quickly() { // Regression: each story's cache lookup searched the whole item tree per story and per list From 3912f9b3fbbc1bd459db1be9fc65c747d6a9087c Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:40:58 +0000 Subject: [PATCH 102/133] Check embedded cells and notes in vars::has_vars and vars::has_running --- crates/compose/src/tests.rs | 35 +++++++++++++++++++++++++++++++++++ crates/compose/src/vars.rs | 27 ++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index b68b16963..0b5ec6fad 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -10600,6 +10600,41 @@ fn a_neighbours_file_name_variable_moves_the_text_its_objects_wrap() { assert_eq!(line_layout(&cache.get(&d, b, None)), fresh); } +#[test] +fn cached_cell_and_footnote_file_name_variables_update_on_rename() { + // Regression: a story whose only File Name variable sits in a table cell or footnote kept its + // cached composition after a title change because `has_vars` inspected only outer `story.text`. + let glyphs = |cs: &ComposedStory| -> usize { + cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum() + }; + + // Table cell only. + let (mut d, sid, _) = table_doc(Rect::new(0.0, 0.0, 400.0, 400.0), designcraft_doc::Table::new(77, 1, 1, 0, 0, 300.0)); + d.title = "Short".into(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string(); + Arc::make_mut(d.story_mut(sid).unwrap().tables.values_mut().next().unwrap()).cell_mut(0, 0).unwrap().text.insert(0, &var); + let cache = Cache::new(); + let before = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text); + d.title = "CatalogEdition".into(); + let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].tables[0].cells[0].text); + let after = glyphs(&cache.get(&d, sid, None).frames[0].tables[0].cells[0].text); + assert!(fresh > before, "rename lengthens the cell text: {before} -> {fresh}"); + assert_eq!(after, fresh); + + // Footnote only. + let (mut d, sid, _) = doc_with("Body text.", Rect::new(36.0, 36.0, 400.0, 400.0), ParaAttrs::default()); + d.title = "Short".into(); + let var = designcraft_doc::vars::var_char(d.variable("File Name").unwrap()).unwrap().to_string(); + d.story_mut(sid).unwrap().insert_note(4, &var, ParaFormat::default()); + let cache = Cache::new(); + let before = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text); + d.title = "CatalogEdition".into(); + let fresh = glyphs(&compose_story(&d, sid, &ComposeOptions::default()).frames[0].notes[0].text); + let after = glyphs(&cache.get(&d, sid, None).frames[0].notes[0].text); + assert!(fresh > before, "rename lengthens the footnote text: {before} -> {fresh}"); + assert_eq!(after, fresh); +} + #[test] fn many_stories_in_continuing_lists_compose_quickly() { // Regression: each story's cache lookup searched the whole item tree per story and per list diff --git a/crates/compose/src/vars.rs b/crates/compose/src/vars.rs index bd9e32ccd..96b817eb9 100644 --- a/crates/compose/src/vars.rs +++ b/crates/compose/src/vars.rs @@ -9,14 +9,31 @@ use designcraft_doc::{Document, SpreadRef, Story, StoryId}; use crate::ComposedStory; -/// Does the story contain any text variable instance? -pub fn has_vars(st: &Story) -> bool { - st.text.chars().any(|c| var_index(c).is_some()) +const MAX_NESTING: usize = 32; + +fn story_any(st: &Story, depth: usize, f: &impl Fn(&Story) -> bool) -> bool { + if f(st) { + return true; + } + if depth >= MAX_NESTING { + return false; + } + st.tables.values().flat_map(|t| &t.cells).any(|c| story_any(&c.text, depth + 1, f)) + || st.notes.iter().chain(&st.endnotes).any(|n| story_any(&n.text, depth + 1, f)) } -/// Does the story contain a running-header variable instance? +/// Does the story (or any embedded table cell, footnote or endnote) contain a text variable +/// instance? +pub fn has_vars(st: &Story) -> bool { + story_any(st, 0, &|s| s.text.chars().any(|c| var_index(c).is_some())) +} + +/// Does the story (or any embedded table cell, footnote or endnote) contain a running-header +/// variable instance? pub fn has_running(doc: &Document, st: &Story) -> bool { - st.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. }))) + story_any(st, 0, &|s| { + s.text.chars().filter_map(var_index).any(|i| matches!(doc.text_variables.get(i).map(|v| &v.kind), Some(VarKind::RunningHeader { .. }))) + }) } /// Absolute page showing story byte `pos` of a composed story. From 1cdfe1b4bb5dcbf765df7a9f59d657daa2f32f6a Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:04:46 +0000 Subject: [PATCH 103/133] UI: highlight a selected empty line's return on text set on a path --- crates/ui-egui/src/canvas/tests.rs | 25 +++++++++++++++++++ crates/ui-egui/src/canvas/text_overlay.rs | 29 ++++++++++------------- 2 files changed, 37 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 55bd1c338..13ff11ea2 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3853,3 +3853,28 @@ fn a_turned_view_draws_the_plain_highlight_while_zooming() { assert!(!rendered(&h), "zoom ×{zoom}: nothing rendered for it"); } } + +/// Selecting an empty line's return on text set on a path draws a visible highlight along the path. +#[test] +fn path_text_empty_line_selection_draws_highlight() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1})).unwrap(); + let id = app.run("line.create", json!({"a": [72, 100], "b": [300, 100]})).unwrap()["id"].as_u64().unwrap(); + app.run("type.onPath", json!({"id": id, "text": "\nSecond"})).unwrap(); + for unit in ["word", "line"] { + app.run("text.selectAt", json!({"frame": id, "point": [80, 100], "unit": unit})).unwrap(); + let st = app.session.doc().unwrap(); + let ts = st.selection.text.unwrap(); + assert_eq!((ts.anchor, ts.focus), (0, 1), "unit={unit}"); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, None); + }); + output.textures_delta.clear(); + let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 110); + let painted = output.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Path(p) if p.fill == tint)).count(); + assert!(painted > 0, "empty line return on a path must draw a highlight (unit={unit})"); + } +} diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index b9ad0aa1b..057f83c0f 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -55,11 +55,8 @@ pub(super) fn draw_text_selection( // Type on a path: the highlight bends with the text. if let Some(map) = compose::PathTextMap::new(it, ft) { for l in &ft.lines { - let (s, e) = (range.start.max(l.range.start), range.end.min(l.range.end)); - if s >= e { - continue; - } - for q in compose::highlight_quads(l, s, e, false) { + let Some((s, e, past)) = line_highlight_span(l, &range) else { continue }; + for q in compose::highlight_quads(l, s, e, past) { let (x0, x1) = (q[0].x.min(q[1].x), q[0].x.max(q[1].x)); let (y0, y1) = (q[0].y.min(q[2].y), q[0].y.max(q[2].y)); // Short slices, each turned with the path. @@ -76,12 +73,7 @@ pub(super) fn draw_text_selection( } let mut quads = Vec::new(); for l in &ft.lines { - let s = range.start.max(l.range.start); - let e = range.end.min(l.range.end); - if s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) { - continue; - } - let past = e == l.range.end && range.end > l.range.end; + let Some((s, e, past)) = line_highlight_span(l, &range) else { continue }; quads.extend(compose::highlight_quads(l, s, e, past)); // A selected drop cap is highlighted down to its baseline. if let Some(dc) = l.drop_cap { @@ -116,6 +108,14 @@ pub(super) fn draw_text_selection( } } +/// Clamped byte span on `l` and whether `range` continues past `l.range.end` (selecting its return). +fn line_highlight_span(l: &compose::Line, range: &std::ops::Range) -> Option<(usize, usize, bool)> { + let s = range.start.max(l.range.start); + let e = range.end.min(l.range.end); + let past = e == l.range.end && range.end > l.range.end; + (s < e || (s == e && past)).then_some((s, e, past)) +} + /// Caret / text highlight inside a table cell (the cell's lines are offset by the cell origin). #[allow(clippy::too_many_arguments)] fn draw_cell_selection( @@ -142,12 +142,7 @@ fn draw_cell_selection( && let Some(cft) = text.frames.first() { for l in &cft.lines { - let s = range.start.max(l.range.start); - let e = range.end.min(l.range.end); - if s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) { - continue; - } - let past = e == l.range.end && range.end > l.range.end; + let Some((s, e, past)) = line_highlight_span(l, &range) else { continue }; for q in compose::highlight_quads(l, s, e, past) { let poly = q.map(|p| xf.to_screen(m * p)); painter.add(egui::Shape::convex_polygon(poly.to_vec(), Color32::from_rgba_unmultiplied(80, 140, 255, 110), Stroke::NONE)); From d1df43b60c27f5851b4a2b5d1778a1acac613f78 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:54:34 +0000 Subject: [PATCH 104/133] UI: limit zero-width past-end highlights to paragraph-ending lines --- crates/ui-egui/src/canvas/tests.rs | 60 +++++++++++++++++++++++ crates/ui-egui/src/canvas/text_overlay.rs | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 13ff11ea2..2a8e787bd 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3878,3 +3878,63 @@ fn path_text_empty_line_selection_draws_highlight() { assert!(painted > 0, "empty line return on a path must draw a highlight (unit={unit})"); } } + +/// A soft-wrapped line (`last_in_para == false`) must not draw a stray end-of-line highlight when +/// the selection starts at the following line (or overset text on a path). +#[test] +fn soft_wrapped_line_gets_no_stray_highlight_when_next_line_is_selected() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"pages": 1})).unwrap(); + app.ui.separations = Some(crate::separations::Separations::default()); + let xf = Xf { min: pos2(0.0, 0.0), origin: Point::new(0.0, 0.0), zoom: 1.0, rot: 0, pivot: pos2(0.0, 0.0) }; + + // Normal text frame: narrow enough to soft-wrap "Hello world" across two lines. + let r = app.run("frame.create", json!({"rect": [72, 72, 120, 200], "content": "text", "text": "Hello world"})).unwrap(); + let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap()); + let (split, end) = { + let st = app.session.doc().unwrap(); + let cs = app.session.cache.get(&st.doc, sid, None); + let lines = &cs.frames[0].lines; + assert_eq!(lines.len(), 2, "must soft-wrap into two lines: {lines:?}"); + assert!(!lines[0].last_in_para); + assert_eq!(lines[0].range.end, lines[1].range.start); + (lines[1].range.start, lines[1].range.end) + }; + app.run("text.select", json!({"story": sid.0, "anchor": split, "focus": end})).unwrap(); + let st = app.session.doc().unwrap(); + let ts = st.selection.text.unwrap(); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, None); + }); + output.textures_delta.clear(); + let plain: Vec<_> = + output.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Path(p) if p.fill == super::text_overlay::PLAIN_HIGHLIGHT)).collect(); + assert_eq!(plain.len(), 1, "only the selected second line must be highlighted, not the soft-wrapped line above it"); + + // Path text: short enough that "world" oversets (`last_in_para == false`); selecting only the + // overset tail must paint nothing on the visible line. + let pid = app.run("line.create", json!({"a": [72, 260], "b": [110, 260]})).unwrap()["id"].as_u64().unwrap(); + let pr = app.run("type.onPath", json!({"id": pid, "text": "Hello world"})).unwrap(); + let psid = designcraft_doc::StoryId(pr["story"].as_u64().unwrap()); + let pend = { + let st = app.session.doc().unwrap(); + let cs = app.session.cache.get(&st.doc, psid, None); + let lines = &cs.frames[0].lines; + assert_eq!(lines.len(), 1); + assert!(!lines[0].last_in_para); + lines[0].range.end + }; + app.run("text.select", json!({"story": psid.0, "anchor": pend, "focus": "Hello world".len()})).unwrap(); + let st = app.session.doc().unwrap(); + let ts = st.selection.text.unwrap(); + let layout = CanvasLayout::new(&st.doc, st.editing_parents); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + draw_text_selection(&app, ui.painter(), &xf, &st.doc, &layout, ts, None); + }); + output.textures_delta.clear(); + let tint = Color32::from_rgba_unmultiplied(80, 140, 255, 110); + let painted = output.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Path(p) if p.fill == tint)).count(); + assert_eq!(painted, 0, "overset selection past a non-final path line must paint no highlight on that line"); +} diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index 057f83c0f..d534d1fdf 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -113,7 +113,7 @@ fn line_highlight_span(l: &compose::Line, range: &std::ops::Range) -> Opt let s = range.start.max(l.range.start); let e = range.end.min(l.range.end); let past = e == l.range.end && range.end > l.range.end; - (s < e || (s == e && past)).then_some((s, e, past)) + (s < e || (s == e && past && l.last_in_para)).then_some((s, e, past)) } /// Caret / text highlight inside a table cell (the cell's lines are offset by the cell origin). From d638573fabec94594e20dac467591d01b31caa29 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH 105/133] feat(nightly): wire craft-nightly for self-isolated direct launches (#3327) --- Cargo.lock | 9 + Cargo.toml | 2 + apps/designcraft/Cargo.toml | 1 + apps/designcraft/src/build_flavor.rs | 34 +- apps/designcraft/src/launch_profile.rs | 333 +++++++------- apps/designcraft/src/main.rs | 74 ++-- apps/designcraft/src/profile.rs | 17 +- apps/designcraft/src/profile_root.rs | 571 ------------------------- 8 files changed, 220 insertions(+), 821 deletions(-) delete mode 100644 apps/designcraft/src/profile_root.rs diff --git a/Cargo.lock b/Cargo.lock index b77607498..f9f2762e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1357,6 +1357,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-offcrypto" version = "0.1.0" @@ -1772,6 +1780,7 @@ name = "designcraft" version = "0.22.0" dependencies = [ "arboard", + "craft-nightly", "craft-update", "craft-window", "designcraft-engine", diff --git a/Cargo.toml b/Cargo.toml index c54020126..a572b77a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,8 @@ craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "33be356 craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "33be35625e252cc4f06aa375b3b428521faea37d", version = "=0.1.0", features = ["flatten"] } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "33be35625e252cc4f06aa375b3b428521faea37d", features = ["egui"] } +# Shared nightly-v1 profile isolation, launch protocol, and security fence (craft-libs). +craft-nightly = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal designcraft-geom = { path = "crates/geom" } designcraft-color = { path = "crates/color" } diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml index 359e00470..1d0ca9800 100644 --- a/apps/designcraft/Cargo.toml +++ b/apps/designcraft/Cargo.toml @@ -11,6 +11,7 @@ default-run = "designcraft" workspace = true [dependencies] +craft-nightly = { workspace = true } designcraft-engine = { workspace = true } designcraft-ui-egui = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "links", "clipboard"] } diff --git a/apps/designcraft/src/build_flavor.rs b/apps/designcraft/src/build_flavor.rs index 0793f44ed..ae6093c9c 100644 --- a/apps/designcraft/src/build_flavor.rs +++ b/apps/designcraft/src/build_flavor.rs @@ -1,12 +1,8 @@ //! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. -use crate::launch_profile::Profile; + use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; pub const COMPILED: BuildFlavor = if cfg!(designcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -16,14 +12,6 @@ pub const VERSION: &str = env!("DESIGNCRAFT_BUILT_VERSION"); /// The plain `designcraft --version` line, unchanged for stable. pub const STABLE_VERSION_LINE: &str = concat!("designcraft ", env!("CARGO_PKG_VERSION")); -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open DesignCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable DesignCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { desktop_session && flavor == BuildFlavor::NightlyV1 } @@ -42,7 +30,7 @@ pub fn version_line(flavor: BuildFlavor, stable: &str, version: &str) -> String #[cfg(test)] mod tests { - use super::*; + use super::{BuildFlavor, COMPILED, VERSION, needs_native_error, version_line, version_query}; #[test] fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { @@ -52,22 +40,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - } - #[test] fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { let version = "0.2.1-nightly.20261124.17.1.gabcdef012345"; diff --git a/apps/designcraft/src/launch_profile.rs b/apps/designcraft/src/launch_profile.rs index f2b421433..1853dfdcd 100644 --- a/apps/designcraft/src/launch_profile.rs +++ b/apps/designcraft/src/launch_profile.rs @@ -1,127 +1,94 @@ -//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. -//! Stable launches retain their original arguments and directory policy. No environment mutation. +//! DesignCraft's `craft-nightly` isolation specification. +//! +//! Nightly builds self-isolate into `craft_nightly::canonical_profile_root("designcraft")` on +//! direct launch and also accept ArtCraft Launcher's `--launch-profile nightly-v1 --profile-root` +//! arguments, fenced away from stable settings, installs, and portable layouts. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; +use std::path::{Component, PathBuf}; -pub const VERSION: &str = "nightly-v1"; +use craft_nightly::AppProfileSpec; -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), +const FOLDER_ONLY_ENTRIES: &[&str] = &["Recovery", "logs"]; + +/// Builds DesignCraft's [`AppProfileSpec`] for `craft-nightly` startup parsing and fencing. +pub fn spec() -> AppProfileSpec { + AppProfileSpec { + app_id: "designcraft", + display_name: "DesignCraft", + stable_dir_names: &["DesignCraft", "designcraft"], + stable_package_id: designcraft_ui_egui::channel::APP_ID, + nightly_package_id: designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, + profile_root_env: None, + forbidden_env_vars: &["DESIGNCRAFT_CONFIG_DIR"], + portable_markers: &[crate::profile::PORTABLE_MARKER], + folder_only_entries: FOLDER_ONLY_ENTRIES, + extra_forbidden_roots: extra_forbidden_roots_with(|key| std::env::var_os(key)), + } } -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } +fn abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + (path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir))).then_some(path) +} - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), +fn extra_forbidden_roots_with(env: impl Fn(&str) -> Option) -> Vec { + #[cfg(target_os = "windows")] + { + let mut roots = Vec::new(); + if let Some(local) = abs_env(&env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join("DesignCraft")); } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); - -pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) -} - -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is -/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = abs_env(&env, key) { + roots.push(base.join("ArtCraft").join("DesignCraft")); + } } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); + roots + } + + #[cfg(all(unix, not(target_os = "macos")))] + { + let mut roots = vec![PathBuf::from("/usr/bin/designcraft"), PathBuf::from("/usr/local/bin/designcraft"), PathBuf::from("/opt/designcraft")]; + if let Some(home) = abs_env(&env, "HOME") { + roots.push(home.join(".var/app/ai.storyteller.designcraft")); } + roots } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + + #[cfg(target_os = "macos")] + { + let mut roots = vec![PathBuf::from("/Applications/DesignCraft.app")]; + if let Some(home) = abs_env(&env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences/DesignCraft.plist")); + roots.push(library.join("Preferences/ai.storyteller.designcraft.plist")); + roots.push(library.join("Saved Application State/ai.storyteller.designcraft.savedState")); + roots.push(home.join("Applications/DesignCraft.app")); } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), + roots } -} -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; + #[cfg(not(any(unix, target_os = "windows")))] + { + let _ = env; + Vec::new() } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old portable/config resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. DesignCraft has no -/// agent SDK folder of its own, so the stable boundary is its settings folder, install folders and -/// portable data only. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile::ensure_writable) } #[cfg(test)] mod tests { - use super::*; - use std::cell::Cell; + use std::ffi::OsString; + use std::path::Path; + use std::sync::atomic::{AtomicU64, Ordering}; + + use craft_nightly::{ + BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup, + validate_and_prepare_root, + }; + + use super::{FOLDER_ONLY_ENTRIES, spec}; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -131,87 +98,107 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\designcraft" } else { "/nightly-data/profiles/designcraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + #[test] + fn spec_preserves_designcraft_isolation_boundaries() { + let s = spec(); + assert_eq!(s.app_id, "designcraft"); + assert_eq!(s.display_name, "DesignCraft"); + assert_eq!(s.stable_dir_names, &["DesignCraft", "designcraft"]); + assert_eq!(s.stable_package_id, designcraft_ui_egui::channel::APP_ID); + assert_eq!(s.nightly_package_id, designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID); + assert_eq!(s.profile_root_env, None); + assert_eq!(s.forbidden_env_vars, &["DESIGNCRAFT_CONFIG_DIR"]); + assert_eq!(s.portable_markers, &[crate::profile::PORTABLE_MARKER]); + assert_eq!(s.folder_only_entries, FOLDER_ONLY_ENTRIES); } #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn direct_nightly_launch_self_isolates_into_canonical_profile_root() { + let s = spec(); + let expected_root = canonical_profile_root("designcraft").unwrap(); + let user_args = args(&["brochure.designcraft", "poster.idml"]); + let launch = parse_startup(BuildFlavor::NightlyV1, &s, user_args.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert_eq!(launch.passthrough_args, user_args); + assert!(launch.leading_flags.is_empty()); + } + + #[test] + fn explicit_launcher_arguments_are_parsed_without_reinterpreting_file_names() { + let s = spec(); + let root = Path::new(absolute()); + let user_args = args(&["--profile-root", "design with spaces.designcraft"]); + let argv = launch_arguments(root, &user_args); + let launch = parse_startup(BuildFlavor::NightlyV1, &s, argv, &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(root.to_path_buf())); + assert_eq!(launch.passthrough_args, user_args); + } + + #[test] + fn stable_build_keeps_normal_args_and_refuses_nightly_flags() { + let s = spec(); for argv in [args(&[]), args(&["--sample", "a.idml"]), args(&["--", "--launch-profile", "file.designcraft"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = parse_startup(BuildFlavor::Stable, &s, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + let nightly_argv = launch_arguments(Path::new(absolute()), &[]); + let err = parse_startup(BuildFlavor::Stable, &s, nightly_argv, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "design with spaces.designcraft"])); - let launch = parse(argv).unwrap(); - assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "design with spaces.designcraft"])); - } - - #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { - for argv in [ - args(&["--launch-profile", VERSION]), - args(&["--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=", VERSION, "--profile-root", absolute(), "--"]), - ] { - assert!(parse(argv).is_err()); - } - } - - #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_for_plain_and_launcher_invocations() { + let s = spec(); + let root = Path::new(absolute()); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } + let plain = parse_startup(BuildFlavor::NightlyV1, &s, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); + + let via_launcher = parse_startup(BuildFlavor::NightlyV1, &s, launch_arguments(root, &args(&[flag])), &StartupOptions::new()).unwrap(); + assert!(via_launcher.is_version_query(), "launcher {flag}"); + + let without_sep = parse_startup( + BuildFlavor::NightlyV1, + &s, + args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(without_sep.is_version_query(), "launcher without separator {flag}"); } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + let file_named_version = parse_startup(BuildFlavor::NightlyV1, &s, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + static NEXT: AtomicU64 = AtomicU64::new(0); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let root = base.join(format!("designcraft-nightly-reopen-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&root); + let s = spec(); - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + let confirmed = validate_and_prepare_root(&root, &s).unwrap(); + assert_eq!(confirmed, root); + for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(confirmed.join(name), b"saved profile data").unwrap(); + } + for name in FOLDER_ONLY_ENTRIES { + std::fs::create_dir(confirmed.join(name)).unwrap(); + } + assert_eq!(validate_and_prepare_root(&root, &s).unwrap(), confirmed); + assert_eq!(std::fs::read(confirmed.join("ui.json")).unwrap(), b"saved profile data"); + + for name in FOLDER_ONLY_ENTRIES { + let path = confirmed.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(validate_and_prepare_root(&root, &s).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + + let _ = std::fs::remove_dir_all(&root); } } diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 23688b3f6..b4af29aef 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -32,7 +32,6 @@ mod nightly_session; mod pointer; mod process_identity; mod profile; -mod profile_root; mod window_frame; use designcraft_engine::Session; @@ -322,41 +321,37 @@ fn report_launch_profile_error(error: &str) { } /// Select the immutable launch profile before any start-up service or side effect: the version -/// answer first, then the profile, the Windows identity, the fenced root and the session record. +/// answer first, then `craft-nightly` startup/fencing (self-isolating direct nightly launches into +/// the canonical profile root and honoring Launcher `--launch-profile`/`--profile-root` flags), +/// the Windows identity, channel selection, and the session record. fn prepare_launch() -> Option { let argv: Vec<_> = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: answered before logging, root validation, process identity or any window. A - // headless runner otherwise hung on macOS and exited 2 on Linux. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) - { + // Plain `--version`/`-V` on Nightly: answered before root resolution, process identity, or any + // window, even in minimal environments without a home directory. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION); + let _ = writeln!(std::io::stdout(), "{line}"); + return None; + } + let spec = launch_profile::spec(); + let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv, &craft_nightly::StartupOptions::new()).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + if launch.is_version_query() { use std::io::Write as _; let line = build_flavor::version_line(build_flavor::COMPILED, build_flavor::STABLE_VERSION_LINE, build_flavor::VERSION); let _ = writeln!(std::io::stdout(), "{line}"); return None; } - let launch = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - if launch.profile.is_nightly() { - process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID).map_err(|error| error.to_string())?; - } - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| { - launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) - }) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let nightly = launch.profile.is_nightly(); + if nightly && let Err(error) = process_identity::initialize(true, designcraft_ui_egui::channel::NIGHTLY_APP_ID) { + report_launch_profile_error(&error.to_string()); + std::process::exit(2); + } let channel = if nightly { designcraft_ui_egui::channel::Channel::NightlyV1 } else { designcraft_ui_egui::channel::Channel::Stable }; - if let Err(error) = launch_profile::install(launch.profile) - .and_then(|()| designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"))) - { + if let Err(error) = designcraft_ui_egui::channel::select(channel, build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT")) { report_launch_profile_error(&error); std::process::exit(2); } @@ -365,7 +360,7 @@ fn prepare_launch() -> Option { let mut session_unavailable = false; if nightly { match nightly_session::Session::begin_with_health( - launch_profile::current().root(), + craft_nightly::current_root(), build_flavor::VERSION, option_env!("DESIGNCRAFT_NIGHTLY_COMMIT"), ) { @@ -381,7 +376,7 @@ fn prepare_launch() -> Option { } } } - Some(Launched { args: launch.args, nightly, session, unclean, session_unavailable }) + Some(Launched { args: launch.passthrough_args, nightly, session, unclean, session_unavailable }) } /// The ordinary command line, once the launch profile was selected. @@ -399,16 +394,14 @@ struct AppCommand { skip: Vec, } -/// Read the arguments left after the launch profile. A Nightly start's first argument is the -/// separator `launch_profile::parse` put there: it is never a document, and an option after it was -/// named by the Launcher as a file. Stable keeps its control, sample and version options and drops -/// a user's own separator, so a literal `--` is never opened as a document. +/// Read the arguments left after `craft-nightly` strips any launcher protocol header and `--` +/// separator. A direct Nightly launch may still start with a user-supplied `--`, which is dropped +/// once so it is never opened as a document. Stable keeps its control, sample and version options +/// and drops a user's own separator, so a literal `--` is never opened as a document. fn app_command(args: impl IntoIterator, nightly: bool) -> AppCommand { let mut command = AppCommand::default(); - let mut args = args.into_iter(); - if nightly { - // `parse` puts the protocol's separator first; skipping it keeps a restart's `--gpu-skip=` - // (appended after that separator) in the ordinary arm below. + let mut args = args.into_iter().peekable(); + if nightly && args.peek().is_some_and(|a| a == "--") { args.next(); } while let Some(a) = args.next() { @@ -710,6 +703,9 @@ mod tests { assert!(!nightly.version, "a flag after the separator is a document"); assert_eq!(nightly.control_port, None); assert!(!nightly.sample); + + let direct = super::app_command(["a.dc", "b.idml"].map(std::ffi::OsString::from), true); + assert_eq!(direct.files, ["a.dc", "b.idml"]); } #[test] @@ -717,6 +713,10 @@ mod tests { let nightly = super::app_command(["--", "a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true); assert_eq!(nightly.files, ["a.dc"]); assert_eq!(nightly.skip, ["vulkan", "gl"]); + + let direct = super::app_command(["a.dc", "--gpu-skip=vulkan,gl"].map(std::ffi::OsString::from), true); + assert_eq!(direct.files, ["a.dc"]); + assert_eq!(direct.skip, ["vulkan", "gl"]); } #[test] diff --git a/apps/designcraft/src/profile.rs b/apps/designcraft/src/profile.rs index 0daa79665..d0eb9fa78 100644 --- a/apps/designcraft/src/profile.rs +++ b/apps/designcraft/src/profile.rs @@ -6,21 +6,20 @@ use std::path::{Path, PathBuf}; /// A file with this name next to the executable makes the install portable: settings, logs and /// recovery data are kept in [`PORTABLE_DATA_DIR`] beside it. The Windows portable zip ships one. pub(crate) const PORTABLE_MARKER: &str = "portable.txt"; -pub(crate) const PORTABLE_DATA_DIR: &str = "DesignCraftData"; +const PORTABLE_DATA_DIR: &str = "DesignCraftData"; -/// The settings folder. A Launcher nightly profile replaces every data root at once: settings, -/// logs, GPU state and recovery all live under it, so the fence in `profile_root` covers the -/// whole of Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included). +/// The settings folder. A nightly profile replaces every data root at once: settings, logs, GPU +/// state and recovery all live under it, so the `craft-nightly` fence covers the whole of +/// Nightly's user state (the engine's `Prefs`, `ui.json` and `recovery` included). pub fn config_dir() -> Option { - if let Some(root) = crate::launch_profile::current().root() { + if let Some(root) = craft_nightly::current_root() { return Some(root.to_path_buf()); } config_dir_with(std::env::consts::OS, |key| std::env::var_os(key), executable_dir().as_deref()) } -/// Whether `dir` exists, or can be created, and takes a new file. The nightly profile validator -/// uses this same probe (`profile_root`), so a profile is accepted only where settings can land. -pub(crate) fn ensure_writable(dir: &Path) -> std::io::Result<()> { +/// Whether `dir` exists, or can be created, and takes a new file. +fn ensure_writable(dir: &Path) -> std::io::Result<()> { std::fs::create_dir_all(dir)?; let probe = dir.join(format!(".write-test-{}", std::process::id())); let result = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe).map(drop); @@ -95,7 +94,7 @@ fn executable_dir() -> Option { } pub fn recovery_dir() -> Option { - if let Some(root) = crate::launch_profile::current().root() { + if let Some(root) = craft_nightly::current_root() { // Recovery stays inside the profile, including the per-run folder's lock. return own_run(root.join("Recovery")); } diff --git a/apps/designcraft/src/profile_root.rs b/apps/designcraft/src/profile_root.rs deleted file mode 100644 index 93b8ee77d..000000000 --- a/apps/designcraft/src/profile_root.rs +++ /dev/null @@ -1,571 +0,0 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. - -use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; - -use crate::profile::{PORTABLE_DATA_DIR, PORTABLE_MARKER}; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned install, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - let mut roots = ["APPDATA", "LOCALAPPDATA"] - .into_iter() - .map(|key| required_base(env, key).map(|p| p.join("DesignCraft"))) - .collect::, _>>()?; - // The MSI's per-machine folder (install-policy.wxi, ProgramFiles6432Folder) and a - // per-user install folder. A custom folder is not known here; the executable's own - // folder is fenced below. - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DesignCraft")); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("DesignCraft")); - } - } - roots - } - Platform::Linux => { - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("designcraft"))) - .collect::, _>>()?; - roots.extend(["/usr/bin/designcraft", "/usr/local/bin/designcraft", "/opt/designcraft"].map(PathBuf::from)); - // The stable Flatpak keeps its data in its own per-app folder. - roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.designcraft")); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support/DesignCraft"), - library.join("Caches/DesignCraft"), - library.join("Caches/ai.storyteller.designcraft"), - library.join("Preferences/DesignCraft.plist"), - library.join("Preferences/ai.storyteller.designcraft.plist"), - library.join("Saved Application State/ai.storyteller.designcraft.savedState"), - home.join("Applications/DesignCraft.app"), - PathBuf::from("/Applications/DesignCraft.app"), - ] - } - }; - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let joined = chosen.join(name); - match std::fs::symlink_metadata(&joined) { - Ok(meta) if !meta.is_dir() => return Err(format!("the nightly {label} must be a directory")), - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")), - } - let child = canonical_future(&joined)?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} - -/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it, -/// so a link there cannot point Nightly's writes at another app's data. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) -} - -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - #[cfg(windows)] - { - use winsafe::{HFILE, co}; - let (file, _) = HFILE::CreateFile( - path.to_str().ok_or("the nightly profile file path is not textual")?, - co::GENERIC::default(), - Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), - None, - co::DISPOSITION::OPEN_EXISTING, - co::FILE_ATTRIBUTE::NORMAL, - Some(co::FILE_FLAG::OPEN_REPARSE_POINT), - None, - None, - ) - .map_err(|e| e.to_string())?; - let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; - if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { - return Err("the nightly profile file must not be an alias or directory".into()); - } - if info.nNumberOfLinks != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - let _ = (path, metadata); - Ok(()) -} - -/// Recognise the shared portable data namespace in both the supplied and resolved path. -/// This is not an inventory of arbitrary custom stable overrides or a Launcher ownership proof. -fn is_portable_layout(path: &Path, platform: Platform) -> bool { - // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a - // marker only counts beside a DesignCraft executable, so an unrelated portable.txt higher up - // (in a user folder or at a drive root) does not refuse the profile. - path.ancestors().enumerate().any(|(depth, ancestor)| { - ancestor.join(PORTABLE_MARKER).is_file() - && (depth == 0 || ["designcraft.exe", "designcraft", "DesignCraft.app"].iter().any(|exe| ancestor.join(exe).exists())) - }) || path.components().any(|component| match component { - Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), - Component::Normal(name) => name == PORTABLE_DATA_DIR, - _ => false, - }) -} - -/// The writable hook is the app's existing probe (`profile::ensure_writable`). Keeping it injected -/// lets filesystem boundary tests exercise the real policy without starting the app or changing -/// global state. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} - -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - if env("DESIGNCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { - // The stable override would silently point every write at another app's data. - return Err("nightly-v1 cannot be combined with DESIGNCRAFT_CONFIG_DIR".into()); - } - // The nightly bundle's own sandbox is the one Flatpak that may reach this code: its per-app - // home is private. Any other id means a native package (or the stable bundle) started here, - // whose runtime socket namespace is not this profile's. - let foreign_sandbox = - env("FLATPAK_ID").filter(|value| !value.is_empty()).is_some_and(|id| id != designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID); - if platform != Platform::Windows && foreign_sandbox { - return Err("nightly-v1 starts only in its own Flatpak bundle, not inside another app's sandbox".into()); - } - let chosen = canonical_future(root)?; - if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { - return Err("the nightly root must not use a portable DesignCraft installation or its DesignCraftData settings folder".into()); - } - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect a write outside it. - entries_stay_inside(&chosen)?; - // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this - // private profile, including toward a stable portable directory not in our known roots. - private_subdirectory(&chosen, "Recovery", "recovery folder")?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); - } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); - } - private_subdirectory(&confirmed, "Recovery", "recovery folder")?; - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) -} - -const PROFILE_FOLDERS: [&str; 2] = ["Recovery", "logs"]; - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::BTreeMap; - use std::sync::atomic::{AtomicU64, Ordering}; - - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, - } - - impl Fixture { - fn new() -> Self { - static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("designcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); - match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(error) => panic!("cannot create owned fixture: {error}"), - } - }; - let home = root.join("home"); - let exe = root.join("install/designcraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } - } - - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for( - platform, - root, - |key| self.get(key), - Some(&self.exe), - |dir| { - let probe = dir.join("exclusive-test-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) - }, - ) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - } - - impl Drop for Fixture { - fn drop(&mut self) { - // Only the directory successfully created by this fixture is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); - } - } - - #[test] - fn every_stable_data_root_is_refused_on_every_platform() { - let fixture = Fixture::new(); - let home = fixture.home(); - let cases = [ - (Platform::Windows, fixture.root.join("roaming/DesignCraft")), - (Platform::Windows, fixture.root.join("local/DesignCraft")), - (Platform::Windows, fixture.root.join("local/Programs/ArtCraft/DesignCraft")), - (Platform::Linux, home.join(".config/designcraft")), - (Platform::Linux, home.join(".local/share/designcraft")), - (Platform::Linux, home.join(".cache/designcraft")), - (Platform::Linux, home.join(".local/state/designcraft")), - (Platform::Linux, home.join(".var/app/ai.storyteller.designcraft")), - (Platform::Linux, PathBuf::from("/opt/designcraft")), - (Platform::Mac, home.join("Library/Application Support/DesignCraft")), - (Platform::Mac, home.join("Library/Caches/DesignCraft")), - (Platform::Mac, home.join("Library/Preferences/ai.storyteller.designcraft.plist")), - (Platform::Mac, home.join("Library/Saved Application State/ai.storyteller.designcraft.savedState")), - (Platform::Mac, home.join("Applications/DesignCraft.app")), - ]; - for (platform, stable) in cases { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{platform:?} accepted {candidate:?}"); - assert!(!probed.get(), "a refused root must not be probed for writing"); - } - } - } - - #[test] - fn the_installation_folder_and_grandparent_overlaps_are_refused() { - let fixture = Fixture::new(); - let install = fixture.exe.parent().unwrap().to_path_buf(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert!(fixture.check(platform, &install).is_err(), "the install folder itself"); - assert!(fixture.check(platform, &install.join("profile")).is_err(), "a folder inside the install"); - assert!(fixture.check(platform, &fixture.root.join("nightly")).is_ok(), "a sibling of the install is private"); - } - } - - #[test] - fn prefix_and_case_lookalikes_are_not_stable_overlaps() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - // `DesignCraftBackups` only starts with the stable folder's name. - assert!(fixture.check(platform, &fixture.home().join("Library/Application Support/DesignCraftBackups/nightly")).is_ok()); - assert!(fixture.check(platform, &fixture.root.join("data-craft/nightly")).is_ok()); - } - // Case folding differs by platform: Windows and macOS fold, Linux does not. - let folded = fixture.root.join("roaming/designcraft"); - assert!(fixture.check(Platform::Windows, &folded).is_err()); - assert!(fixture.check(Platform::Linux, &folded).is_ok(), "a different case is a different Linux path"); - } - - #[test] - fn portable_settings_from_another_install_are_refused_before_any_probe() { - let fixture = Fixture::new(); - let stable_install = fixture.root.join("stable portable install"); - let stable_data = stable_install.join(PORTABLE_DATA_DIR); - std::fs::create_dir_all(&stable_data).unwrap(); - std::fs::write(stable_install.join(PORTABLE_MARKER), b"owned portable fixture").unwrap(); - std::fs::write(stable_data.join("ui.json"), b"stable settings must not change").unwrap(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - for candidate in [&stable_data, &stable_data.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "a different portable install is not a private Nightly profile"); - assert!(!probed.get(), "reject portable data before a writable probe"); - assert!(!stable_data.join("nested nightly").exists()); - assert_eq!(std::fs::read(stable_data.join("ui.json")).unwrap(), b"stable settings must not change"); - } - } - let private = fixture.root.join("DesignCraftData-backup-name/nightly"); - assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); - } - - #[test] - fn the_stable_settings_override_and_a_flatpak_instance_are_refused() { - let fixture = Fixture::new(); - let target = fixture.root.join("nightly"); - for value in ["/somewhere/else", ""] { - let env = |key: &str| if key == "DESIGNCRAFT_CONFIG_DIR" { Some(OsString::from(value)) } else { fixture.get(key) }; - let result = validate_for(Platform::Linux, &target, env, Some(&fixture.exe), |_| Ok(())); - if value.is_empty() { - assert!(result.is_ok(), "an empty override is not a stable data redirection"); - } else { - let error = result.unwrap_err(); - assert!(error.contains("DESIGNCRAFT_CONFIG_DIR"), "{error}"); - } - } - let flatpak = |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft")) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_err()); - assert!(validate_for(Platform::Windows, &target, flatpak, Some(&fixture.exe), |_| Ok(())).is_ok(), "Windows has no Flatpak namespace"); - // The nightly bundle's own sandbox is private; a lookalike id is still another app's. - let nightly_bundle = - |key: &str| if key == "FLATPAK_ID" { Some(OsString::from(designcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID)) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, nightly_bundle, Some(&fixture.exe), |_| Ok(())).is_ok()); - let lookalike = - |key: &str| if key == "FLATPAK_ID" { Some(OsString::from("ai.storyteller.designcraft.nightly-v1")) } else { fixture.get(key) }; - assert!(validate_for(Platform::Linux, &target, lookalike, Some(&fixture.exe), |_| Ok(())).is_err()); - } - - #[cfg(unix)] - #[test] - fn recovery_aliases_cannot_redirect_to_stable_or_outward_data() { - let fixture = Fixture::new(); - let stable = fixture.home().join(".local/share/designcraft/Recovery"); - std::fs::create_dir_all(&stable).unwrap(); - std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); - for target in [stable.clone(), fixture.root.to_path_buf(), fixture.root.join("Recovery/../../elsewhere")] { - let profile = fixture.root.join(format!("profile-{}", target.file_name().unwrap().to_string_lossy().replace('.', "_"))); - std::fs::create_dir_all(&profile).unwrap(); - std::os::unix::fs::symlink(&target, profile.join("Recovery")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "{target:?}"); - assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); - } - } - - #[cfg(unix)] - #[test] - fn a_created_profile_is_private_and_a_failed_write_probe_never_falls_back() { - let fixture = Fixture::new(); - let probe = fixture.root.join("profile for probe"); - let error = validate_for(Platform::Linux, &probe, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only"))) - .unwrap_err(); - assert!(error.contains("not writable"), "{error}"); - use std::os::unix::fs::PermissionsExt; - assert_eq!(std::fs::metadata(&probe).unwrap().permissions().mode() & 0o777, 0o700); - } - - #[test] - fn relative_and_parent_traversing_are_refused_and_link_ancestors_are_resolved() { - let fixture = Fixture::new(); - for candidate in [PathBuf::from("relative/nightly"), fixture.root.join("a/../nightly")] { - assert!(fixture.check(Platform::Linux, &candidate).is_err(), "{candidate:?}"); - } - #[cfg(unix)] - { - let elsewhere = fixture.root.join("elsewhere"); - std::fs::create_dir_all(&elsewhere).unwrap(); - std::os::unix::fs::symlink(&elsewhere, fixture.root.join("linked")).unwrap(); - // `canonical_future` resolves the existing ancestors before anything is created, so a - // root reached through a link is validated and created at the link's real location. - // That location is what the fence checks, and it is where every write then lands. - let resolved = fixture.check(Platform::Linux, &fixture.root.join("linked/nightly")).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(elsewhere.join("nightly")).unwrap()); - assert!(resolved.is_dir()); - assert_eq!(std::fs::canonicalize(fixture.root.join("linked")).unwrap(), elsewhere); - } - } - - #[test] - fn a_valid_profile_is_returned_resolved_and_created() { - let fixture = Fixture::new(); - let chosen = fixture.root.join("launcher data/profiles/designcraft"); - let resolved = fixture.check(Platform::Linux, &chosen).unwrap(); - assert_eq!(resolved, std::fs::canonicalize(&chosen).unwrap()); - assert!(resolved.is_dir()); - } - - #[test] - fn nightly_profile_reopens_after_saving_settings_and_session_state() { - let fixture = Fixture::new(); - for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { - let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); - assert_eq!(fixture.check(platform, &private).unwrap(), private); - for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } - } -} From ba0ebd36b6e83ac4b22749ae99b96fbbd790f037 Mon Sep 17 00:00:00 2001 From: DesignCraft contributor Date: Thu, 19 Nov 2026 12:21:21 +0000 Subject: [PATCH 106/133] Hyphenate Hindi, Malayalam, Tamil and eight other Indian languages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable hypher's Indic patterns (Santhosh Thottingal's hyph-utf8 0.9.0, MIT) for Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and Malayalam, and offer those languages in the Language menu with their names mapped to BCP 47 tags. Sanskrit is left out: its patterns carry a free-form licence outside the allowlist. Two fixes make the patterns usable: - Viramas, nuktas and ZWJ/ZWNJ are not Unicode-alphabetic, so hyphenation split a word such as विद्यार्थी at each conjunct into fragments too short to break. They now count as word characters. - A hyphenation point was put after the first glyph of a cluster (the one owning its bytes) instead of its last. In Devanagari वि is drawn as ि then व, so the break fell between them and produced an empty hyphenated line. The point now goes after the cluster's last glyph, and suppress_hyphens matches the cluster's end for its trailing glyphs. Tests: patterns per language, words hyphenated across conjuncts, joiners and nuktas kept in words, a composed Hindi/Malayalam paragraph whose hyphenated lines end at syllable prefixes, and Indian language names mapped to tags. Each new test fails without its fix. --- NOTICE | 16 ++++ crates/compose/Cargo.toml | 2 +- crates/compose/src/hyphen.rs | 78 +++++++++++++++++++- crates/compose/src/lib.rs | 21 ++++-- crates/compose/src/tests.rs | 21 ++++++ crates/doc/src/attrs/language.rs | 11 +++ crates/doc/src/attrs/tests.rs | 26 +++++++ crates/ui-egui/src/panels/properties/text.rs | 11 +++ 8 files changed, 178 insertions(+), 8 deletions(-) diff --git a/NOTICE b/NOTICE index 3b19745fa..882e2a764 100644 --- a/NOTICE +++ b/NOTICE @@ -130,6 +130,22 @@ list (author, source, license) is in ASSETS.md. AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +- Indic hyphenation patterns, embedded through the hypher crate (features "hindi", "marathi", + "bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada", + "malayalam"): hyph-hi.tex, hyph-mr.tex, hyph-bn.tex, hyph-as.tex, hyph-gu.tex, hyph-pa.tex, + hyph-or.tex, hyph-ta.tex, hyph-te.tex, hyph-kn.tex and hyph-ml.tex 0.9.0 (2016-01-16) from + hyph-utf8, https://github.com/hyphenation/tex-hyphen. Copyright (C) 2016 Santhosh Thottingal. + Available under the MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this + software and associated documentation files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: The above copyright notice + and this permission notice shall be included in all copies or substantial portions of the + Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - German hyphenation patterns, embedded through the hypher crate (feature "german"): hyph-de-1996.tex 2024-02-28, German reformed orthography (2006), from hyph-utf8, https://github.com/typst/hypher/blob/d81cc506416bffef2a75ee2dc969d4b41bc36613/patterns/hyph-de-1996.tex. diff --git a/crates/compose/Cargo.toml b/crates/compose/Cargo.toml index 9f1f7dd39..48116b1fe 100644 --- a/crates/compose/Cargo.toml +++ b/crates/compose/Cargo.toml @@ -21,7 +21,7 @@ log = { workspace = true } regex = { workspace = true } fancy-regex = { workspace = true } miniz_oxide = "0.8" -hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish"] } +hypher = { version = "0.1.8", default-features = false, features = ["alloc", "croatian", "dutch", "french", "german", "greek", "italian", "portuguese", "spanish", "norwegian", "danish", "hindi", "marathi", "bengali", "assamese", "gujarati", "panjabi", "oriya", "tamil", "telugu", "kannada", "malayalam"] } [dev-dependencies] designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/compose/src/hyphen.rs b/crates/compose/src/hyphen.rs index 25f76097f..8046573f2 100644 --- a/crates/compose/src/hyphen.rs +++ b/crates/compose/src/hyphen.rs @@ -10,6 +10,10 @@ //! Flipo, Bernard Gaulle, Arthur Reutenauer), MIT; Italian is `hyph-it.tex` 4.9 from hyph-utf8 //! (Claudio Beccari), LPPL or MIT, taken under MIT. A word with an elision (`l'imprimerie`) //! hyphenates after its apostrophe. +//! Hindi, Marathi, Bengali, Assamese, Gujarati, Punjabi, Odia, Tamil, Telugu, Kannada and +//! Malayalam are Santhosh Thottingal's `hyph-{hi,mr,bn,as,gu,pa,or,ta,te,kn,ml}.tex` 0.9.0 from +//! hyph-utf8, MIT. Viramas, nuktas and the zero-width (non-)joiner count as word characters +//! ([`is_indic_joiner`]), so a word is not split at its conjuncts. //! German uses `hyph-de-1996.tex` (2024-02-28, Deutschsprachige Trennmustermannschaft, MIT): //! despite the filename, these are the reformed 2006 spelling patterns. Only the two 2006 reform //! names and German locale codes without a reform year or with 2006 use this set. Traditional, @@ -138,7 +142,21 @@ fn is_apostrophe(c: char) -> bool { } fn is_word_char(c: char) -> bool { - c.is_alphabetic() || is_apostrophe(c) + c.is_alphabetic() || is_apostrophe(c) || is_indic_joiner(c) +} + +/// Signs inside Indic words that Unicode doesn't class as alphabetic: each script's virama (which +/// joins consonants into conjuncts), its nukta, Malayalam's vertical and circular viramas, and the +/// zero-width joiner and non-joiner that select conjunct and chillu forms. Without them a word +/// such as विद्यार्थी splits at every conjunct into fragments too short to hyphenate. +fn is_indic_joiner(c: char) -> bool { + matches!( + c, + '\u{094D}' | '\u{09CD}' | '\u{0A4D}' | '\u{0ACD}' | '\u{0B4D}' | '\u{0BCD}' | '\u{0C4D}' | '\u{0CCD}' | '\u{0D4D}' // viramas + | '\u{0D3B}' | '\u{0D3C}' // Malayalam vertical and circular viramas + | '\u{093C}' | '\u{09BC}' | '\u{0A3C}' | '\u{0ABC}' | '\u{0B3C}' | '\u{0C3C}' | '\u{0CBC}' // nuktas + | '\u{200C}' | '\u{200D}' // ZWNJ, ZWJ + ) } /// Unrestricted break points of one lowercase core (letters and `'` only, no leading/trailing `'`). @@ -821,6 +839,64 @@ mod tests { } } + #[test] + fn indic_languages_use_the_hyph_utf8_patterns() { + for (name, code, lang) in [ + ("Hindi", "hi", hypher::Lang::Hindi), + ("Marathi", "mr", hypher::Lang::Marathi), + ("Bengali", "bn", hypher::Lang::Bengali), + ("Assamese", "as", hypher::Lang::Assamese), + ("Gujarati", "gu", hypher::Lang::Gujarati), + ("Punjabi", "pa", hypher::Lang::Panjabi), + ("Odia", "or", hypher::Lang::Oriya), + ("Oriya", "or_IN", hypher::Lang::Oriya), + ("Tamil", "ta", hypher::Lang::Tamil), + ("Telugu", "te", hypher::Lang::Telugu), + ("Kannada", "kn", hypher::Lang::Kannada), + ("Malayalam", "ml_IN", hypher::Lang::Malayalam), + ] { + assert_eq!(Lang::for_language(name), Some(Lang::Patterns(lang)), "{name}"); + assert_eq!(Lang::for_language(code), Some(Lang::Patterns(lang)), "{code}"); + } + assert_eq!(Lang::for_language("Sanskrit"), None, "no Sanskrit patterns are built in"); + } + + /// A virama joins consonants inside a word: the word is hyphenated whole, between syllables, + /// never inside a conjunct. Before viramas counted as word characters, विद्यार्थी was + /// hyphenated as the fragments वि, द, यार and थी, which gave it no break at all. + #[test] + fn indic_words_hyphenate_between_syllables_across_their_conjuncts() { + let lang = |name: &str| Lang::for_language(name).unwrap(); + assert_eq!(marked("विद्यार्थी", lang("Hindi")), "वि-द्या-र्थी"); + assert_eq!(marked("प्रधानमंत्री", lang("Hindi")), "प्र-धा-न-मं-त्री"); + assert_eq!(marked("महाराष्ट्र", lang("Marathi")), "महा-रा-ष्ट्र"); + assert_eq!(marked("വിദ്യാർത്ഥി", lang("Malayalam")), "വി-ദ്യാർ-ത്ഥി"); + assert_eq!(marked("തിരുവനന്തപുരം", lang("Malayalam")), "തി-രു-വ-ന-ന്ത-പു-രം"); + assert_eq!(marked("தொழில்நுட்பம்", lang("Tamil")), "தொ-ழில்-நுட்-பம்"); + // The default Before Last limit keeps the final য় with the ল before it. + assert_eq!(marked("বিশ্ববিদ্যালয়", lang("Bengali")), "বি-শ্ব-বি-দ্যা-লয়"); + assert_eq!(marked("విశ్వవిద్యాలయం", lang("Telugu")), "వి-శ్వ-వి-ద్యా-ల-యం"); + assert_eq!(marked("ವಿಶ್ವವಿದ್ಯಾಲಯ", lang("Kannada")), "ವಿ-ಶ್ವ-ವಿ-ದ್ಯಾ-ಲಯ"); + assert_eq!(marked("વિશ્વવિદ્યાલય", lang("Gujarati")), "વિ-શ્વ-વિ-દ્યા-લય"); + } + + /// A zero-width joiner or non-joiner (old-style Malayalam chillus, explicit half forms) and a + /// nukta stay inside the word they're in, so no break lands next to them. + #[test] + fn indic_joiners_and_nuktas_do_not_split_words() { + for c in ['\u{094D}', '\u{0D4D}', '\u{0BCD}', '\u{093C}', '\u{200C}', '\u{200D}'] { + assert!(is_word_char(c), "U+{:04X}", c as u32); + } + let hi = Lang::for_language("Hindi").unwrap(); + let (pts, _) = word_breaks_in("पढ़ना", hi); + assert!(!pts.contains(&2), "no break between ढ and its nukta: {pts:?}"); + assert!(pts.contains(&3), "पढ़-ना: {pts:?}"); + // Old chillu encoding (ന + virama + ZWJ): the word stays one word. + let ml = Lang::for_language("Malayalam").unwrap(); + let (pts, _) = word_breaks_in("അവന്\u{200D}റെ", ml); + assert!(pts.iter().all(|&p| !matches!("അവന്\u{200D}റെ".chars().nth(p), Some('\u{200D}' | '\u{0D4D}'))), "{pts:?}"); + } + #[test] fn norwegian_uses_the_hyph_no_patterns() { let nb = Lang::for_language("Norwegian: Bokmål").unwrap(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index df1736750..972184326 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5965,13 +5965,18 @@ fn foreign_ranges( .collect() } -/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. +/// Leave out the hyphenation points after the glyphs that end at story bytes `at`. A glyph +/// without bytes of its own (len 0) is part of the cluster before it and ends where that does. fn suppress_hyphens(hy: &mut [bool], glyphs: &[Glyph], at: &[usize]) { if at.is_empty() { return; } + let mut end = 0; for (h, g) in hy.iter_mut().zip(glyphs) { - if *h && at.contains(&(g.byte + g.len)) { + if g.len > 0 || end == 0 { + end = g.byte + g.len; + } + if *h && at.contains(&end) { *h = false; } } @@ -6095,13 +6100,17 @@ fn hyphenation_points( } }; if !pts.is_empty() { - // char index p → byte → the first glyph whose cluster ends at that byte. Both - // indexed once per word: looking each point up by scanning was quadratic in - // a long word's length. + // char index p → byte → the last glyph of the cluster that ends at that byte. + // A cluster's first glyph owns its bytes and the glyphs after it (len 0) are + // the rest of it: a Devanagari syllable such as वि is drawn as the ि sign + // before the व, so the break goes after the last of them, not between them. + // Both indexed once per word: looking each point up by scanning was quadratic + // in a long word's length. let char_bytes: Vec = word.char_indices().map(|(bi, _)| bi).collect(); let mut glyph_ending_at: HashMap = HashMap::new(); for k in (i..j).filter(|&k| glyphs[k].len > 0) { - glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(k); + let last = (k + 1..j).take_while(|&m| glyphs[m].len == 0).last().unwrap_or(k); + glyph_ending_at.entry(glyphs[k].byte + glyphs[k].len).or_insert(last); } for &p in pts.iter() { let byte = a + char_bytes.get(p).copied().unwrap_or(word.len()); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 0a1f67184..fc031258b 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5811,6 +5811,27 @@ fn croatian_text_gets_croatian_hyphenation() { } } +/// Hindi and Malayalam text set in its language hyphenates between syllables, never inside a +/// conjunct: each hyphenated line ends in a prefix the patterns allow. +#[test] +fn indian_language_text_hyphenates_between_syllables() { + for (language, word, prefixes) in [("Hindi", "विद्यार्थी", &["वि", "विद्या"][..]), ("Malayalam", "വിദ്യാർത്ഥി", &["വി", "വിദ്യാർ"][..])] + { + let text = [word; 8].join(" "); + let (mut d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 76.0, 700.0), ParaAttrs::default()); + let st = d.story_mut(sid).unwrap(); + let n = st.len(); + st.format_chars(0..n, |f| f.over.language = Some(language.into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let breaks: Vec<&str> = all_lines(&cs).into_iter().filter(|l| l.hyphenated).map(|l| text[l.range.clone()].trim_end()).collect(); + assert!(!breaks.is_empty(), "{language} text is hyphenated"); + for b in breaks { + let tail = b.rsplit(' ').next().unwrap_or(b); + assert!(prefixes.contains(&tail), "{language}: {b:?} ends in a syllable prefix of {word}"); + } + } +} + #[test] fn cjk_aki_adds_space_without_scaling_outlines() { let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default()); diff --git a/crates/doc/src/attrs/language.rs b/crates/doc/src/attrs/language.rs index a116bf754..e8b1ffe52 100644 --- a/crates/doc/src/attrs/language.rs +++ b/crates/doc/src/attrs/language.rs @@ -89,6 +89,17 @@ pub fn language_tag(language: &str) -> Option<&'static str> { "hebrew" => "he", "georgian" => "ka", "esperanto" => "eo", + "hindi" => "hi", + "marathi" => "mr", + "bengali" | "bangla" => "bn", + "assamese" => "as", + "gujarati" => "gu", + "punjabi" | "panjabi" => "pa", + "odia" | "oriya" => "or", + "tamil" => "ta", + "telugu" => "te", + "kannada" => "kn", + "malayalam" => "ml", _ => return None, }) } diff --git a/crates/doc/src/attrs/tests.rs b/crates/doc/src/attrs/tests.rs index 78c62b77b..fa6cf9649 100644 --- a/crates/doc/src/attrs/tests.rs +++ b/crates/doc/src/attrs/tests.rs @@ -94,6 +94,32 @@ fn language_names_map_to_bcp47_tags() { assert_eq!(language_tag(""), None); } +/// Indian languages by the names the Language menu and IDML use, so their text gets the font's +/// localized forms (Marathi ल and श) and hyphenates with its own patterns. +#[test] +fn indian_language_names_map_to_their_tags() { + for (name, tag) in [ + ("Hindi", "hi"), + ("Marathi", "mr"), + ("Bengali", "bn"), + ("Bangla", "bn"), + ("Assamese", "as"), + ("Gujarati", "gu"), + ("Punjabi", "pa"), + ("Panjabi", "pa"), + ("Odia", "or"), + ("Oriya", "or"), + ("Tamil", "ta"), + ("Telugu", "te"), + ("Kannada", "kn"), + ("Malayalam", "ml"), + ("$ID/Malayalam", "ml"), + ] { + assert_eq!(language_tag(name), Some(tag), "{name}"); + } + assert_eq!(language_tag("hi_IN"), Some("hi-IN")); +} + #[test] fn chinese_japanese_and_korean_names_map_in_their_common_spellings() { for (name, tag) in [ diff --git a/crates/ui-egui/src/panels/properties/text.rs b/crates/ui-egui/src/panels/properties/text.rs index f3a727b36..4eacfff8d 100644 --- a/crates/ui-egui/src/panels/properties/text.rs +++ b/crates/ui-egui/src/panels/properties/text.rs @@ -721,6 +721,17 @@ pub(crate) const LANGUAGES: &[&str] = &[ "Korean", "Arabic", "Hebrew", + "Hindi", + "Marathi", + "Bengali", + "Assamese", + "Gujarati", + "Punjabi", + "Odia", + "Tamil", + "Telugu", + "Kannada", + "Malayalam", "Esperanto", ]; From 125eb7594ab3fd4af719e059c15bf909b2154709 Mon Sep 17 00:00:00 2001 From: DesignCraft contributor Date: Thu, 19 Nov 2026 14:59:40 +0000 Subject: [PATCH 107/133] Break Indian-script words at line ends without a hyphen A word in an Indian script (Devanagari, Bengali, Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada, Malayalam) that is hyphenated at a line end now splits between syllables with no hyphen drawn, and the breaker keeps no room for one. Latin and other scripts keep the hyphen. - shape::breaks_without_hyphen decides by the letter the break follows (the last one before any soft hyphens), so Knuth-Plass, the single-line composer and line layout agree. - hyphen_width is 0 after such a letter; the greedy breaker measures a soft hyphen's hyphen after the glyph before it, as Knuth-Plass and line layout already do. - A break at a zero-width automatic hyphen is still a hyphenated line (it counts toward the consecutive-hyphen limit); `auto` tells it from the break after an explicit '-'. Tests: hyphenated Hindi and Malayalam lines draw no hyphen (fails without the change); hyphenated English lines still end in one. --- crates/compose/src/breaker.rs | 18 ++++++++++++++---- crates/compose/src/lib.rs | 7 ++++++- crates/compose/src/shape.rs | 8 ++++++++ crates/compose/src/tests.rs | 19 ++++++++++++++++++- 4 files changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index bd9351119..73b031c2b 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -365,8 +365,12 @@ fn hyphen_hang(g: &Glyph, hw: f64, sp: &Spacing) -> f64 { if sp.optical { hw * hang('-').1 * optical_scale(g, sp) } else { 0.0 } } -/// Advance of the hyphen glyph that would follow `g` (cached per face). +/// Advance of the hyphen glyph that would follow `g` (cached per face); none after a letter of +/// an Indian script, whose broken words take no hyphen ([`crate::shape::breaks_without_hyphen`]). fn hyphen_width(g: &Glyph, cache: &mut Vec<(u32, f64)>) -> f64 { + if crate::shape::breaks_without_hyphen(g) { + return 0.0; + } let id = g.face.id(); let units = match cache.iter().find(|c| c.0 == id) { Some(c) => c.1, @@ -887,9 +891,12 @@ fn breaks_from_positions(items: &[Item], ig: &[usize], glyphs: &[Glyph], chain: let (end, hyphen, forced) = match it.kind { Kind::Penalty => { let e = ig[b].min(n); - // A flagged penalty with width = an inserted hyphen (not an explicit '-'). + // A flagged penalty with width = an inserted hyphen (not an explicit '-'). A + // hyphenation point after a letter of an Indian script inserts one of no width + // (no hyphen is drawn there) but is still a hyphenated break: `auto` tells it from + // the break after an explicit '-'. let explicit = e > 0 && matches!(glyphs[e - 1].ch, '-' | '\u{2010}'); - (e, it.flagged && it.w > 0.0 && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF) + (e, it.flagged && (it.w > 0.0 || it.auto) && !explicit || (it.flagged && e > 0 && glyphs[e - 1].ch == SOFT_HYPHEN), it.p <= -INF) } Kind::Glue | Kind::Box => (ig[b], false, false), }; @@ -1005,7 +1012,10 @@ pub fn greedy( if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) { if g.ch == SOFT_HYPHEN { if may_hyphenate(hyphens) { - let hw = hyphen_width(g, &mut hy_cache); + // The hyphen follows the last glyph before the soft hyphen(s), as in + // Knuth–Plass and line layout. + let base = glyphs[..i].iter().rev().find(|p| p.ch != SOFT_HYPHEN).unwrap_or(g); + let hw = hyphen_width(base, &mut hy_cache); let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0); if x + hy <= w + shrink + FIT_EPS { last_ok = Some((i + 1, true)); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 972184326..203c546e5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -5270,7 +5270,12 @@ fn layout_line( g.shift += cjk_alignment_shift(g, &reference); } } - if hyphen && let Some(g) = line.last() { + // No hyphen after a word of an Indian script (its last letter before any soft hyphens). + let marked = line.iter().rev().find(|g| g.ch != shape::SOFT_HYPHEN).is_none_or(|g| !shape::breaks_without_hyphen(g)); + if hyphen + && marked + && let Some(g) = line.last() + { let h = shape::hyphen_after(g); line.push(h); } diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 1de4b823c..0455237b3 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1427,6 +1427,14 @@ fn fit_auto_tcy(glyphs: &mut [Glyph], auto: &[std::ops::Range]) { } } +/// Whether a word broken after `g` takes no hyphen mark: Indian scripts (Devanagari, Bengali, +/// Gurmukhi, Gujarati, Odia, Tamil, Telugu, Kannada and Malayalam). Their words split between +/// syllables at a line end without a hyphen, so nothing is drawn there and no room is kept for +/// one. Latin and other scripts keep the hyphen. +pub(crate) fn breaks_without_hyphen(g: &Glyph) -> bool { + matches!(g.ch as u32, 0x0900..=0x0DFF) +} + /// A hyphen glyph in the face/size of `g`, placed after it (zero source length). pub(crate) fn hyphen_after(g: &Glyph) -> Glyph { let gid = designcraft_fonts::first_glyph(&g.face, &['-', '\u{2010}']); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index fc031258b..7f53f9422 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5812,7 +5812,8 @@ fn croatian_text_gets_croatian_hyphenation() { } /// Hindi and Malayalam text set in its language hyphenates between syllables, never inside a -/// conjunct: each hyphenated line ends in a prefix the patterns allow. +/// conjunct: each hyphenated line ends in a prefix the patterns allow, with no hyphen drawn +/// after it (Indian scripts split words at a line end without one). #[test] fn indian_language_text_hyphenates_between_syllables() { for (language, word, prefixes) in [("Hindi", "विद्यार्थी", &["वि", "विद्या"][..]), ("Malayalam", "വിദ്യാർത്ഥി", &["വി", "വിദ്യാർ"][..])] @@ -5829,6 +5830,22 @@ fn indian_language_text_hyphenates_between_syllables() { let tail = b.rsplit(' ').next().unwrap_or(b); assert!(prefixes.contains(&tail), "{language}: {b:?} ends in a syllable prefix of {word}"); } + for l in all_lines(&cs).into_iter().filter(|l| l.hyphenated) { + assert!(l.glyphs.iter().all(|g| g.rendered_char != '-'), "{language}: no hyphen drawn on {:?}", &text[l.range.clone()]); + } + } +} + +/// Latin text keeps its hyphen at a hyphenated line end. +#[test] +fn latin_text_still_draws_its_hyphen() { + let text = "internationalization internationalization internationalization"; + let (d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 106.0, 700.0), ParaAttrs::default()); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let hyphenated: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.hyphenated).collect(); + assert!(!hyphenated.is_empty(), "English text is hyphenated"); + for l in hyphenated { + assert_eq!(l.glyphs.iter().rev().find(|g| g.visible).map(|g| g.rendered_char), Some('-'), "{:?}", &text[l.range.clone()]); } } From 804684234df571be3c7f2354c24e4972485a1932 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 30 Nov 2026 00:21:22 +0530 Subject: [PATCH 108/133] Fix Indic hyphenation review findings - Record a rejected column-end break at the end of the cluster that owns it, so suppress_hyphens drops it when a syllable's last glyph has no bytes of its own. - Keep a word's last cluster when its last glyph is a cluster continuation. - Leave Sinhala out of the no-hyphen range (end at U+0D7F). - Track the last non-soft-hyphen glyph in greedy instead of scanning back for each soft hyphen, and correct its comment. Co-authored-by: dileep2in <318591845+dileep2in@users.noreply.github.com> --- crates/compose/src/breaker.rs | 11 ++++++++--- crates/compose/src/lib.rs | 11 ++++++++--- crates/compose/src/shape.rs | 2 +- crates/compose/src/tests.rs | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 73b031c2b..6bfb6a76e 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -961,8 +961,14 @@ pub fn greedy( let mut last_space: Option<(usize, f64)> = None; // (break position, line width there) let mut i = start; let mut brk: Option<(usize, bool, bool)> = None; + // The last glyph before `i` that is not a soft hyphen, kept as `i` advances. + let mut plain = glyphs[..start].iter().rposition(|p| p.ch != SOFT_HYPHEN); while i < n { let g = &glyphs[i]; + let before = plain; + if g.ch != SOFT_HYPHEN { + plain = Some(i); + } if is_forced(g.ch) { brk = Some((i + 1, false, true)); break; @@ -1013,9 +1019,8 @@ pub fn greedy( if g.ch == SOFT_HYPHEN { if may_hyphenate(hyphens) { // The hyphen follows the last glyph before the soft hyphen(s), as in - // Knuth–Plass and line layout. - let base = glyphs[..i].iter().rev().find(|p| p.ch != SOFT_HYPHEN).unwrap_or(g); - let hw = hyphen_width(base, &mut hy_cache); + // Knuth–Plass (line layout inserts it after `line.last()`). + let hw = hyphen_width(before.map_or(g, |b| &glyphs[b]), &mut hy_cache); let hy = (hw - hyphen_hang(g, hw, sp)).max(0.0); if x + hy <= w + shrink + FIT_EPS { last_ok = Some((i + 1, true)); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 203c546e5..03e05c639 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2717,8 +2717,13 @@ fn place_paragraph_lines(shared: PlacementShared<'_, '_>, paragraph: ParagraphLi cur.last_descent = desc; cur.pending = 0.0; cur.grid_next = grid_end.map(|end| (baseline, end)); - hyphen_at = - e.checked_sub(1).filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)).and_then(|i| glyphs.get(i)).map(|g| g.byte + g.len); + // The end of the cluster that owns the break glyph (a glyph without bytes of its own is + // part of the cluster before it), which is what `suppress_hyphens` compares against. + hyphen_at = e + .checked_sub(1) + .filter(|&i| b.hyphen && hyph_after.get(i) == Some(&true)) + .and_then(|i| glyphs.get(..=i)?.iter().rev().find(|g| g.len > 0)) + .map(|g| g.byte + g.len); line_no += 1; // An Indent to Here character in this line moves the start of the lines after it: // break them again with that indent (it holds into the next columns too). @@ -6069,7 +6074,7 @@ fn hyphenation_points( } // A discretionary hyphen in a word (or right before it) replaces automatic hyphenation. let discretionary = glyphs[i..j].iter().any(|g| g.ch == shape::SOFT_HYPHEN) || (i > 0 && glyphs[i - 1].ch == shape::SOFT_HYPHEN); - let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len); + let (a, b) = (glyphs[i].byte, glyphs[i..j].iter().map(|g| g.byte + g.len).max().unwrap_or(glyphs[i].byte)); if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) { let word = &text[a..b]; // The whitespace-delimited token the word sits in: a Latin run with a Korean particle diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs index 0455237b3..c44fae8bd 100644 --- a/crates/compose/src/shape.rs +++ b/crates/compose/src/shape.rs @@ -1432,7 +1432,7 @@ fn fit_auto_tcy(glyphs: &mut [Glyph], auto: &[std::ops::Range]) { /// syllables at a line end without a hyphen, so nothing is drawn there and no room is kept for /// one. Latin and other scripts keep the hyphen. pub(crate) fn breaks_without_hyphen(g: &Glyph) -> bool { - matches!(g.ch as u32, 0x0900..=0x0DFF) + matches!(g.ch as u32, 0x0900..=0x0D7F) } /// A hyphen glyph in the face/size of `g`, placed after it (zero source length). diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 7f53f9422..9bb581a78 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5836,6 +5836,39 @@ fn indian_language_text_hyphenates_between_syllables() { } } +/// With hyphenation across columns off, no column of Hindi text ends in a hyphenated break. The +/// break goes after a syllable's last glyph, which has no bytes of its own (the vowel sign of वि +/// is drawn before the consonant), so the rejected break is recorded at its cluster's end. +#[test] +fn hyphenate_across_column_off_holds_for_indian_scripts() { + let text = ["विद्यार्थी विश्वविद्यालय अंतरराष्ट्रीय प्रधानमंत्री स्वतंत्रता"; 6].join(" "); + let ends = |across: bool, composer: designcraft_doc::Composer| { + let mut ends = 0; + for h in (20..240).step_by(3) { + let para = ParaAttrs { + align: Some(Align::Left), + hyph_weight: Some(0.0), + hyph_across_column: Some(across), + composer: Some(composer), + ..Default::default() + }; + let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 120.0, h as f64), para); + d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2; + let st = d.story_mut(sid).unwrap(); + let n = st.len(); + st.format_chars(0..n, |f| f.over.language = Some("Hindi".into())); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + let col0: Vec<&Line> = all_lines(&cs).into_iter().filter(|l| l.column == 0).collect(); + ends += usize::from(col0.last().is_some_and(|l| l.hyphenated)); + } + ends + }; + for c in [designcraft_doc::Composer::Paragraph, designcraft_doc::Composer::SingleLine] { + assert!(ends(true, c) > 0, "{c:?}: Hindi columns end in hyphenated breaks with it on"); + assert_eq!(ends(false, c), 0, "{c:?}"); + } +} + /// Latin text keeps its hyphen at a hyphenated line end. #[test] fn latin_text_still_draws_its_hyphen() { From 9aa4536de53ed46b92d8b2f4ac22e512d57f9573 Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:57:59 +0000 Subject: [PATCH 109/133] Export linked anchored images in HTML and reflowable EPUB (#3273) --- crates/engine/src/cmd/export/formats.rs | 25 ++-- crates/engine/src/cmd/export/linked_tests.rs | 75 ++++++++++++ crates/epub/src/html.rs | 51 ++++++-- crates/epub/src/lib.rs | 2 +- crates/epub/src/story_writer.rs | 121 ++++++++++++++++++- crates/epub/src/tests.rs | 102 ++++++++++++++++ 6 files changed, 343 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/export/formats.rs b/crates/engine/src/cmd/export/formats.rs index 8828f006c..e30d12ec5 100644 --- a/crates/engine/src/cmd/export/formats.rs +++ b/crates/engine/src/cmd/export/formats.rs @@ -28,24 +28,9 @@ pub(super) fn print_booklet(s: &mut Session, p: &Value) -> Result { /// HTML and reflowable EPUB read embedded bytes only: every used linked asset gets its output /// bytes embedded, and EPS its preview. The session's own assets stay as they are. fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Document>, Vec) { - // Match the exporter's reading order (including Article exclusions), not every asset - // in the document: unused or hidden graphics must not prevent an export. - let mut used = std::collections::BTreeSet::new(); - for block in designcraft_epub::reading_order(d) { - let designcraft_epub::Block::Image(id) = block else { - continue; - }; - let Some(it) = d.item(id) else { continue }; - let designcraft_doc::Content::Graphic(g) = &it.content else { - continue; - }; - used.insert(g.asset); - if d.assets.get(&g.asset).is_some_and(|a| designcraft_doc::media_kind(&a.mime).is_some()) - && let Some(poster) = it.media.as_ref().and_then(|m| m.poster) - { - used.insert(poster); - } - } + // Match the exporter's reading order and visible story content (including Article exclusions), + // not every asset in the document: unused or hidden graphics must not prevent an export. + let used = designcraft_epub::used_assets(d); let mut out = Cow::Borrowed(d); let mut warnings = Vec::new(); for id in used { @@ -81,6 +66,10 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu let a = Arc::make_mut(a); if eps { a.mime = "image/png".into(); + } else if got.proxied + && let Some(proxy) = &a.proxy + { + a.mime = proxy.mime.clone(); } a.data = designcraft_doc::AssetData::embedded(data); } diff --git a/crates/engine/src/cmd/export/linked_tests.rs b/crates/engine/src/cmd/export/linked_tests.rs index 4509a2fd1..d6a064185 100644 --- a/crates/engine/src/cmd/export/linked_tests.rs +++ b/crates/engine/src/cmd/export/linked_tests.rs @@ -168,3 +168,78 @@ fn a_package_copies_a_modified_link_from_disk_with_a_warning() { assert_eq!(std::fs::read(out.join("Links/art.png")).unwrap(), changed); assert!(r.to_string().contains("file on disk"), "{r}"); } + +#[test] +fn html_and_epub_export_linked_inline_anchored_image_and_report_changes_or_missing() { + use std::io::Read; + + let dir = Dir::new("anchored-svg"); + let svg_path = dir.0.join("dot.svg"); + let svg = br#""#; + std::fs::write(&svg_path, svg).unwrap(); + + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let text_frame = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": " Text"})).unwrap(); + let story = text_frame["story"].as_u64().unwrap(); + let graphic_frame = s.execute("frame.create", &json!({"rect": [500, 72, 512, 84], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(); + let placed = s.execute("file.place", &json!({"path": svg_path.to_string_lossy(), "frame": graphic_frame})).unwrap(); + let aid = AssetId(placed["asset"].as_u64().unwrap()); + s.execute("anchored.insert", &json!({"ids": [graphic_frame], "story": story, "pos": 0, "position": "inline"})).unwrap(); + assert!(s.doc().unwrap().doc.assets[&aid].data.is_linked()); + + // Linked inline anchored SVG exports cleanly in HTML and EPUB without mutating the document. + let before = s.doc().unwrap().doc.clone(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(html["warnings"].as_array().unwrap().is_empty(), "{}", warnings(&html)); + let body = html["text"].as_str().unwrap(); + let encoded = body.split("data:image/svg+xml;base64,").nth(1).expect("inline SVG data URI").split('"').next().unwrap(); + assert_eq!(crate::cmd::base64_decode(encoded), svg); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + + let epub = s.execute("file.exportEpub", &json!({})).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(crate::cmd::base64_decode(epub["base64"].as_str().unwrap()))).unwrap(); + let mut xhtml = String::new(); + z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut xhtml).unwrap(); + assert!(xhtml.contains(""#; + std::fs::write(&svg_path, updated).unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(warnings(&html).contains("file on disk"), "{}", warnings(&html)); + let encoded = html["text"].as_str().unwrap().split("data:image/svg+xml;base64,").nth(1).expect("updated SVG data URI").split('"').next().unwrap(); + assert_eq!(crate::cmd::base64_decode(encoded), updated); + + // Delete the linked file while a proxy exists: exports the proxy with the proxy's MIME type and warns. + let proxy_mime = s.doc().unwrap().doc.assets[&aid].proxy.as_ref().expect("proxy built").mime.clone(); + assert_ne!(proxy_mime, "image/svg+xml"); + std::fs::remove_file(&svg_path).unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(warnings(&html).contains("preview"), "{}", warnings(&html)); + let body = html["text"].as_str().unwrap(); + assert!(body.contains(&format!("data:{proxy_mime};base64,")), "proxy MIME used: {body}"); + assert!(!body.contains("data:image/svg+xml;base64,")); + + // Without a proxy, the missing linked graphic is omitted with an explicit warning. + s.edit(|d, _| { + Arc::make_mut(d.assets.get_mut(&aid).unwrap()).proxy = None; + Ok(()) + }) + .unwrap(); + let html = s.execute("file.exportHtml", &json!({})).unwrap(); + assert!(!html["text"].as_str().unwrap().contains("