DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
fix(text): preserve document state while threading and formatting
skylar taylor-barrick9b7a0ec66d30
diff --cc Cargo.lockindex a9c1b23fd,ef525c84e..138a753db--- a/Cargo.lock+++ b/Cargo.lock@@@ -887,9 -887,8 +887,9 @@@ dependencies =[[package]]name = "designcraft"- version = "0.6.0"+ version = "0.7.1"dependencies = [+ "arboard","designcraft-engine","designcraft-ui-egui","eframe",diff --cc ROADMAP.mdindex 69c49ed1f,8a0f82071..abcd4990b--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,14 -129,33 +128,40 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+- **2026-10-12** · Text threads by hand: click a selected text frame's in or out port to load+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the+ frame just added; click the linked frame or double-click a port to break the thread.+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No+ readiness percentage change.+ - **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.+ - **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.+ - **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.+ - **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.+ - **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.+ - **2026-10-12** · Save As, library edits and book collection edits persist prospective values before changing live state; failed writes preserve the document and existing collections. Save a Copy rebases data-source paths for its destination without changing the open document. No readiness percentage change.+ - **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.+ - **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.+ - **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.+ - **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.+ - **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.+ - **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.+ - **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.+ - **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. No readiness percentage change.+ - **2026-10-11** · Corner Options keep curved sides curved and round every corner point, including where an arc meets a line (a Pathfinder quarter circle with rounded corners stayed a triangle). No readiness percentage change.+ - **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.+ - **2026-10-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.+ - **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.+ - **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.+ - **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.+ - **2026-10-12** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.+ - **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.+ - **2026-10-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.+ - **2026-10-12** · The Eyedropper samples a placed image: clicking the photo with text (or objects) selected fills them with the image's colour under the pointer, as an unnamed colour (`color.sample`), as in InDesign. Images on locked layers can be sampled. No readiness percentage change.- **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.+ - **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.+ - **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). No readiness percentage change.- **2026-10-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.- **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.diff --cc apps/designcraft/src/main.rsindex 2996d4fb0,26ce2ee4f..2ac607bb8--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -186,8 -209,7 +209,8 @@@ fn services() -> Services})),pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),- write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),+ write: Some(Box::new(|p: &str, b: &[u8]| designcraft_engine::atomic::write_atomic(std::path::Path::new(p), b).map_err(|e| e.to_string()))),+ clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())),..Default::default()}}diff --cc crates/compose/src/lib.rsindex 92dd82f6d,cd0e7cbd9..4ed599b04--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -330,7 -316,7 +330,8 @@@ pub struct FrameSpecimpl FrameSpec {pub fn columns(&self) -> Vec<Rect> {let a = self.area;-- let n = self.opts.columns.max(1);++ // Primary frames inherit the document limit (216), beyond the interactive frame editor's 40.++ let n = self.opts.columns.clamp(1, 216);match self.opts.columns_kind {designcraft_doc::ColumnsKind::FixedWidth if self.opts.column_width > 0.0 => (0..n).map(|i| {@@@ -3613,3 -3275,3 +3674,47 @@@ pub fn path_glyphs}runs}++++#[cfg(test)]++mod column_allocation_safety_tests {++ use super::*;++++ fn frame(kind: designcraft_doc::ColumnsKind) -> FrameSpec {++ FrameSpec {++ id: ItemId(1),++ area: Rect::new(0., 0., 300., 100.),++ opts: TextFrameOptions { columns: 217, columns_kind: kind, column_width: 20., gutter: 12., ..Default::default() },++ vertical: false,++ exclusions: vec![],++ page_name: None,++ page: None,++ grid: None,++ left_page: false,++ page_rect: None,++ }++ }++ fn check(kind: designcraft_doc::ColumnsKind) {++ let mut f = frame(kind);++ // Fail safely at a small boundary before exercising hostile native options.++ assert_eq!(f.columns().len(), 216);++ f.opts.columns = u32::MAX;++ assert_eq!(f.columns().len(), 216);++ f.opts.columns = 0;++ assert_eq!(f.columns().len(), 1);++ f.opts.columns = 2;++ let expected = if kind == designcraft_doc::ColumnsKind::FixedWidth {++ vec![Rect::new(0., 0., 20., 100.), Rect::new(32., 0., 52., 100.)]++ } else {++ vec![Rect::new(0., 0., 144., 100.), Rect::new(156., 0., 300., 100.)]++ };++ assert_eq!(f.columns(), expected);++ }++ #[test]++ fn column_allocation_caps_equal_width_frame_count() {++ check(designcraft_doc::ColumnsKind::FixedNumber);++ }++ #[test]++ fn column_allocation_caps_fixed_width_frame_count() {++ check(designcraft_doc::ColumnsKind::FixedWidth);++ }++}diff --cc crates/doc/src/edit.rsindex 51e17abbb,38de38ac7..7b2168e30--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@@ -209,115 -206,77 +209,195 @@@ impl Documentif from == to {return Err(DocError::Invalid("cannot thread a frame to itself".into()));}- let fs = self.item(from).and_then(|i| i.text_frame()).map(|t| t.story).ok_or(DocError::NoItem(from))?;- // Convert unassigned/graphic-less frames into text frames.- let ts = match self.item(to).ok_or(DocError::NoItem(to))?.content.clone() {- Content::Text(t) => Some(t.story),- Content::Unassigned => None,- _ => return Err(DocError::Invalid("can only thread to text or empty frames".into())),++ self.check_thread_links(from, to, false)?;+ let ts = self.frame_story(to)?;+ let fs = match self.frame_story(from)? {+ Some(s) => s,+ None => self.give_empty_story(from)?,};if ts == Some(fs) {return Err(DocError::Invalid("frames are already in the same story".into()));}- if let Some(ts) = ts {- let other = self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?;- let other = Arc::unwrap_or_clone(other);- // Frames of the other story after `to` follow along; frames before it are left as empty new stories.- let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);- let before: Vec<ItemId> = other.frames[..pos_to].to_vec();- let after: Vec<ItemId> = other.frames[pos_to..].to_vec();- {- let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;- if !other.text.is_empty() {- st.text.push('\n');- st.text.push_str(&other.text);- st.paras.extend(other.paras.iter().cloned());- // Char runs: '\n' takes the last run's format, then the other story's runs.- if let Some(last) = st.chars.last_mut() {- last.len += 1;- }- st.chars.extend(other.chars.iter().filter(|r| r.len > 0).cloned());- st.tables.extend(other.tables.iter().map(|(k, v)| (*k, v.clone())));- for n in &other.notes {- let id = st.next_note_id();- st.notes.push(Arc::new(crate::Footnote { id, text: n.text.clone() }));- }- st.anchors.extend(other.anchors.iter().cloned());- st.xrefs.extend(other.xrefs.iter().cloned());- st.index_refs.extend(other.index_refs.iter().cloned());- st.objects.extend(other.objects.iter().cloned());- st.rev += 1;- }- let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);- for (k, f) in after.iter().enumerate() {- st.frames.insert(at + k, *f);- }+ let Some(ts) = ts else {+ let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;+ let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);+ st.frames.insert(at, to);+ st.rev += 1;+ let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;+ it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });+ return Ok(());+ };+ let mut other = Arc::unwrap_or_clone(self.stories.remove(&ts).ok_or(DocError::NoStory(ts))?);+ // Frames of the other story from `to` on follow along; frames before it are left as an empty new story.+ let pos_to = other.frames.iter().position(|f| *f == to).unwrap_or(0);+ let after = other.frames.split_off(pos_to);+ let before = std::mem::take(&mut other.frames);+ let (vertical, direction) = (other.vertical, other.direction);++ let offset;+ {+ let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;++ offset = if st.text.is_empty() { 0 } else { st.text.len().saturating_add(1) };+ // The story keeps its own direction, even when it was empty and takes the other's text.+ let own = (st.vertical, st.direction);+ st.append_story(other);+ (st.vertical, st.direction) = own;+ let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);+ for (k, f) in after.iter().enumerate() {+ st.frames.insert(at + k, *f);+ }+ st.rev += 1;+ }++ self.remap_thread_story_refs(ts, fs, offset);+ for f in &after {+ if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {+ t.story = fs;}- for f in &after {+ }+ if !before.is_empty() {+ let nid = StoryId(self.alloc());+ let mut ns = Story::new(nid);+ ns.frames = before.clone();+ ns.vertical = vertical;+ ns.direction = direction;+ for f in &before {if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {- t.story = fs;+ t.story = nid;}}- if !before.is_empty() {- let nid = StoryId(self.alloc());- let mut ns = Story::new(nid);- ns.frames = before.clone();- ns.vertical = other.vertical;- ns.direction = other.direction;- for f in &before {- if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {- t.story = nid;- }- }- self.stories.insert(nid, Arc::new(ns));+ self.stories.insert(nid, Arc::new(ns));+ }+ Ok(())+ }++ /// [`Document::thread`], except that an empty `from` alone in its story, threaded in front of+ /// the first frame of `to`'s story, joins that story: the story with the text keeps its id+ /// (and whatever refers to it).+ pub fn thread_keeping_story(&mut self, from: ItemId, to: ItemId) -> Result<()> {+ let fs = self.frame_story(from)?;+ let from_empty = fs.is_none_or(|fs| self.story(fs).is_some_and(|s| s.text.is_empty() && s.frames == [from]));+ let ts = self.frame_story(to)?;+ let to_first = ts.and_then(|ts| self.story(ts)).is_some_and(|s| s.frames.first() == Some(&to));+ let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else { return self.thread(from, to) };++ self.check_thread_links(from, to, true)?;+ if let Some(fs) = fs {+ self.stories.remove(&fs);++ self.remap_thread_story_refs(fs, ts, 0);+ }+ let st = self.story_mut(ts).ok_or(DocError::NoStory(ts))?;+ st.frames.insert(0, from);+ st.rev += 1;+ let it = self.item_mut(from).ok_or(DocError::NoItem(from))?;+ match it.text_frame_mut() {+ Some(t) => t.story = ts,+ None => it.content = Content::Text(TextFrame { story: ts, options: TextFrameOptions::default() }),+ }+ Ok(())+ }+++ /// Story-external text addresses move with the incoming text when threading merges stories.++ /// Linked children follow the surviving whole story, including for an empty removed parent;++ /// their copied content stays unchanged until an explicit Update Link.++ fn remap_thread_story_refs(&mut self, from: StoryId, to: StoryId, offset: usize) {++ // The child's old snapshot is not a snapshot of the newly merged parent. Force it++ // out of date even when the old and surviving revision numbers happen to coincide.++ let stale_rev = self.story(to).map_or(0, |st| st.rev.wrapping_sub(1));++ for st in self.stories.values_mut() {++ if st.link.is_some_and(|(parent, _)| parent == from) {++ Arc::make_mut(st).link = Some((to, stale_rev));++ }++ }++ for link in &mut self.hyperlinks {++ if let crate::HyperlinkSource::Text { story, start, end } = &mut link.source++ && *story == from++ {++ *story = to;++ *start = start.saturating_add(offset);++ *end = end.saturating_add(offset);+ }++ }++ for placeholder in &mut self.data_merge.placeholders {++ if let crate::PlaceholderAnchor::Text { story, start, end } = &mut placeholder.anchor++ && *story == from++ {++ *story = to;++ *start = start.saturating_add(offset);++ *end = end.saturating_add(offset);++ }++ }++ if self.settings.primary_story == Some(from) {++ self.settings.primary_story = Some(to);++ }++ }++++ /// A linked child is replaced wholesale on update. Only empty, unlinked frame++ /// extensions can join it without losing a link or newly appended body text.++ fn check_thread_links(&self, from: ItemId, to: ItemId, keep_to: bool) -> Result<()> {++ let fs = self.frame_story(from)?;++ let ts = self.frame_story(to)?;++ let first = fs.and_then(|id| self.story(id));++ let second = ts.and_then(|id| self.story(id));++ let incompatible = if keep_to {++ first.is_some_and(|st| st.link.is_some()) || second.is_some_and(|st| st.link.is_some_and(|(parent, _)| Some(parent) == fs))+ } else {- let st = self.story_mut(fs).ok_or(DocError::NoStory(fs))?;- let at = st.frames.iter().position(|f| *f == from).map_or(st.frames.len(), |p| p + 1);- st.frames.insert(at, to);- let it = self.item_mut(to).ok_or(DocError::NoItem(to))?;- it.content = Content::Text(TextFrame { story: fs, options: TextFrameOptions::default() });++ second.is_some_and(|st| st.link.is_some())++ || first.is_some_and(|st| {++ st.link.is_some()++ && second.is_some_and(|incoming| !incoming.text.is_empty() || st.link.is_some_and(|(parent, _)| parent == incoming.id))++ })++ };++ if incompatible {++ return Err(DocError::Invalid("unlink the linked story before merging its text".into()));+ }- if let Some(st) = self.story_mut(fs) {- st.rev += 1;++ Ok(())++ }+++ /// Can a user thread `from` → `to`? Both are text frames or empty frames (not lines), on+ /// document spreads or on the same parent spread, not in one story already, and no frame+ /// threads into `to` yet. [`Document::thread`] itself is less strict (import and autoflow).+ pub fn check_thread(&self, from: ItemId, to: ItemId) -> Result<()> {+ if from == to {+ return Err(DocError::Invalid("cannot thread a frame to itself".into()));+ }+ for id in [from, to] {+ let it = self.item(id).ok_or(DocError::NoItem(id))?;+ if !matches!(it.content, Content::Text(_) | Content::Unassigned) || it.shape == Shape::GraphicLine {+ return Err(DocError::Invalid(format!("{id} is not a text frame or an empty frame")));+ }+ if it.locked || self.layer(it.layer).is_some_and(|l| l.locked) {+ return Err(DocError::Invalid(format!("{id} is locked or on a locked layer")));+ }+ }+ let (Some(fl), Some(tl)) = (self.find(from), self.find(to)) else { return Err(DocError::NoItem(to)) };+ let same_place = match (fl.spread, tl.spread) {+ (SpreadRef::Doc(_), SpreadRef::Doc(_)) => true,+ (a, b) => a == b,+ };+ if !same_place {+ return Err(DocError::Invalid("frames on a parent spread thread only to frames on the same parent".into()));+ }+ let story = |id: ItemId| self.item(id).and_then(|i| i.text_frame()).map(|t| t.story);+ if story(from).is_some() && story(from) == story(to) {+ return Err(DocError::Invalid("the frames are already in the same thread".into()));+ }++ // Generated text is rebuilt from its source data. Merging body text into it would++ // silently discard that text on the next update (endnotes update after every edit).++ let generated = |sid| {++ self.endnote_story == Some(sid)++ || self.toc.as_ref().is_some_and(|t| t.story == sid)++ || self.index.as_ref().is_some_and(|i| i.story == sid)++ };++ let (fs, ts) = (story(from), story(to));++ if fs.is_some_and(generated) && ts.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty()) {++ return Err(DocError::Invalid("cannot merge body text into a generated story".into()));++ }++ if ts.is_some_and(generated) && fs.and_then(|sid| self.story(sid)).is_some_and(|st| !st.text.is_empty() || st.frames != [from]) {++ return Err(DocError::Invalid("a generated story can only take a new empty first frame".into()));++ }++ let keep_to = fs.is_none_or(|sid| self.story(sid).is_some_and(|st| st.text.is_empty() && st.frames == [from]))++ && ts.and_then(|sid| self.story(sid)).is_some_and(|st| st.frames.first() == Some(&to));++ self.check_thread_links(from, to, keep_to)?;+ if self.prev_frame(to).is_some() {+ return Err(DocError::Invalid(format!("text already flows into {to} from another frame: break that thread first")));}Ok(())}diff --cc crates/doc/src/ids.rsindex 3dbb94c44,3dbb94c44..fed2cb8fc--- a/crates/doc/src/ids.rs+++ b/crates/doc/src/ids.rs@@@ -21,3 -21,3 +21,24 @@@ id_type!(SpreadId, "sp")id_type!(PageId, "p");id_type!(LayerId, "l");id_type!(AssetId, "a");++++/// Fresh story-local id. Keep monotonically increasing ids normally; a loaded MAX id must++/// not make the next insertion overwrite it. In that case choose the first unused gap.++pub(crate) fn next_local_id(ids: impl Iterator<Item = u64> + Clone) -> u64 {++ if let Some(next) = ids.clone().max().unwrap_or(0).checked_add(1) {++ return next;++ }++ let mut used: Vec<_> = ids.collect();++ used.sort_unstable();++ let mut next = 1u64;++ for id in used {++ if id > next {++ break;++ }++ if id == next {++ // An allocated Vec cannot contain every u64 id, so this always finds a gap.++ next = next.saturating_add(1);++ }++ }++ next++}diff --cc crates/doc/src/notes.rsindex 94f6b8425,b681542cb..46a339653--- a/crates/doc/src/notes.rs+++ b/crates/doc/src/notes.rs@@@ -178,7 -178,7 +178,7 @@@ impl Story}pub(crate) fn next_note_id(&self) -> u64 {- self.notes.iter().map(|n| n.id).max().unwrap_or(0).saturating_add(1)- self.notes.iter().map(|n| n.id).max().unwrap_or(0) + 1++ crate::ids::next_local_id(self.notes.iter().map(|n| n.id))}/// Insert empty footnotes for `n` new reference characters before which `k` references sit.diff --cc crates/doc/src/page.rsindex f1eaa48ad,f1eaa48ad..1fa753b3b--- a/crates/doc/src/page.rs+++ b/crates/doc/src/page.rs@@@ -246,7 -246,7 +246,8 @@@ impl Page/// Split `area` into `n` equal columns separated by `gutter`.pub fn column_rects(area: Rect, n: u32, gutter: f64) -> Vec<Rect> {-- let n = n.max(1) as usize;++ // The public allocator also receives native/imported options, outside command validation.++ let n = n.clamp(1, 216) as usize;let w = ((area.width() - gutter * (n as f64 - 1.0)) / n as f64).max(0.0);(0..n).map(|i| Rect::new(area.x0 + i as f64 * (w + gutter), area.y0, area.x0 + i as f64 * (w + gutter) + w, area.y1)).collect()}@@@ -403,3 -403,3 +404,18 @@@ mod testsassert_eq!(s.page_at_x(5000.0), Some(1));}}++++#[cfg(test)]++mod column_allocation_safety_tests {++ use super::*;++++ #[test]++ fn column_allocation_caps_page_count_and_preserves_geometry() {++ let area = Rect::new(0., 0., 300., 100.);++ // Fail safely at a small boundary before exercising hostile counts.++ assert_eq!(column_rects(area, 217, 0.).len(), 216);++ assert_eq!(column_rects(area, u32::MAX, 0.).len(), 216);++ assert_eq!(column_rects(area, 0, 12.), vec![area]);++ assert_eq!(column_rects(area, 2, 12.), vec![Rect::new(0., 0., 144., 100.), Rect::new(156., 0., 300., 100.)]);++ }++}diff --cc crates/doc/src/slice.rsindex 6afbad109,f85ec4adc..ebf59b6a8--- a/crates/doc/src/slice.rs+++ b/crates/doc/src/slice.rs@@@ -126,61 -126,6 +126,66 @@@ impl Storyself.rev += 1;end}++ /// Append the whole of `other` as new paragraphs after this story's text (threading two+ /// stories merges them this way). Its formatting, notes, endnotes, editorial notes, markers,+ /// anchored objects and tables come along; footnotes, endnotes, editorial notes and tables get+ /// ids that are free in this story. An empty story simply takes `other`'s content. Frames stay.+ pub fn append_story(&mut self, mut other: Story) {+ if other.text.is_empty() {+ return;+ }+ if self.text.is_empty() {+ let (id, frames, rev, link) = (self.id, std::mem::take(&mut self.frames), self.rev, self.link.take());+ *self = Story { id, frames, rev: rev.saturating_add(1), link, ..other };+ return;+ }+ if !other.tables.is_empty() {- let mut next = self.tables.keys().max().copied().unwrap_or(0).saturating_add(1);+ let mut ids = std::collections::HashMap::new();++ let mut next = crate::ids::next_local_id(self.tables.keys().copied());+ for (old, t) in std::mem::take(&mut other.tables) {+ let new = next;- next = next.saturating_add(1);+ let mut t = Arc::unwrap_or_clone(t);+ t.id = new;+ ids.insert(old, new);+ self.tables.insert(new, Arc::new(t));++ // Continue through free ids without rescanning the table map for its maximum.++ // On exhaustion wrap to gaps; an allocated map cannot occupy every u64 id.++ next = next.checked_add(1).unwrap_or(1);++ while self.tables.contains_key(&next) {++ next = next.checked_add(1).unwrap_or(1);++ }+ }+ for p in &mut other.paras {+ p.table = p.table.and_then(|id| ids.get(&id).copied());+ }+ }+ self.text.push('\n');+ self.text.push_str(&other.text);+ // The paragraph end takes the last run's format.+ if let Some(last) = self.chars.last_mut() {+ last.len += 1;+ }+ self.chars.extend(other.chars.into_iter().filter(|r| r.len > 0));+ self.paras.extend(other.paras);+ for n in other.notes {+ let id = self.next_note_id();+ self.notes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));+ }+ for n in other.endnotes {- let id = self.endnotes.iter().map(|x| x.id).max().unwrap_or(0).saturating_add(1);++ let id = crate::ids::next_local_id(self.endnotes.iter().map(|x| x.id));+ self.endnotes.push(Arc::new(crate::notes::Footnote { id, text: n.text.clone() }));+ }+ for n in other.editorial {- let id = self.editorial.iter().map(|x| x.id).max().unwrap_or(0).saturating_add(1);++ let id = crate::ids::next_local_id(self.editorial.iter().map(|x| x.id));+ self.editorial.push(Arc::new(crate::endnotes::EditorialNote { id, ..(*n).clone() }));+ }+ self.anchors.extend(other.anchors);+ self.xrefs.extend(other.xrefs);+ self.index_refs.extend(other.index_refs);+ self.objects.extend(other.objects);+ self.rev = self.rev.saturating_add(1);+ }}#[cfg(test)]@@@ -214,22 -159,4 +219,52 @@@ mod testsassert_eq!(part.notes.len(), 1);assert!(a.extract(2..8).notes.is_empty());}+++ #[test]++ fn append_tables_preserves_sparse_and_wrapping_ids() {++ for existing in [vec![1, 3, u64::MAX], vec![1, 3, u64::MAX - 1], vec![1, 3, 8]] {++ let story = |id, ids: &[u64]| {++ let mut s = Story::with_text(StoryId(id), &vec![crate::TABLE_ANCHOR.to_string(); ids.len()].join("\n"), ParaFormat::default());++ for (p, &tid) in s.paras.iter_mut().zip(ids) {++ p.table = Some(tid);++ let mut t = crate::table::Table::new(tid, 1, 1, 0, 0, 100.0);++ t.cells[0].text = Story::with_text(StoryId(0), &format!("{id}:{tid}"), ParaFormat::default());++ s.tables.insert(tid, Arc::new(t));++ }++ s++ };++ let mut a = story(1, &existing);++ let b = story(2, &[1, 2, 3]);++ a.check().unwrap();++ b.check().unwrap();++ a.append_story(b);++ a.check().unwrap();++ assert_eq!(a.tables.len(), 6);++ for (p, tid) in a.paras.iter().take(3).zip(&existing) {++ assert_eq!(p.table, Some(*tid));++ assert_eq!(a.tables[tid].cells[0].text.text, format!("1:{tid}"));++ }++ for (p, tid) in a.paras.iter().skip(3).zip(1..=3) {++ assert_eq!(a.tables[&p.table.unwrap()].cells[0].text.text, format!("2:{tid}"));++ }++ }++ }+++ #[test]+ fn append_story_with_maximal_ids_does_not_overflow() {+ let mut a = Story::with_text(StoryId(1), "Alpha", ParaFormat::default());+ a.tables.insert(u64::MAX, Arc::new(crate::table::Table::new(u64::MAX, 1, 1, 0, 0, 100.0)));+ let note = |id| Arc::new(crate::notes::Footnote { id, text: Story::with_text(StoryId(0), "n", ParaFormat::default()) });+ a.endnotes.push(note(u64::MAX));+ a.notes.push(note(u64::MAX));+ a.rev = u64::MAX;+ let mut b = Story::with_text(StoryId(2), "Beta", ParaFormat::default());+ b.tables.insert(1, Arc::new(crate::table::Table::new(1, 1, 1, 0, 0, 100.0)));+ b.endnotes.push(note(1));+ b.notes.push(note(1));+ a.append_story(b);+ assert_eq!(a.text, "Alpha\nBeta");+ assert_eq!(a.endnotes.len(), 2);+ assert_eq!(a.notes.len(), 2);+ }}diff --cc crates/engine/src/cmd/edit.rsindex 9f52184f6,e7190acb4..0885d1554--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@@ -81,73 -88,7 +81,73 @@@ fn paste_text(s: &mut Session, text: Op});}let text = text.or_else(|| clip.map(|(_, p)| p)).ok_or_else(|| super::bad("edit.paste", "clipboard is empty"))?;- s.execute("text.insert", &json!({"text": text.replace("\r\n", "\n").replace('\r', "\n"), "raw": true}))+ let text = outside_text(&text)?;+ s.execute("text.insert", &json!({"text": text, "raw": true}))+}++/// Text from the system clipboard as story text: Unix line ends, and none of the private-use+/// characters (U+E000–U+E1FF) that stories use as markers for breaks, footnotes, tables and+/// variables, since a stray one would be read as a marker without its payload.+fn outside_text(text: &str) -> Result<String> {+ let text: String = text.replace("\r\n", "\n").replace('\r', "\n").chars().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect();+ if text.is_empty() { Err(super::bad("edit.paste", "the clipboard holds no text")) } else { Ok(text) }+}++/// Pasted text with no insertion point: a new text frame holding it, as wide as the first column+/// of the page's margin area and as tall as the text (at most the margin area's height), centred+/// on `at` (spread coordinates) or else on the margin area. The frame ends up selected. With+/// `slice` (the text copied here), the frame's story is that formatted copy.+fn paste_text_frame(s: &mut Session, p: &Value, text: &str, slice: Option<&designcraft_doc::Story>) -> Result<Value> {+ use designcraft_geom::{Point, Rect, shapes};+ const LIMIT: f64 = 1.0e5;- let sr = super::spread_param(p, "spread");++ let sr = super::spread_param(p, "spread")?;+ let at = super::point_param(p, "at")+ .filter(|a| a.x.is_finite() && a.y.is_finite())+ .map(|a| Point::new(a.x.clamp(-LIMIT, LIMIT), a.y.clamp(-LIMIT, LIMIT)));+ let lid = s.doc()?.active_layer;+ let cache = s.cache.clone();+ let text = if slice.is_some() { String::new() } else { outside_text(text)? };+ s.edit(|d, sel| {+ let sp = d.spread(sr).ok_or_else(|| super::bad("edit.paste", "no such spread"))?;+ let page = at.and_then(|a| sp.page_at_x(a.x)).and_then(|i| sp.pages.get(i)).or_else(|| sp.pages.first());+ let page = page.ok_or_else(|| super::bad("edit.paste", "the spread has no pages"))?;+ let margins = page.margin_rect();+ let column = page.column_rects().first().copied().unwrap_or(margins);+ let w = column.width().max(12.0);+ let max_h = margins.height().max(12.0);+ let c = at.unwrap_or(Point::new(column.center().x, margins.center().y));+ let rect = |h: f64| Rect::new(c.x - w / 2.0, c.y - h / 2.0, c.x + w / 2.0, c.y + h / 2.0);+ let para = match slice.and_then(|sl| sl.paras.first()) {+ Some(pf) => designcraft_doc::ParaFormat { table: None, ..pf.clone() },+ None => designcraft_doc::ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() },+ };+ let (id, sid) = d.add_text_frame(sr, rect(max_h), lid, &text, para)?;+ if let Some(sl) = slice {+ d.story_mut(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?.insert_story(0, sl);+ }+ // Shrink to the composed text unless it already fills the frame.+ let composed = cache.get(d, sid, None);+ if !composed.is_overset()+ && let Some(ft) = composed.frame(id)+ {+ let inset = d.item(id).and_then(|i| i.text_frame()).map_or(0.0, |tf| tf.options.inset[0] + tf.options.inset[2]);+ let h = (ft.content_height + inset + 0.5).clamp(12.0, max_h);+ if h.is_finite()+ && h < max_h+ && let Some(it) = d.item_mut(id)+ {+ it.path = shapes::rectangle(rect(h));+ // Keep the full height if the last line no longer fits.+ if cache.get(d, sid, None).is_overset()+ && let Some(it) = d.item_mut(id)+ {+ it.path = shapes::rectangle(rect(max_h));+ }+ }+ }+ *sel = Selection::items(vec![id]);+ Ok(json!({"id": id.0, "story": sid.0}))+ })}fn strip_objects(st: &designcraft_doc::Story) -> designcraft_doc::Story {@@@ -169,6 -110,6 +169,8 @@@ pub fn specs() -> Vec<CommandSpec>st.doc = e.doc;st.selection = e.selection;st.revision += 1;++ // Pending typing overrides belong to the current edit state, not a restored snapshot.++ s.typing_format = None;Ok(json!({"undone": e.label}))}),cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| {@@@ -178,6 -119,6 +180,7 @@@st.doc = e.doc;st.selection = e.selection;st.revision += 1;++ s.typing_format = None;Ok(json!({"redone": e.label}))}),cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| {diff --cc crates/engine/src/cmd/style.rsindex 3eb241b28,c4d20f099..0280612d1--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@@ -180,10 -180,19 +180,19 @@@ pub fn specs() -> Vec<CommandSpec>"Apply Color",[],None,- "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour on the selected text or objects; `text` also targets the text of selected frames",+ "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",- |s| super::has_text(s).or_else(|_| super::has_selection(s)),+ has_text_or_selection,apply_color),+ cmd!(+ "color.sample",+ "Sample Color (Eyedropper)",+ [],+ None,+ "{at: [x,y] (spread coords), spread?, target?: fill|stroke, ids?} → {color: \"#rrggbb\", swatch, from: image id} — the Eyedropper on a placed image: the image's colour at the point (an unnamed colour) fills the selected text, else the selected objects",+ has_text_or_selection,+ sample_color+ ),cmd!("swatch.addToSwatches","Add to Swatches",@@@ -620,7 -631,27 +631,26 @@@ fn delete_para(s: &mut Session, p: &Valfn create_char(s: &mut Session, p: &Value) -> Result<Value> {let base = str_param(p, "name").unwrap_or("Character Style 1").to_string();- let chars: CharAttrs = attrs(p.get("chars"), |a: &mut CharAttrs, k, v| a.set_json(k, v))?;+ let mut chars: CharAttrs = attrs(p.get("chars"), |a: &mut CharAttrs, k, v| a.set_json(k, v))?;+ // Validate caller-supplied fills; captured formatting may retain a deleted swatch name.+ super::text::validate_char_fill(&s.doc()?.doc, &chars, "style.character.create")?;+ if p.get("fromSelection").and_then(Value::as_bool).unwrap_or(false)+ && let Some(target) = super::text::format_targets_pub(s).first()+ {+ let st = s.doc()?;- let story = st.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;+ // Match paragraph fromSelection's first-character/caret policy, but keep paragraph+ // attributes inherited instead of freezing the fully resolved character properties.- let format = if target.range.is_empty() { story.char_format_at(target.range.start) } else { story.format_after(target.range.start) };++ let format = super::text::effective_char_format(s, target)?;+ let mut captured = st.doc.styles.char_style_attrs(&format.style);+ captured.merge(&format.over);+ // Replay the explicit fields so null clears a captured value rather than looking absent.+ if let Some(overrides) = p.get("chars").and_then(Value::as_object) {+ for (key, value) in overrides {+ captured.set_json(key, value).map_err(|e| bad("style", e))?;+ }+ }+ chars = captured;+ }// Based on [None] is based on nothing.let based_on = str_param(p, "basedOn").filter(|b| *b != designcraft_doc::NO_CHAR_STYLE).map(str::to_string);s.edit(|d, _| {@@@ -947,59 -983,165 +982,148 @@@ fn apply_gradient(s: &mut Session, p: &fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {let color = p.get("color").and_then(parse_color).ok_or_else(|| bad("object.color", "missing or bad color"))?;let stroke = str_param(p, "target") == Some("stroke");- let text = p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some();+ let named = p.get("ids").is_some() || p.get("id").is_some();+ let text = !named+ && (p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some() || s.doc()?.selection.cells.is_some());- if text {- let targets = super::text::format_targets(s);- // A caret in existing text has no editable range. Refuse it before creating a swatch- // or history; an empty story has a format run that the next insertion inherits.- if !targets- .iter()- .any(|t| !t.range.is_empty() || s.active().is_some_and(|d| d.doc.text_story(t.story, t.cell).is_some_and(|st| st.is_empty())))- {- return Err(bad("object.color", "select the text to colour"));- }- return s.edit(|d, _| {- let name = color_swatch(d, color);- for t in &targets {- let Some(story) = d.text_story_mut(t.story, t.cell) else { continue };- let set = |f: &mut designcraft_doc::CharFormat| {- if stroke {- (f.over.stroke, f.over.stroke_tint) = (Some(name.clone()), Some(1.0));- } else {- (f.over.fill, f.over.fill_tint) = (Some(name.clone()), Some(1.0));- }- };- if t.range.is_empty() {- if story.is_empty()- && let Some(run) = story.chars.first_mut()- {- set(&mut run.format);- story.rev = story.rev.wrapping_add(1);- }- } else {- story.format_chars(t.range.clone(), set);- }- }- Ok(json!({"swatch": name}))- });+ let (ids, texts) = if text { (vec![], super::text::format_targets_pub(s)) } else { (super::targets(s, p)?, vec![]) };++ if text && texts.is_empty() {++ return Err(bad("object.color", "select the text to colour"));+ }- let ids = super::targets(s, p)?;- s.edit(|d, _| {+ // A caret: the colour is for the next typing (once the swatch exists).+ let caret = matches!(texts.as_slice(), [t] if t.range.is_empty());+ let r = s.edit(|d, _| {- // Reuse a swatch holding exactly this colour, else add an unnamed one.- let existing = d- .swatches- .iter()- .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))- .map(|w| w.name.clone());- let name = match existing {- Some(n) => n,- None => {- let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));- d.swatches.push(Swatch {- name: name.clone(),- value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },- locked: false,- named: false,- hidden: true,- });- name- }- };- for id in &ids {- if let Some(it) = d.item_mut(*id) {- if stroke {- it.stroke.swatch = name.clone();- it.stroke.tint = 1.0;- } else {- it.fill.swatch = name.clone();- it.fill.tint = 1.0;- }- }- }+ let name = color_swatch(d, color);+ color_items(d, &ids, &name, stroke);+ if !caret {+ let a = if stroke {+ CharAttrs { stroke: Some(name.clone()), stroke_tint: Some(1.0), ..Default::default() }+ } else {+ CharAttrs { fill: Some(name.clone()), fill_tint: Some(1.0), ..Default::default() }+ };+ super::text::apply_char_attrs(d, &texts, &a, &[]);+ }Ok(json!({"swatch": name}))- })+ })?;+ if caret && let Some(name) = r.get("swatch").cloned() {+ let attrs = if stroke { json!({"stroke": name, "strokeTint": 1.0}) } else { json!({"fill": name, "fillTint": 1.0}) };+ super::text::format_chars(s, &attrs)?;+ }+ Ok(r)}+ /// A process swatch holding exactly `color`, else a new unnamed one (hidden from the Swatches+ /// panel until Add to Swatches).+ fn color_swatch(d: &mut designcraft_doc::Document, color: designcraft_color::Color) -> String {+ let existing = d+ .swatches+ .iter()+ .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))+ .map(|w| w.name.clone());+ if let Some(n) = existing {+ return n;+ }+ let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));+ d.swatches.push(Swatch {+ name: name.clone(),+ value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },+ locked: false,+ named: false,+ hidden: true,+ });+ name+ }++ fn color_items(d: &mut designcraft_doc::Document, ids: &[designcraft_doc::ItemId], name: &str, stroke: bool) {+ for id in ids {+ if let Some(it) = d.item_mut(*id) {+ if stroke {+ it.stroke.swatch = name.to_string();+ it.stroke.tint = 1.0;+ } else {+ it.fill.swatch = name.to_string();+ it.fill.tint = 1.0;+ }+ }+ }+ }++ fn has_text_or_selection(s: &Session) -> std::result::Result<(), String> {+ has_doc(s)?;+ if s.active().is_some_and(|d| d.selection.text.is_some() || d.selection.cells.is_some()) { Ok(()) } else { super::has_selection(s) }+ }++ /// The Eyedropper on a placed image (InDesign samples the pixel under the pointer): that colour,+ /// as an unnamed colour, fills the selected text (characters), or the selected objects.+ fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "color.sample";+ let at = super::point_param(p, "at").ok_or_else(|| bad(ID, "missing at"))?;+ let sr = super::spread_param(p, "spread")?;+ let st = s.doc()?;+ let (from, color) = image_color_at(&st.doc, sr, at).ok_or_else(|| bad(ID, "no placed image under the point"))?;+ let hex = color.to_hex();+ let mut params = p.clone();+ params["color"] = json!(hex);+ let mut result = apply_color(s, ¶ms)?;+ result["color"] = json!(hex);+ result["from"] = json!(from.0);+ Ok(result)+ }++ /// The colour of the placed raster image at `at` on spread `sr`: the frontmost visible image whose+ /// frame shows that point (locked ones too, as sampling changes nothing). (image frame, colour);+ /// None over no image, a transparent pixel, or a graphic that is not a raster (PDF, EPS).+ pub(crate) fn image_color_at(+ d: &designcraft_doc::Document,+ sr: designcraft_doc::SpreadRef,+ at: designcraft_geom::Point,+ ) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {+ let sp = d.spread(sr)?;+ let mut items: Vec<&designcraft_doc::Item> = sp.items.iter().map(|i| &**i).collect();+ items.sort_by_key(|i| d.layer_rank(i.layer));+ items+ .into_iter()+ .rev()+ .filter(|it| d.layer(it.layer).is_none_or(|l| l.visible))+ .find_map(|it| sample_item(d, it, designcraft_geom::Affine::IDENTITY, at, 0))+ }++ fn sample_item(+ d: &designcraft_doc::Document,+ it: &designcraft_doc::Item,+ outer: designcraft_geom::Affine,+ at: designcraft_geom::Point,+ depth: usize,+ ) -> Option<(designcraft_doc::ItemId, designcraft_color::Color)> {+ use designcraft_doc::Content;+ if it.hidden || depth > 64 {+ return None;+ }+ let xf = outer * it.xf;+ match &it.content {+ Content::Group { items } => items.iter().rev().find_map(|c| sample_item(d, c, xf, at, depth + 1)),+ Content::Graphic(g) => {+ let inner = xf.inverse() * at;+ if !designcraft_geom::hit::fill_contains(&it.path.to_bezpath(), designcraft_geom::FillRule::NonZero, inner) {+ return None;+ }+ let gp = g.xf.inverse() * inner;+ let (w, h) = g.size;+ // Written so that NaN (a degenerate transform) is outside too.+ if !(w > 0.0 && h > 0.0 && gp.x >= 0.0 && gp.y >= 0.0 && gp.x < w && gp.y < h) {+ return None;+ }+ let asset = d.assets.get(&g.asset).filter(|a| a.is_raster())?;+ let img = designcraft_images::decode_rgba(&asset.data)?;+ let (pw, ph) = img.dimensions();+ let px = ((gp.x / w * f64::from(pw)) as u32).min(pw.checked_sub(1)?);+ let py = ((gp.y / h * f64::from(ph)) as u32).min(ph.checked_sub(1)?);+ let [r, gr, b, a] = img.get_pixel_checked(px, py)?.0;+ (a > 0).then(|| (it.id, designcraft_color::Color::rgb8(r, gr, b)))+ }+ _ => None,+ }+ }+fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {let st = s.doc()?;let name = match str_param(p, "swatch") {@@@ -1011,7 -1153,7 +1135,7 @@@}};let rename = str_param(p, "name").map(str::to_string);-- s.edit(|d, _| {++ let result = s.edit(|d, _| {let w = d.swatches.iter_mut().find(|w| w.name == name).ok_or_else(|| bad("swatch.addToSwatches", format!("no swatch `{name}`")))?;if w.locked {return Err(bad("swatch.addToSwatches", "special swatches are already listed"));@@@ -1038,76 -1180,8 +1162,84 @@@rename_in(std::sync::Arc::make_mut(top), &name, &new);}}+ for st in d.stories.values_mut() {+ let mut copy = (**st).clone();- if rename_in_story(&mut copy, &name, &new) {++ if rename_in_story(&mut copy, &name, &new, 0)? {+ *st = std::sync::Arc::new(copy);+ }+ }Ok(json!({"name": new}))-- })++ })?;++ if let Some(new) = result.get("name").and_then(Value::as_str) {++ super::text::rename_typing_swatch(s, &name, new);++ }++ Ok(result)+}++/// Point text colours (character fill, stroke, underline and strikethrough; paragraph shading,+/// border and rules; table cells, borders and alternating fills) at a renamed swatch, in a story+/// and the texts inside it (table cells, footnotes, endnotes). Returns whether anything changed.- fn rename_in_story(st: &mut designcraft_doc::Story, from: &str, to: &str) -> bool {++fn rename_in_story(st: &mut designcraft_doc::Story, from: &str, to: &str, depth: usize) -> Result<bool> {++ // Refuse the whole edit instead of leaving deeper references pointing at a removed name.++ if depth > 32 {++ return Err(bad("swatch.addToSwatches", "story nesting exceeds 32 levels"));++ }+ fn fix(s: &mut String, from: &str, to: &str) -> bool {+ let hit = s == from;+ if hit {+ *s = to.to_string();+ }+ hit+ }+ let mut n = 0;+ let mut f = |s: &mut String| n += usize::from(fix(s, from, to));+ for r in &mut st.chars {+ let o = &mut r.format.over;+ for c in [&mut o.fill, &mut o.stroke, &mut o.underline_color, &mut o.strikethrough_color].into_iter().flatten() {+ f(c);+ }+ }+ for pf in &mut st.paras {+ let a = &mut pf.para;+ for c in [&mut a.shading_color, &mut a.border_color].into_iter().flatten() {+ f(c);+ }+ for r in [&mut a.rule_above, &mut a.rule_below].into_iter().flatten() {+ f(&mut r.color);+ }+ }+ let mut nested = false;+ for t in st.tables.values_mut() {+ let t = std::sync::Arc::make_mut(t);+ let o = &mut t.options;+ f(&mut o.border.color);+ for b in o.borders.iter_mut().flatten() {+ f(&mut b.color);+ }+ for a in [&mut o.alt_rows, &mut o.alt_cols].into_iter().flatten() {+ f(&mut a.first_color);+ f(&mut a.next_color);+ }+ for k in [&mut o.row_strokes, &mut o.column_strokes].into_iter().flatten() {+ f(&mut k.first_stroke.color);+ f(&mut k.next_stroke.color);+ }+ for c in &mut t.cells {+ f(&mut c.fill);+ for k in &mut c.strokes {+ f(&mut k.color);+ }- nested |= rename_in_story(&mut c.text, from, to);++ nested |= rename_in_story(&mut c.text, from, to, depth + 1)?;+ }+ }+ for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {- nested |= rename_in_story(&mut std::sync::Arc::make_mut(note).text, from, to);++ nested |= rename_in_story(&mut std::sync::Arc::make_mut(note).text, from, to, depth + 1)?;+ }+ let changed = n > 0 || nested;+ if changed {+ st.rev = st.rev.wrapping_add(1);+ }- changed++ Ok(changed)}/// Point fills and strokes of an item (and its children) at a renamed swatch.@@@ -1455,3 -1643,111 +1735,116 @@@ mod cjk_testsassert!(s.execute("style.compositeFont.set", &definition(-1.0)).is_err());}}++ #[cfg(test)]+ mod sample_color_tests {+ use designcraft_color::{Color, SwatchValue};+ use designcraft_doc::ItemId;+ use serde_json::json;++ use crate::Session;++ /// A 2×1 image, red then blue, placed 144 pt wide at (72, 72): each pixel is 72 pt.+ fn session_with_image() -> (Session, u64) {+ let png = designcraft_render::Rendered { width: 2, height: 1, pixels: vec![255, 0, 0, 255, 0, 0, 255, 255] }.to_png();+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let b64 = super::super::file::base64_encode(&png);+ let r = s.execute("file.place", &json!({"base64": b64, "name": "rb.png", "x": 72, "y": 72, "width": 144})).unwrap();+ (s, r["id"].as_u64().unwrap())+ }++ fn swatch_color(s: &Session, name: &str) -> Color {+ match &s.doc().unwrap().doc.swatch(name).unwrap().value {+ SwatchValue::Color { color, .. } => *color,+ other => panic!("{other:?}"),+ }+ }++ #[test]+ fn the_eyedropper_colours_selected_text_with_the_image_under_it() {+ let (mut s, image) = session_with_image();+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text", "text": "Elevate."})).unwrap();+ let fid = ItemId(f["id"].as_u64().unwrap());+ let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 7})).unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ let r = s.execute("color.sample", &json!({"at": [180, 100]})).unwrap();+ assert_eq!((r["color"].as_str(), r["from"].as_u64()), (Some("#0000ff"), Some(image)), "{r}");+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");+ let name = r["swatch"].as_str().unwrap().to_string();+ assert_eq!(swatch_color(&s, &name), Color::rgb8(0, 0, 255));+ assert!(s.doc().unwrap().doc.swatch(&name).unwrap().hidden, "an unnamed colour");+ let st = s.doc().unwrap().doc.story(story).unwrap().clone();+ assert_eq!(st.format_after(0).over.fill.as_deref(), Some(name.as_str()));+ assert_eq!(st.format_after(7).over.fill, None, "the full stop keeps its colour");+ // The frame itself is not coloured.+ assert!(s.doc().unwrap().doc.item(fid).unwrap().fill.is_none());+ }++ #[test]+ fn the_eyedropper_fills_selected_objects_and_samples_locked_images() {+ let (mut s, _) = session_with_image();+ let lid = s.doc().unwrap().doc.layers[0].id.0;+ s.execute("layer.set", &json!({"id": lid, "locked": true})).unwrap();+ s.execute("layer.new", &json!({"name": "TEXT"})).unwrap();+ let rect = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [rect]})).unwrap();+ let r = s.execute("color.sample", &json!({"at": [100, 100], "target": "stroke"})).unwrap();+ assert_eq!(r["color"], "#ff0000", "{r}");+ let it = s.doc().unwrap().doc.item(ItemId(rect)).unwrap().clone();+ assert_eq!(swatch_color(&s, &it.stroke.swatch), Color::rgb8(255, 0, 0));+ // Sampling the same colour again reuses its swatch.+ let again = s.execute("color.sample", &json!({"at": [90, 90]})).unwrap();+ assert_eq!(again["swatch"], r["swatch"]);+ }++ #[test]- fn nothing_to_sample_or_nothing_to_colour_is_refused_without_an_edit() {++ fn nothing_to_sample_is_refused_without_an_edit() {+ let (mut s, _) = session_with_image();+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text", "text": "Hi"})).unwrap();+ let fid = ItemId(f["id"].as_u64().unwrap());+ let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": story.0, "anchor": 1, "focus": 1})).unwrap();++ let sampled = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap();++ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], sampled["swatch"]);++ assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Hi", "caret color waits for typing");+ let undo = s.doc().unwrap().history.undo.len();- let caret = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap_err().to_string();- assert!(caret.contains("select the text"), "{caret}");+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();+ let none = s.execute("color.sample", &json!({"at": [600, 600]})).unwrap_err().to_string();+ assert!(none.contains("no placed image"), "{none}");+ // Just past the image's right edge.+ assert!(s.execute("color.sample", &json!({"at": [216.5, 100]})).is_err());+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ }++ #[test]+ fn sampling_and_explicit_colour_use_the_same_text_application_path() {+ for command in ["color.sample", "object.color"] {+ let (mut s, _) = session_with_image();+ let f = s.execute("frame.create", &json!({"rect": [300, 300, 500, 360], "content": "text"})).unwrap();+ let story = designcraft_doc::StoryId(f["story"].as_u64().unwrap());+ s.execute("text.select", &json!({"story": story.0, "anchor": 0})).unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ let r = s.execute(command, &json!({"at": [100, 100], "color": "#ff0000"})).unwrap();+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{command}");+ s.execute("text.insert", &json!({"text": "Hi"})).unwrap();+ let text = s.doc().unwrap().doc.story(story).unwrap();+ assert_eq!(text.format_after(0).over.fill.as_deref(), r["swatch"].as_str(), "empty-story typing: {command}");+ // Explicit ids override text targeting, including with a text selection active.+ let fid = ItemId(f["id"].as_u64().unwrap());+ s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();+ let r = s.execute(command, &json!({"at": [180, 100], "color": "#0000ff", "id": fid.0})).unwrap();+ assert_eq!(s.doc().unwrap().doc.item(fid).unwrap().fill.swatch, r["swatch"].as_str().unwrap());+ let text = s.doc().unwrap().doc.story(story).unwrap();+ assert_ne!(text.format_after(0).over.fill.as_deref(), r["swatch"].as_str(), "text unchanged: {command}");+ let r = s.execute(command, &json!({"at": [180, 100], "color": "#0000ff", "target": "stroke"})).unwrap();+ let text = s.doc().unwrap().doc.story(story).unwrap();+ assert_eq!(text.format_after(0).over.stroke.as_deref(), r["swatch"].as_str(), "selected text stroke: {command}");+ }+ }+ }++++#[cfg(test)]++#[path = "text_color_tests.rs"]++mod text_color_tests;diff --cc crates/engine/src/cmd/text.rsindex de48e4884,b57e9e88a..e928ce472--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -22,27 -22,32 +22,36 @@@ pub fn specs() -> Vec<CommandSpec>release),cmd!(noundo "text.extendTo", "Extend Text Selection", [], None, "{frame, point}", has_doc, |s, p| place(s, p, true)),- cmd!(noundo "text.selectWord", "Select Word", [], None, "{frame, point}", has_doc, |s, p| {- place(s, p, false)?;- let st = s.doc_mut()?;- let Some(t) = st.selection.text else { return ok() };- let text = &st.doc.text_story(t.story, t.cell).map(|x| x.text.clone()).unwrap_or_default();- let (a, b) = word_bounds(text, t.focus);- st.selection.text = Some(TextSel { anchor: a, focus: b, ..t });- ok()+ cmd!(noundo "text.selectWord", "Select Word", [], None, "{frame, point} — the word (or run of spaces) under the point", has_doc, |s, p| {+ select_at(s, p, "word")}),- cmd!(noundo "text.selectSentence", "Select Sentence", [], None, "{frame, point} — the sentence under the point (triple click)", has_doc, |s, p| {+ cmd!(+ noundo "text.selectAt",+ "Select Text Unit",+ [],+ None,+ "{frame, point, unit: word|line|paragraph|story} — what a double, triple, quadruple or quintuple click selects: the word (or run of spaces) under the point, its line, its paragraph with the paragraph return, or the whole story",+ has_doc,+ |s, p| select_at(s, p, str_param(p, "unit").unwrap_or("word"))+ ),++ cmd!(noundo "text.selectSentence", "Select Sentence", [], None, "{frame, point} — the sentence under the point", has_doc, |s, p| {+ select_around(s, p, "text.selectSentence", sentence_bounds)+ }),- cmd!(noundo "text.selectParagraph", "Select Paragraph", [], None, "{frame, point} — the paragraph under the point (quadruple click)", has_doc, |s, p| {++ cmd!(noundo "text.selectParagraph", "Select Paragraph", [], None, "{frame, point} — the paragraph under the point, without its paragraph return", has_doc, |s, p| {+ select_around(s, p, "text.selectParagraph", para_bounds)+ }),- cmd!(noundo "text.selectStory", "Select Story", [], None, "{frame, point} — all the text of the story under the point, threaded frames included (quintuple click)", has_doc, |s, p| {++ cmd!(noundo "text.selectStory", "Select Story", [], None, "{frame, point} — all the text of the story under the point, threaded frames included", has_doc, |s, p| {+ select_around(s, p, "text.selectStory", |t, _| (0, t.len()))+ }),cmd!(noundo "text.select", "Select Text", [], None, "{story, anchor, focus} (UTF-8 byte offsets into the story text, as find.find reports them: á or — counts 2 or 3)", has_doc, |s, p| {let sid = StoryId(p.get("story").and_then(Value::as_u64).unwrap_or(0));- s.typing_format = None;let st = s.doc_mut()?;let text = &st.doc.story(sid).ok_or_else(|| bad("text.select", "no such story"))?.text;let a = floor_char_boundary(text, p.get("anchor").and_then(Value::as_u64).unwrap_or(0) as usize);let f = floor_char_boundary(text, p.get("focus").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(a));st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: f, frame: None, cell: None });st.revision += 1;++ s.typing_format = None;ok()}),cmd!("text.insert", "Type", [], None, "{text, raw?: bool (no typographer's quotes)} — replaces the selected text", has_text, insert),@@@ -156,24 -161,8 +165,33 @@@s,&json!({"align": "leftJustified"}))),- cmd!("type.bold", "Bold", [], Some("Cmd+Shift+B"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"fontStyle": "Bold"}))),- cmd!("type.italic", "Italic", [], Some("Cmd+Shift+I"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"fontStyle": "Italic"}))),+ cmd!(+ "type.bold",+ "Bold",+ [],+ Some("Cmd+Shift+B"),+ "{on?: bool} — the family's bold style, keeping italic (style linking); toggles when `on` is left out",+ has_text_or_frames,+ |s, p| link_style(s, p, true)+ ),+ cmd!(+ "type.italic",+ "Italic",+ [],+ Some("Cmd+Shift+I"),+ "{on?: bool} — the family's italic style, keeping the weight (style linking); toggles when `on` is left out",+ has_text_or_frames,+ |s, p| link_style(s, p, false)+ ),++ cmd!(++ "type.swapFillStroke",++ "Swap Text Fill and Stroke",++ [],++ None,++ "{} — swap each selected character's resolved fill/stroke and tints; at a caret, swap the next typing's colors",++ has_text_or_frames,++ swap_fill_stroke++ ),cmd!("type.underline", "Underline", [], Some("Cmd+Shift+U"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"underline": true}))),cmd!("type.allCaps", "All Caps", [], Some("Cmd+Shift+K"), "{}", has_text_or_frames, |s, _| format_chars(s,@@@ -310,13 -288,15 +328,15 @@@ fn hit_byte_withlet inner = xf.inverse() * pt;let cs = s.cache.get(&st.doc, sid, None);let fi = cs.frames.iter().position(|f| f.frame == frame)?;- // Type on a path: the click lands on the line where it is along the path.++ // Map path-text hits along the curve before choosing the character unit.+ let inner = cs.frames.get(fi).and_then(|ft| compose::PathTextMap::new(it, ft)).map_or(inner, |m| m.to_line(inner));- if let Some((table, row, col, b)) = compose::hit_cell(&cs, fi, inner) {+ if let Some((table, row, col, b)) = compose::hit_cell_with(&cs, fi, inner, hit) {return Some((sid, b, Some(CellAddr { table, row, col })));}- if let Some((id, b)) = compose::hit_note(&cs, fi, inner) {+ if let Some((id, b)) = compose::hit_note_with(&cs, fi, inner, hit) {return Some((sid, b, Some(CellAddr::footnote(id))));}- let b = compose::hit(&cs, fi, inner).unwrap_or(0);+ let b = hit(&cs, fi, inner).unwrap_or(0);Some((sid, b, None))}@@@ -482,9 -385,7 +502,8 @@@ fn insert(s: &mut Session, p: &Value) -let text = if s.prefs.typographers_quotes && !raw { smart_quotes(s, &text) } else { text };let tracking = s.doc()?.doc.settings.track_changes;let autocorrect = (s.prefs.autocorrect && !tracking && !raw).then(|| s.prefs.autocorrect_list.clone());- s.edit(|d, sel| {+ let typing = typing_format(s).cloned();- s.typing_format = None;- s.edit(|d, sel| {++ let result = s.edit(|d, sel| {let t = sel.text.ok_or_else(|| bad("text.insert", "no insertion point"))?;let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?;let r = t.range();@@@ -562,7 -455,7 +581,11 @@@let pos = r.start + text.len() - trail;sel.text = Some(TextSel { anchor: pos, focus: pos, ..t });Ok(json!({"pos": pos}))-- })++ });++ if result.is_ok() {++ s.typing_format = None;++ }++ result}fn smart_quotes(s: &Session, text: &str) -> String {@@@ -739,6 -632,68 +762,62 @@@ pub fn prev_word(s: &str, i: usize) ->}0}-fn word_bounds(s: &str, i: usize) -> (usize, usize) {- let a = s[..i.min(s.len())].char_indices().rev().take_while(|(_, c)| is_word(*c)).last().map(|(k, _)| k).unwrap_or(i);- let b = s[i.min(s.len())..].char_indices().find(|(_, c)| !is_word(*c)).map(|(k, _)| i + k).unwrap_or(s.len());- (a, b)-}-+ /// Selects `bounds(text, byte)` around the byte under `point` in `frame`. Unlike a caret+ /// placement, a press inside the current selection is no start of a text drag here: it is the+ /// third or later click of a row, which lands in the word or sentence just selected.+ fn select_around(s: &mut Session, p: &Value, id: &str, bounds: fn(&str, usize) -> (usize, usize)) -> Result<Value> {+ let frame = id_param(p, "frame").ok_or_else(|| bad(id, "missing frame"))?;+ let pt = point_param(p, "point").unwrap_or(Point::ZERO);+ let (sid, b, cell) = hit_byte(s, frame, pt).ok_or_else(|| bad(id, "not a text frame"))?;+ let st = s.doc_mut()?;+ let text = st.doc.text_story(sid, cell).map(|x| x.text.clone()).unwrap_or_default();+ let (anchor, focus) = bounds(&text, floor_char_boundary(&text, b));+ st.selection = Selection::text(TextSel { story: sid, anchor, focus, frame: Some(frame), cell });+ st.revision += 1;+ Ok(json!({"story": sid.0, "anchor": anchor, "focus": focus}))+ }++ /// The paragraph around byte `i`, without its `\n`.+ fn para_bounds(s: &str, i: usize) -> (usize, usize) {+ let i = i.min(s.len());+ let a = s.get(..i).and_then(|t| t.rfind('\n')).map_or(0, |k| k + 1);+ let b = s.get(i..).and_then(|t| t.find('\n')).map_or(s.len(), |k| i + k);+ (a, b)+ }++ /// The sentence around byte `i`, within its paragraph: it ends after `.`, `!`, `?` or `…` (and+ /// any closing quotes or brackets) followed by a space or the paragraph end, or after a CJK full+ /// stop, and takes the spaces after it, as deleting a sentence should leave none behind.+ fn sentence_bounds(s: &str, i: usize) -> (usize, usize) {+ let (pa, pb) = para_bounds(s, i);+ let para = s.get(pa..pb).unwrap_or("");+ let mut start = 0;+ let mut it = para.char_indices().peekable();+ while let Some((_, c)) = it.next() {+ let cjk = matches!(c, '。' | '!' | '?');+ if !cjk && !matches!(c, '.' | '!' | '?' | '…') {+ continue;+ }+ while it.peek().is_some_and(|&(_, c)| {+ matches!(c, '.' | '!' | '?' | '…' | '。' | '!' | '?' | '"' | '\'' | '”' | '’' | '»' | '›' | ')' | ']' | '」' | '』' | ')')+ }) {+ it.next();+ }+ if !cjk && it.peek().is_some_and(|&(_, c)| !c.is_whitespace()) {+ continue;+ }+ while it.peek().is_some_and(|&(_, c)| c.is_whitespace()) {+ it.next();+ }+ let end = it.peek().map_or(para.len(), |&(k, _)| k);+ if pa + end > i || end == para.len() {+ return (pa + start, pa + end);+ }+ start = end;+ }+ (pa + start, pb)+ }+/// Type ▸ Story Direction.fn story_direction(s: &mut Session, p: &Value) -> Result<Value> {let vertical = p.get("vertical").and_then(Value::as_bool).ok_or_else(|| bad("type.storyDirection", "missing vertical"))?;@@@ -951,24 -905,31 +1042,25 @@@ pub(crate) fn format_chars(s: &mut Sessa.set_json(k, v).map_err(|e| bad("type.char", e))?;}}+ validate_char_fill(&s.doc()?.doc, &a, "type.char")?;let cleared: Vec<String> = attrs.as_object().map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect()).unwrap_or_default();let targets = format_targets(s);+ // A caret in text: the format is for the next typing.+ if let [t] = targets.as_slice()+ && t.range.is_empty()+ && let Some(at) = s.doc()?.selection.text+ && s.doc()?.doc.text_story(t.story, t.cell).is_some_and(|st| !st.is_empty())+ {+ let doc = s.doc()?.uid;+ let mut f = typing_format(s).cloned().unwrap_or(TypingFormat { doc, at, attrs: CharAttrs::default(), cleared: vec![] });+ f.attrs.merge(&a);+ f.cleared.retain(|k| attrs.get(k).is_none_or(|v| v.is_null()) && !cleared.contains(k));+ f.cleared.extend(cleared);+ s.typing_format = Some(f);+ return ok();+ }s.edit(|d, _| {- for t in &targets {- let r = &t.range;- let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };- if r.is_empty() {- // Caret: change the typing format (the empty run at the caret).- let pos = r.start;- if st.is_empty() {- st.chars[0].format.over.merge(&a);- st.rev += 1;- } else {- let _ = pos;- }- continue;- }- st.format_chars(r.clone(), |f| {- f.over.merge(&a);- for k in &cleared {- let _ = f.over.set_json(k, &Value::Null);- }- });- }+ apply_char_attrs(d, &targets, &a, &cleared);ok()})}@@@ -1108,76 -1056,14 +1211,178 @@@ fn selection_attrs(s: &mut Session, _plet pi = story.para_at(r.start);let pf = &story.paras[pi];let (pp, base) = st.doc.styles.resolve_para(pf);- let mut cf = if r.is_empty() { story.char_format_at(r.start) } else { story.format_after(r.start) }.clone();- if let Some(f) = typing_format(s) {- apply_typing_format(&mut cf, f);- }- let cf = if r.is_empty() { story.char_format_at(r.start) } else { story.format_after(r.start) };- let cp = st.doc.styles.resolve_char(&base, cf);- // The selected text (its start, on one line), for previews such as the font menu's.++ let cf = effective_char_format(s, &Target { story: sid, cell, range: r.clone() })?;+ let cp = st.doc.styles.resolve_char(&base, &cf);+ let selected = selected_text_preview(story.text.get(r.start..r.end).unwrap_or_default().chars());Ok(json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,- "paraOverrides": pf.para.count(), "charOverrides": cf.over.count()}))+ "paraOverrides": pf.para.count(), "charOverrides": cf.over.count(), "selectedText": selected.trim()}))+ }+++/// The first target character, with any pending caret overrides. Keep character-style++/// inheritance separate from paragraph defaults for style creation from the selection.++pub(crate) fn effective_char_format(s: &Session, target: &Target) -> Result<designcraft_doc::CharFormat> {++ let story = s.doc()?.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;++ let mut format = if target.range.is_empty() { story.char_format_at(target.range.start) } else { story.format_after(target.range.start) }.clone();++ if let Some(pending) = typing_format(s)++ && target.story == pending.at.story++ && target.cell == pending.at.cell++ && target.range == pending.at.range()++ {++ apply_typing_format(&mut format, pending);++ }++ Ok(format)++}++++/// A swatch promoted to a named color keeps any not-yet-inserted text pointing at it.++pub(crate) fn rename_typing_swatch(s: &mut Session, from: &str, to: &str) {++ let Some(uid) = s.active().map(|st| st.uid) else { return };++ if let Some(pending) = &mut s.typing_format++ && pending.doc == uid++ {++ for name in [&mut pending.attrs.fill, &mut pending.attrs.stroke, &mut pending.attrs.underline_color, &mut pending.attrs.strikethrough_color]++ .into_iter()++ .flatten()++ {++ if name == from {++ *name = to.to_string();++ }++ }++ }++}++++fn swapped_colors(cp: &designcraft_doc::CharProps) -> CharAttrs {++ CharAttrs {++ fill: Some(cp.stroke.clone()),++ fill_tint: Some(cp.stroke_tint),++ stroke: Some(cp.fill.clone()),++ stroke_tint: Some(cp.fill_tint),++ ..Default::default()++ }++}++++/// Resolve each paragraph/run before editing: a mixed selection must not take the first run's colors.++fn swap_fill_stroke(s: &mut Session, _p: &Value) -> Result<Value> {++ const ID: &str = "type.swapFillStroke";++ let targets = format_targets(s);++ if let [target] = targets.as_slice()++ && target.range.is_empty()++ && s.doc()?.selection.text.is_some()++ {++ let st = s.doc()?;++ let story = st.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;++ let pf = story.paras.get(story.para_at(target.range.start)).ok_or_else(|| bad(ID, "missing paragraph"))?;++ let (_, base) = st.doc.styles.resolve_para(pf);++ let cp = st.doc.styles.resolve_char(&base, &effective_char_format(s, target)?);++ return format_chars(s, &json!({"fill": cp.stroke, "fillTint": cp.stroke_tint, "stroke": cp.fill, "strokeTint": cp.fill_tint}));++ }++ let mut edits = Vec::new();++ let d = &s.doc()?.doc;++ for target in targets {++ let story = d.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;++ if story.is_empty() {++ let pf = story.paras.first().ok_or_else(|| bad(ID, "missing paragraph"))?;++ let (_, base) = d.styles.resolve_para(pf);++ let attrs = swapped_colors(&d.styles.resolve_char(&base, story.char_format_at(0)));++ validate_char_fill(d, &attrs, ID)?;++ edits.push((target, attrs));++ continue;++ }++ let mut runs = story.runs().peekable();++ for (pi, para) in story.para_ranges().into_iter().enumerate() {++ let start = para.start.max(target.range.start);++ let end = para.end.saturating_add(1).min(story.len()).min(target.range.end);++ if start >= end {++ continue;++ }++ let pf = story.paras.get(pi).ok_or_else(|| bad(ID, "missing paragraph"))?;++ let (_, base) = d.styles.resolve_para(pf);++ while let Some((range, format)) = runs.peek() {++ if range.end <= start {++ runs.next();++ continue;++ }++ if range.start >= end {++ break;++ }++ let attrs = swapped_colors(&d.styles.resolve_char(&base, format));++ validate_char_fill(d, &attrs, ID)?;++ edits.push((Target { range: start.max(range.start)..end.min(range.end), ..target.clone() }, attrs));++ if range.end > end {++ break;++ }++ runs.next();++ }++ }++ }++ s.edit(|d, _| {++ for (target, attrs) in &edits {++ apply_char_attrs(d, std::slice::from_ref(target), attrs, &[]);++ }++ ok()++ })+}++fn apply_typing_format(cf: &mut designcraft_doc::CharFormat, f: &TypingFormat) {+ cf.over.merge(&f.attrs);+ for k in &f.cleared {+ let _ = cf.over.set_json(k, &Value::Null);+ }+}++/// Bold (`bold`) or italic from the font family (style linking), per run of the selection: on or+/// off as asked, else the opposite of the first selected character.+fn link_style(s: &mut Session, p: &Value, bold: bool) -> Result<Value> {+ let id = if bold { "type.bold" } else { "type.italic" };+ let cur = selection_attrs(s, &json!({}))?;+ let family = cur["chars"]["fontFamily"].as_str().unwrap_or_default().to_string();+ let style = cur["chars"]["fontStyle"].as_str().unwrap_or_default().to_string();+ // The document's own fonts count too.+ let db = designcraft_fonts::FontDb::global().scoped(s.doc()?.doc.font_scope);+ let (weight, italic) = db.traits_of(&family, &style);+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(if bold { weight < 650.0 } else { !italic });+ let (want_bold, want_italic) = if bold { (Some(on), None) } else { (None, Some(on)) };+ let targets = format_targets(s);+ // A caret: the linked style of the format there, for the next typing.+ if let [t] = targets.as_slice()+ && t.range.is_empty()+ {+ let linked = db.linked_style(&family, &style, want_bold, want_italic).ok_or_else(|| bad(id, format!("{family} has no style for that")))?;+ format_chars(s, &json!({"fontStyle": linked}))?;+ return Ok(json!({"on": on, "fontStyle": linked}));+ }+ let mut changed = 0;+ let r = s.edit(|d, _| {+ let styles = d.styles.clone();+ for t in &targets {+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };+ for (pi, pr) in st.para_ranges().into_iter().enumerate() {+ let (a, b) = (pr.start.max(t.range.start), pr.end.min(t.range.end));+ if a >= b {+ continue;+ }+ let Some(pf) = st.paras.get(pi) else { continue };+ let (_, pc) = styles.resolve_para(pf);+ st.format_chars(a..b, |f| {+ let cp = styles.resolve_char(&pc, f);+ if let Some(linked) = db.linked_style(&cp.font_family, &cp.font_style, want_bold, want_italic)+ && linked != cp.font_style+ {+ f.over.font_style = Some(linked);+ changed += 1;+ }+ });+ }+ }+ // No undo step for nothing.+ if changed == 0 {+ return Err(bad(id, "nothing to change"));+ }+ ok()+ });+ r?;+ Ok(json!({"on": on, "changed": changed}))+}+/// Our own filler text (not Adobe's).pub const PLACEHOLDER: &str = "Ovid ellum quisque arcet velut tempora sint, ne veriora pareant laudemque fieri. Lorem novum strata ponet amicos, \et tamen uti ferrum caelo tempus mollit. Quisque sinat oppida retro, nec tenuere longas animi semper vias. \@@@ -2286,3 -2007,44 +2522,44 @@@ mod story_query_contract_testsassert_eq!(s.execute("story.get", &json!({})).unwrap()["text"], "");}}++ #[cfg(test)]-mod multi_click_tests {++mod sentence_selection_tests {+ use super::{para_bounds, sentence_bounds};++ fn sentence(s: &str, at: &str) -> String {+ let i = s.find(at).unwrap();+ let (a, b) = sentence_bounds(s, i);+ s[a..b].to_string()+ }++ #[test]+ fn sentences_end_at_a_stop_before_a_space_or_the_paragraph_end() {+ let s = "It costs 3.5 euros. \u{201C}Really?\u{201D} (Twice!) Yes\u{2026} fine.\nNext one. Last";+ assert_eq!(sentence(s, "costs"), "It costs 3.5 euros. ");+ assert_eq!(sentence(s, "Really"), "\u{201C}Really?\u{201D} ");+ assert_eq!(sentence(s, "Twice"), "(Twice!) ");+ assert_eq!(sentence(s, "Yes"), "Yes\u{2026} ");+ assert_eq!(sentence(s, "fine"), "fine.");+ assert_eq!(sentence(s, "one"), "Next one. ");+ assert_eq!(sentence(s, "Last"), "Last");+ // The caret at the very end of a paragraph is in its last sentence.+ let end = s.find('\n').unwrap();+ assert_eq!(sentence_bounds(s, end), (s.find("fine").unwrap(), end));+ }++ #[test]+ fn cjk_full_stops_end_sentences_without_a_space() {+ let s = "これは文です。次の文!最後";+ assert_eq!(sentence(s, "次"), "次の文!");+ assert_eq!(sentence(s, "最後"), "最後");+ }++ #[test]+ fn paragraphs_stop_at_returns() {+ let s = "One.\nTwo two.\n";+ assert_eq!(para_bounds(s, 6), (5, 13));+ assert_eq!(para_bounds(s, 0), (0, 4));+ assert_eq!(para_bounds(s, s.len()), (s.len(), s.len()));+ }+ }diff --cc crates/engine/src/cmd/text_color_tests.rsindex 000000000,000000000..5f2c35765new file mode 100644--- /dev/null+++ b/crates/engine/src/cmd/text_color_tests.rs@@@ -1,0 -1,0 +1,181 @@@++//! Cross-command caret color and character-style regressions.++use crate::Session;++use designcraft_doc::StoryId;++use serde_json::{Value, json};++++fn setup(text: &str) -> (Session, u64) {++ let mut s = Session::new();++ s.execute("file.new", &json!({})).unwrap();++ let f = s.execute("frame.create", &json!({"rect": [36,36,300,200], "content":"text", "text":text})).unwrap();++ let sid = f["story"].as_u64().unwrap();++ s.execute("text.select", &json!({"story":sid,"anchor":text.len()})).unwrap();++ (s, sid)++}++fn attrs(s: &mut Session) -> Value {++ s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"].clone()++}++#[test]++fn integration_color_character_style_captures_pending_and_null() {++ let (mut s, sid) = setup("hello");++ s.execute("type.char", &json!({"size":30,"tracking":40,"fill":"[Paper]"})).unwrap();++ s.execute("style.character.create", &json!({"name":"Pending","fromSelection":true,"chars":{"tracking":null}})).unwrap();++ let a = &s.doc().unwrap().doc.styles.char_style("Pending").unwrap().chars;++ assert_eq!(a.size, Some(30.0));++ assert_eq!(a.fill.as_deref(), Some("[Paper]"));++ assert_eq!(a.tracking, None);++ assert_eq!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().text, "hello");++}++#[test]++fn integration_color_pending_follows_promoted_swatch() {++ for target in ["fill", "stroke"] {++ let (mut s, sid) = setup("hello");++ let old = s.execute("object.color", &json!({"color":"#123456","target":target})).unwrap()["swatch"].clone();++ s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();++ assert_eq!(attrs(&mut s)[target], "Brand");++ s.execute("text.insert", &json!({"text":"X"})).unwrap();++ let st = s.doc().unwrap().doc.story(StoryId(sid)).unwrap();++ let f = &st.format_after(5).over;++ assert_eq!(if target == "fill" { f.fill.as_deref() } else { f.stroke.as_deref() }, Some("Brand"));++ }++}++#[test]++fn integration_color_undo_discards_missing_pending_swatch() {++ let (mut s, sid) = setup("hello");++ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();++ s.execute("edit.undo", &json!({})).unwrap();++ assert!(s.doc().unwrap().doc.swatch(&old).is_none());++ assert_ne!(attrs(&mut s)["fill"], old);++ s.execute("text.insert", &json!({"text":"X"})).unwrap();++ assert_ne!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().format_after(5).over.fill.as_deref(), Some(old.as_str()));++}++#[test]++fn integration_color_empty_story_uses_one_undo_step() {++ let (mut s, sid) = setup("");++ let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();++ let n = s.doc().unwrap().history.undo.len();++ s.execute("object.color", &json!({"color":"#123456"})).unwrap();++ assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);++ let colored = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), colored);++ s.execute("text.insert", &json!({"text":"X"})).unwrap();++ assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().format_after(0).over.fill.is_some());++}++++#[test]++fn integration_color_swap_resolves_each_paragraph_and_keeps_unselected_text() {++ let (mut s, sid) = setup("ab\ncd");++ for (name, fill, stroke, ft, st, start, end) in++ [("First", "[Paper]", "[Black]", 0.2, 0.8, 0, 2), ("Second", "[Black]", "[Paper]", 0.4, 0.6, 3, 5)]++ {++ s.execute("style.paragraph.create", &json!({"name":name,"chars":{"fill":fill,"stroke":stroke,"fillTint":ft,"strokeTint":st}})).unwrap();++ s.execute("text.select", &json!({"story":sid,"anchor":start,"focus":end})).unwrap();++ s.execute("style.paragraph.apply", &json!({"name":name})).unwrap();++ }++ s.execute("text.select", &json!({"story":sid,"anchor":1,"focus":4})).unwrap();++ let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();++ let n = s.doc().unwrap().history.undo.len();++ s.execute("type.swapFillStroke", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().history.undo.len(), n + 1);++ for (pos, fill, stroke, ft, st) in [++ (0, "[Paper]", "[Black]", 0.2, 0.8),++ (1, "[Black]", "[Paper]", 0.8, 0.2),++ (2, "[Black]", "[Paper]", 0.8, 0.2),++ (3, "[Paper]", "[Black]", 0.6, 0.4),++ (4, "[Black]", "[Paper]", 0.4, 0.6),++ ] {++ s.execute("text.select", &json!({"story":sid,"anchor":pos,"focus":pos+1})).unwrap();++ let a = attrs(&mut s);++ assert_eq!(a["fill"], fill);++ assert_eq!(a["stroke"], stroke);++ assert!((a["fillTint"].as_f64().unwrap() - ft).abs() < 1e-6);++ assert!((a["strokeTint"].as_f64().unwrap() - st).abs() < 1e-6);++ }++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);++}++++#[test]++fn integration_color_swap_caret_applies_only_to_next_typing() {++ let (mut s, sid) = setup("hello");++ s.execute("type.char", &json!({"fill":"[Paper]","stroke":"[Black]","fillTint":0.2,"strokeTint":0.8})).unwrap();++ let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();++ s.execute("type.swapFillStroke", &json!({})).unwrap();++ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);++ let a = attrs(&mut s);++ assert_eq!(a["fill"], "[Black]");++ assert_eq!(a["stroke"], "[Paper]");++ s.execute("text.insert", &json!({"text":"X"})).unwrap();++ let st = s.doc().unwrap().doc.story(StoryId(sid)).unwrap();++ assert_eq!(st.text, "helloX");++ assert_eq!(st.format_after(0).over.fill, None);++ assert_eq!(st.format_after(5).over.stroke.as_deref(), Some("[Paper]"));++ assert_eq!(st.format_after(5).over.fill_tint, Some(0.8));++}++++#[test]++fn integration_color_swap_selected_empty_cells_keeps_each_format() {++ let (mut s, sid) = setup("hello");++ let result = s.execute("table.insert", &json!({"rows":1,"cols":2})).unwrap();++ let tid = result["table"].as_u64().unwrap();++ s.edit(|d, _| {++ let table = std::sync::Arc::make_mut(d.story_mut(StoryId(sid)).unwrap().tables.get_mut(&tid).unwrap());++ for (c, fill, stroke) in [(0, "[Paper]", "[Black]"), (1, "[Black]", "[Paper]")] {++ let attrs = &mut table.cell_mut(0, c).unwrap().text.chars[0].format.over;++ attrs.fill = Some(fill.into());++ attrs.stroke = Some(stroke.into());++ }++ Ok(())++ })++ .unwrap();++ s.execute("table.select", &json!({"story":sid,"table":tid,"what":"table"})).unwrap();++ let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();++ s.execute("type.swapFillStroke", &json!({})).unwrap();++ let table = &s.doc().unwrap().doc.story(StoryId(sid)).unwrap().tables[&tid];++ assert_eq!(table.cell(0, 0).unwrap().text.chars[0].format.over.fill.as_deref(), Some("[Black]"));++ assert_eq!(table.cell(0, 1).unwrap().text.chars[0].format.over.fill.as_deref(), Some("[Paper]"));++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);++}++++#[test]++fn integration_color_failed_promotion_preserves_pending_and_history() {++ let (mut s, _) = setup("hello");++ s.execute("swatch.create", &json!({"name":"Brand","color":"#654321"})).unwrap();++ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].clone();++ let before = s.doc().unwrap().clone();++ let pending = attrs(&mut s);++ assert!(s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).is_err());++ assert_eq!(attrs(&mut s), pending);++ assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before.doc));++ assert_eq!(s.doc().unwrap().history.undo.len(), before.history.undo.len());++}++++#[test]++fn integration_color_promote_undo_redo_never_reuses_a_missing_pending_name() {++ let (mut s, _) = setup("hello");++ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].clone();++ s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();++ s.execute("edit.undo", &json!({})).unwrap();++ let fill = attrs(&mut s)["fill"].as_str().unwrap().to_string();++ assert!(s.doc().unwrap().doc.swatch(&fill).is_some());++ s.execute("edit.redo", &json!({})).unwrap();++ let fill = attrs(&mut s)["fill"].as_str().unwrap().to_string();++ assert!(s.doc().unwrap().doc.swatch(&fill).is_some());++}++++#[test]++fn integration_color_swap_validates_new_fill_before_any_edit() {++ let (mut s, sid) = setup("hello");++ s.execute("text.select", &json!({"story":sid,"anchor":0,"focus":5})).unwrap();++ s.execute("type.char", &json!({"fill":"[Paper]","stroke":"Missing Ink"})).unwrap();++ let before = s.doc().unwrap().clone();++ let journal = s.journal.clone();++ let error = s.execute("type.swapFillStroke", &json!({})).unwrap_err().to_string();++ assert!(error.contains("Missing Ink"), "{error}");++ assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before.doc));++ assert_eq!(s.doc().unwrap().history.undo.len(), before.history.undo.len());++ assert_eq!(s.journal, journal);++}diff --cc crates/engine/src/cmd/thread.rsindex 8cedac277,000000000..bdc2ffafdmode 100644,000000..100644--- a/crates/engine/src/cmd/thread.rs+++ b/crates/engine/src/cmd/thread.rs@@@ -1,379 -1,0 +1,396 @@@+//! Threading text frames: thread a frame after another (their stories merge), break a thread,+//! take a frame out of its thread. The Selection tool's loaded text cursor runs these.++use designcraft_doc::{Document, ItemId, ParaFormat, Selection, StoryId};+use designcraft_geom::Rect;+use serde_json::{Value, json};++use super::{CommandSpec, bad, bool_or, cmd, has_doc, id_param, rect_param, spread_param, str_param};+use crate::{Result, Session};++/// Pages Shift-click autoflow may add before it gives up.+const AUTOFLOW_MAX_PAGES: usize = 2000;++pub fn specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "text.thread",+ "Thread Text Frames",+ [],+ None,+ "{from?, to?, rect?: [x0,y0,x1,y1] (spread coords), spread?, autoflow?: bool} — threads frame `to` right after frame `from` (between `from` and the frame that followed it, if any). `to` is an empty frame or a text frame nothing threads into yet; its text joins the end of the story. Give `rect` in place of `from` or `to` to thread a new text frame made there on `spread`: `{from, rect}` adds it after `from`, `{rect, to}` in front of `to`. autoflow: then add pages with threaded frames until the story fits. Selects the frame that joined the thread. → {story, from, to, overset, pagesAdded}",+ has_doc,+ thread+ ),+ cmd!(+ "text.unthread",+ "Break Thread",+ [],+ None,+ "{frame?, side?: after|before} — breaks the thread after (or before) `frame` (default: the selected text frame). The frames from the break on stay threaded to each other but become empty; the text stays in the story, overset if the earlier frames can't hold it",+ has_doc,+ unthread+ ),+ cmd!(+ "text.removeFromThread",+ "Remove Frame from Thread",+ [],+ None,+ "{frame?} — takes `frame` (default: the selected text frame) out of its thread: the frames before and after it join up and keep the text, `frame` stays empty",+ has_doc,+ remove_from_thread+ ),+ ]+}++/// `frame` param, or the first selected text frame.+fn frame_param(s: &Session, p: &Value, cmd: &str) -> Result<ItemId> {+ let st = s.doc()?;+ let id = id_param(p, "frame")+ .or_else(|| st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| it.is_text_frame())))+ .ok_or_else(|| bad(cmd, "no text frame given or selected"))?;+ if !st.doc.item(id).is_some_and(|it| it.is_text_frame()) {+ return Err(bad(cmd, format!("{id} is not a text frame")));+ }++ check_editable(&st.doc, id, cmd)?;+ Ok(id)+}+++fn check_editable(d: &Document, id: ItemId, cmd: &str) -> Result<()> {++ let it = d.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?;++ if it.locked || d.layer(it.layer).is_some_and(|l| l.locked) {++ return Err(bad(cmd, format!("{id} is locked or on a locked layer")));++ }++ Ok(())++}+++/// A rect param made safe for a frame: finite, ordered, at least half a point each way.+fn frame_rect(p: &Value) -> Result<Option<Rect>> {+ let Some(r) = rect_param(p, "rect") else { return Ok(None) };+ if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {+ return Err(bad("text.thread", "rect must be finite"));+ }+ let (x0, x1) = (r.x0.min(r.x1), r.x0.max(r.x1));+ let (y0, y1) = (r.y0.min(r.y1), r.y0.max(r.y1));+ Ok(Some(Rect::new(x0, y0, x1.max(x0 + 0.5), y1.max(y0 + 0.5))))+}++fn thread(s: &mut Session, p: &Value) -> Result<Value> {+ let (from, to, rect) = (id_param(p, "from"), id_param(p, "to"), frame_rect(p)?);- let sr = spread_param(p, "spread");++ let sr = spread_param(p, "spread")?;+ let autoflow = bool_or(p, "autoflow", false);+ let layer = s.doc()?.active_layer;+ s.edit(|d, sel| {+ let mut new_frame = || -> Result<ItemId> {+ let r = rect.ok_or_else(|| bad("text.thread", "give two of from, to and rect"))?;+ if d.layer(layer).is_none_or(|l| l.locked || !l.visible) {+ return Err(bad("text.thread", "the active layer is locked or hidden"));+ }+ let para = ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() };+ Ok(d.add_text_frame(sr, r, layer, "", para)?.0)+ };+ let (from, to, joined) = match (from, to) {+ (Some(f), Some(t)) if rect.is_none() => (f, t, t),+ (Some(f), None) => {+ let t = new_frame()?;+ (f, t, t)+ }+ (None, Some(t)) => {+ let f = new_frame()?;+ (f, t, f)+ }+ _ => return Err(bad("text.thread", "give two of from, to and rect")),+ };+ d.check_thread(from, to)?;+ d.thread_keeping_story(from, to)?;+ let sid = d.item(from).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad("text.thread", "threading lost the story"))?;+ let pages = if autoflow { super::place_text_autoflow(d, sid, AUTOFLOW_MAX_PAGES, "text.thread")? } else { 0 };+ *sel = Selection::items(vec![joined]);+ Ok(json!({"story": sid.0, "from": from.0, "to": to.0, "overset": overset(d, sid), "pagesAdded": pages}))+ })+}++fn overset(d: &Document, sid: StoryId) -> bool {+ designcraft_compose::compose_story(d, sid, &Default::default()).overset_at.is_some()+}++fn unthread(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "text.unthread";+ let frame = frame_param(s, p, CMD)?;+ let d0 = &s.doc()?.doc;+ let at = match str_param(p, "side").unwrap_or("after") {+ "after" => d0.next_frame(frame).map(|_| frame).ok_or_else(|| bad(CMD, format!("no frame follows {frame} in its thread")))?,+ "before" => d0.prev_frame(frame).ok_or_else(|| bad(CMD, format!("no frame comes before {frame} in its thread")))?,+ other => return Err(bad(CMD, format!("unknown side `{other}` (after, before)"))),+ };++ check_editable(d0, at, CMD)?;++ if let Some(next) = d0.next_frame(at) {++ check_editable(d0, next, CMD)?;++ }+ s.edit(|d, _| {+ d.unthread_after(at)?;+ let sid = d.item(at).and_then(|i| i.text_frame()).map(|t| t.story).ok_or_else(|| bad(CMD, "no story"))?;+ Ok(json!({"story": sid.0, "overset": overset(d, sid)}))+ })+}++fn remove_from_thread(s: &mut Session, p: &Value) -> Result<Value> {+ let frame = frame_param(s, p, "text.removeFromThread")?;++ let d = &s.doc()?.doc;++ for neighbour in [d.prev_frame(frame), d.next_frame(frame)].into_iter().flatten() {++ check_editable(d, neighbour, "text.removeFromThread")?;++ }+ s.edit(|d, _| {+ d.remove_from_thread(frame)?;+ Ok(json!({}))+ })+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use crate::Session;++ fn session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ s+ }++ fn text_frame(s: &mut Session, rect: [f64; 4], text: &str) -> (u64, u64) {+ let r = s.execute("frame.create", &json!({"rect": rect, "content": "text", "text": text, "caret": false})).unwrap();+ (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())+ }++ fn story(s: &mut Session, frame: u64) -> serde_json::Value {+ s.execute("story.get", &json!({"frame": frame})).unwrap()+ }++ fn frames(s: &mut Session, frame: u64) -> Vec<u64> {+ story(s, frame)["frames"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect()+ }++ const LONG: &str = "Threaded text keeps flowing from one frame into the next one. ";++ #[test]+ fn thread_into_an_empty_frame_and_undo() {+ let mut s = session();+ let (a, sid) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(10));+ let b = s.execute("frame.create", &json!({"rect": [72, 300, 200, 400], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ assert!(!story(&mut s, a)["overset"].is_null(), "the first frame is overset");+ let r = s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ assert_eq!(r["story"].as_u64(), Some(sid));+ assert_eq!(frames(&mut s, a), [a, b]);+ let d = &s.doc().unwrap().doc;+ assert!(d.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());+ assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(b)]);+ // The text now reaches the second frame.+ let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, designcraft_doc::StoryId(sid), &Default::default());+ assert!(cs.frames.iter().any(|f| f.frame.0 == b && !f.range.is_empty()), "text flows into the new frame");+ s.doc().unwrap().doc.check().unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(frames(&mut s, a), [a]);+ assert!(!s.doc().unwrap().doc.item(designcraft_doc::ItemId(b)).unwrap().is_text_frame());+ }++ #[test]+ fn thread_into_a_text_frame_merges_its_story() {+ let mut s = session();+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 200.0], "First");+ let (b, sb) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "Second");+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ let st = story(&mut s, b);+ assert_eq!(st["id"].as_u64(), Some(sa));+ assert_eq!(st["text"], "First\nSecond");+ assert!(s.doc().unwrap().doc.story(designcraft_doc::StoryId(sb)).is_none());+ s.doc().unwrap().doc.check().unwrap();+ }++ #[test]+ fn thread_into_the_middle_of_a_thread() {+ let mut s = session();+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));+ let (c, _) = text_frame(&mut s, [72.0, 500.0, 200.0, 600.0], "");+ s.execute("text.thread", &json!({"from": a, "to": c})).unwrap();+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ assert_eq!(frames(&mut s, a), [a, b, c]);+ s.doc().unwrap().doc.check().unwrap();+ }++ #[test]+ fn bad_threads_are_errors_and_change_nothing() {+ let mut s = session();+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], "a");+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "b");+ let (x, _) = text_frame(&mut s, [300.0, 72.0, 400.0, 120.0], "x");+ let (y, _) = text_frame(&mut s, [300.0, 300.0, 400.0, 400.0], "y");+ let g = s.execute("line.create", &json!({"a": [300, 500], "b": [400, 600]})).unwrap()["id"].as_u64().unwrap();+ let group = {+ let p = s.execute("frame.create", &json!({"rect": [500, 500, 550, 550], "content": "unassigned"})).unwrap()["id"].clone();+ let q = s.execute("frame.create", &json!({"rect": [560, 500, 600, 550], "content": "unassigned"})).unwrap()["id"].clone();+ s.execute("selection.set", &json!({"ids": [p, q]})).unwrap();+ s.execute("object.group", &json!({})).unwrap();+ s.doc().unwrap().selection.items[0].0+ };+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ s.execute("text.thread", &json!({"from": x, "to": y})).unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ let doc = s.doc().unwrap().doc.clone();+ for p in [+ json!({"from": a, "to": a}),+ json!({"from": a, "to": g}),+ json!({"from": g, "to": a}),+ json!({"from": a, "to": group}),+ // Earlier in the same thread.+ json!({"from": b, "to": a}),+ // Text already flows into y from x.+ json!({"from": a, "to": y}),+ json!({"from": a, "to": 999_999}),+ json!({"from": a}),+ json!({"from": a, "to": b, "rect": [0, 0, 10, 10]}),+ json!({"rect": [0, 0, 10, 10]}),+ json!({"from": a, "rect": [0, 0, 10, 10], "spread": 99}),+ json!({"from": "a", "to": [1]}),+ json!([1, 2]),+ ] {+ assert!(s.execute("text.thread", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ assert_eq!(*s.doc().unwrap().doc, *doc);+ }++ #[test]+ fn locked_frames_and_layers_refuse_threads() {+ let mut s = session();+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));+ let (b, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 400.0], "");+ let layer = s.doc().unwrap().active_layer.0;+ let undo = s.doc().unwrap().history.undo.len();+ s.execute("object.lock", &json!({"ids": [b]})).unwrap();+ assert!(s.execute("text.thread", &json!({"from": a, "to": b})).is_err(), "locked frame");+ assert!(s.execute("text.thread", &json!({"from": b, "to": a})).is_err(), "locked frame");+ s.execute("edit.undo", &json!({})).unwrap();+ for (set, rect) in [(json!({"locked": true}), false), (json!({"locked": true}), true), (json!({"visible": false}), true)] {+ let mut p = json!({"id": layer});+ p.as_object_mut().unwrap().extend(set.as_object().unwrap().clone());+ s.execute("layer.set", &p).unwrap();+ let t = if rect { json!({"from": a, "rect": [300, 300, 400, 400]}) } else { json!({"from": a, "to": b}) };+ assert!(s.execute("text.thread", &t).is_err(), "{p} {t}");+ s.execute("edit.undo", &json!({})).unwrap();+ }+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ assert_eq!(frames(&mut s, a), [a]);+ }++ #[test]+ fn thread_a_new_frame_after_or_in_front() {+ let mut s = session();+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &LONG.repeat(8));+ let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 200, 400]})).unwrap();+ let n = r["to"].as_u64().unwrap();+ assert_eq!(frames(&mut s, a), [a, n]);+ assert_eq!(s.doc().unwrap().selection.items, [designcraft_doc::ItemId(n)]);+ let b = s.doc().unwrap().doc.item(designcraft_doc::ItemId(n)).unwrap().bounds();+ assert_eq!(b, Rect::new(72.0, 300.0, 200.0, 400.0));+ // In front of the first frame: the story keeps its id and text.+ let r = s.execute("text.thread", &json!({"rect": [300, 72, 400, 120], "to": a})).unwrap();+ let m = r["from"].as_u64().unwrap();+ assert_eq!(r["story"].as_u64(), Some(sa));+ assert_eq!(frames(&mut s, a), [m, a, n]);+ assert_eq!(story(&mut s, a)["text"], LONG.repeat(8));+ s.doc().unwrap().doc.check().unwrap();+ // One undo step each.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(frames(&mut s, a), [a, n]);+ }++ use designcraft_geom::Rect;++ #[test]+ fn thread_with_autoflow_adds_pages_until_the_text_fits() {+ let mut s = session();+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 300.0, 200.0], &LONG.repeat(300));+ let r = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "autoflow": true})).unwrap();+ assert_eq!(r["overset"], false);+ assert!(r["pagesAdded"].as_u64().unwrap() >= 1, "{r}");+ assert!(frames(&mut s, a).len() >= 3);+ s.doc().unwrap().doc.check().unwrap();+ // One undo removes the frames and the pages.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(frames(&mut s, a), [a]);+ assert_eq!(s.doc().unwrap().doc.page_count(), 2);+ }++ #[test]+ fn autoflow_from_a_parent_frame_is_an_error() {+ let mut s = session();+ let parent = json!({"kind": "parent", "index": 0});+ let r = s.execute(+ "frame.create",+ &json!({"rect": [72, 72, 300, 200], "content": "text", "text": LONG.repeat(300), "caret": false, "spread": parent}),+ );+ let a = r.unwrap()["id"].as_u64().unwrap();+ let undo = s.doc().unwrap().history.undo.len();+ let doc = s.doc().unwrap().doc.clone();+ let e = s.execute("text.thread", &json!({"from": a, "rect": [72, 300, 300, 700], "spread": parent, "autoflow": true})).unwrap_err();+ assert!(e.to_string().contains("text.thread"), "{e}");+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);+ assert_eq!(*s.doc().unwrap().doc, *doc);+ assert_eq!(s.doc().unwrap().doc.page_count(), 2);+ }++ #[test]+ fn unthread_after_and_before() {+ let mut s = session();+ let text = LONG.repeat(12);+ let (a, sa) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);+ let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");+ let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();+ // Break after the first frame: b and c stay threaded to each other, empty.+ let r = s.execute("text.unthread", &json!({"frame": a})).unwrap();+ assert_eq!(r["story"].as_u64(), Some(sa));+ assert_eq!(r["overset"], true);+ assert_eq!(frames(&mut s, a), [a]);+ assert_eq!(story(&mut s, a)["text"], text);+ assert_eq!(frames(&mut s, b), [b, c]);+ assert_eq!(story(&mut s, b)["text"], "");+ s.doc().unwrap().doc.check().unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(frames(&mut s, a), [a, b, c]);+ // Break before the last frame, with the frame selected.+ s.execute("selection.set", &json!({"ids": [c]})).unwrap();+ s.execute("text.unthread", &json!({"side": "before"})).unwrap();+ assert_eq!(frames(&mut s, a), [a, b]);+ assert_eq!(frames(&mut s, c), [c]);+ // Nothing to break.+ assert!(s.execute("text.unthread", &json!({"frame": b})).is_err());+ assert!(s.execute("text.unthread", &json!({"frame": a, "side": "before"})).is_err());+ assert!(s.execute("text.unthread", &json!({"frame": a, "side": "sideways"})).is_err());+ assert!(s.execute("text.unthread", &json!({"frame": 999_999})).is_err());+ }++ #[test]+ fn deleting_or_removing_a_threaded_frame_keeps_the_text_flowing() {+ let mut s = session();+ let text = LONG.repeat(12);+ let (a, _) = text_frame(&mut s, [72.0, 72.0, 200.0, 120.0], &text);+ let (b, _) = text_frame(&mut s, [72.0, 200.0, 200.0, 250.0], "");+ let (c, _) = text_frame(&mut s, [72.0, 300.0, 200.0, 350.0], "");+ s.execute("text.thread", &json!({"from": a, "to": b})).unwrap();+ s.execute("text.thread", &json!({"from": b, "to": c})).unwrap();+ s.execute("text.removeFromThread", &json!({"frame": b})).unwrap();+ assert_eq!(frames(&mut s, a), [a, c]);+ assert_eq!(story(&mut s, a)["text"], text);+ assert_eq!(story(&mut s, b)["text"], "");+ assert!(s.execute("text.removeFromThread", &json!({"frame": b})).is_err());+ s.execute("edit.undo", &json!({})).unwrap();+ s.execute("edit.clear", &json!({"ids": [b]})).unwrap();+ assert_eq!(frames(&mut s, a), [a, c]);+ assert_eq!(story(&mut s, a)["text"], text);+ s.doc().unwrap().doc.check().unwrap();+ }+}diff --cc crates/engine/tests/primary_frame_columns.rsindex 000000000,000000000..1a08a7081new file mode 100644--- /dev/null+++ b/crates/engine/tests/primary_frame_columns.rs@@@ -1,0 -1,0 +1,34 @@@++//! Primary text frames retain all columns supported by the new-document command.++use designcraft_doc::Document;++use designcraft_engine::Session;++use serde_json::json;++++fn assert_primary_columns(doc: &Document, expected: u32) {++ let mut frames = 0;++ for story in doc.stories.values() {++ for spec in designcraft_compose::frame_specs(doc, story.id) {++ assert_eq!(spec.opts.columns, expected);++ let columns = spec.columns();++ assert_eq!(columns.len(), expected as usize);++ assert!(columns.iter().all(|r| r.width() > 0. && [r.x0, r.x1, r.y0, r.y1].into_iter().all(f64::is_finite)));++ frames += 1;++ }++ }++ assert!(frames > 0, "the primary text frame must exist");++}++++#[test]++fn primary_columns_survive_composition_native_reopen_and_idml_round_trip() {++ for columns in [41, 216] {++ let mut s = Session::new();++ s.execute("file.new", &json!({"columns":columns,"gutter":0,"primaryTextFrame":true})).unwrap();++ assert_primary_columns(&s.doc().unwrap().doc, columns);++ let bytes = s.execute("file.serialize", &json!({})).unwrap();++ let mut reopened = Session::new();++ reopened.execute("file.openBytes", &json!({"name":"primary-columns.designcraft","base64":bytes["base64"]})).unwrap();++ assert_primary_columns(&reopened.doc().unwrap().doc, columns);++ let idml = designcraft_idml::export_idml(&reopened.doc().unwrap().doc);++ let imported = designcraft_idml::import_idml(&idml).unwrap();++ assert_primary_columns(&imported, columns);++ }++}diff --cc crates/engine/tests/text_thread_regressions.rsindex 000000000,000000000..2bca1b06dnew file mode 100644--- /dev/null+++ b/crates/engine/tests/text_thread_regressions.rs@@@ -1,0 -1,0 +1,277 @@@++use designcraft_doc::{ParaFormat, Story, StoryId};++use designcraft_engine::Session;++use serde_json::{Value, json};++use std::sync::Arc;++fn setup() -> Session {++ let mut s = Session::new();++ s.execute("file.new", &json!({})).unwrap();++ s++}++fn frame(s: &mut Session, text: &str) -> (u64, u64) {++ let r = s.execute("frame.create", &json!({"rect":[72,72,300,300],"content":"text","text":text,"caret":false})).unwrap();++ (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap())++}++fn snapshot(s: &Session) -> Value {++ let d = s.doc().unwrap();++ json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":d.history.undo.len(),"redo":d.history.redo.len(),"journal":s.journal})++}++#[test]++fn rejected_thread_is_atomic_with_new_frame_and_redo() {++ let mut s = setup();++ let (a, _) = frame(&mut s, "hello");++ frame(&mut s, "undo");++ s.execute("edit.undo", &json!({})).unwrap();++ let before = snapshot(&s);++ assert!(s.execute("text.thread", &json!({"from":999999,"rect":[0,0,100,100]})).is_err());++ assert_eq!(snapshot(&s), before);++ assert!(s.execute("text.thread", &json!({"from":a,"rect":[0,0,100,100],"spread":999})).is_err());++ assert_eq!(snapshot(&s), before);++}++#[test]++fn locked_frame_cannot_be_unthreaded() {++ let mut s = setup();++ let (a, _) = frame(&mut s, "hello");++ let (b, _) = frame(&mut s, "");++ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();++ s.execute("object.lock", &json!({"ids":[a]})).unwrap();++ let before = snapshot(&s);++ let r = s.execute("text.unthread", &json!({"frame":a}));++ assert!(r.is_err(), "unthread accepted locked frame: {r:?}");++ assert_eq!(snapshot(&s), before);++}++#[test]++fn locked_frame_cannot_be_removed_from_thread() {++ let mut s = setup();++ let (a, _) = frame(&mut s, "hello");++ let (b, _) = frame(&mut s, "");++ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();++ s.execute("object.lock", &json!({"ids":[a]})).unwrap();++ let before = snapshot(&s);++ let r = s.execute("text.removeFromThread", &json!({"frame":a}));++ assert!(r.is_err(), "remove accepted locked frame: {r:?}");++ assert_eq!(snapshot(&s), before);++}++#[test]++fn rejected_selection_preserves_pending_typing() {++ let mut s = setup();++ let (_, sid) = frame(&mut s, "hello");++ s.execute("text.select", &json!({"story":sid,"anchor":3})).unwrap();++ s.execute("type.char", &json!({"attrs":{"size":30}})).unwrap();++ let before = s.execute("type.selectionAttrs", &json!({})).unwrap();++ assert!(s.execute("text.select", &json!({"story":999999,"anchor":0})).is_err());++ let after = s.execute("type.selectionAttrs", &json!({})).unwrap();++ assert_eq!(after, before, "rejected selection reset pending typing");++}++#[test]++fn append_max_id_preserves_both_tables() {++ use designcraft_doc::table::Table;++ let mut a = Story::with_text(StoryId(1), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());++ let mut b = Story::with_text(StoryId(2), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());++ let mut ta = Table::new(u64::MAX, 1, 1, 0, 0, 100.);++ ta.cells[0].text = Story::with_text(StoryId(0), "ORIGINAL", ParaFormat::default());++ a.tables.insert(u64::MAX, Arc::new(ta));++ let mut tb = Table::new(1, 1, 1, 0, 0, 100.);++ tb.cells[0].text = Story::with_text(StoryId(0), "INCOMING", ParaFormat::default());++ b.tables.insert(1, Arc::new(tb));++ a.paras[0].table = Some(u64::MAX);++ b.paras[0].table = Some(1);++ a.check().unwrap();++ b.check().unwrap();++ a.append_story(b);++ let contents: Vec<_> = a.tables.values().map(|t| t.cells[0].text.text.clone()).collect();++ assert!(contents.contains(&"ORIGINAL".into()) && contents.contains(&"INCOMING".into()), "table loss: {contents:?}");++}++#[test]++fn idml_dropcap_detail_preserves_inherited_other_bit() {++ use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, build::NewDocument};++ let mut d = Document::new(&NewDocument::default());++ let parent = ParagraphStyle {++ name: "Parent".into(),++ based_on: None,++ next_style: None,++ para: ParaAttrs { drop_cap_align_left: Some(false), drop_cap_scale_descenders: Some(true), ..Default::default() },++ chars: Default::default(),++ shortcut: String::new(),++ };++ let child = ParagraphStyle {++ name: "Child".into(),++ based_on: Some("Parent".into()),++ next_style: None,++ para: ParaAttrs { drop_cap_scale_descenders: Some(false), ..Default::default() },++ chars: Default::default(),++ shortcut: String::new(),++ };++ d.styles_mut().paragraph.extend([parent, child]);++ let before = d.styles.resolve_para_style("Child").0;++ let bytes = designcraft_idml::export_idml(&d);++ let back = designcraft_idml::import_idml(&bytes).unwrap();++ let after = back.styles.resolve_para_style("Child").0;++ assert_eq!(++ (after.drop_cap_align_left, after.drop_cap_scale_descenders),++ (before.drop_cap_align_left, before.drop_cap_scale_descenders),++ "IDML export resets inherited align-left bit"++ );++}++#[test]++fn threading_preserves_incoming_text_hyperlink() {++ let mut s = setup();++ let (a, sa) = frame(&mut s, "First");++ let (b, sb) = frame(&mut s, "Second");++ s.execute("text.select", &json!({"story":sb,"anchor":0,"focus":6})).unwrap();++ s.execute("hyperlink.create", &json!({"url":"https://example.com"})).unwrap();++ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();++ let d = &s.doc().unwrap().doc;++ let back = designcraft_format::load(&designcraft_format::save(d).unwrap()).unwrap();++ match &back.hyperlinks[0].source {++ designcraft_doc::HyperlinkSource::Text { story, start, end } => {++ assert_eq!(story.0, sa, "hyperlink points to deleted incoming story");++ assert_eq!((*start, *end), (6, 12));++ }++ _ => panic!("wrong source"),++ };++}++#[test]++fn thread_cannot_destroy_body_by_joining_generated_endnotes() {++ let mut s = setup();++ let (body, sid) = frame(&mut s, "KEEP THIS BODY");++ s.execute("text.select", &json!({"story":sid,"anchor":14})).unwrap();++ let e = s.execute("endnote.insert", &json!({"text":"a note"})).unwrap();++ let ef = e["frame"].as_u64().unwrap();++ let before = snapshot(&s);++ let r = s.execute("text.thread", &json!({"from":ef,"to":body}));++ assert!(++ r.is_err(),++ "thread into generated endnotes accepted: {r:?}; stories: {:?}",++ s.doc().unwrap().doc.stories.values().map(|s| &s.text).collect::<Vec<_>>()++ );++ assert_eq!(snapshot(&s), before);++}++#[test]++fn generated_endnotes_accept_empty_extensions_but_reject_reverse_body_merge() {++ let mut s = setup();++ let (body, sid) = frame(&mut s, "Body");++ s.execute("text.select", &json!({"story":sid,"anchor":4})).unwrap();++ let r = s.execute("endnote.insert", &json!({"text":"note"})).unwrap();++ let ef = r["frame"].as_u64().unwrap();++ let esid = s.doc().unwrap().doc.endnote_story.unwrap();++ let before = snapshot(&s);++ assert!(s.execute("text.thread", &json!({"from":body,"to":ef})).is_err());++ assert_eq!(snapshot(&s), before);++ s.execute("text.thread", &json!({"from":ef,"rect":[72,72,300,300]})).unwrap();++ assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));++ s.execute("text.thread", &json!({"to":ef,"rect":[72,72,300,300]})).unwrap();++ assert_eq!(s.doc().unwrap().doc.endnote_story, Some(esid));++ assert_eq!(s.doc().unwrap().doc.story(esid).unwrap().frames.len(), 3);++ assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().text.starts_with("Body"));++ s.doc().unwrap().doc.check().unwrap();++}++#[test]++fn threading_moves_data_placeholders_and_primary_story_with_text() {++ use designcraft_doc::{Placeholder, PlaceholderAnchor, PlaceholderRole};++ let mut s = setup();++ let (a, sa) = frame(&mut s, "First");++ let (b, sb) = frame(&mut s, "<<name>>");++ s.edit(|d, _| {++ d.settings.primary_story = Some(StoryId(sb));++ d.data_merge.placeholders.push(Placeholder {++ id: 123,++ source_id: 0,++ field: "name".into(),++ role: PlaceholderRole::Text,++ anchor: PlaceholderAnchor::Text { story: StoryId(sb), start: 0, end: 8 },++ });++ Ok(())++ })++ .unwrap();++ let before = s.doc().unwrap().doc.clone();++ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();++ let d = &s.doc().unwrap().doc;++ assert_eq!(d.settings.primary_story, Some(StoryId(sa)));++ assert_eq!(d.data_merge.placeholders.len(), 1);++ assert_eq!(d.data_merge.placeholders[0].anchor, PlaceholderAnchor::Text { story: StoryId(sa), start: 6, end: 14 });++ let after = d.clone();++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, before);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(s.doc().unwrap().doc, after);++}++#[test]++fn append_max_ids_preserves_addressable_footnotes_and_endnotes() {++ let mut a = Story::with_text(StoryId(1), "A", ParaFormat::default());++ let mut b = Story::with_text(StoryId(2), "B", ParaFormat::default());++ a.insert_note(1, "original footnote", ParaFormat::default());++ b.insert_note(1, "incoming footnote", ParaFormat::default());++ Arc::make_mut(&mut a.notes[0]).id = u64::MAX;++ a.insert_endnote(1, "original endnote", ParaFormat::default());++ b.insert_endnote(1, "incoming endnote", ParaFormat::default());++ Arc::make_mut(&mut a.endnotes[0]).id = u64::MAX;++ a.check().unwrap();++ b.check().unwrap();++ a.append_story(b);++ a.check().unwrap();++ assert_ne!(a.notes[0].id, a.notes[1].id);++ assert_ne!(a.endnotes[0].id, a.endnotes[1].id);++ assert_eq!(a.notes[0].text.text, "original footnote");++ assert_eq!(a.endnotes[1].text.text, "incoming endnote");++}++#[test]++fn locked_layer_and_neighbour_reject_unthread_atomically() {++ for lock_layer in [false, true] {++ let mut s = setup();++ let (a, _) = frame(&mut s, "A");++ let (b, _) = frame(&mut s, "B");++ s.execute("text.thread", &json!({"from":a,"to":b})).unwrap();++ if lock_layer {++ let lid = s.doc().unwrap().active_layer.0;++ s.execute("layer.set", &json!({"id":lid,"locked":true})).unwrap();++ } else {++ s.execute("object.lock", &json!({"ids":[b]})).unwrap();++ }++ let before = snapshot(&s);++ assert!(s.execute("text.unthread", &json!({"frame":a})).is_err());++ assert_eq!(snapshot(&s), before);++ }++}++#[test]++fn idml_partial_dropcap_bits_resolve_both_style_and_paragraph_inheritance() {++ use designcraft_doc::{Document, ParaAttrs, ParagraphStyle, SpreadRef, build::NewDocument};++ use designcraft_geom::Rect;++ for parent_align in [false, true] {++ for parent_scale in [false, true] {++ for local_align in [false, true] {++ let mut d = Document::new(&NewDocument::default());++ d.styles_mut().paragraph.push(ParagraphStyle {++ name: "Parent".into(),++ based_on: None,++ next_style: None,++ para: ParaAttrs { drop_cap_align_left: Some(parent_align), drop_cap_scale_descenders: Some(parent_scale), ..Default::default() },++ chars: Default::default(),++ shortcut: String::new(),++ });++ let layer = d.default_layer();++ let (_, sid) = d++ .add_text_frame(++ SpreadRef::Doc(0),++ Rect::new(10., 10., 200., 200.),++ layer,++ "Body",++ ParaFormat {++ style: "Parent".into(),++ para: ParaAttrs { drop_cap_align_left: Some(local_align), ..Default::default() },++ ..Default::default()++ },++ )++ .unwrap();++ let bytes = designcraft_idml::export_idml(&d);++ let back = designcraft_idml::import_idml(&bytes).unwrap();++ let st = back.stories.values().find(|s| s.text == "Body").unwrap();++ let actual = back.styles.resolve_para(&st.paras[0]).0;++ let expected = d.styles.resolve_para(&d.story(sid).unwrap().paras[0]).0;++ assert_eq!(++ (actual.drop_cap_align_left, actual.drop_cap_scale_descenders),++ (expected.drop_cap_align_left, expected.drop_cap_scale_descenders)++ );++ }++ }++ }++}diff --cc crates/engine/tests/thread_color_safety.rsindex 000000000,000000000..501df92b9new file mode 100644--- /dev/null+++ b/crates/engine/tests/thread_color_safety.rs@@@ -1,0 -1,0 +1,223 @@@++//! Linked-story threading and text-color transaction safety.++use designcraft_doc::{ParaFormat, Story, StoryId, table::Table};++use designcraft_engine::Session;++use serde_json::{Value, json};++use std::sync::Arc;++++fn setup() -> Session {++ let mut s = Session::new();++ s.execute("file.new", &json!({})).unwrap();++ s++}++fn frame(s: &mut Session, text: &str) -> (u64, StoryId) {++ let f = s.execute("frame.create", &json!({"rect":[36,36,200,100],"content":"text","text":text,"caret":false})).unwrap();++ (f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))++}++fn child(s: &mut Session, parent: StoryId) -> (u64, StoryId) {++ let f = s.execute("story.placeAndLink", &json!({"story":parent.0,"rect":[36,150,200,100]})).unwrap();++ (f["id"].as_u64().unwrap(), StoryId(f["story"].as_u64().unwrap()))++}++fn state(s: &Session) -> Value {++ let d = s.doc().unwrap();++ json!({"doc":d.doc,"selection":d.selection,"revision":d.revision,"dirty":d.is_dirty(),"undo":format!("{:?}",d.history),"journal":s.journal})++}++fn link(s: &mut Session, sid: StoryId) -> Value {++ s.execute("story.links", &json!({})).unwrap().as_array().unwrap().iter().find(|l| l["story"] == sid.0).unwrap().clone()++}++++#[test]++fn safety_linked_parent_follows_merge_and_updates_after_native_reopen() {++ let mut s = setup();++ let (first, survivor) = frame(&mut s, "PREFIX");++ let (incoming, parent) = frame(&mut s, "PARENT");++ let (_, linked) = child(&mut s, parent);++ // A coincident old parent revision must not hide the change of parent identity/content.++ let future_rev = s.doc().unwrap().doc.story(survivor).unwrap().rev + 2;++ s.edit(|d, _| {++ d.story_mut(linked).unwrap().link = Some((parent, future_rev));++ Ok(())++ })++ .unwrap();++ s.execute("text.thread", &json!({"from":first,"to":incoming})).unwrap();++ assert_eq!(link(&mut s, linked)["parent"], survivor.0);++ assert_eq!(link(&mut s, linked)["outOfDate"], true);++ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "PARENT");++ let bytes = s.execute("file.serialize", &json!({})).unwrap();++ let mut reopened = Session::new();++ reopened.execute("file.openBytes", &json!({"name":"links.designcraft","base64":bytes["base64"]})).unwrap();++ assert_eq!(link(&mut reopened, linked)["parent"], survivor.0);++ reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();++ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "PREFIX\nPARENT");++ assert_eq!(link(&mut reopened, linked)["outOfDate"], false);++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(link(&mut s, linked)["parent"], parent.0);++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(link(&mut s, linked)["parent"], survivor.0);++}++++#[test]++fn safety_linked_child_cannot_merge_body_text_in_either_direction() {++ for reverse in [false, true] {++ let mut s = setup();++ let (_, parent) = frame(&mut s, "SOURCE");++ let (linked, child) = child(&mut s, parent);++ let (body, _) = frame(&mut s, "BODY");++ let (from, to) = if reverse { (body, linked) } else { (linked, body) };++ let before = state(&s);++ let error = s.execute("text.thread", &json!({"from":from,"to":to})).unwrap_err();++ assert!(error.to_string().contains("linked story"));++ assert_eq!(state(&s), before);++ s.execute("story.updateLink", &json!({"story":child.0})).unwrap();++ assert!(s.doc().unwrap().doc.stories.values().any(|st| st.text == "BODY"));++ }++}++++#[test]++fn safety_linked_child_allows_empty_extensions_in_both_directions() {++ for reverse in [false, true] {++ let mut s = setup();++ let (_, parent) = frame(&mut s, "SOURCE");++ let (linked, child) = child(&mut s, parent);++ let (empty, _) = frame(&mut s, "");++ let (from, to) = if reverse { (empty, linked) } else { (linked, empty) };++ s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();++ assert_eq!(link(&mut s, child)["parent"], parent.0);++ s.execute("story.setText", &json!({"story":parent.0,"text":"UPDATED"})).unwrap();++ assert_eq!(link(&mut s, child)["outOfDate"], true);++ s.execute("story.updateLink", &json!({"story":child.0})).unwrap();++ let st = s.doc().unwrap().doc.story(child).unwrap();++ assert_eq!(st.text, "UPDATED");++ assert_eq!(st.frames.len(), 2);++ assert_eq!(link(&mut s, child)["outOfDate"], false);++ }++}++++#[test]++fn safety_linked_empty_parent_cannot_be_merged_into_its_child() {++ let mut s = setup();++ let (parent_frame, parent) = frame(&mut s, "");++ let (linked, _) = child(&mut s, parent);++ let before = state(&s);++ assert!(s.execute("text.thread", &json!({"from":parent_frame,"to":linked})).is_err());++ assert_eq!(state(&s), before);++}++++#[test]++fn safety_text_color_without_target_is_atomic_and_carets_remain_valid() {++ let mut s = setup();++ let f = s.execute("frame.create", &json!({"rect":[36,36,200,100]})).unwrap();++ s.execute("selection.set", &json!({"ids":[f["id"]]})).unwrap();++ let before = state(&s);++ assert!(s.execute("object.color", &json!({"color":"#123456","text":true})).is_err());++ assert_eq!(state(&s), before);++ for text in ["", "Words"] {++ let (_, sid) = frame(&mut s, text);++ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();++ let color = s.execute("object.color", &json!({"color":"#654321","text":true})).unwrap();++ s.execute("text.insert", &json!({"text":"X"})).unwrap();++ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().format_after(0).over.fill.as_deref(), color["swatch"].as_str());++ }++}++++fn nested_story(depth: usize, name: &str) -> Story {++ let mut st = Story::with_text(StoryId(0), "leaf", ParaFormat::default());++ st.chars[0].format.over.fill = Some(name.into());++ for _ in 0..depth {++ let mut outer = Story::with_text(StoryId(0), &designcraft_doc::TABLE_ANCHOR.to_string(), ParaFormat::default());++ let mut t = Table::new(1, 1, 1, 0, 0, 100.);++ t.cells[0].text = st;++ outer.tables.insert(1, Arc::new(t));++ outer.paras[0].table = Some(1);++ st = outer;++ }++ st++}++++#[test]++fn safety_deep_swatch_rename_rejects_atomically_with_pending_color() {++ // A small boundary probe, never an attempted stack-overflow reproduction.++ for depth in [33, 34] {++ let mut s = setup();++ let (_, sid) = frame(&mut s, "root");++ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();++ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();++ s.edit(|d, _| {++ let st = d.story_mut(sid).unwrap();++ let frames = st.frames.clone();++ *st = nested_story(depth, &old);++ st.id = sid;++ st.frames = frames;++ Ok(())++ })++ .unwrap();++ let pending = s.execute("type.selectionAttrs", &json!({})).unwrap();++ let before = state(&s);++ let doc = s.doc().unwrap().doc.clone();++ let error = s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap_err();++ assert!(error.to_string().contains("nesting"));++ assert!(Arc::ptr_eq(&doc, &s.doc().unwrap().doc));++ assert_eq!(state(&s), before);++ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap(), pending);++ }++}++++#[test]++fn safety_swatch_rename_reaches_last_supported_depth() {++ let mut s = setup();++ let (_, sid) = frame(&mut s, "root");++ s.execute("text.select", &json!({"story":sid.0,"anchor":0})).unwrap();++ let old = s.execute("object.color", &json!({"color":"#123456"})).unwrap()["swatch"].as_str().unwrap().to_string();++ s.edit(|d, _| {++ let st = d.story_mut(sid).unwrap();++ let frames = st.frames.clone();++ *st = nested_story(32, &old);++ st.id = sid;++ st.frames = frames;++ Ok(())++ })++ .unwrap();++ s.execute("swatch.addToSwatches", &json!({"swatch":old,"name":"Brand"})).unwrap();++ let mut st = s.doc().unwrap().doc.story(sid).unwrap();++ for _ in 0..32 {++ st = &st.tables[&1].cells[0].text;++ }++ assert_eq!(st.format_after(0).over.fill.as_deref(), Some("Brand"));++ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], "Brand");++}++++#[test]++fn safety_empty_linked_parent_follows_survivor_only_on_explicit_update() {++ for incoming_empty in [false, true] {++ for alternate_layout in [false, true] {++ let mut s = setup();++ let (empty, parent) = frame(&mut s, "");++ let linked = if alternate_layout {++ s.execute("layout.createAlternate", &json!({"name":"Alternate","width":600,"height":800})).unwrap();++ let links = s.execute("story.links", &json!({})).unwrap();++ StoryId(links.as_array().unwrap().iter().find(|l| l["parent"] == parent.0).unwrap()["story"].as_u64().unwrap())++ } else {++ child(&mut s, parent).1++ };++ let (body, survivor) = frame(&mut s, "BODY");++ let (from, to) = if incoming_empty { (body, empty) } else { (empty, body) };++ s.execute("text.thread", &json!({"from":from,"to":to})).unwrap();++ assert!(s.doc().unwrap().doc.story(parent).is_none());++ assert_eq!(link(&mut s, linked)["parent"], survivor.0);++ assert_eq!(link(&mut s, linked)["outOfDate"], true);++ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");++ s.execute("edit.undo", &json!({})).unwrap();++ assert_eq!(link(&mut s, linked)["parent"], parent.0);++ assert_eq!(s.doc().unwrap().doc.story(linked).unwrap().text, "");++ s.execute("edit.redo", &json!({})).unwrap();++ assert_eq!(link(&mut s, linked)["parent"], survivor.0);++ let bytes = s.execute("file.serialize", &json!({})).unwrap();++ let mut reopened = Session::new();++ reopened.execute("file.openBytes", &json!({"name":"empty-parent.designcraft","base64":bytes["base64"]})).unwrap();++ assert_eq!(link(&mut reopened, linked)["outOfDate"], true);++ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "");++ reopened.execute("story.updateLink", &json!({"story":linked.0})).unwrap();++ assert_eq!(reopened.doc().unwrap().doc.story(linked).unwrap().text, "BODY");++ assert_eq!(link(&mut reopened, linked)["outOfDate"], false);++ }++ }++}diff --cc crates/fonts/src/fontdb.rsindex 35d4f87fd,bbe08af09..bc9c9e65f--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -122,9 -118,11 +122,11 @@@ pub struct FontFace/// Basic Multilingual Plane coverage bitset, built on first use.bmp: std::sync::OnceLock<Box<[u64]>>,/// The ideographic em box, read on first use.- em: std::sync::OnceLock<(f64, f64)>,+ em: std::sync::OnceLock<((f64, f64), bool)>,/// The font menu group and native family name, read on first use.group: std::sync::OnceLock<(FontGroup, Option<String>)>,+ /// Format, class and PANOSE numbers (the font menus), read on first use.+ kind: std::sync::OnceLock<crate::kind::FaceKind>,}/// A cheap `Copy` handle to a face. Faces are never unloaded, so the handle lives for the rest ofdiff --cc crates/geom/src/corners.rsindex bcbdf9005,6b0c9cb0a..3eecacdc8--- a/crates/geom/src/corners.rs+++ b/crates/geom/src/corners.rs@@@ -185,32 -221,67 +221,93 @@@ mod testsassert!((a - std::f64::consts::PI * 100.0).abs() < 1.0, "{a}");}+ /// InDesign draws a 28.35 pt radius on a 51.02 pt tall frame as 25.51 (half the shorter side),+ /// as a circular arc (handles 0.5523 × the radius).+ #[test]+ fn radius_is_clamped_to_half_the_shorter_side() {+ let r = rectangle(Rect::new(0.0, 0.0, 200.0, 51.02));+ let bp = apply(&r, &CornerOptions::uniform(CornerShape::Rounded, 28.35));+ let half = 51.02 / 2.0;+ let mut arcs = 0;+ let mut last = Point::ZERO;+ for el in bp.elements() {+ match *el {+ kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => last = p,+ kurbo::PathEl::CurveTo(c1, c2, p) => {+ assert!(((p - last).x.abs() - half).abs() < 1e-9 && ((p - last).y.abs() - half).abs() < 1e-9, "{last:?} → {p:?}");+ assert!(((c1 - last).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ assert!(((c2 - p).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ arcs += 1;+ last = p;+ }+ _ => {}+ }+ }+ assert_eq!(arcs, 4);+ assert!((crate::shapes::KAPPA - 0.5523).abs() < 1e-4);+ }++ fn nearest(bp: &BezPath, p: Point) -> f64 {+ use kurbo::ParamCurveNearest;+ bp.segments().map(|s| s.nearest(p, 1e-6).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)+ }++ /// A quarter disc of radius 100 centred on (0, 100): its arc from (0, 0) to (100, 100).+ fn quarter_disc() -> PathData {+ let k = 100.0 * crate::shapes::KAPPA;+ let mut a0 = crate::path::Anchor::corner(Point::new(0.0, 0.0));+ a0.h_out = Point::new(k, 0.0);+ let mut a1 = crate::path::Anchor::corner(Point::new(100.0, 100.0));+ a1.h_in = Point::new(100.0, 100.0 - k);+ let a2 = crate::path::Anchor::corner(Point::new(0.0, 100.0));+ PathData::new(vec![SubPath { anchors: vec![a0, a1, a2], closed: true }])+ }++ #[test]+ fn rounded_corners_keep_curved_sides_and_round_where_an_arc_meets_a_line() {+ let p = quarter_disc();+ let bp = apply(&p, &CornerOptions::uniform(CornerShape::Rounded, 20.0));+ // Still a quarter disc (area pi/4 * 100^2 = 7854), less three small rounded corners; a+ // triangle would be 5000.+ let area = bp.area().abs();+ assert!(area > 7300.0 && area < 7854.0, "area {area}");+ // The middle of the arc is kept.+ let mid = Point::new(100.0 * std::f64::consts::FRAC_1_SQRT_2, 100.0 - 100.0 * std::f64::consts::FRAC_1_SQRT_2);+ assert!(nearest(&bp, mid) < 0.05, "{}", nearest(&bp, mid));+ // All three corners are rounded off: the line-line one and both where the arc meets a line.+ for corner in [Point::new(0.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)] {+ assert!(nearest(&bp, corner) > 3.0, "{corner:?} is still sharp");+ }+ }++ #[test]+ fn straight_sides_are_trimmed_exactly() {+ let r = rectangle(Rect::new(0.0, 0.0, 100.0, 60.0));+ let bp = apply(&r, &CornerOptions::uniform(CornerShape::Bevel, 10.0));+ // Every point a bevelled rectangle goes through sits exactly 10 pt from a corner.+ let pts: Vec<Point> = bp+ .elements()+ .iter()+ .filter_map(|e| match e {+ kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => Some(*p),+ _ => None,+ })+ .collect();+ assert_eq!(pts.len(), 9, "{pts:?}");+ for p in pts {+ assert!([0.0, 10.0, 90.0, 100.0].contains(&p.x) && [0.0, 10.0, 50.0, 60.0].contains(&p.y), "{p:?}");+ }+ }++ #[test]+ fn smooth_points_are_not_corners() {+ let e = crate::shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 60.0));+ for shape in CornerShape::ALL.into_iter().skip(1) {+ let bp = apply(&e, &CornerOptions::uniform(shape, 20.0));+ assert!((bp.area().abs() - e.to_bezpath().area().abs()).abs() < 1e-6, "{shape:?}");+ }+ }+#[test]fn size_is_clamped_to_half_edge() {let r = rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));diff --cc crates/idml/src/export.rsindex 6fce9c77c,d01abe9e7..b7e5ca3c6--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@@ -1396,12 -1377,6 +1403,12 @@@ impl<'a> Ex<'a>n!(space_after, "SpaceAfter");n!(drop_cap_lines, "DropCapLines");n!(drop_cap_chars, "DropCapCharacters");+ if a.drop_cap_align_left.is_some() || a.drop_cap_scale_descenders.is_some() {- let d = designcraft_doc::ParaProps::default();++ let d = parent.map(|name| self.d.styles.resolve_para_style(name).0).unwrap_or_default();+ let bits = u32::from(a.drop_cap_align_left.unwrap_or(d.drop_cap_align_left))+ | u32::from(a.drop_cap_scale_descenders.unwrap_or(d.drop_cap_scale_descenders)) << 1;+ el.set("DropcapDetail", bits);+ }if let Some(g) = a.grid_align {match g {designcraft_doc::GridAlign::None => el.set("GridAlignment", "None"),diff --cc crates/idml/src/import.rsindex 4ae4d15db,59ca44be7..1a4fa65e3--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -770,10 -788,10 +791,10 @@@ impl<'r> Importer<'r>/// A swatch reference (Self id) → our swatch name; unnamed colours become value-named swatches./// A `TextFramePreference`, with its column rule colour resolved to a swatch.- fn frame_options(&mut self, e: &El) -> TextFrameOptions {- let mut o = text_frame_options(e);- if let Some(r) = e.get("ColumnRuleStrokeColor") {- o.column_rule_color = self.swatch_ref(r);+ fn frame_options(&mut self, prefs: &[&El]) -> TextFrameOptions {+ let mut o = text_frame_options(prefs);- if let Some(r) = Prefs(prefs).get("ColumnRuleStrokeColor") {- o.column_rule_color = self.swatch_ref(r);++ if let Some(r) = Prefs(prefs).prop("ColumnRuleStrokeColor") {++ o.column_rule_color = self.swatch_ref(&r);}o}@@@ -2227,13 -2227,7 +2251,13 @@@sid}};- let mut options = e.find("TextFramePreference").map(|t| self.frame_options(t)).unwrap_or_default();+ // Options the frame doesn't set come from its object style chain.+ let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();+ let mut options = text_frame_options(&prefs);+ // `prefs` borrows the object styles, so the rule colour's swatch is resolved after it.- if let Some(r) = Prefs(&prefs).get("ColumnRuleStrokeColor").map(str::to_string) {++ if let Some(r) = Prefs(&prefs).prop("ColumnRuleStrokeColor") {+ options.column_rule_color = self.swatch_ref(&r);+ }if let Some(g) = e.find("BaselineFrameGridOption")&& g.get("UseCustomBaselineFrameGrid") == Some("true"){@@@ -2554,26 -2525,24 +2578,26 @@@ fn ace_char(v: &str) -> Option<char>}fn margins_of(m: &El) -> (Margins, Columns) {-- let g = |k: &str, d: f64| m.num(k).unwrap_or(d);++ let g = |k: &str, d: f64| m.num(k).filter(|v| v.is_finite()).unwrap_or(d);(Margins { top: g("Top", 36.0), bottom: g("Bottom", 36.0), inside: g("Left", 36.0), outside: g("Right", 36.0) },-- Columns { count: g("ColumnCount", 1.0).max(1.0) as u32, gutter: g("ColumnGutter", 12.0), positions: None },++ Columns { count: g("ColumnCount", 1.0).clamp(1.0, 216.0) as u32, gutter: g("ColumnGutter", 12.0), positions: None },)}-fn text_frame_options(e: &El) -> TextFrameOptions {+/// Text Frame Options from `TextFramePreference` elements: each attribute from the first that sets it.+fn text_frame_options(prefs: &[&El]) -> TextFrameOptions {+ let e = Prefs(prefs);let mut o = TextFrameOptions::default();if let Some(v) = e.num("TextColumnCount") {-- o.columns = v.max(1.0) as u32;++ o.columns = v.clamp(1.0, 216.0) as u32;}if let Some(v) = e.num("TextColumnGutter") {o.gutter = v;}-- o.columns_kind = if e.get("UseFixedColumnWidth") == Some("true") {++ o.columns_kind = if e.prop("UseFixedColumnWidth").as_deref().map(str::trim) == Some("true") {ColumnsKind::FixedWidth-- } else if e.get("UseFlexibleColumnWidth") == Some("true") {++ } else if e.prop("UseFlexibleColumnWidth").as_deref().map(str::trim) == Some("true") {ColumnsKind::FlexibleWidth} else {ColumnsKind::FixedNumber@@@ -2583,33 -2552,31 +2607,33 @@@{o.column_width = v;}-- o.balance_columns = e.get("VerticalBalanceColumns") == Some("true");- if let Some(inset) = inset_spacing(e) {++ o.balance_columns = e.prop("VerticalBalanceColumns").as_deref().map(str::trim) == Some("true");+ if let Some(p) = prefs.iter().find(|p| p.prop("InsetSpacing").is_some())+ && let Some(inset) = inset_spacing(p)+ {o.inset = inset;}-- if let Some(v) = e.get("VerticalJustification") {-- o.vertical_justification = names::vj_in(v);++ if let Some(v) = e.prop("VerticalJustification") {++ o.vertical_justification = names::vj_in(v.trim());}if let Some(v) = e.num("VerticalThreshold") {o.vj_paragraph_spacing_limit = v;}-- if let Some(v) = e.get("FirstBaselineOffset") {-- o.first_baseline = names::first_baseline_in(v);++ if let Some(v) = e.prop("FirstBaselineOffset") {++ o.first_baseline = names::first_baseline_in(v.trim());}if let Some(v) = e.num("MinimumFirstBaselineOffset") {o.first_baseline_min = v;}-- o.ignore_wrap = e.get("IgnoreWrap") == Some("true");-- if let Some(v) = e.get("AutoSizingType") {-- o.auto_size = names::auto_size_in(v);++ o.ignore_wrap = e.prop("IgnoreWrap").as_deref().map(str::trim) == Some("true");++ if let Some(v) = e.prop("AutoSizingType") {++ o.auto_size = names::auto_size_in(v.trim());}-- if let Some(v) = e.get("AutoSizingReferencePoint") {-- o.auto_size_ref = names::REF_POINTS.iter().position(|p| *p == v).unwrap_or(1) as u8;++ if let Some(v) = e.prop("AutoSizingReferencePoint") {++ o.auto_size_ref = names::REF_POINTS.iter().position(|p| *p == v.trim()).unwrap_or(1) as u8;}// Column rules (the colour is a swatch reference: see `Importer::frame_options`).-- o.column_rule = e.get("ColumnRuleOverride") == Some("true");++ o.column_rule = e.prop("ColumnRuleOverride").as_deref().map(str::trim) == Some("true");let finite = |k: &str| e.num(k).filter(|v| v.is_finite());if let Some(v) = finite("ColumnRuleStrokeWidth") {o.column_rule_weight = v.clamp(0.0, 1000.0);@@@ -2629,59 -2596,6 +2653,60 @@@o}+/// Deepest table-in-cell or note nesting the drop cap pass walks into.+const MAX_STORY_NESTING: usize = 32;++/// [`Importer::clear_inherited_drop_cap_styles`] for one story's paragraphs and those of the table+/// cells, footnotes and endnotes in it.+fn clear_story_drop_cap_styles(styles: &Styles, story: &mut Story, depth: usize) {+ for p in &mut story.paras {+ if p.para.drop_cap_style.is_none() && p.para.nested_styles.is_some() && inherits_drop_cap_style(styles, Some(&p.style)) {+ p.para.drop_cap_style = Some(st::NO_CHAR_STYLE.into());+ }+ }+ if depth >= MAX_STORY_NESTING {+ return;+ }+ for table in story.tables.values_mut() {+ for cell in &mut Arc::make_mut(table).cells {+ clear_story_drop_cap_styles(styles, &mut cell.text, depth + 1);+ }+ }+ for note in story.notes.iter_mut().chain(story.endnotes.iter_mut()) {+ clear_story_drop_cap_styles(styles, &mut Arc::make_mut(note).text, depth + 1);+ }+}++/// Does paragraph style `name` (and its based-on chain) set a drop cap character style? A style+/// with a nested style list of its own and no drop cap style has none.+fn inherits_drop_cap_style<'a>(styles: &'a Styles, mut name: Option<&'a str>) -> bool {+ let mut seen = HashSet::new();+ while let Some(n) = name {+ let Some(s) = styles.para(n).filter(|_| seen.insert(n)) else { break };+ if let Some(c) = s.para.drop_cap_style.as_deref() {+ return !c.is_empty() && c != st::NO_CHAR_STYLE;+ }+ if s.para.nested_styles.is_some() {+ return false;+ }+ name = s.based_on.as_deref();+ }+ false+}+- /// Attribute lookup over several elements: the first that has it.++/// Property lookup over preference levels: the nearest level wins, attributes before children.+struct Prefs<'a>(&'a [&'a El]);++impl Prefs<'_> {- fn get(&self, k: &str) -> Option<&str> {- self.0.iter().find_map(|e| e.get(k))++ fn prop(&self, k: &str) -> Option<String> {++ self.0.iter().find_map(|e| e.prop(k))+ }+ fn num(&self, k: &str) -> Option<f64> {- self.get(k).and_then(|v| v.trim().parse().ok())++ // The nearest preference wins; within it, attributes precede property children.++ self.prop(k).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())+ }+}+/// A scalar applies to every edge; a list is top, left, bottom, right. Keep the/// existing property-element precedence over the legacy scalar attribute, even/// when the property is malformed. Finite negative insets remain supported.@@@ -2738,3 -2652,3 +2763,244 @@@ pub(crate) fn uri_to_path(uri: &str) -};percent_decode(rest)}++++#[cfg(test)]++mod numeric_property_tests {++ use super::*;++++ fn pref(attrs: &[(&str, &str)], props: &[(&str, &str)]) -> El {++ let mut e = El::new("TextFramePreference");++ for (key, value) in attrs {++ e.set(key, *value);++ }++ let mut p = El::new("Properties");++ for (key, value) in props {++ p.push(El::new(key).text(*value));++ }++ e.push(p);++ e++ }++++ #[test]++ fn numeric_property_forms_import_every_frame_option() {++ let local = pref(++ &[("UseFixedColumnWidth", "true")],++ &[++ ("TextColumnCount", "3"),++ ("TextColumnGutter", "17"),++ ("TextColumnFixedWidth", "123"),++ ("VerticalThreshold", "19"),++ ("MinimumFirstBaselineOffset", "8"),++ ("ColumnRuleStrokeWidth", "2"),++ ("ColumnRuleStrokeTint", "25"),++ ("ColumnRuleOffset", "3"),++ ("ColumnRuleTopInset", "4"),++ ("ColumnRuleBottomInset", "5"),++ ],++ );++ let o = text_frame_options(&[&local]);++ assert_eq!((o.columns, o.gutter, o.column_width), (3, 17., 123.));++ assert_eq!((o.vj_paragraph_spacing_limit, o.first_baseline_min), (19., 8.));++ assert_eq!(++ (o.column_rule_weight, o.column_rule_tint, o.column_rule_offset, o.column_rule_top_inset, o.column_rule_bottom_inset),++ (2., 0.25, 3., 4., 5.)++ );++ }++++ #[test]++ fn numeric_property_precedence_is_nearest_level_then_attribute() {++ let local = pref(&[("TextColumnCount", "4")], &[("TextColumnCount", "5"), ("TextColumnGutter", "17")]);++ let child = pref(++ &[("TextColumnGutter", "90"), ("MinimumFirstBaselineOffset", "8")],++ &[("MinimumFirstBaselineOffset", "9"), ("VerticalThreshold", "19")],++ );++ let base = pref(&[("VerticalThreshold", "99")], &[("ColumnRuleStrokeWidth", "2")]);++ let o = text_frame_options(&[&local, &child, &base]);++ assert_eq!((o.columns, o.gutter, o.first_baseline_min, o.vj_paragraph_spacing_limit, o.column_rule_weight), (4, 17., 8., 19., 2.));++ // An explicit invalid value still masks inherited values, as attribute lookup did.++ let invalid = pref(&[("TextColumnCount", "bad")], &[("TextColumnCount", "6")]);++ assert_eq!(text_frame_options(&[&invalid, &local]).columns, TextFrameOptions::default().columns);++ }++}++++#[cfg(test)]++mod frame_preference_safety_tests {++ use super::*;++++ fn pref(attrs: &[(&str, &str)], props: &[(&str, &str)]) -> El {++ let mut e = El::new("TextFramePreference");++ for (key, value) in attrs {++ e.set(key, *value);++ }++ let mut p = El::new("Properties");++ for (key, value) in props {++ p.push(El::new(key).text(*value));++ }++ e.push(p);++ e++ }++++ #[test]++ fn frame_preference_nonfinite_numbers_keep_finite_defaults() {++ const KEYS: [&str; 10] = [++ "TextColumnCount",++ "TextColumnGutter",++ "TextColumnFixedWidth",++ "VerticalThreshold",++ "MinimumFirstBaselineOffset",++ "ColumnRuleStrokeWidth",++ "ColumnRuleStrokeTint",++ "ColumnRuleOffset",++ "ColumnRuleTopInset",++ "ColumnRuleBottomInset",++ ];++ let fallback = pref(&[("UseFixedColumnWidth", "true")], &[]);++ let expected = text_frame_options(&[&fallback]);++ for value in ["NaN", "inf", "-inf", "1e309"] {++ for attribute in [true, false] {++ let values: Vec<_> = KEYS.iter().map(|key| (*key, value)).collect();++ let mut invalid = if attribute { pref(&values, &[]) } else { pref(&[], &values) };++ invalid.set("UseFixedColumnWidth", "true");++ let inherited = pref(&[], &[("TextColumnCount", "7"), ("TextColumnGutter", "9")]);++ assert_eq!(text_frame_options(&[&invalid, &inherited]), expected, "{value}, attribute={attribute}");++ }++ }++ }++++ #[test]++ fn frame_preference_property_booleans_enums_and_precedence() {++ let base = pref(++ &[++ ("UseFixedColumnWidth", "true"),++ ("UseFlexibleColumnWidth", "false"),++ ("VerticalBalanceColumns", "false"),++ ("IgnoreWrap", "false"),++ ("ColumnRuleOverride", "false"),++ ("VerticalJustification", "TopAlign"),++ ("FirstBaselineOffset", "AscentOffset"),++ ("AutoSizingType", "Off"),++ ("AutoSizingReferencePoint", "TopCenterPoint"),++ ],++ &[],++ );++ let local = pref(++ &[],++ &[++ ("UseFixedColumnWidth", "false"),++ ("UseFlexibleColumnWidth", "true"),++ ("VerticalBalanceColumns", "true"),++ ("IgnoreWrap", "true"),++ ("ColumnRuleOverride", "true"),++ ("VerticalJustification", "BottomAlign"),++ ("FirstBaselineOffset", "FixedHeight"),++ ("AutoSizingType", "HeightAndWidth"),++ ("AutoSizingReferencePoint", "BottomRightPoint"),++ ],++ );++ let o = text_frame_options(&[&local, &base]);++ assert_eq!(o.columns_kind, ColumnsKind::FlexibleWidth);++ assert!(o.balance_columns && o.ignore_wrap && o.column_rule);++ assert_eq!(o.vertical_justification, designcraft_doc::VerticalJustification::Bottom);++ assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::Fixed);++ assert_eq!(o.auto_size, designcraft_doc::AutoSize::HeightAndWidth);++ assert_eq!(o.auto_size_ref, 8);++ let fixed = pref(&[], &[("UseFixedColumnWidth", "true")]);++ assert_eq!(text_frame_options(&[&fixed, &local, &base]).columns_kind, ColumnsKind::FixedWidth);++ // At one level an attribute wins over a conflicting property child, for every key.++ let mut same_level = local.clone();++ for (key, value) in &base.attrs {++ same_level.set(key, value);++ }++ assert_eq!(text_frame_options(&[&same_level, &local]), text_frame_options(&[&base]));++ // Malformed nearer values mask ancestors and use the normal per-field fallback.++ let mut malformed = El::new("TextFramePreference");++ for (key, _) in &base.attrs {++ malformed.set(key, "invalid");++ }++ assert_eq!(text_frame_options(&[&malformed, &local]), TextFrameOptions { auto_size_ref: 1, ..Default::default() });++ }++}++++#[cfg(test)]++mod page_column_import_safety_tests {++ use super::*;++++ #[test]++ fn frame_preference_page_columns_are_bounded_and_finite() {++ for (raw, expected) in [("4000000000", 216), ("1e300", 216), ("-10", 1), ("NaN", 1), ("inf", 1)] {++ let m = El::new("MarginPreference")++ .attr("ColumnCount", raw)++ .attr("ColumnGutter", "NaN")++ .attr("Top", "inf")++ .attr("Bottom", "-inf")++ .attr("Left", "NaN")++ .attr("Right", "1e309");++ let (margins, columns) = margins_of(&m);++ assert_eq!(columns.count, expected);++ assert_eq!(columns.gutter, 12.);++ assert_eq!(margins, Margins::uniform(36.));++ }++ }++}++++#[cfg(test)]++mod frame_preference_scalar_tests {++ use super::*;++++ #[test]++ fn frame_preference_scalar_whitespace() {++ let values = [++ ("UseFixedColumnWidth", "true"),++ ("UseFlexibleColumnWidth", "false"),++ ("VerticalBalanceColumns", "true"),++ ("IgnoreWrap", "true"),++ ("ColumnRuleOverride", "true"),++ ("VerticalJustification", "BottomAlign"),++ ("FirstBaselineOffset", "FixedHeight"),++ ("AutoSizingType", "HeightAndWidth"),++ ("AutoSizingReferencePoint", "BottomRightPoint"),++ ];++ let preference = |properties: bool, padded: bool, fixed: bool| {++ let mut e = El::new("TextFramePreference");++ let mut props = El::new("Properties");++ for (key, raw) in values {++ let raw = match key {++ "UseFixedColumnWidth" if !fixed => "false",++ "UseFlexibleColumnWidth" if !fixed => "true",++ _ => raw,++ };++ let value = if padded { format!("\n {raw}\t ") } else { raw.to_string() };++ if properties {++ props.push(El::new(key).text(value));++ } else {++ e.set(key, value);++ }++ }++ e.push(props);++ e++ };++ for fixed in [false, true] {++ let clean = preference(false, false, fixed);++ let expected = text_frame_options(&[&clean]);++ assert_eq!(expected.columns_kind, if fixed { ColumnsKind::FixedWidth } else { ColumnsKind::FlexibleWidth });++ assert!(expected.balance_columns && expected.ignore_wrap && expected.column_rule);++ assert_eq!(expected.vertical_justification, designcraft_doc::VerticalJustification::Bottom);++ assert_eq!(expected.first_baseline, designcraft_doc::FirstBaseline::Fixed);++ assert_eq!(expected.auto_size, designcraft_doc::AutoSize::HeightAndWidth);++ assert_eq!(expected.auto_size_ref, 8);++ for properties in [false, true] {++ let padded = preference(properties, true, fixed);++ assert_eq!(text_frame_options(&[&padded]), expected);++ }++ // A malformed nearest attribute masks both its own valid child and farther values.++ let mut invalid = preference(true, true, fixed);++ for (key, _) in values {++ invalid.set(key, " invalid ");++ }++ assert_eq!(text_frame_options(&[&invalid, &clean]), TextFrameOptions { auto_size_ref: 1, ..Default::default() });++ }++ // Object identities use the raw property lookup, not scalar whitespace normalization.++ let exact = El::new("TextFramePreference").child(El::new("Properties").child(El::new("ColumnRuleStrokeColor").text(" Color/Named ")));++ assert_eq!(Prefs(&[&exact]).prop("ColumnRuleStrokeColor").as_deref(), Some(" Color/Named "));++ }++}diff --cc crates/idml/src/tests.rsindex ebd591ce5,a2ee8f2d5..57801e34f--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1480,625 -1456,26 +1481,691 @@@ fn list_numbering_format_expression_andcheck(&import_idml(&export_idml(&d)).unwrap());}+fn fixture_with_styles(styles: &str) -> Vec<u8> {+ 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),+ ])+}++/// Paragraph styles `Body` (based on the root) and `Loose` (no BasedOn), both with `attrs`.+fn keep_styles(attrs: &str) -> String {+ format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <RootParagraphStyleGroup Self="rp">+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12"/>+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {attrs}>+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" {attrs}/>+ </RootParagraphStyleGroup>+</idPkg:Styles>"#+ )+}++/// Keep Lines Together whose mode no style sets is InDesign's default: at start/end of paragraph.+/// An explicit mode still wins.+#[test]+fn keep_lines_mode_defaults_to_start_and_end() {+ let keep = r#"KeepLinesTogether="true" KeepFirstLines="2" KeepLastLines="2""#;+ for (attrs, all) in [(keep.to_string(), false), (format!(r#"{keep} KeepAllLinesTogether="true""#), true)] {+ let d = import_idml_with(&fixture_with_styles(&keep_styles(&attrs)), &|_| None).unwrap();+ for name in ["Body", "Loose"] {+ let (pp, _) = d.styles.resolve_para_style(name);+ assert_eq!((pp.keep_lines_together, pp.keep_all_lines, pp.keep_first, pp.keep_last), (true, all, 2, 2), "{name}: {attrs}");+ }+ }+}++type Resolved = (designcraft_doc::ParaProps, designcraft_doc::CharProps);++/// (IDML attribute, InDesign's default as IDML writes it, another value, the resolved field,+/// its value for InDesign's default, its value for the other value).+type AttrRow = (&'static str, &'static str, &'static str, fn(&Resolved) -> String, String, String);++macro_rules! attr_rows {+ ($($attr:literal: $default:literal => $dv:expr, $other:literal => $ov:expr, |$r:ident| $field:expr;)*) => {+ vec![$(($attr, $default, $other, (|$r: &Resolved| format!("{:?}", $field)) as fn(&Resolved) -> String, format!("{:?}", $dv), format!("{:?}", $ov)),)*]+ };+}++/// InDesign's defaults for a new document's [No Paragraph Style], for every paragraph and+/// character attribute the importer reads (except the font family: see below).+fn indesign_text_defaults() -> Vec<AttrRow> {+ use designcraft_doc::{Align, Capitalization, Composer, Digits, GridAlign, Leading, ListType, Position, StartParagraph, TextDirection};+ attr_rows! {+ "Justification": "LeftAlign" => Align::Left, "CenterAlign" => Align::Center, |r| r.0.align;+ "ParagraphDirection": "LeftToRightDirection" => TextDirection::LeftToRight, "RightToLeftDirection" => TextDirection::RightToLeft, |r| r.0.direction;+ "LeftIndent": "0" => 0.0, "6" => 6.0, |r| r.0.left_indent;+ "RightIndent": "0" => 0.0, "6" => 6.0, |r| r.0.right_indent;+ "FirstLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.first_line_indent;+ "LastLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.last_line_indent;+ "SpaceBefore": "0" => 0.0, "6" => 6.0, |r| r.0.space_before;+ "SpaceAfter": "0" => 0.0, "6" => 6.0, |r| r.0.space_after;+ "DropCapLines": "0" => 0, "3" => 3, |r| r.0.drop_cap_lines;+ "DropCapCharacters": "0" => 0, "1" => 1, |r| r.0.drop_cap_chars;+ "DropcapDetail": "1" => (true, false), "2" => (false, true), |r| (r.0.drop_cap_align_left, r.0.drop_cap_scale_descenders);+ "GridAlignment": "None" => GridAlign::None, "AlignToBaseline" => GridAlign::AllLines, |r| r.0.grid_align;+ "Composer": "HL Composer" => Composer::Paragraph, "HL Single" => Composer::SingleLine, |r| r.0.composer;+ "Hyphenation": "true" => true, "false" => false, |r| r.0.hyphenate;+ "HyphenateWordsLongerThan": "5" => 5, "7" => 7, |r| r.0.hyph_min_word;+ "HyphenateAfterFirst": "2" => 2, "3" => 3, |r| r.0.hyph_after_first;+ "HyphenateBeforeLast": "2" => 2, "3" => 3, |r| r.0.hyph_before_last;+ "HyphenateLadderLimit": "3" => 3, "0" => 0, |r| r.0.hyph_limit;+ "HyphenationZone": "36" => 36.0, "18" => 18.0, |r| r.0.hyph_zone;+ "HyphenateCapitalizedWords": "true" => true, "false" => false, |r| r.0.hyph_capitalized;+ "HyphenateLastWord": "true" => true, "false" => false, |r| r.0.hyph_last_word;+ "HyphenateAcrossColumns": "true" => true, "false" => false, |r| r.0.hyph_across_column;+ "HyphenWeight": "5" => 0.5, "9" => 0.9, |r| r.0.hyph_weight;+ "MinimumWordSpacing": "80" => 0.8, "70" => 0.7, |r| r.0.word_space_min;+ "DesiredWordSpacing": "100" => 1.0, "90" => 0.9, |r| r.0.word_space_desired;+ "MaximumWordSpacing": "133" => 1.33, "150" => 1.5, |r| r.0.word_space_max;+ "MinimumLetterSpacing": "0" => 0.0, "-5" => -0.05, |r| r.0.letter_space_min;+ "DesiredLetterSpacing": "0" => 0.0, "1" => 0.01, |r| r.0.letter_space_desired;+ "MaximumLetterSpacing": "0" => 0.0, "5" => 0.05, |r| r.0.letter_space_max;+ "MinimumGlyphScaling": "100" => 1.0, "97" => 0.97, |r| r.0.glyph_scale_min;+ "DesiredGlyphScaling": "100" => 1.0, "101" => 1.01, |r| r.0.glyph_scale_desired;+ "MaximumGlyphScaling": "100" => 1.0, "103" => 1.03, |r| r.0.glyph_scale_max;+ "AutoLeading": "120" => 1.2, "100" => 1.0, |r| r.0.auto_leading;+ "SingleWordJustification": "FullyJustified" => Align::FullyJustified, "LeftAlign" => Align::Left, |r| r.0.single_word_justify;+ "KeepWithNext": "0" => 0, "1" => 1, |r| r.0.keep_with_next;+ "KeepLinesTogether": "false" => false, "true" => true, |r| r.0.keep_lines_together;+ "KeepAllLinesTogether": "false" => false, "true" => true, |r| r.0.keep_all_lines;+ "KeepFirstLines": "2" => 2, "3" => 3, |r| r.0.keep_first;+ "KeepLastLines": "2" => 2, "3" => 3, |r| r.0.keep_last;+ "StartParagraph": "Anywhere" => StartParagraph::Anywhere, "NextColumn" => StartParagraph::NextColumn, |r| r.0.start_paragraph;+ "BulletsAndNumberingListType": "NoList" => ListType::None, "BulletList" => ListType::Bullets, |r| r.0.list_type;+ "BalanceRaggedLines": "NoBalancing" => false, "FullyBalanced" => true, |r| r.0.balance_ragged;+ "Kashidas": "DefaultKashidas" => true, "KashidasOff" => false, |r| r.0.kashidas;+ "RuleAbove": "false" => false, "true" => true, |r| r.0.rule_above.on;+ "RuleAboveColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_above.color;+ "RuleAboveTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_above.tint;+ "RuleBelow": "false" => false, "true" => true, |r| r.0.rule_below.on;+ "RuleBelowColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_below.color;+ "RuleBelowTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.tint;+ "ParagraphShadingOn": "false" => false, "true" => true, |r| r.0.shading_on;+ "ParagraphShadingColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.shading_color;+ "ParagraphShadingTint": "20" => 0.2f32, "50" => 0.5f32, |r| r.0.shading_tint;+ "ParagraphBorderOn": "false" => false, "true" => true, |r| r.0.border_on;+ "ParagraphBorderColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.border_color;+ "ParagraphBorderTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.border_tint;+ "FontStyle": "Regular" => "Regular", "Bold" => "Bold", |r| r.1.font_style;+ "PointSize": "12" => 12.0, "9" => 9.0, |r| r.1.size;+ "Leading": "Auto" => Leading::Auto, "14" => Leading::Points(14.0), |r| r.1.leading;+ "KerningMethod": "$ID/Metrics" => designcraft_doc::Kerning::Metrics, "$ID/Optical" => designcraft_doc::Kerning::Optical, |r| r.1.kerning;+ "Tracking": "0" => 0.0, "20" => 20.0, |r| r.1.tracking;+ "HorizontalScale": "100" => 1.0, "90" => 0.9, |r| r.1.h_scale;+ "VerticalScale": "100" => 1.0, "90" => 0.9, |r| r.1.v_scale;+ "BaselineShift": "0" => 0.0, "2" => 2.0, |r| r.1.baseline_shift;+ "Skew": "0" => 0.0, "10" => 10.0, |r| r.1.skew;+ "FillColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.1.fill;+ "FillTint": "-1" => 1.0, "50" => 0.5, |r| r.1.fill_tint;+ "StrokeColor": "Swatch/None" => "[None]", "Color/Black" => "[Black]", |r| r.1.stroke;+ "StrokeTint": "-1" => 1.0, "50" => 0.5, |r| r.1.stroke_tint;+ "StrokeWeight": "1" => 1.0, "2" => 2.0, |r| r.1.stroke_weight;+ "Capitalization": "Normal" => Capitalization::Normal, "AllCaps" => Capitalization::AllCaps, |r| r.1.capitalization;+ "Position": "Normal" => Position::Normal, "Superscript" => Position::Superscript, |r| r.1.position;+ "Underline": "false" => false, "true" => true, |r| r.1.underline;+ "StrikeThru": "false" => false, "true" => true, |r| r.1.strikethrough;+ "UnderlineTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.underline_tint;+ "StrikeThruTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.strikethrough_tint;+ "Ligatures": "true" => true, "false" => false, |r| r.1.ligatures;+ "NoBreak": "false" => false, "true" => true, |r| r.1.no_break;+ "OTFContextualAlternate": "true" => true, "false" => false, |r| designcraft_doc::otf::is_on(&r.1.otf_features, "calt");+ "DigitsType": "DefaultDigits" => Digits::Default, "ArabicDigits" => Digits::Arabic, |r| r.1.digits;+ "AppliedLanguage": "$ID/English: USA" => "English: USA", "$ID/German: 2006 Reform" => "German: 2006 Reform", |r| r.1.language;+ }+}++/// [No paragraph style] with `root` attributes and `Body`, based on it, with `body` attributes.+fn text_styles(root: &str, body: &str) -> String {+ format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <RootParagraphStyleGroup Self="rp">+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" {root}/>+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {body}>+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>+</idPkg:Styles>"#+ )+}++fn resolve_body(root: &str, body: &str) -> Resolved {+ let d = import_idml_with(&fixture_with_styles(&text_styles(root, body)), &|_| None).unwrap();+ d.styles.resolve_para_style("Body")+}++/// Text attributes an IDML file leaves unset are InDesign's defaults; written ones win, and a+/// file that writes every default (as InDesign's own exports do) imports the same.+#[test]+fn absent_text_attributes_take_indesign_defaults() {+ let rows = indesign_text_defaults();+ let all = |pick: fn(&AttrRow) -> &str| rows.iter().map(|r| format!(r#"{}="{}""#, r.0, pick(r))).collect::<Vec<_>>().join(" ");+ let (defaults, others) = (all(|r| r.1), all(|r| r.2));+ let omitted = resolve_body("", "");+ let written = resolve_body(&defaults, "");+ for (attr, _, _, field, want, _) in &rows {+ assert_eq!(field(&omitted), *want, "{attr} omitted");+ assert_eq!(field(&written), *want, "{attr} written as InDesign's default");+ }+ assert_eq!(omitted, written);+ for (root, body) in [(others.as_str(), ""), ("", others.as_str())] {+ let r = resolve_body(root, body);+ for (attr, _, _, field, _, want) in &rows {+ assert_eq!(field(&r), *want, "{attr} written on the {}", if root.is_empty() { "style" } else { "root" });+ }+ }+ // Product difference: InDesign's default face isn't available, so unset fonts are DesignCraft's.+ assert_eq!(omitted.1.font_family, designcraft_doc::CharProps::default().font_family);+}++/// A tint of -1 is the colour's own tint (100 %): written on a style, it replaces its parent's.+/// Tints are never negative or above 100 %.+#[test]+fn minus_one_tint_is_the_colours_own() {+ let tints = |v: &str| {+ ["UnderlineTint", "StrikeThruTint", "FillTint", "StrokeTint", "ParagraphShadingTint", "ParagraphBorderTint", "RuleAboveTint", "RuleBelowTint"]+ .map(|k| format!(r#"{k}="{v}""#))+ .join(" ")+ + r#" RuleAbove="true" RuleBelow="true""#+ };+ for (body, want) in [("-1", 1.0), ("150", 1.0)] {+ let r = resolve_body(&tints("50"), &tints(body));+ let got = [+ r.1.underline_tint,+ r.1.strikethrough_tint,+ r.1.fill_tint,+ r.1.stroke_tint,+ r.0.shading_tint,+ r.0.border_tint,+ r.0.rule_above.tint,+ r.0.rule_below.tint,+ ];+ assert_eq!(got, [want; 8], "{body}");+ }+ // Footnote rules, table fills and strokes, cell fills.+ let prefs = PREFS.replace("</idPkg:Preferences>", r#"<FootnoteOption RuleTint="-1"/></idPkg:Preferences>"#);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartRowFillTint="-1" EndRowFillTint="-1" TopBorderStrokeTint="-1">+<Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0" FillColor="Color/Black" FillTint="-1" TopEdgeStrokeTint="-1"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>+</idPkg:Story>"#;+ let d = import_idml_with(+ &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),+ ]),+ &|_| None,+ )+ .unwrap();+ assert_eq!(d.footnote_options.rule.tint, 1.0);+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let alt = t.options.alt_rows.as_ref().unwrap();+ assert_eq!((alt.first_tint, alt.next_tint, t.options.border.tint), (1.0, 1.0, 1.0));+ let c = t.cell(0, 0).unwrap();+ assert_eq!((c.fill_tint, c.strokes[0].tint), (1.0, 1.0));+}++/// Rules in Text Color take the colour of the paragraph's text; they round-trip as Text Color.+#[test]+fn text_color_rules_round_trip() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let rule = designcraft_doc::Rule { on: true, ..Default::default() };+ assert_eq!(rule.color, designcraft_doc::TEXT_COLOR);+ let para = designcraft_doc::ParaAttrs {+ rule_above: Some(rule.clone()),+ rule_below: Some(designcraft_doc::Rule { color: "[Black]".into(), ..rule }),+ kashidas: Some(false),+ ..Default::default()+ };+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Ruled", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().paras[0].para = para.clone();+ let bytes = export_idml(&d);+ let story = zip_text(&bytes, "Stories/");+ assert!(story.contains(r#"<RuleAboveColor type="string">Text Color</RuleAboveColor>"#), "{story}");+ assert!(story.contains(r#"Kashidas="KashidasOff""#), "{story}");+ let back = import_idml(&bytes).unwrap();+ let p = &back.stories.values().find(|s| s.text == "Ruled").unwrap().paras[0];+ assert_eq!((p.para.rule_above.as_ref(), p.para.rule_below.as_ref()), (para.rule_above.as_ref(), para.rule_below.as_ref()));+ assert_eq!(p.para.kashidas, Some(false));+}++/// `[Basic Paragraph]` is InDesign's `$ID/NormalParagraphStyle`, both ways.+#[test]+fn basic_paragraph_is_normal_paragraph_style() {+ let d = import_idml_with(&fixture(), &|_| None).unwrap();+ let basic = d.styles.para(st::BASIC_PARAGRAPH).unwrap();+ assert_eq!(basic.based_on.as_deref(), Some(designcraft_doc::NO_PARA_STYLE));+ assert_eq!(d.styles.para("Text/Body").unwrap().based_on.as_deref(), Some(st::BASIC_PARAGRAPH));+ let s = d.stories.values().find(|s| s.text.starts_with("Hello")).unwrap();+ assert_eq!(s.paras[1].style, st::BASIC_PARAGRAPH);+ assert!(d.styles.paragraph.iter().all(|p| !p.name.contains("NormalParagraphStyle")));+ let bytes = export_idml(&d);+ let styles = zip_text(&bytes, "Resources/Styles.xml");+ assert!(styles.contains(r#"Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle""#), "{styles}");+ assert!(zip_text(&bytes, "Stories/").contains(r#"AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle""#));+ let back = import_idml(&bytes).unwrap();+ assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1);+}++/// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults+/// for a new document.+#[test]+fn absent_item_and_document_attributes_take_indesign_defaults() {+ use designcraft_doc::{Cap, FirstBaseline, Join, StrokeAlign, VerticalJustification};+ use designcraft_geom::corners::CornerShape;+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">+<NumberingList Self="NumberingList/Steps" Name="Steps"/>+<RootTableStyleGroup Self="rts"><TableStyle Self="TableStyle/Banded" Name="Banded" StartRowFillCount="1"/></RootTableStyleGroup>+<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartColumnFillCount="2"><Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>+<Spread Self="sp1"><Page Self="p1"/>+<Rectangle Self="plain">{}</Rectangle>+<Rectangle Self="round" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner">{}</Rectangle>+<Rectangle Self="legacy" CornerOption="RoundedCorner">{}</Rectangle>+<Rectangle Self="sized" TopLeftCornerOption="RoundedCorner" TopLeftCornerRadius="5">{}</Rectangle>+<TextFrame Self="tf" ParentStory="s1">{}</TextFrame>+</Spread>+</Document>"#,+ path(0.0),+ path(100.0),+ path(200.0),+ path(300.0),+ path(400.0)+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ // Document Setup, margins and columns, grids, Advanced Type, transparency, black.+ let s = &d.settings;+ assert_eq!((s.page_width, s.page_height, s.facing_pages, s.intent), (612.0, 792.0, true, designcraft_doc::Intent::Print));+ assert_eq!((s.bleed, s.slug), ([0.0; 4], [0.0; 4]));+ let page = &d.spreads[0].pages[0];+ assert_eq!((page.margins.top, page.margins.bottom, page.margins.inside, page.margins.outside), (36.0, 36.0, 36.0, 36.0));+ assert_eq!((page.columns.count, page.columns.gutter), (1, 12.0));+ assert_eq!((s.baseline_grid.start, s.baseline_grid.increment, s.baseline_grid.view_threshold), (36.0, 12.0, 0.75));+ assert_eq!((s.grid.horizontal, s.grid.vertical, s.grid.subdivisions, s.grid.in_back), (72.0, 72.0, 8, true));+ let a = &s.advanced_type;+ assert_eq!((a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position), (58.3, 33.3, 58.3, 33.3));+ assert_eq!((s.blend_space, s.overprint_black, s.keyboard_increment), (designcraft_doc::BlendSpace::Cmyk, true, 1.0));+ // Fill, stroke, transparency, wrap and corners of a frame with no attributes.+ let item = |n: usize| d.spreads[0].items[n].clone();+ let plain = item(0);+ assert!(plain.fill.is_none() && plain.stroke.is_none());+ let st = &plain.stroke;+ assert_eq!((st.weight, st.miter_limit, st.cap, st.join, st.align), (1.0, 4.0, Cap::Butt, Join::Miter, StrokeAlign::Center));+ assert_eq!((plain.opacity, plain.blend, plain.wrap.mode), (1.0, designcraft_color::BlendMode::Normal, designcraft_doc::WrapMode::None));+ assert!(plain.corners.is_none());+ // A corner shape without a size: 12 pt.+ for n in [1, 2] {+ assert_eq!(item(n).corners.corners.map(|c| (c.shape, c.size)), [(CornerShape::Rounded, 12.0); 4], "item {n}");+ }+ assert_eq!(item(3).corners.corners[0].size, 5.0);+ // Text Frame Options.+ let tf = item(4);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset, o.balance_columns, o.ignore_wrap), (1, 12.0, [0.0; 4], false, false));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Top, FirstBaseline::Ascent, 0.0));+ assert_eq!((o.auto_size, o.auto_size_ref), (designcraft_doc::AutoSize::Off, 4), "auto-size from the centre");+ // Numbered lists don't continue across stories.+ assert_eq!(d.settings.lists, vec![designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: false }]);+ // Table and cell options.+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!((t.options.space_before, t.options.space_after, t.options.repeat_header), (4.0, -4.0, true));+ assert_eq!((t.options.border.weight, t.options.border.color.as_str()), (1.0, "[Black]"));+ assert_eq!((t.rows[0].mode, t.rows[0].height), (designcraft_doc::RowHeightMode::AtLeast, 3.0));+ // Alternating fills: the first rows or columns Black 20 %, the next None.+ let fills = |a: &designcraft_doc::AltFills| (a.first_color.clone(), a.first_tint, a.next_color.clone(), a.next_tint, a.next);+ let want = ("[Black]".to_string(), 0.2f32, "[None]".to_string(), 1.0f32, 1);+ assert_eq!(fills(t.options.alt_rows.as_ref().unwrap()), want);+ let cols = t.options.alt_cols.as_ref().unwrap();+ assert_eq!((fills(cols), cols.first), (want.clone(), 2));+ let banded = d.styles.table.iter().find(|s| s.name == "Banded").unwrap();+ let mut bt = designcraft_doc::Table::new(0, 1, 1, 0, 0, 100.0);+ d.styles.resolve_table_style(&banded.name).apply_to(&mut bt, &d.styles.cell);+ assert_eq!(fills(bt.options.alt_rows.as_ref().unwrap()), want);+ let c = t.cell(0, 0).unwrap();+ assert_eq!((c.insets, c.vj, c.fill.as_str()), ([4.0; 4], VerticalJustification::Top, "[None]"));+ for e in &c.strokes {+ assert_eq!((e.weight, e.color.as_str(), e.tint, &e.kind), (1.0, "[Black]", 1.0, &designcraft_doc::StrokeType::Solid));+ }+}++/// IDML has no attribute for a drop cap's character style: it is the nested style list's leading+/// "through 1 Dropcap" entry, read into the drop cap style and written back from it.+#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap and its character style; a paragraph overriding both locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2">+ <Properties><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/$ID/[No character style]</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ let bytes = 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 check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]), "one entry, not duplicated");+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"), "not an IDML attribute");+ check(&import_idml(&bytes).unwrap());+ // A drop cap style set without nested styles is written as one; Align Left Edge and Scale for+ // Descenders as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.nested_styles = None;+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), Some("Strong")));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]));+}++/// IDML styles and stories with an `Opener` style whose drop cap style is `Strong`, plus `styles`+/// (more paragraph styles) and `paras` (the story's paragraph ranges). `WORDS` in them stands for+/// a nested style list of `Strong` through 1 word.+fn drop_cap_fixture(styles: &str, paras: &str) -> Vec<u8> {+ let nested = |style: &str, delim: &str| {+ format!(+ r#"<AllNestedStyles type="list"><ListItem type="record"><AppliedCharacterStyle type="object">CharacterStyle/{style}</AppliedCharacterStyle><Delimiter type="enumeration">{delim}</Delimiter><Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles>"#+ )+ };+ let words = nested("Strong", "AnyWord");+ let opener = format!(+ r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3"><Properties>{}</Properties></ParagraphStyle>+ {}+ </RootParagraphStyleGroup>"#,+ nested("Strong", "Dropcap"),+ styles.replace("WORDS", &words)+ );+ let styles = STYLES.replace("</RootParagraphStyleGroup>", &opener);+ let story = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">{}</Story>+</idPkg:Story>"#,+ paras.replace("WORDS", &words)+ );+ 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),+ ])+}++/// A nested style list replaces the inherited one, drop cap style entry included: a style or+/// paragraph with a list of its own and no Dropcap entry has no drop cap style.+#[test]+fn own_nested_styles_clear_an_inherited_drop_cap_style() {+ let styles = r#"<ParagraphStyle Self="ParagraphStyle/Child" Name="Child"><Properties><BasedOn type="object">ParagraphStyle/Opener</BasedOn>WORDS</Properties></ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Plain" Name="Plain"><Properties>WORDS</Properties></ParagraphStyle>"#;+ let paras = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener"><Properties>WORDS</Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Cleared</Content><Br/></CharacterStyleRange>+ </ParagraphStyleRange>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Inherited</Content></CharacterStyleRange>+ </ParagraphStyleRange>"#;+ let d = import_idml_with(&drop_cap_fixture(styles, paras), &|_| None).unwrap();+ let cap = |name: &str| d.styles.para(name).unwrap().para.drop_cap_style.clone();+ assert_eq!(cap("Opener").as_deref(), Some("Strong"));+ assert_eq!(cap("Child").as_deref(), Some(st::NO_CHAR_STYLE), "its own list replaces Opener's");+ assert_eq!(cap("Plain"), None, "nothing to clear");+ let story = d.stories.values().find(|s| s.text.starts_with("Cleared")).unwrap();+ assert_eq!(story.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ assert_eq!(story.paras[1].para.drop_cap_style, None);+ assert_eq!(d.styles.resolve_para(&story.paras[1]).0.drop_cap_style, "Strong");+}++/// Paragraphs in table cells and footnotes are cleared like story paragraphs.+#[test]+fn own_nested_styles_clear_an_inherited_drop_cap_style_in_cells_and_notes() {+ let opener = |text: &str| {+ format!(+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener"><Properties>WORDS</Properties><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>"#+ )+ };+ let paras = format!(+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">+<Content>Body</Content><Footnote>{}</Footnote>+<Table HeaderRowCount="0" FooterRowCount="0"><Row Name="0" MinimumHeight="24"/><Column Name="0" SingleColumnWidth="60"/><Cell Name="0:0">{}</Cell></Table>+</CharacterStyleRange></ParagraphStyleRange>"#,+ opener("Note"),+ opener("Cell")+ );+ let d = import_idml_with(&drop_cap_fixture("", ¶s), &|_| None).unwrap();+ let story = d.stories.values().find(|s| !s.notes.is_empty()).expect("story with a footnote");+ let note = &story.notes[0].text;+ assert_eq!(note.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE), "{:?}", note.text);+ let cell = &story.tables.values().next().expect("a table").cell(0, 0).unwrap().text;+ assert_eq!(cell.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE), "{:?}", cell.text);+}++/// A paragraph that clears its style's drop cap style without nested styles of its own round-trips:+/// it is written with the style's list, the Dropcap entry set to [None].+#[test]+fn a_cleared_drop_cap_style_round_trips() {+ let paras = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>"#;+ let mut d = import_idml_with(&drop_cap_fixture("", paras), &|_| None).unwrap();+ let sid = *d.stories.keys().next().unwrap();+ let clear = |d: &mut Document| d.story_mut(sid).unwrap().paras[0].para.drop_cap_style = Some(st::NO_CHAR_STYLE.into());+ let resolved = |d: &Document| {+ let st = d.stories.values().find(|s| s.text.starts_with("Once")).unwrap();+ d.styles.resolve_para(&st.paras[0]).0+ };+ clear(&mut d);+ let back = import_idml(&export_idml(&d)).unwrap();+ let pp = resolved(&back);+ assert_eq!(pp.drop_cap_style, st::NO_CHAR_STYLE);+ assert_eq!(pp.nested_styles, vec![designcraft_doc::NestedStyle::drop_cap(st::NO_CHAR_STYLE)]);+ // The style's drop cap style without nested styles: the paragraph is written with an empty+ // list, which clears it on import.+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.nested_styles = None;+ }+ assert_eq!(resolved(&d).drop_cap_style, st::NO_CHAR_STYLE);+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.styles.para("Opener").unwrap().para.drop_cap_style.as_deref(), Some("Strong"));+ let pp = resolved(&back);+ assert_eq!(pp.drop_cap_style, st::NO_CHAR_STYLE);+ assert!(pp.nested_styles.iter().all(|ns| ns.style != "Strong"), "{:?}", pp.nested_styles);+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}+ #[test]+ fn type_on_a_path_keeps_its_start_and_end_brackets() {+ use designcraft_geom::{Anchor, PathData, Point, SubPath};+ for end in [Some(250.0), None] {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let id = designcraft_doc::ItemId(d.alloc());+ let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(100.0, 300.0)), Anchor::corner(Point::new(500.0, 300.0))], false));+ let mut it = designcraft_doc::Item::new(id, lid, Shape::GraphicLine, line);+ let sid = designcraft_doc::StoryId(d.alloc());+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };+ tf.options.path = Some(designcraft_doc::PathType { start: 30.0, end, ..Default::default() });+ it.content = designcraft_doc::Content::Text(tf);+ let mut story = designcraft_doc::Story::with_text(sid, "Along", Default::default());+ story.frames = vec![id];+ d.stories.insert(sid, std::sync::Arc::new(story));+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let back = import_idml(&export_idml(&d)).unwrap();+ let pt = back.spreads[0].items[0].text_frame().unwrap().options.path.clone().unwrap();+ assert!((pt.start - 30.0).abs() < 1e-6, "{pt:?}");+ assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");+ }+ }++++#[test]++fn frame_preference_import_caps_column_count_without_composition() {++ for (raw, expected) in [("4000000000", 216), ("1e300", 216), ("-100", 1), ("0", 1), ("NaN", 1), ("inf", 1), ("-inf", 1)] {++ for attribute in [true, false] {++ let preference = if attribute {++ format!(r#"<TextFramePreference TextColumnCount="{raw}"/>"#)++ } else {++ format!(++ r#"<TextFramePreference><Properties><TextColumnCount type="number">{raw}</TextColumnCount></Properties></TextFramePreference>"#++ )++ };++ let document = format!(++ r#"<Document><Story Self="s"/><Spread Self="spread"><Page Self="page"/><TextFrame Self="frame" ParentStory="s">{preference}</TextFrame></Spread></Document>"#++ );++ let d = import_idml_with(&zip_files(&[("designmap.xml", &document)]), &|_| None).unwrap();++ let frame = d.spreads[0].items[0].text_frame().unwrap();++ // Inspect imported data only: never compose an unbounded input value.++ assert_eq!(frame.options.columns, expected, "{raw}, attribute={attribute}");++ }++ }++}++++#[test]++fn frame_preference_property_color_resolves_for_frames_and_object_styles() {++ let document = r#"<Document>++<Color Self="Color/Near" Model="Process" Space="RGB" ColorValue="255 0 0" Name="Near" Visible="true"/>++<Color Self="Color/Far" Model="Process" Space="RGB" ColorValue="0 0 255" Name="Far" Visible="true"/>++<RootObjectStyleGroup Self="root">++<ObjectStyle Self="ObjectStyle/Base" Name="Base" EnableTextFrameGeneralOptions="true"><TextFramePreference ColumnRuleStrokeColor="Color/Far"/></ObjectStyle>++<ObjectStyle Self="ObjectStyle/Child" Name="Child" EnableTextFrameGeneralOptions="true"><Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></ObjectStyle>++</RootObjectStyleGroup>++<Story Self="s"/><Spread Self="spread"><Page Self="page"/>++<TextFrame Self="local" ParentStory="s" AppliedObjectStyle="ObjectStyle/Base"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>++<TextFrame Self="inherited" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"/>++<TextFrame Self="attribute" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference ColumnRuleStrokeColor="Color/Far"><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>++<TextFrame Self="invalid" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">missing</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>++</Spread></Document>"#;++ let d = import_idml_with(&zip_files(&[("designmap.xml", document)]), &|_| None).unwrap();++ let colors: Vec<_> = d.spreads[0].items.iter().map(|it| it.text_frame().unwrap().options.column_rule_color.as_str()).collect();++ assert_eq!(colors, vec!["Near", "Near", "Far", designcraft_color::swatch::NONE]);++ assert_eq!(d.styles.object_style("Child").unwrap().text_frame.as_ref().unwrap().column_rule_color, "Near");++}diff --cc crates/mcp/src/backend.rsindex c4930cc99,debdbb124..73da6c93b--- a/crates/mcp/src/backend.rs+++ b/crates/mcp/src/backend.rs@@@ -107,6 -128,96 +128,98 @@@ mod testsuse super::*;use std::net::TcpListener;+ fn closed_remote() -> (Remote, String) {+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let addr = listener.local_addr().unwrap().to_string();+ let mut remote = Remote::connect(&addr).unwrap();+ let (mut stream, _) = listener.accept().unwrap();+ stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();+ stream.set_write_timeout(Some(Duration::from_secs(2))).unwrap();+ let server = std::thread::spawn(move || {+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut line = String::new();+ assert!(reader.read_line(&mut line).unwrap() > 0);+ let request: Value = serde_json::from_str(&line).unwrap();+ assert_eq!(request["method"], "document.inspect");+ writeln!(stream, "{}", json!({"id": request["id"], "ok": true, "result": null})).unwrap();+ stream.shutdown(std::net::Shutdown::Both).unwrap();+ drop(listener);+ });+ assert_eq!(remote.call("document.inspect", json!({})), Ok(Value::Null));+ server.join().unwrap();+ let stream = &remote.conn.as_ref().unwrap().1;+ stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();+ assert_eq!(stream.peek(&mut [0]).unwrap(), 0, "FIN must be observable before the next call");+ (remote, addr)+ }++ #[test]+ fn remote_executes_once_when_app_restarts_between_calls() {+ let (mut remote, addr) = closed_remote();+ let listener = TcpListener::bind(&addr).unwrap();+ listener.set_nonblocking(true).unwrap();+ let server = std::thread::spawn(move || {+ let deadline = std::time::Instant::now() + Duration::from_secs(2);+ let mut stream = loop {+ match listener.accept() {+ Ok((stream, _)) => break stream,+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {+ if std::time::Instant::now() >= deadline {+ return 0;+ }+ std::thread::yield_now();+ }+ Err(e) => panic!("accept failed: {e}"),+ }+ };++ // The listener polls accept; the connection blocks while waiting for its request.++ stream.set_nonblocking(false).unwrap();+ stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();+ stream.set_write_timeout(Some(Duration::from_secs(2))).unwrap();+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut applied = 0;+ loop {+ let mut line = String::new();+ assert!(reader.read_line(&mut line).unwrap() > 0);+ let request: Value = serde_json::from_str(&line).unwrap();+ match request["method"].as_str().unwrap() {+ "engine.execute" => {+ assert_eq!(request["params"]["command"], "frame.create");+ applied += 1;+ }+ "document.inspect" => {}+ method => panic!("unexpected method: {method}"),+ }+ writeln!(stream, "{}", json!({"id": request["id"], "ok": true, "result": {"applied": applied}})).unwrap();+ if request["method"] == "document.inspect" {+ return applied;+ }+ }+ });++ let result = remote.call("engine.execute", json!({"command": "frame.create", "params": {"rect": [0, 0, 100, 100]}}));+ let inspected = match &result {+ Ok(_) => remote.call("document.inspect", json!({})),+ Err(_) => Err("edit failed".to_string()),+ };+ let applied = server.join().unwrap();++ assert_eq!(result, Ok(json!({"applied": 1})), "the first edit after restart must succeed");+ assert_eq!(inspected, Ok(json!({"applied": 1})));+ assert_eq!(applied, 1);+ }++ #[test]+ fn remote_reports_nothing_sent_when_reconnect_has_no_listener() {+ let (mut remote, _addr) = closed_remote();++ let error = remote.call("engine.execute", json!({"command": "frame.create", "params": {}})).unwrap_err();++ assert!(error.contains("not reachable"), "{error}");+ assert!(error.contains("nothing was sent"), "{error}");+ assert!(!error.contains("operation may have completed"), "{error}");+ }+#[test]fn remote_does_not_replay_when_reply_is_lost() {let listener = TcpListener::bind("127.0.0.1:0").unwrap();diff --cc crates/tools/src/select.rsindex c80c75973,fc9a8c316..b2ac97731--- a/crates/tools/src/select.rs+++ b/crates/tools/src/select.rs@@@ -40,11 -38,11 +40,16 @@@ enum Dragstart: Point,cur: Point,},+ /// A press with the loaded text cursor.+ Place {+ start: Point,+ cur: Point,+ },+ /// Dragging a type-on-a-path bracket along its path (`end`: the end bracket).+ Bracket {+ id: ItemId,+ end: bool,+ },Anchor {id: u64,si: usize,@@@ -801,13 -807,9 +867,14 @@@ impl Tool for SelectionToolfn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {match &self.drag {+ Drag::Place { start, cur } if crate::thread::is_drag(cx, *start, *cur) => {+ let Some((sr, r, guides)) = crate::thread::drag_frame(cx, *start, *cur) else { return vec![] };+ let r = Rect::from_points(cx.layout.to_canvas(sr, Point::new(r.x0, r.y0)), cx.layout.to_canvas(sr, Point::new(r.x1, r.y1)));+ std::iter::once(Overlay::Marquee(r)).chain(guides).collect()+ }Drag::Marquee { start, cur } => vec![Overlay::Marquee(Rect::from_points(*start, *cur))],Drag::Move { .. } | Drag::Resize { .. } | Drag::Rotate { .. } | Drag::Anchor { .. } => self.guides.clone(),+ Drag::None | Drag::Bracket { .. } => brackets(cx),_ => vec![],}}diff --cc crates/tools/src/tests.rsindex 213ccc68c,6776902aa..6df86485a--- a/crates/tools/src/tests.rs+++ b/crates/tools/src/tests.rs@@@ -706,285 -706,173 +706,456 @@@ fn pen_click_snaps_to_a_guide()assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");}+/// A text frame with overset text (selected), an empty frame and a threaded pair x → y, on page 1.+struct ThreadDoc {+ d: Document,+ l: CanvasLayout,+ s: Selection,+ c: Cache,+ /// The selected text frame.+ a: ItemId,+ /// An empty (unassigned) frame.+ e: ItemId,+ x: ItemId,+ y: ItemId,+}++fn thread_doc() -> ThreadDoc {+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });+ let lid = d.default_layer();+ let (a, _) = d+ .add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 250.0, 160.0), lid, &"Words flow on. ".repeat(40), ParaFormat::default())+ .unwrap();+ let e = ItemId(d.alloc());+ d.insert_item(SpreadRef::Doc(0), Item::new(e, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 400.0, 250.0, 500.0))), None).unwrap();+ let (x, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 100.0, 450.0, 160.0), lid, "x", ParaFormat::default()).unwrap();+ let (y, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 400.0, 450.0, 500.0), lid, "", ParaFormat::default()).unwrap();+ d.thread(x, y).unwrap();+ let l = CanvasLayout::new(&d, false);+ ThreadDoc { s: Selection::items(vec![a]), c: Cache::new(), l, d, a, e, x, y }+}++impl ThreadDoc {+ fn cx(&self) -> ToolContext<'_> {+ ctx(&self.d, &self.s, &self.c, &self.l)+ }+ /// Canvas point of a spread-0 point.+ fn at(&self, x: f64, y: f64) -> Point {+ self.l.to_canvas(SpreadRef::Doc(0), Point::new(x, y))+ }+ fn port(&self, id: ItemId, out: bool) -> Point {+ thread::port_center(&self.d, &self.l, id, out, 1.0).unwrap()+ }+}++fn click(t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {+ let mut v = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods));+ v.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y).with_mods(mods)));+ v+}++fn thread_exec(p: serde_json::Value) -> Vec<Action> {+ vec![Action::Exec("text.thread".into(), p)]+}++#[test]+fn out_port_loads_text_and_a_click_threads_an_empty_frame() {+ let td = thread_doc();+ let cx = td.cx();+ let mut t = create("selection");+ let port = td.port(td.a, true);+ // The out port sits on the right edge, 12 px above the bottom-right corner.+ assert!((port - td.at(250.0, 148.0)).hypot() < 1e-9, "{port:?}");+ // A press just off the port's centre still loads (any zoom: tolerance is in pixels).+ assert!(click(&mut t, &cx, port + designcraft_geom::Vec2::new(3.0, -3.0), Mods::default()).is_empty());+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);+ let over_e = td.at(175.0, 450.0);+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::ThreadLink);+ // A frame something already threads into can't join; neither can the loaded frame itself.+ assert_eq!(t.cursor(&cx, td.at(375.0, 450.0), Mods::default()), Cursor::NotAllowed);+ assert_eq!(t.cursor(&cx, td.at(175.0, 130.0), Mods::default()), Cursor::LoadedText);+ assert_eq!(click(&mut t, &cx, over_e, Mods::default()), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));+ // Unloaded again: the cursor and clicks are back to normal.+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::Arrow);+}++#[test]+fn ports_hit_at_any_zoom() {+ let td = thread_doc();+ let mut cx = td.cx();+ cx.zoom = 4.0;+ let port = thread::port_center(&td.d, &td.l, td.a, false, 4.0).unwrap();+ assert!((port - td.at(100.0, 100.0 + 14.5 / 4.0)).hypot() < 1e-9);+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(1.5, 1.5)), Some((td.a, false)));+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(4.0, 0.0)), None, "8 screen px away at 4×");+}++#[test]+fn loaded_click_on_empty_page_makes_a_column_frame() {+ let td = thread_doc();+ let cx = td.cx();+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.a, true), Mods::default());+ let col = td.d.spreads[0].pages[0].column_rects()[0];+ let a = click(&mut t, &cx, td.at(200.0, 600.0), Mods::default());+ assert_eq!(a, thread_exec(serde_json::json!({"from": td.a.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}})));+}++#[test]+fn loaded_drag_makes_a_frame_of_that_size_and_shift_autoflows() {+ let td = thread_doc();+ let cx = td.cx();+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.a, true), Mods::default());+ let (p0, p1) = (td.at(320.0, 560.0), td.at(470.0, 700.0));+ let shift = Mods { shift: true, ..Default::default() };+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y).with_mods(shift)).is_empty());+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y).with_mods(shift)).is_empty());+ assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::from_points(p0, p1))]);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y).with_mods(shift));+ assert_eq!(+ a,+ thread_exec(+ serde_json::json!({"from": td.a.0, "rect": [320.0, 560.0, 470.0, 700.0], "spread": {"kind": "doc", "index": 0}, "autoflow": true})+ )+ );+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow, "autoflow unloads");+}++#[test]+fn loaded_drag_snaps_like_frame_drawing() {+ let td = thread_doc();+ let cx = ToolContext { snap: SnapView::FACTORY, ..td.cx() };+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.a, true), Mods::default());+ let col = td.d.spreads[0].pages[0].column_rects()[0];+ // Press and release a point or two inside the column's edges: both sides snap to them.+ let (p0, p1) = (td.at(col.x0 + 1.5, 560.0), td.at(col.x1 - 2.0, 650.0));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y));+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y));+ let Some(Overlay::Marquee(m)) = t.overlays(&cx).first().cloned() else { panic!("no marquee") };+ assert!((m.x0 - td.at(col.x0, 0.0).x).abs() < 1e-9 && (m.x1 - td.at(col.x1, 0.0).x).abs() < 1e-9, "{m:?}");+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y));+ let [Action::Exec(id, p)] = a.as_slice() else { panic!("{a:?}") };+ assert_eq!(id, "text.thread");+ let r: Vec<f64> = p["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();+ assert_eq!((r[0], r[2]), (col.x0, col.x1), "{p}");+}++#[test]+fn alt_click_stays_loaded() {+ let mut td = thread_doc();+ let original = td.d.clone();+ let mut t = create("selection");+ let alt = Mods { alt: true, ..Default::default() };+ let col = td.d.spreads[0].pages[0].column_rects()[0];+ let empty = td.at(200.0, 600.0);+ let new_frame_from =+ |f: ItemId| thread_exec(serde_json::json!({"from": f.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}}));+ {+ let cx = td.cx();+ click(&mut t, &cx, td.port(td.a, true), Mods::default());+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);+ // The thread failed (the document is unchanged): still loaded from a.+ assert_eq!(click(&mut t, &cx, empty, alt), new_frame_from(td.a));+ }+ // That click's command ran: the next click threads after the frame it added.+ let (n, _) =+ td.d.add_text_frame(SpreadRef::Doc(0), Rect::new(col.x0, 600.0, col.x1, col.y1), td.d.default_layer(), "", ParaFormat::default()).unwrap();+ td.d.thread(td.a, n).unwrap();+ {+ let cx = td.cx();+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": n.0, "to": td.e.0})));+ }+ // Undone: back on a, not on a's old neighbour or the frame the undo removed.+ td.d = original;+ {+ let cx = td.cx();+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.a));+ }+ // From x, which threads into y: when threading e in between fails, x stays loaded, not y.+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };+ let cx = td.cx();+ click(&mut t, &cx, td.port(td.x, true), Mods::default());+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.x.0, "to": td.e.0})));+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.x));+}++#[test]+fn escape_unloads_and_keeps_the_selection() {+ let td = thread_doc();+ let cx = td.cx();+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.a, true), Mods::default());+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);+ // An ordinary click on empty space deselects again.+ let p = td.at(500.0, 700.0);+ assert_eq!(+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)),+ vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]+ );+}++#[test]+fn loaded_click_on_the_linked_frame_unthreads() {+ // x is selected; its out port links to y.+ let td = thread_doc();+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };+ let cx = td.cx();+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.x, true), Mods::default());+ let over_y = td.at(375.0, 450.0);+ assert_eq!(t.cursor(&cx, over_y, Mods::default()), Cursor::Unthread);+ assert_eq!(+ click(&mut t, &cx, over_y, Mods::default()),+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))]+ );+ // From y's in port, x is the frame before.+ let td = ThreadDoc { s: Selection::items(vec![td.y]), ..td };+ let cx = td.cx();+ click(&mut t, &cx, td.port(td.y, false), Mods::default());+ assert_eq!(+ click(&mut t, &cx, td.at(375.0, 130.0), Mods::default()),+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.y.0, "side": "before"}))]+ );+}++#[test]+fn in_port_threads_in_front() {+ let td = thread_doc();+ let cx = td.cx();+ let mut t = create("selection");+ click(&mut t, &cx, td.port(td.a, false), Mods::default());+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), Mods::default()), thread_exec(serde_json::json!({"from": td.e.0, "to": td.a.0})));+}++#[test]+fn double_click_on_a_port_breaks_its_link() {+ let td = thread_doc();+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };+ let cx = td.cx();+ // A double click sent as such (control channel), and the canvas's second press.+ let second = |p: Point| [PointerEvent::new(PointerKind::DoubleClick, p.x, p.y), PointerEvent::new(PointerKind::Down, p.x, p.y).with_clicks(2)];+ let p = td.port(td.x, true);+ for ev in second(p) {+ let mut t = create("selection");+ click(&mut t, &cx, p, Mods::default());+ let a = t.pointer(&cx, &ev);+ assert_eq!(a, vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))], "{ev:?}");+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p.x, p.y)).is_empty());+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);+ // The in port of the first frame has no link: nothing to break.+ let q = td.port(td.x, false);+ for ev in second(q) {+ assert!(t.pointer(&cx, &ev).is_empty(), "{ev:?}");+ }+ }+}++#[test]+fn clicks_in_a_row_edit_and_select_text() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 300.0, 200.0), lid, "Two words", ParaFormat::default()).unwrap();+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let (x, y) = (150.0 + off.x, 110.0 + off.y);+ let press = |n: u8| PointerEvent::new(PointerKind::Down, x, y).with_clicks(n);+ // Selection tool: the second press of a double click edits the text there.+ let mut t = create("selection");+ let a = t.pointer(&cx, &press(1));+ assert!(matches!(&a[0], Action::Exec(id, _) if id == "selection.set"), "{a:?}");+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));+ let a = t.pointer(&cx, &press(2));+ assert_eq!(a.first(), Some(&Action::SwitchTool("type".into())));+ assert!(matches!(&a[1], Action::Exec(id, p) if id == "text.placeCaret" && p["frame"] == fid.0), "{a:?}");+ // Type tool: word, line, paragraph, then the story.+ let mut t = create("type");+ let unit = |a: Vec<Action>| match a.as_slice() {+ [Action::Exec(id, p)] if id == "text.selectAt" => p["unit"].as_str().map(str::to_string),+ [Action::Exec(id, _)] if id == "text.placeCaret" => None,+ other => panic!("{other:?}"),+ };+ assert_eq!(unit(t.pointer(&cx, &press(1))), None);+ for (n, want) in [(2, "word"), (3, "line"), (4, "paragraph"), (5, "story"), (9, "story")] {+ assert_eq!(unit(t.pointer(&cx, &press(n))).as_deref(), Some(want), "{n} clicks");+ }+ // A double click sent as such (control channel) selects a word too.+ assert_eq!(unit(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x, y))).as_deref(), Some("word"));+ // Moving a little while pressed keeps the unit selected.+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());+}+++ #[test]+ fn pen_continues_an_open_path_from_either_end_point() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let anchors = vec![+ designcraft_geom::Anchor::corner(Point::new(100.0, 100.0)),+ designcraft_geom::Anchor {+ p: Point::new(200.0, 100.0),+ h_in: Point::new(170.0, 80.0),+ h_out: Point::new(230.0, 120.0),+ kind: designcraft_geom::AnchorKind::Smooth,+ },+ ];+ let mut it = Item::new(id, lid, Shape::Path, designcraft_geom::PathData::single(designcraft_geom::SubPath::new(anchors, false)));+ it.stroke = Stroke::default();+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));+ let cx = ctx(&d, &s, &c, &l);+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let at = |x: f64, y: f64| (x + off.x, y + off.y);+ let ev = |k: PointerKind, (x, y): (f64, f64)| PointerEvent::new(k, x, y);+ let mut t = create("pen");+ // The cursor says the end point continues the path; elsewhere it's the plain pen.+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::PenContinue);+ assert_eq!(t.cursor(&cx, Point::new(at(150.0, 300.0).0, at(150.0, 300.0).1), Mods::default()), Cursor::Pen);+ // Clicking the last anchor adds nothing yet; the next click appends to that path.+ assert!(t.pointer(&cx, &ev(PointerKind::Down, at(200.0, 100.0))).is_empty());+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(200.0, 100.0))).is_empty(), "a click on the end point changes nothing");+ t.pointer(&cx, &ev(PointerKind::Down, at(300.0, 200.0)));+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(300.0, 200.0)));+ let [Action::Exec(cmd, p)] = a.as_slice() else { panic!("{a:?}") };+ assert_eq!((cmd.as_str(), p["id"].as_u64(), p["subpath"].as_u64()), ("path.appendAnchor", Some(id.0), Some(0)));+ assert_eq!((p["anchor"]["p"][0].as_f64(), p["anchor"]["p"][1].as_f64()), (Some(300.0), Some(200.0)));+ // Clicking the first anchor of the other end closes it.+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));+ assert_eq!(a, vec![Action::Exec("path.close".into(), serde_json::json!({"id": id.0, "subpath": 0}))]);+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(100.0, 100.0))).is_empty());+ // From the first anchor, the path is reversed first; a drag there sets its direction lines.+ let mut t = create("pen");+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));+ assert_eq!(a, vec![Action::Exec("path.reverse".into(), serde_json::json!({"ids": [id.0], "subpath": 0}))]);+ t.pointer(&cx, &ev(PointerKind::Drag, at(80.0, 140.0)));+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(80.0, 140.0)));+ assert_eq!(+ a,+ vec![Action::Exec(+ "path.setAnchor".into(),+ serde_json::json!({"id": id.0, "subpath": 0, "anchor": "last", "in": [120.0, 60.0], "out": [80.0, 140.0]})+ )]+ );+ // Closed paths and locked paths aren't continued.+ let mut d2 = d.clone();+ d2.item_mut(id).unwrap().locked = true;+ let cx = ctx(&d2, &s, &c, &l);+ let t = create("pen");+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::Pen);+ }++ #[test]+ fn the_selection_tool_drags_a_path_type_bracket_along_its_path() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let id = ItemId(d.alloc());+ let line = designcraft_geom::PathData::single(designcraft_geom::SubPath::new(+ vec![designcraft_geom::Anchor::corner(Point::new(100.0, 300.0)), designcraft_geom::Anchor::corner(Point::new(500.0, 300.0))],+ false,+ ));+ let mut it = Item::new(id, lid, Shape::GraphicLine, line);+ let sid = designcraft_doc::StoryId(d.alloc());+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };+ tf.options.path = Some(designcraft_doc::PathType { start: 40.0, end: Some(300.0), ..Default::default() });+ it.content = designcraft_doc::Content::Text(tf);+ let mut st = designcraft_doc::Story::with_text(sid, "On the line", Default::default());+ st.frames = vec![id];+ d.stories.insert(sid, Arc::new(st));+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);+ let ev = |k: PointerKind, p: Point| PointerEvent::new(k, p.x, p.y);+ // Not selected: no brackets.+ let none = Selection::default();+ assert!(create("selection").overlays(&ctx(&d, &none, &c, &l)).is_empty());+ let s = Selection { items: vec![id], ..Default::default() };+ let cx = ctx(&d, &s, &c, &l);+ let mut t = create("selection");+ // Both brackets drawn across the path at 140 and 400 (a line and a tick each).+ let o = t.overlays(&cx);+ let xs: Vec<f64> = o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { (a.x == b.x).then_some(a.x - off.x) } else { None }).collect();+ assert_eq!(xs, [140.0, 400.0], "{o:?}");+ assert_eq!(t.cursor(&cx, at(140.0, 300.0), Mods::default()), Cursor::PathBracket);+ assert_ne!(t.cursor(&cx, at(250.0, 300.0), Mods::default()), Cursor::PathBracket);+ // Drag the start bracket: its distance along the path follows the pointer, off the path too.+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, at(140.0, 301.0))), vec![Action::Begin("Move Bracket".into())]);+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(220.0, 330.0)));+ let [Action::Preview(cmd, p)] = a.as_slice() else { panic!("{a:?}") };+ assert_eq!((cmd.as_str(), p["id"].as_u64()), ("type.pathOptions", Some(id.0)));+ assert!((p["start"].as_f64().unwrap() - 120.0).abs() < 1e-6, "{p}");+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, at(220.0, 330.0))), vec![Action::Commit]);+ // The end bracket.+ t.pointer(&cx, &ev(PointerKind::Down, at(400.0, 300.0)));+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(450.0, 290.0)));+ let [Action::Preview(_, p)] = a.as_slice() else { panic!("{a:?}") };+ assert!((p["end"].as_f64().unwrap() - 350.0).abs() < 1e-6, "{p}");+ }++ #[test]+ fn eyedropper_samples_a_placed_image_and_matches_other_objects() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let photo = ItemId(d.alloc());+ let mut it = Item::new(photo, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {+ asset: designcraft_doc::AssetId(1),+ size: (100.0, 100.0),+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ });+ d.assets.insert(+ designcraft_doc::AssetId(1),+ std::sync::Arc::new(designcraft_doc::Asset {+ id: designcraft_doc::AssetId(1),+ name: "photo.png".into(),+ mime: "image/png".into(),+ link: None,+ data: std::sync::Arc::new(vec![]),+ pixels: Some((100, 100)),+ page: 0,+ }),+ );+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ // An unfilled text frame over part of the photo lets it show through.+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(150.0, 150.0, 250.0, 250.0), lid, "x", ParaFormat::default()).unwrap();+ let swatch = add_rect(&mut d, Rect::new(300.0, 100.0, 350.0, 150.0));+ d.item_mut(swatch).unwrap().fill.swatch = "[Black]".into();+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));+ // The photo's layer is locked: sampling it still works.+ d.layers.iter_mut().for_each(|l| l.locked = true);+ let s = Selection { items: vec![target], ..Default::default() };+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));+ let off = l.xf(SpreadRef::Doc(0)).translation();+ let cx = ctx(&d, &s, &c, &l);+ let mut t = create("eyedropper");+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ let sample = |x: f64, y: f64| Action::Exec("color.sample".into(), serde_json::json!({"at": [x, y], "spread": {"kind": "doc", "index": 0}}));+ assert_eq!(a, vec![sample(120.0, 130.0)]);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 180.0 + off.x, 180.0 + off.y));+ assert_eq!(a, vec![sample(180.0, 180.0)], "through the text frame");+ // A filled object is matched as before (here on a locked layer: not reachable, so nothing).+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y)).is_empty());+ let mut d2 = d.clone();+ d2.layers.iter_mut().for_each(|l| l.locked = false);+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": swatch.0}))]);+ // Vector graphics and missing assets must retain the ordinary attribute-matching path.+ for mime in ["application/pdf", "application/postscript", "image/svg+xml", "application/octet-stream"] {+ std::sync::Arc::make_mut(d2.assets.get_mut(&designcraft_doc::AssetId(1)).unwrap()).mime = mime.into();+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))], "{mime}");+ }+ d2.assets.clear();+ let cx = ctx(&d2, &s, &c, &l);+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);+ }diff --cc crates/ui-egui/src/canvas.rsindex 181b947de,077ae2944..b2ce3172a--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1900,6 -1831,86 +1925,86 @@@ mod tests}}+ /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a+ /// row must land within the double-click delay).+ fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": text})).unwrap();+ let id = r["id"].as_u64().unwrap();+ app.run("tool.select", json!({"tool": "type"})).unwrap();+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ (h, id)+ }++ /// The screen point over the first line of frame `id` where a click puts the caret at a byte+ /// in `bytes`.+ fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range<usize>) -> Pos2 {+ let mut x = 74.0;+ let p = loop {+ assert!(x < 400.0, "no point on the first line hits {bytes:?}");+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap();+ if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) {+ break Point::new(x, 80.0);+ }+ x += 1.0;+ };+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ let app = h.state();+ let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p);+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)+ }++ fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ }++ fn selected(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {+ h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default()+ }++ #[test]- fn clicks_in_a_row_select_word_sentence_paragraph_and_story() {++ fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() {+ let text = "One two. Three four! Five six.\nSecond para here.";+ let (mut h, id) = typing(text);- // Inside "Three", the second sentence: its start is not the paragraph's.++ // Inside "Three": double-click selects the word, then line and paragraph with return.+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ let mut got = vec![];+ for _ in 0..5 {+ click(&mut h, p);+ let r = selected(&h);+ got.push(text[r].to_string());+ }- assert_eq!(got[1..], ["Three", "Three four! ", "One two. Three four! Five six.", text], "{got:?}");++ assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}");+ assert!(got[0].is_empty(), "one click places the caret: {got:?}");+ }++ #[test]+ fn slow_clicks_do_not_add_up() {+ let (mut h, id) = typing("One two. Three four!");+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ for _ in 0..3 {+ click(&mut h, p);+ h.run_steps(30);+ }+ assert!(selected(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected(&h));+ }+#[test]fn rulers_open_no_units_menu_without_a_document() {let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()));diff --cc crates/ui-egui/src/control.rsindex 44e3c0bda,5a4de0058..15da79df8--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -100,15 -100,7 +100,16 @@@ fn key_from(name: &str) -> Option<egui:})}+/// Handle one control request. Commands it runs leave the user's system clipboard alone.pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {++ app.install_clipboard_guard(ctx);+ let was = std::mem::replace(&mut app.in_control, true);+ let out = handle_request(app, ctx, req);+ app.in_control = was;+ out+}++fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {let p = &req.params;let s = |k: &str| p.get(k).and_then(Value::as_str);match req.method.as_str() {@@@ -180,21 -165,21 +181,28 @@@mac_cmd: b("cmd") && cfg!(target_os = "macos"),command: b("cmd"),};-- app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });-- app.synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m });++ app.control_synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: m });++ app.control_synthetic.push(egui::Event::Key { key: k, physical_key: None, pressed: false, repeat: false, modifiers: m });if let Some(t) = s("text") {-- app.synthetic.push(egui::Event::Text(t.to_string()));++ app.control_synthetic.push(egui::Event::Text(t.to_string()));}ctx.request_repaint();ok(Value::Null)}"ui.move" => {let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32);-- app.synthetic.push(egui::Event::PointerMoved(pos));++ app.control_synthetic.push(egui::Event::PointerMoved(pos));ctx.request_repaint();ok(Value::Null)}"ui.click" | "ui.drag" => {++ let count = match p.get("count") {++ None => 1,++ Some(v) => match v.as_u64().filter(|n| (1..=255).contains(n)) {++ Some(n) => n,++ None => return err("`count` must be an integer from 1 through 255"),++ },++ };// Screen-space (egui points) pointer input through egui itself: reaches every widget.let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;let button = match s("button") {@@@ -212,21 -197,21 +220,20 @@@};let a = egui::pos2(f("x"), f("y"));let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };-- app.synthetic.push(egui::Event::PointerMoved(a));-- app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });++ app.control_synthetic.push(egui::Event::PointerMoved(a));++ app.control_synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });if req.method == "ui.drag" {// From the caller: a huge count would queue events until memory runs out.let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(8).clamp(1, 10_000);for i in 1..=steps {let t = i as f32 / steps as f32;-- app.synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));++ app.control_synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));}}-- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });-- let count = p.get("count").and_then(Value::as_u64).unwrap_or(1);++ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });for _ in 1..count {-- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });-- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });++ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });++ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });}ctx.request_repaint();ok(Value::Null)@@@ -236,7 -221,7 +243,7 @@@// Focused widgets retain the synthetic keyboard route. Document automation uses// the explicit caret independently of the active tool, unlike ordinary typing.if ctx.text_edit_focused() || app.ui.dialog.is_some() || app.ui.palette.is_some() {-- app.synthetic.push(egui::Event::Text(text.to_string()));++ app.control_synthetic.push(egui::Event::Text(text.to_string()));ctx.request_repaint();ok(Value::Null)} else {@@@ -453,7 -439,7 +461,7 @@@ mod automation_contract_tests}assert!(ctx.text_edit_focused());assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"field"}))["ok"], true);-- let events = std::mem::take(&mut app.synthetic);++ let events = std::mem::take(&mut app.control_synthetic);frame(&mut app, &ctx, events);assert_eq!(app.ui.palette.as_deref(), Some("field"));assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello");@@@ -490,41 -476,3 +498,117 @@@assert!(writes.lock().unwrap().is_empty());}}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };++ #[test]+ fn control_paste_never_reads_the_system_clipboard() {+ let calls = Arc::new(AtomicUsize::new(0));+ let seen = calls.clone();+ let services = crate::Services {+ clipboard_text: Some(Box::new(move || {+ seen.fetch_add(1, Ordering::SeqCst);+ Some("SECRET".into())+ })),+ ..Default::default()+ };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ assert!(app.session.active().unwrap().selection.text.is_some(), "the new frame is being typed in");+ let text = |app: &DesignApp| app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone();+ let ctx = egui::Context::default();+ let (req, _rx) = ControlRequest::new("engine.execute", json!({"command": "edit.paste"}));+ let _ = handle(&mut app, &ctx, &req);+ assert_eq!(calls.load(Ordering::SeqCst), 0, "the control channel must not read the system clipboard");+ assert!(!text(&app).contains("SECRET"));+ assert!(!app.in_control);+ // The same command chosen by the user does paste the system clipboard.+ let _ = app.run("edit.paste", json!({}));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert!(text(&app).contains("SECRET"));+ }+}++++#[cfg(test)]++mod deferred_clipboard_tests {++ use super::*;++ use std::sync::{++ Arc,++ atomic::{AtomicUsize, Ordering},++ };++++ #[test]++ fn synthetic_paste_keeps_mock_clipboard_private() {++ let reads = Arc::new(AtomicUsize::new(0));++ let observed = reads.clone();++ let mut app = DesignApp::new(++ designcraft_engine::Session::new(),++ crate::Services {++ clipboard_text: Some(Box::new(move || {++ observed.fetch_add(1, Ordering::SeqCst);++ Some("SYNTHETIC_CLIPBOARD_SENTINEL".to_string())++ })),++ ..Default::default()++ },++ );++ app.run("file.new", json!({})).unwrap();++ let frame = app.run("frame.create", json!({"content":"text", "text":"Original", "rect":[72,72,200,100], "caret":false})).unwrap();++ app.run("selection.set", json!({"ids":[frame["id"]]})).unwrap();++ assert!(!app.session.wants_text());++ let ctx = egui::Context::default();++ let (req, _) = ControlRequest::new("ui.key", json!({"key":"V", "cmd":true}));++ assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(v) if v["ok"]==true));++ assert!(!app.in_control);++ for step in 0..3 {++ let mut raw = egui::RawInput { time: Some(step as f64 * 0.05), ..Default::default() };++ app.raw_input_hook(&mut raw);++ ctx.run_ui(raw, |ui| menus::shortcuts(&mut app, ui.ctx())).textures_delta.clear();++ }++ let texts: Vec<String> = app.session.active().unwrap().doc.stories.values().map(|story| story.text.clone()).collect();++ assert_eq!(reads.load(Ordering::SeqCst), 0, "synthetic command read mocked system clipboard; stories={texts:?}");++ assert!(!texts.iter().any(|text| text.contains("SYNTHETIC_CLIPBOARD_SENTINEL")));++ // Once control input is drained, an ordinary user paste still reads its clipboard.++ let mut raw = egui::RawInput::default();++ app.raw_input_hook(&mut raw);++ app.run("edit.paste", json!({})).unwrap();++ assert_eq!(reads.load(Ordering::SeqCst), 1);++ }++ #[test]++ fn deferred_control_widget_copy_leaves_native_clipboard_output_alone() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ let ctx = egui::Context::default();++ let (req, _) = ControlRequest::new("ui.move", json!({"x":10,"y":10}));++ let _ = handle(&mut app, &ctx, &req);++ let mut raw = egui::RawInput::default();++ app.raw_input_hook(&mut raw);++ let mut private = ctx.run_ui(raw, |ui| ui.ctx().copy_text("control field".into()));++ assert!(!private.platform_output.commands.iter().any(|cmd| matches!(cmd, egui::OutputCommand::CopyText(_))));++ private.textures_delta.clear();++ let mut raw = egui::RawInput::default();++ app.raw_input_hook(&mut raw);++ let mut native = ctx.run_ui(raw, |ui| ui.ctx().copy_text("native field".into()));++ assert!(native.platform_output.commands.iter().any(|cmd| matches!(cmd, egui::OutputCommand::CopyText(text) if text=="native field")));++ native.textures_delta.clear();++ }++++ #[test]++ fn control_click_rejects_unbounded_counts_before_queuing_input() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ let ctx = egui::Context::default();++ for count in [json!(u64::MAX), json!(256), json!(0), json!(-1), json!(1.5)] {++ let (req, _) = ControlRequest::new("ui.click", json!({"x":10,"y":10,"count":count}));++ assert!(matches!(handle(&mut app, &ctx, &req), Outcome::Done(v) if v["ok"]==false));++ assert!(app.control_synthetic.is_empty());++ assert!(app.synthetic.is_empty());++ assert!(!app.in_control);++ }++ }++}diff --cc crates/ui-egui/src/lib.rsindex ec52bd141,fc7a3e634..1db2f591d--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -499,6 -496,6 +504,10 @@@ pub struct DesignApppub color_applied: bool,pub perf: Perf,pub synthetic: Vec<egui::Event>,++ /// Control input stays separate from native-menu input until its frame is processed.++ pub(crate) control_synthetic: Vec<egui::Event>,++ control_input_frame: std::sync::Arc<std::sync::atomic::AtomicBool>,++ clipboard_guard_installed: bool,/// Story open in the Story Editor.pub story_editor: Option<designcraft_doc::StoryId>,control_rx: Option<Receiver<ControlRequest>>,@@@ -518,15 -515,18 +527,27 @@@last_time: f64,/// When recovery data was last written (seconds, egui time).pub last_recovery: f64,+ /// The egui context (set by the first frame): copied text goes to the system clipboard through it.+ egui_ctx: Option<egui::Context>,+ /// A control-channel request is being handled: commands it runs never read or write the+ /// user's system clipboard (a control client must not see or replace it).+ pub(crate) in_control: bool,+ /// The system clipboard's text that stands for the last object copy: what that copy put there+ /// (no native menu: without it the paste keys produce no paste event), or what it held then+ /// (native menu). It is never pasted as text: Paste with it pastes the copied objects.+ object_clip_text: Option<String>,+ /// Quit was chosen: close the window on the next frame, as its close button does.+ quit_requested: bool,+ /// Close the window without asking about unsaved changes (the control channel's `app.quit`).+ pub(crate) quit_without_asking: bool,+ /// No document is discarded until every unsaved document has an up-to-date approval.+ quitting: Option<QuitState>,+ }++ struct QuitState {+ original_active: Option<u64>,+ accepted: HashMap<u64, u64>,+ pending: Option<u64>,}impl DesignApp {@@@ -550,6 -550,6 +571,9 @@@color_applied: false,perf: Perf::default(),synthetic: vec![],++ control_synthetic: vec![],++ control_input_frame: Default::default(),++ clipboard_guard_installed: false,story_editor: None,control_rx: None,pending_shots: vec![],@@@ -564,9 -564,9 +588,12 @@@native_shortcuts: Default::default(),last_time: 0.0,last_recovery: 0.0,+ egui_ctx: None,+ in_control: false,+ object_clip_text: None,+ quit_requested: false,+ quit_without_asking: false,+ quitting: None,}}@@@ -610,35 -610,10 +637,35 @@@if let Some(r) = menus::run_ui(self, id, ¶ms) {return r;}+ // Only user-initiated runs touch the system clipboard, never the control channel's.- let system_clipboard = !self.in_control;++ let system_clipboard = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed);+ let params = if system_clipboard { self.with_system_clipboard(id, params) } else { params };let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());self.after_engine();- if let Err(e) = &r {- self.status(e.clone());+ match &r {+ Err(e) => self.status(e.clone()),+ // Copied text goes to the system clipboard too, whichever way Copy was chosen.+ Ok(v) if system_clipboard && matches!(id, "edit.copy" | "edit.cut") => {+ let text = match v.get("text").and_then(Value::as_str) {+ Some(t) => {+ self.object_clip_text = None;+ Some(t.to_string())+ }+ None if !self.native_menu => {+ self.object_clip_text = Some(self.copied_objects_text());+ self.object_clip_text.clone()+ }+ None => {+ self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f());+ None+ }+ };+ if let (Some(t), Some(ctx)) = (text, &self.egui_ctx) {+ ctx.copy_text(t);+ ctx.request_repaint();+ }+ }+ Ok(_) => {}}r}@@@ -898,7 -807,7 +925,7 @@@if self.fonts_ready {self.drain_inbox();}-- if !self.synthetic.is_empty() {++ if !self.synthetic.is_empty() || !self.control_synthetic.is_empty() {ctx.request_repaint();}self.collect_screenshots(ctx);@@@ -951,19 -1005,19 +1123,39 @@@r}-- /// Inject synthetic events (one pointer event per frame).-- pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) {-- if self.synthetic.is_empty() {++ /// Keep widget clipboard output private while a queued control event is running.++ pub(crate) fn install_clipboard_guard(&mut self, ctx: &egui::Context) {++ if self.clipboard_guard_installed {return;}-- let n = match self.synthetic[0] {++ let private = self.control_input_frame.clone();++ ctx.on_end_pass(++ "control clipboard",++ std::sync::Arc::new(move |ui| {++ if private.load(std::sync::atomic::Ordering::Relaxed) {++ ui.ctx().output_mut(|o| {++ o.commands.retain(|cmd| !matches!(cmd, egui::OutputCommand::CopyText(_) | egui::OutputCommand::CopyImage(_)))++ });++ }++ }),++ );++ self.clipboard_guard_installed = true;++ }++++ /// Inject synthetic events (one pointer event per frame), retaining control provenance.++ pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) {++ let private = !self.control_synthetic.is_empty();++ self.control_input_frame.store(private, std::sync::atomic::Ordering::Relaxed);++ let events = if private { &mut self.control_synthetic } else { &mut self.synthetic };++ let Some(first) = events.first() else { return };++ let n = match first {egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } => 1,-- _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1),++ _ => events.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(events.len(), |i| i + 1),};-- if let Some(egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() {++ if let egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } = first {raw.events.push(egui::Event::PointerMoved(*p));}-- raw.events.extend(self.synthetic.drain(..n));++ raw.events.extend(events.drain(..n));}/// Lay out the whole window.diff --cc crates/ui-egui/src/menus.rsindex ee28b6447,872cb81d0..dc8b88bf2--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -85,12 -86,20 +86,26 @@@ pub const UI_COMMANDS: &[(&str, &str, O("view.zoom", "Zoom To", None, "{zoom: 1.0 = 100%}"),("view.screenMode", "Screen Mode", None, "{mode: normal|preview|bleed|slug|presentation}"),("view.togglePreview", "Toggle Normal/Preview", Some("W"), "{}"),+ (+ "app.formattingAffectsText",+ "Formatting Affects Text",+ Some("J"),+ "{on?: bool} — with text frames selected, colours go to their text (on) or the frames (off); toggles without `on`",+ ),+ (+ "color.defaultFillStroke",+ "Default Fill and Stroke",+ Some("D"),+ "{} — the selection gets no fill and a black stroke (object.defaultFillStroke)",+ ),+ (+ "color.swapFillStroke",+ "Swap Fill and Stroke",+ Some("Shift+X"),+ "{} — each selected object's fill and stroke colours (and tints) trade places (object.swapFillStroke)",+ ),+ ("color.toggleFillStroke", "Toggle Fill and Stroke", Some("X"), "{} → {strokeFront} — which of fill and stroke the proxy has in front"),+ ("color.applyNone", "Apply None", Some("/"), "{} — [None] for the fill or stroke in front of the proxy"),("view.frameEdges", "Show/Hide Frame Edges", Some("Cmd+H"), "{}"),("view.rulers", "Show/Hide Rulers", Some("Cmd+R"), "{}"),("view.guides", "Show/Hide Guides", Some("Cmd+;"), "{}"),@@@ -2385,31 -2482,6 +2492,35 @@@ mod testsassert!(!egui::Popup::is_any_open(&ctx), "choosing a command dismisses the menu");}+ #[test]+ fn formatting_affects_text_sends_swatches_to_the_text() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();++ for (name, color) in [("Cyan", "#00ffff"), ("Magenta", "#ff00ff")] {++ let created = app.run("swatch.create", json!({"name": name, "color": color})).unwrap();++ assert_eq!(created["name"], name);++ }+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap();+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [fid]})).unwrap();+ let text_fill = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();+ st.char_format_at(2).over.fill.clone()+ };+ let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();+ assert!(!crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Cyan", None).unwrap();+ assert_eq!(frame_fill(&app), "Cyan");+ assert_eq!(text_fill(&app), None);+ let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap();+ assert_eq!(r["on"], true, "toggles on");+ assert!(crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Magenta", Some(0.5)).unwrap();+ assert_eq!(frame_fill(&app), "Cyan", "the frame is left alone");+ assert_eq!(text_fill(&app).as_deref(), Some("Magenta"));+ assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("Magenta".to_string(), 0.5)));+ }+#[test]fn transform_menu_items_open_their_dialogs() {for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] {diff --cc crates/ui-egui/src/panels/swatches.rsindex 5bbf5fd29,7544347a9..967ff38f4--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@@ -206,11 -208,9 +206,10 @@@ pub fn color_panel(app: &mut DesignApp));return;};+ let text = super::colors_affect_text(app);let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };- let stroke_id = egui::Id::new("color_panel_stroke");let mode_id = egui::Id::new("color_panel_mode");- let mut stroke: bool = ui.data(|d| d.get_temp(stroke_id)).unwrap_or(false);+ let mut stroke = app.ui.stroke_front;let default_mode = if doc.settings.intent == designcraft_doc::Intent::Print { ColorMode::Cmyk } else { ColorMode::Rgb };let mut mode: ColorMode = ui.data(|d| d.get_temp(mode_id)).unwrap_or(default_mode);let target = if stroke { "stroke" } else { "fill" };diff --cc crates/ui-egui/src/toolbar.rsindex 03b297dd4,20f49475d..6e7d98487--- a/crates/ui-egui/src/toolbar.rs+++ b/crates/ui-egui/src/toolbar.rs@@@ -194,13 -194,13 +194,12 @@@ pub fn show(app: &mut DesignApp, ui: &m/// utility button and the Screen Mode well.fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {let t = Tokens::get(ui.ctx());- let info = crate::panels::sel_info(app);+ let target = crate::panels::color_target(app);let doc = app.session.active().map(|d| d.doc.clone());- let stroke_front_id = egui::Id::new("proxy_stroke_front");- let stroke_front: bool = ui.data(|d| d.get_temp(stroke_front_id)).unwrap_or(false);- let text_id = egui::Id::new("proxy_text");+ let stroke_front = app.ui.stroke_front;- let text_mode: bool = ui.data(|d| d.get_temp(text_id)).unwrap_or(false);- let (fill_sw, stroke_sw) = match &info {- Some(i) => (i.fill.clone(), i.stroke.clone()),+ let text_mode = crate::panels::colors_affect_text(app) || app.ui.formatting_affects_text;+ let (fill_sw, stroke_sw) = match &target {+ Some((fill, _, stroke, _)) => (fill.clone(), stroke.clone()),None => ("[None]".to_string(), "[Black]".to_string()),};let x0 = ui.max_rect().min.x + (width - 30.0) / 2.0;@@@ -279,10 -277,23 +276,26 @@@if fresp.clicked() || sresp.clicked() {let front =if stroke_front { !fresp.clicked() } else { sresp.clicked() && !fill_r.contains(sresp.interact_pointer_pos().unwrap_or_default()) };- ui.data_mut(|d| d.insert_temp(stroke_front_id, front));+ app.ui.stroke_front = front;}+ // A double-click opens the Color Picker for that box (as InDesign's), with the selection's+ // colour: the selected text's when text is selected.if fresp.double_clicked() || sresp.double_clicked() {- let _ = app.run("window.panel", json!({"panel": "swatches"}));+ let on_fill = fresp.double_clicked() && (!stroke_front || !sresp.double_clicked());+ let stroke = !on_fill;+ let text = crate::panels::text_attrs(app).filter(|_| app.session.active().is_some_and(|d| d.selection.text.is_some()));+ let current = match text {+ Some(a) => a["chars"][if stroke { "stroke" } else { "fill" }].as_str().unwrap_or("[None]").to_string(),+ None if stroke => stroke_sw.clone(),+ None => fill_sw.clone(),+ };+ let rgb = doc.as_ref().and_then(|d| d.resolve_color(¤t, 1.0)).map_or([0.0; 3], |c| c.to_rgb());+ let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let hex = format!("#{:02x}{:02x}{:02x}", byte(rgb[0]), byte(rgb[1]), byte(rgb[2]));- app.ui.dialog = Some(crate::dialogs::Dialog::new("colorPicker", json!({"target": if stroke { "stroke" } else { "fill" }, "hex": hex})));++ app.ui.dialog = Some(crate::dialogs::Dialog::new(++ "colorPicker",++ json!({"target": if stroke { "stroke" } else { "fill" }, "hex": hex, "text": crate::panels::colors_affect_text(app)}),++ ));}ui.add_space(3.0);// Formatting affects container / text.@@@ -317,8 -328,9 +330,8 @@@let chip = egui::Rect::from_center_size(well.center(), vec2(14.0, 14.0));crate::widgets::paint_chip(ui.painter(), chip, None, None);flyout_triangle(ui.painter(), well, t.icon);- let target = if stroke_front { "object.stroke" } else { "object.fill" };if resp.clicked() {- let _ = crate::panels::apply_swatch(app, stroke_front, "[None]", None);+ let _ = app.run("color.applyNone", json!({}));}egui::Popup::context_menu(&resp).show(|ui| {for (label, sw) in [("Apply Color", "[Black]"), ("Apply None", "[None]")] {@@@ -411,6 -423,28 +424,31 @@@ fn tool_button(ui: &mut egui::Ui, icon})}+ /// Default Fill and Stroke (D): no fill, a black stroke.+ pub(crate) fn default_fill_stroke(app: &mut DesignApp) -> Result<Value, String> {- app.run("object.defaultFillStroke", json!({}))++ if crate::panels::colors_affect_text(app) {++ app.run("type.char", json!({"fill": "[Black]", "fillTint": 1.0, "stroke": "[None]", "strokeTint": 1.0}))++ } else {++ app.run("object.defaultFillStroke", json!({}))++ }+ }++ /// Swap Fill and Stroke (Shift+X): each selected object's fill and stroke trade places.+ pub(crate) fn swap_fill_stroke(app: &mut DesignApp) -> Result<Value, String> {- app.run("object.swapFillStroke", json!({}))++ if crate::panels::colors_affect_text(app) { app.run("type.swapFillStroke", json!({})) } else { app.run("object.swapFillStroke", json!({})) }+ }++ /// Fill/Stroke toggle (X): brings the other of fill and stroke to the front of the proxy.+ pub(crate) fn toggle_fill_stroke(app: &mut DesignApp) -> Result<Value, String> {+ app.ui.stroke_front = !app.ui.stroke_front;+ Ok(json!({"strokeFront": app.ui.stroke_front}))+ }++ /// Apply None (/): to the fill or the stroke, whichever is in front of the proxy.+ pub(crate) fn apply_none(app: &mut DesignApp) -> Result<Value, String> {- let target = if app.ui.stroke_front { "object.stroke" } else { "object.fill" };- app.run(target, json!({"swatch": "[None]"}))++ crate::panels::apply_swatch(app, app.ui.stroke_front, "[None]", None)+ }+#[cfg(test)]mod tests {use egui::{pos2, vec2};@@@ -482,4 -546,42 +550,122 @@@wheel(&mut h, panel.center(), vec2(0.0, -2000.0));assert_eq!((rect(&h, LAST_TOOL), rect(&h, FILL)), before);}+ /// The Fill/Stroke proxy's keys run on the selection and stay out of text being typed.+ #[test]+ fn fill_stroke_proxy_keys() {+ use egui::{Event, Key, Modifiers};+ use serde_json::json;+ fn press(app: &mut crate::DesignApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) {+ let events = [true, false].map(|pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }).to_vec();+ ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::menus::shortcuts(app, ui.ctx())).textures_delta.clear();+ }+ fn colors(app: &crate::DesignApp) -> (String, f32, String, f32) {+ let st = app.session.active().unwrap();+ let it = st.doc.item(st.selection.items[0]).unwrap();+ (it.fill.swatch.clone(), it.fill.tint, it.stroke.swatch.clone(), it.stroke.tint)+ }+ let mut app = app(false);+ let ctx = egui::Context::default();+ app.run("file.new", json!({})).unwrap();+ let f = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap();+ app.run("selection.set", json!({"ids": [f["id"]]})).unwrap();+ app.run("object.fill", json!({"swatch": "[Paper]", "tint": 0.5})).unwrap();+ app.run("object.stroke", json!({"swatch": "[Black]", "tint": 1.0})).unwrap();++ press(&mut app, &ctx, Key::X, Modifiers::SHIFT);+ assert_eq!(colors(&app), ("[Black]".into(), 1.0, "[Paper]".into(), 0.5), "Shift+X swaps, tints included");+ press(&mut app, &ctx, Key::D, Modifiers::NONE);+ assert_eq!(colors(&app), ("[None]".into(), 1.0, "[Black]".into(), 1.0), "D: no fill, black stroke");+ press(&mut app, &ctx, Key::X, Modifiers::NONE);+ assert!(app.ui.stroke_front, "X brings the stroke to the front");+ press(&mut app, &ctx, Key::Slash, Modifiers::NONE);+ assert_eq!(colors(&app).2, "[None]", "/ applies None to the stroke in front");++ // Typing in a story: the keys are text, not shortcuts.+ app.session.execute("text.select", &json!({"story": f["story"], "anchor": 5})).unwrap();+ app.select_tool("type");+ assert!(app.session.wants_text());+ press(&mut app, &ctx, Key::X, Modifiers::NONE);+ assert!(app.ui.stroke_front, "X while typing leaves the proxy alone");+ }+ }++++#[cfg(test)]++mod text_color_tests {++ use super::*;++ use designcraft_doc::{ItemId, StoryId};++++ #[test]++ fn integration_color_swap_preserves_each_run_and_frame() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({})).unwrap();++ let mut frames = vec![];++ let mut stories = vec![];++ for text in ["abcd", "efgh"] {++ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":text})).unwrap();++ frames.push(f["id"].clone());++ stories.push(f["story"].as_u64().unwrap());++ }++ let pairs = [("[Paper]", "[Black]", 0.2, 0.8), ("[Black]", "[Paper]", 0.4, 0.6)];++ for (i, sid) in stories.iter().enumerate() {++ for j in 0..2 {++ let (fill, stroke, ft, st) = pairs[(i + j) % 2];++ app.run("text.select", json!({"story":sid,"anchor":j*2,"focus":j*2+2})).unwrap();++ app.run("type.char", json!({"fill":fill,"stroke":stroke,"fillTint":ft,"strokeTint":st})).unwrap();++ }++ }++ app.run("selection.set", json!({"ids":frames})).unwrap();++ app.run("app.formattingAffectsText", json!({"on":true})).unwrap();++ let before = serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap();++ let n = app.session.doc().unwrap().history.undo.len();++ swap_fill_stroke(&mut app).unwrap();++ assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1);++ for (i, sid) in stories.iter().enumerate() {++ let story = app.session.doc().unwrap().doc.story(StoryId(*sid)).unwrap();++ for j in 0..2 {++ let (fill, stroke, ft, st) = pairs[(i + j) % 2];++ let a = &story.format_after(j * 2).over;++ assert_eq!((a.fill.as_deref(), a.stroke.as_deref(), a.fill_tint, a.stroke_tint), (Some(stroke), Some(fill), Some(st), Some(ft)));++ }++ }++ let swapped = serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap();++ app.run("edit.undo", json!({})).unwrap();++ assert_eq!(serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap(), before);++ app.run("edit.redo", json!({})).unwrap();++ assert_eq!(serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap(), swapped);++ }++++ #[test]++ fn integration_color_toolbar_picker_targets_selected_frame_text() {++ use egui_kittest::kittest::Queryable;++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({})).unwrap();++ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"hello"})).unwrap();++ app.run("selection.set", json!({"ids":[f["id"]]})).unwrap();++ app.run("app.formattingAffectsText", json!({"on":true})).unwrap();++ let before = app.session.doc().unwrap().doc.item(ItemId(f["id"].as_u64().unwrap())).unwrap().fill.clone();++ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(0.001).build_ui_state(++ |ui, app: &mut DesignApp| {++ app.logic(&ui.ctx().clone());++ app.ui(ui);++ },++ app,++ );++ h.run_steps(6);++ let at = h.get_by_label("Fill (X)").rect().center();++ h.hover_at(at);++ h.step();++ for pressed in [true, false, true, false] {++ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });++ h.step();++ }++ h.run_steps(3);++ let d = h.state().ui.dialog.clone().unwrap();++ assert_eq!(d.id, "colorPicker");++ assert_eq!(d.fields["text"], true);++ h.state_mut().run("object.color", json!({"color":"#123456","target":"fill","text":d.fields["text"]})).unwrap();++ let doc = &h.state().session.doc().unwrap().doc;++ assert_eq!(doc.item(ItemId(f["id"].as_u64().unwrap())).unwrap().fill, before);++ assert!(doc.story(StoryId(f["story"].as_u64().unwrap())).unwrap().format_after(0).over.fill.is_some());++ }+}diff --cc docs/target-app-parity.mdindex 9457774e4,eb7d7e5c1..daaa3f44c--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -265,10 -265,10 +265,10 @@@ The inventory below was the "Working toIt is evidence of breadth: each item exists. It is not a claim of InDesign-level depth.- Document model: facing/non-facing spreads, parent pages with page-number markers, sections, layers, frames (text / graphic / unassigned), threaded stories, paragraph/character/object styles with based-on, swatches (process/spot/tints/gradients), corner options, text wrap, drop shadow, opacity/blend.-- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together, widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.+- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together — at start/end of paragraph by default, as in InDesign — widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.- FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.- - UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.+ - UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.