DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge autoflow-columns: Autoflow: one frame per column, as the page's columns are set (#625)
aiongg86848092ed1d
diff --cc ROADMAP.mdindex b687addb0,554f44a74..8951518d4--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,37 -129,8 +128,38 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-12** · Autoflow on Place threads one frame per page column (right to left in a right-to-left story), so text no longer runs across the gutter; pages Smart Text Reflow adds get a primary frame with the page's columns (#625). No readiness percentage change.+- **2026-10-12** · Vector art copied in Illustrator, VectorCraft, Figma or Inkscape pastes as editable paths, as InDesign pastes Illustrator art: the SVG those apps put on the clipboard becomes paths with their fills, strokes (weight, caps, joins, dashes) and opacity, groups stay groups and text comes in as outlines, centred in the view (`edit.pasteSvg`, `ui.paste`). Edit › Paste reads the system clipboard when nothing was copied in DesignCraft. No readiness percentage change.+- **2026-10-12** · Pages panel: double-clicking a parent shows that parent and selects only its row; parent rows show rendered thumbnails. Commands name parents by id, full name, or a prefix only one parent has; an unknown or ambiguous name is an error instead of clearing the page's parent (#624). No readiness percentage change.+- **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. 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-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.+- **2026-10-11** · Font menu laid out like InDesign's: filters (classification, favourites,+ recently added), families opening to their styles, the selected text as the sample in three+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.+- **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-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** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). No readiness percentage change.+- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.+- **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** · 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** · 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** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). 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** · Text frame auto-size: Height Only, Width Only, Height and Width (also keeping proportions) frames grow and shrink to fit their text after edits and IDML import, around their reference point, with minimum sizes and No Line Breaks, in the same undo step (#180). No readiness percentage change.+- **2026-10-12** · Text Frame Options › Balance Columns (`object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`) evens out the columns of the frame a story ends in, from its last column break on; frames the text runs on from fill normally (#609). 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** · Windows: dragging the window across monitors with different display scales keeps its size instead of growing until it crashes (winit pinned to its 0.30.x backport of the fix). The GPU surface may be as large as the adapter's largest texture (16384 px on DirectX 12, Vulkan and Metal hardware) instead of 8192, and a wgpu error is logged instead of closing the app. 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.diff --cc crates/engine/src/cmd/file.rsindex 58d028433,f1e690209..b7bde70ad--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -124,7 -102,7 +124,7 @@@ pub fn specs() -> Vec<CommandSpec>"Place…",["File"],Some("Cmd+D"),- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: threads one frame per page column (from the first frame on), adding pages until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",++ "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: threads one frame per page column (from the first frame on), adding pages until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",has_doc,file_place),diff --cc crates/engine/src/cmd/place_text.rsindex 71cd3d66f,8d3e1ba3b..6f5276eda--- a/crates/engine/src/cmd/place_text.rs+++ b/crates/engine/src/cmd/place_text.rs@@@ -122,41 -123,102 +122,108 @@@ fn fit(d: &Document, sid: StoryId) -> ((cs.overset_at, held, full)}- /// Thread new frames on new pages (margin rectangles) until the story fits. Returns pages added.+ /// The frames autoflow sets on a page: one per column inside the margins, in the order a story+ /// of direction `dir` runs through them. A vertical story gets one frame on the live area.+ fn flow_rects(d: &Document, dir: TextDirection, vertical: bool, page: usize) -> Vec<Rect> {+ let Some(p) = d.page(page) else { return Vec::new() };+ if vertical {+ return vec![p.margin_rect()];+ }+ let mut cols = p.column_rects();+ if dir == TextDirection::RightToLeft {+ cols.reverse();+ }+ cols+ }++ fn same_rect(a: Rect, b: Rect) -> bool {+ [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|v| v.abs() < 0.01)+ }++ /// Thread new frames until the story fits: first into the columns after the last frame's column+ /// on its page (when it sits in one), then one frame per column on each page it adds. With+ /// `primary` (Smart Text Reflow of the primary text frame), each added page gets one frame on the+ /// live area with the page's columns instead. Empty frames it made at the end of the thread are+ /// removed again, except the first on a page. Returns pages added.-pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, primary: bool) -> Result<usize> {- let (dir, story_vertical) = d.story(sid).map(|s| (s.direction, s.vertical)).ok_or_else(|| bad("file.place", "no such story"))?;+/// A story on a parent spread doesn't autoflow: its frames thread only on that parent. Errors+/// name `cmd`, the command that autoflows.- pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, cmd: &str) -> Result<usize> {++pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize, cmd: &str, primary: bool) -> Result<usize> {+ let last = d.story(sid).and_then(|s| s.frames.last().copied()).ok_or_else(|| bad(cmd, "the story has no frame"))?;+ if !matches!(d.find(last).map(|l| l.spread), Some(SpreadRef::Doc(_))) {+ return Err(bad(cmd, "autoflow works only from a frame on a document page"));+ }++ let (dir, story_vertical) = d.story(sid).map(|s| (s.direction, s.vertical)).ok_or_else(|| bad(cmd, "no such story"))?;+ // One frame per page: on the live area, its columns those of the page.+ let vertical = story_vertical || primary;let mut added = 0;+ let mut made = Vec::new();+ let mut first = true;loop {let (overset, held, full) = fit(d, sid);- let Some(at) = overset else { return Ok(added) };- if added >= max_pages {- return Err(bad(cmd, format!("autoflow stopped after {max_pages} pages")));- }+ let Some(at) = overset else { break };let len = d.story(sid).map_or(0, |s| s.len());// Frames still needed at the rate the full ones are filled (at least one); with no full- // frame to go by yet, one more page.- let want = held.checked_div(full).map_or(1, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))).clamp(1, max_pages - added);+ // frame to go by yet, one more.+ let want = held.checked_div(full).map_or(1, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))).max(1);- let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad("file.place", "the story has no frame"))?;+ let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad(cmd, "the story has no frame"))?;- let mut page = d.page_of_item(last).unwrap_or(d.page_count().saturating_sub(1));- let parent = d.page_loc(page).and_then(|(si, pi)| d.spreads[si].pages[pi].parent);- d.insert_pages(Some(page), want, parent)?;+ let page = d.page_of_item(last).unwrap_or(d.page_count().saturating_sub(1));let layer = d.default_layer();let mut prev = last;- for _ in 0..want {- page += 1;- let (si, pi) = d.page_loc(page).ok_or_else(|| bad(cmd, "page insert failed"))?;- let r = d.spreads[si].pages[pi].margin_rect();- let (fid, _) = d.add_text_frame(SpreadRef::Doc(si), r, layer, "", ParaFormat::default())?;- d.thread(prev, fid)?;- prev = fid;+ if std::mem::take(&mut first) {+ let rects = flow_rects(d, dir, vertical, page);+ let next = d.item(last).and_then(|it| rects.iter().position(|r| same_rect(*r, it.bounds()))).map_or(rects.len(), |k| k + 1);+ if let (Some(rest), Some((si, _))) = (rects.get(next..).filter(|r| !r.is_empty()), d.page_loc(page)) {+ for r in rest.iter().take(want) {+ prev = add_flow_frame(d, si, *r, layer, prev)?;+ made.push(prev);+ }+ continue;+ }}- added += want;+ if added >= max_pages {- return Err(bad("file.place", format!("autoflow stopped after {max_pages} pages")));++ return Err(bad(cmd, format!("autoflow stopped after {max_pages} pages")));+ }+ let per_page = if vertical { 1 } else { d.page(page).map_or(1, |p| p.columns.count.max(1) as usize) };+ let pages = want.div_ceil(per_page).clamp(1, max_pages - added);+ let parent = d.page_loc(page).and_then(|(si, pi)| d.spreads[si].pages[pi].parent);+ d.insert_pages(Some(page), pages, parent)?;+ for pg in page + 1..=page + pages {- let (si, pi) = d.page_loc(pg).ok_or_else(|| bad("file.place", "page insert failed"))?;++ let (si, pi) = d.page_loc(pg).ok_or_else(|| bad(cmd, "page insert failed"))?;+ let columns = d.spreads[si].pages[pi].columns.clone();+ for r in flow_rects(d, dir, vertical, pg) {+ prev = add_flow_frame(d, si, r, layer, prev)?;+ made.push(prev);+ if primary && let Some(tf) = d.item_mut(prev).and_then(|it| it.text_frame_mut()) {+ tf.options.columns = columns.count.max(1);+ tf.options.gutter = columns.gutter;+ }+ }+ }+ added += pages;}+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ while let Some(&f) = made.last() {+ let frames = d.story(sid).map_or(&[][..], |s| s.frames.as_slice());+ let [.., before, tail] = frames else { break };+ if *tail != f || cs.frame(f).is_some_and(|ft| !ft.range.is_empty()) || d.page_of_item(*before) != d.page_of_item(f) {+ break;+ }+ d.remove_item(f)?;+ made.pop();+ }+ Ok(added)+ }++ fn add_flow_frame(+ d: &mut Document,+ si: usize,+ r: Rect,+ layer: designcraft_doc::LayerId,+ prev: designcraft_doc::ItemId,+ ) -> Result<designcraft_doc::ItemId> {+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(si), r, layer, "", ParaFormat::default())?;+ d.thread(prev, fid)?;+ Ok(fid)}pub(super) fn place_text(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result<Value> {@@@ -235,7 -299,7 +304,7 @@@*sel = designcraft_doc::Selection::items(vec![fid]);sid};- let pages = if autoflow_on { autoflow(d, sid, 2000, "file.place")? } else { 0 };- let pages = if autoflow_on { autoflow(d, sid, 2000, false)? } else { 0 };++ let pages = if autoflow_on { autoflow(d, sid, 2000, "file.place", false)? } else { 0 };let overset = fit(d, sid).0.is_some();Ok(json!({"story": sid.0, "pagesAdded": pages, "overset": overset, "warnings": warnings}))})@@@ -296,29 -422,6 +427,29 @@@ mod tests}let _ = std::fs::remove_dir_all(&dir);}++ #[test]+ fn autoflow_adds_the_pages_odd_and_even_page_breaks_ask_for() {+ // From page 1, an odd page break needs pages 2 and 3 (2 stays empty), an even one page 2.+ // A frame such a break ends early holds few characters; taken for a full frame, it made+ // autoflow add a page per few characters left.+ use designcraft_doc::{EVEN_PAGE_BREAK, ODD_PAGE_BREAK, build::NewDocument};+ for (brk, added) in [(ODD_PAGE_BREAK, 2), (EVEN_PAGE_BREAK, 1)] {+ let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, primary_text_frame: true, ..Default::default() });+ let sid = d.settings.primary_story.unwrap();+ d.story_mut(sid).unwrap().insert(+ 0,+ &format!(+ "a{brk}+{}",+ "word ".repeat(200)+ ),+ );- assert_eq!(autoflow(&mut d, sid, 50, "file.place").unwrap(), added, "{brk:?}");++ assert_eq!(autoflow(&mut d, sid, 50, "file.place", false).unwrap(), added, "{brk:?}");+ assert_eq!(d.page_count(), added + 1, "{brk:?}");+ assert_eq!(designcraft_compose::compose_story(&d, sid, &Default::default()).overset_at, None, "{brk:?}");+ }+ }}#[cfg(test)]diff --cc crates/engine/src/cmd/thread.rsindex 8cedac277,000000000..ac13cb2f8mode 100644,000000..100644--- a/crates/engine/src/cmd/thread.rs+++ b/crates/engine/src/cmd/thread.rs@@@ -1,379 -1,0 +1,379 @@@+//! 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")));+ }+ Ok(id)+}++/// 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 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 };++ let pages = if autoflow { super::place_text_autoflow(d, sid, AUTOFLOW_MAX_PAGES, "text.thread", false)? } 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)"))),+ };+ 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")?;+ 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/src/lib.rsindex cede9b0cb,f640daaa9..5f647e34e--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -577,24 -472,20 +577,20 @@@ impl Session}let mut d = (*st.doc).clone();if overset {- let _ = cmd::place_text_autoflow(&mut d, sid, 500, "Smart Text Reflow");- let _ = cmd::place_text_autoflow(&mut d, sid, 500, true);++ let _ = cmd::place_text_autoflow(&mut d, sid, 500, "Smart Text Reflow", true);} else {- // Drop empty trailing frames on the last pages (one frame, nothing else there).+ // Drop the last pages while all they hold is empty frames of the story.while let Some(story) = d.story(sid) {- if story.frames.len() < 2 {- break;- }let Some(&last) = story.frames.last() else { break };- let cs = designcraft_compose::compose_story(&d, sid, &Default::default());- if cs.frame(last).is_some_and(|ft| !ft.range.is_empty()) {- break;- }let Some(page) = d.page_of_item(last) else { break };- let alone = d.spreads.iter().flat_map(|sp| sp.items.iter()).filter(|i| d.page_of_item(i.id) == Some(page)).count() == 1;- if page + 1 != d.page_count() || !alone || d.page_count() < 2 {+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());+ let on_page: Vec<_> =+ d.spreads.iter().flat_map(|sp| sp.items.iter()).map(|i| i.id).filter(|id| d.page_of_item(*id) == Some(page)).collect();+ let empty = |id: &designcraft_doc::ItemId| story.frames.contains(id) && cs.frame(*id).is_none_or(|ft| ft.range.is_empty());+ if page + 1 != d.page_count() || d.page_count() < 2 || !on_page.iter().all(empty) || on_page.len() >= story.frames.len() {break;}- if d.remove_item(last).is_err() || d.delete_pages(&[page]).is_err() {+ if on_page.iter().any(|id| d.remove_item(*id).is_err()) || d.delete_pages(&[page]).is_err() {break;}}diff --cc docs/target-app-parity.mdindex 97922261a,07d1eefa9..3cfc36f8a--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -291,13 -291,11 +291,13 @@@ It is evidence of breadth: each item ex- Native engine saves, Save a Copy, snippets, books, libraries, swatches and engine/MCP exports use same-folder atomic replacement, as do desktop Services writes and CLI raster exports. Failed writes before replacement retain the original; existing Unix permissions apply before staging document bytes, and already-open readers retain the old bytes. Parent-folder flushing is best effort, so this is not a power-loss durability guarantee.- Save As prepares destination-relative data-source paths before writing and installs them only after a successful save. Failed Save As retains the document, saved state and history; Save a Copy rebases only the saved copy. Library and book collection edits likewise update live values only after persistence succeeds.- Crash recovery: unsaved documents are written every 30 s into a locked folder owned by that running app and reopened (unsaved, remembering their files) after a crash. Startup takes entries from ended runs and leaves live runs alone; writes and cleanup validate current folder and lock ownership. Failed isolation disables recovery with a warning. Recovered checkpoints remain available through another crash before autosave; restarting IDs and explicit recovery from another folder preserve unopened snapshots. Successful Save, Close or Revert clears the document's checkpoints, including manual recovery while autosave is disabled; failed republishing keeps the original. Concurrent older versions still use unlocked root entries; mixed-version isolation remains open. File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.-- Window close and application/menu Quit ask about every unsaved document. Cancel or a cancelled/failed save keeps all tabs open; Don't Save approvals discard nothing until the complete plan is current. Later edits and new documents are checked before closing. Control-channel quit remains immediate; a cancelable macOS Dock Quit prompt is still missing (#544).+- Window close, application/menu Quit and macOS Dock Quit ask about every unsaved document. Cancel or a cancelled/failed save keeps all tabs open; Don't Save approvals discard nothing until the complete plan is current. Later edits and new documents are checked before closing. Repeated native requests preserve an active dialog and partial approvals. Control-channel quit remains immediate.- Graphics backend chosen before the window exists (DirectX 12 on Windows, Vulkan on Linux, Metal on macOS, OpenGL as the fallback; `WGPU_BACKEND` overrides) with a start-up fallback: a backend whose start never showed a frame is skipped at the next start and the status bar says so (`gpu.json`). Found on an AMD hybrid-graphics laptop whose Vulkan driver faulted at the first present.+- Graphics adapter chosen by the app: the GPU that drives the primary display (Windows `EnumDisplayDevices`, Linux sysfs), then the power preference (`WGPU_POWER_PREF`, `WGPU_ADAPTER_NAME` override). An adapter that fails or hangs while the window starts is left out and the app starts again on the next one, then on the next backend, with software renderers last; wgpu's indirect-call check is off (it lost the Metal device on an Intel Mac, #334); why the app stopped is logged, also when the window never opened (#273). Ported from VectorCraft.- Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).- Color panel (fill/stroke proxy, CMYK/RGB/Lab sliders with channel ramps, tint slider for swatches, spectrum ramp, Add to Swatches) and Color Picker (double-click the proxy); mixed colours are unnamed (not listed in Swatches until added); `object.color`, `swatch.addToSwatches`, `swatch.addUnnamed`.+- Threading: click a selected text frame's in or out port (overset or not) to load the text cursor, then click a frame to thread it (stories merge), click empty space for a column-wide frame down to the bottom margin, or drag a frame; Shift-click autoflows, Alt-click stays loaded; click the linked frame or double-click a port to break the thread; Esc unloads. Link and unthread cursors show where a click threads or unthreads. `text.thread`, `text.unthread`, `text.removeFromThread`.- - Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).+ - Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow threads one frame per page column and adds pages until the text fits; Remove Styles option (`designcraft-textimport`).- Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).- File ▸ Export Text (`file.exportText`): a story as Text Only or RTF (fonts, styles, alignment, indents, tables as tab-separated rows); Export EPUB now asks for a path in the UI.