DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
fix: integrate parent deletion with current main (#956)
harrisonoconnorhover9434e96dbf00
diff --cc ROADMAP.mdindex fa42b4c24,9bd0274ef..866d8fc30--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -214,7 -215,8 +215,9 @@@ same references), and from the app's JS| # | Milestone | State |**Stage: pre-alpha** · next: alpha, ~0% and ~15–25 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (undoable parent deletion) · **Target:** Adobe InDesign 2026+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (A0, A1 and A2 poster presets) · **Target:** Adobe InDesign 2026+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (parent canvas refresh) · **Target:** Adobe InDesign 2026> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (bounded control click/drag input) · **Target:** Adobe InDesign 2026> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text stroke behind fill) · **Target:** Adobe InDesign 2026@@@ -343,16 -346,63 +347,65 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log- - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.-- - **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.-Newest first.- - **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.- - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.- - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.- - **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.++- **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change.+++ - **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change.+ - **2026-10-16** · Greek text hyphenates. The patterns were never compiled in, so Greek set unhyphenated however narrow the column; `"Greek"`, `"Greek: Greece"`, `el` and `el-GR` all resolve now and ανθρωπος breaks αν-θρω-πος. They are the monotonic patterns (hyph-el-monoton, Dimitrios Filippou, under MIT), which is what polytonic text hyphenates by too. Five of InDesign's ~40 hyphenation languages. No readiness percentage change.+ - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `<Image FillColor>` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change.+ - **2026-10-15** · Color Theme: the toolbar tool previews up to five colours from a placed raster and adds them as one undoable swatch group. Local deterministic extraction; transparent padding is ignored. No readiness percentage change.+ - **2026-10-15** · Applying text styles removes matching local formatting so capture sources+ inherit later edits; real overrides and named character styles remain.+ - **2026-10-15** · Redefine paragraph and character styles from local formatting, including the+ Styles panel context menu, global updates and one-step undo.+ - **2026-10-15** · Paragraph Styles marks local character overrides and offers Clear Overrides+ in the style row menu; named character styles and equal local values are not false overrides.+ - **2026-10-15** · Existing paragraph and character styles preview their attribute edits in+ Style Options; Cancel restores the document and OK records one edit.+ - **2026-10-15** · Paragraph Style Options summarizes captured and pending color, size and+ paragraph settings relative to the Based On style.+ - **2026-10-15** · Typography uses named panel groups with the Control panel and restores that+ arrangement on Reset Workspace, leaving the page clear until a panel is opened. No readiness percentage change.+ - **2026-10-15** · Character panel: dragging a variable font axis slider previews on the page and is one undo step when let go (with several axes it piled up an undo step per frame); each axis takes a typed value, and narrow axes (Skia's 0.48–3.2) step by hundredths instead of jumping to whole numbers. The fields line up in two columns, auto leading shows in parentheses, and an axis-set style shows its axes. New `edit.preview` / `edit.commitPreview` / `edit.cancelPreview` commands give panels, the control channel and MCP live previews. No readiness percentage change.+ - **2026-10-15** · Selection tool: once a frame's content is selected (double-click, or the content grabber), the pointer is a hand over it and a drag anywhere on it moves the content inside the frame (Shift keeps one axis), as in InDesign; it moved the frame unless the press was on the grabber. No readiness percentage change.+ - **2026-10-15** · Scaling a text frame (Cmd+Shift-dragging a handle, the Scale tool, Transform panel scale fields) sets its text larger or smaller and leaves the frame at 100%, as InDesign's default When Scaling: Apply to Content does; it used to keep the text's size with the scale on the frame. No readiness percentage change.+ - **2026-10-15** · With nothing selected, the Tools panel's fill and stroke (the Color Picker, swatches, Apply None, Swap, Default) set the colours new shapes are drawn with, as InDesign's document defaults; the proxy shows them. They were refused ("nothing selected").+ - **2026-10-15** · The Eyedropper with text selected picks up the formatting of the text it clicks (character style and overrides, paragraph style and overrides) and applies it to the selection, as InDesign's does; it copied the clicked frame's fill and stroke instead. No readiness percentage change.+ - **2026-10-15** · A0, A1 and A2 poster presets are available in New Document, Document Setup, Properties, the Page tool and the Pages panel's size menu, as well as `file.new` and `layout.pageSize`. No readiness percentage change.+ - **2026-10-15** · Define Lists… is listed under Type › Bulleted & Numbered Lists in command search and Edit › Menus, matching the menu, and the parity doc no longer lists a Type › Paragraph Rules… menu item that does not exist. No readiness percentage change.+ - **2026-10-15** · Pressing Enter in the Layers panel's rename field without typing leaves an unnamed object unnamed, so it keeps following its automatic label instead of taking it as a fixed name. No readiness percentage change.+ - **2026-10-15** · Apply Gradient (.) with the Stroke box in front puts a new default gradient on the stroke in one undo step and leaves the fill's swatch and tint as they were. No readiness percentage change.+ - **2026-10-15** · In a facing-pages document, two odd-numbered pages in a row after a section restart (page 2 starting at 1) each get their own spread and stay right pages, instead of sharing a spread with an odd page on the left. No readiness percentage change.+ - **2026-10-15** · Character formatting set at a caret on a blank line (an empty paragraph) applies to the line's paragraph mark and to the text typed there, also after the caret has left the line and come back; typed text used to take the previous paragraph's format. No readiness percentage change.+ - **2026-10-15** · Very wide effects stay sharp at high zoom: a wide Basic Feather draws the object itself at full resolution, with only the soft mask at a reduced one, and wide inner shadows, inner glows, satin and bevels are clipped to the shape at full resolution, so they no longer blur the object or bleed past its edge. No readiness percentage change.+ - **2026-10-15** · The Typography panel controls every OpenType feature a character format carries: Other Features lists Proportional Metrics, Horizontal Kana, Localized Forms, Mark Positioning, Justification Alternates and Roman Italics. Lining, Oldstyle, Tabular or Proportional chosen alone also sets the other figure axis, so IDML export keeps the figure style instead of writing Default. Standard Ligatures follows and sets Character › Ligatures. No readiness percentage change.+ - **2026-10-15** · Join Path and Convert Point leave a path on a locked layer or inside a locked group unchanged, as the other path edits do. No readiness percentage change.+ - **2026-10-15** · A kerning value chosen in the Character panel or Properties at a caret kerns the pair at the caret (the character before it takes the value, in one undo step), and the field shows that pair's kerning; at the start of a story or paragraph it is kept for the next typing, and a selection is kerned as before (`type.kernPair`). No readiness percentage change.+ - **2026-10-15** · Japanese, Chinese and Korean input methods type into stories with the Type tool: the marked text shows in place, underlined (the clause being converted twice), with the candidate window at the caret, and the commit is one undo step. Keys, shortcuts, the clipboard and Undo wait while the input method composes; a click, a tool switch or another command keeps the marked text as typed. Not yet checked by hand with a system input method. No readiness percentage change.+ - **2026-10-15** · IDML placed PDFs keep their page and Crop to box (`PDFAttribute` `PageNumber` and `PDFCrop`, written for every placed PDF); two crops of one PDF page stay two assets; a page the PDF lacks is left out of PDF export with a warning instead of failing it; `$ID/` font names resolve; the IDML in a package links the images in its Links folder without embedding them. No readiness percentage change.+ - **2026-10-15** · The CJK leading model and character alignment take effect only in paragraphs set with a Japanese composer (`HL Composer J`, `HL Single J`), which IDML import and export keep: Western and Arabic paragraphs set baseline to baseline on the Roman baseline, a paragraph switched to a Japanese composer gets the file's Aki Below spacing, and under Aki Below a line's leading is the space below it. No readiness percentage change.+ - **2026-10-15** · Document pages follow their parent page's margins and columns unless margins were set on the page itself (`Page::local_margins`): applying a different parent gives a page that parent's margins, a page that changes side after an insert takes the other parent page's, and a page given margins equal to its parent's keeps them when the parent changes. IDML import and older files mark pages whose margins differ from their parent as their own. No readiness percentage change.+ - **2026-10-15** · Start-up picks the GPU that drives the display (or the kind `WGPU_POWER_PREF` or the adapter `WGPU_ADAPTER_NAME` names), and when a start-up fails or hangs it restarts on the next adapter, then the next backend, then a software renderer, keeping recovered documents; start-up errors are logged to standard error and the log file (#273, #334). No readiness percentage change.+ - **2026-10-15** · IDML: liquid guides keep their type on document and parent pages instead of reopening as ordinary ruler guides. Positions, orientation, Fit to Page, locks and layers are preserved; object liquid constraints remain unmapped (#872). No readiness percentage change.+ - **2026-10-15** · Table ▸ Convert Rows ▸ To Header / To Body / To Footer, as in InDesign: the selected rows become header rows when they touch the top of the table or its header rows, footer rows when they touch the bottom or its footer rows, and header or footer rows next to the body go back to body rows. The items are greyed out when the rows can't change (a gap, the last body row, a merged cell across the new boundary); one undo step. No readiness percentage change.+ - **2026-10-15** · Table of Contents: each included style can set a character style for its page number and for the text between entry and number, and Sort Entries in Alphabetical Order lists its entries alphabetically among their siblings, each with the entries under it (#1069). Both survive Update Table of Contents, renaming or deleting the character style, and IDML (`PageNumberStyle`, `SeparatorStyle`, `Sort`). No readiness percentage change.+ - **2026-10-15** · Measures in inches show four decimals, as InDesign's fields do (A4 is 8.2677 × 11.6929 in, a 1p0 gutter 0.1667 in); other units keep three.+ - **2026-10-15** · Ruler menus as InDesign's: right-clicking where the rulers meet sets the units of both; each ruler's menu lists InDesign's units and Hide Rulers, the horizontal one Delete All Guides on Spread.+ - **2026-10-15** · Properties › Edit Page works as InDesign's: the Page tool on the page in view, and Properties shows that page alone (Page Size: page, preset, orientation, W/H; Margins and Columns; Quick Actions) with Back. It opened Document Setup, which changes every page.+ - **2026-10-15** · Deleting pages that contain objects asks first, as InDesign does ("The affected page contains objects. Delete the page anyway?", with Don't show again), from the Pages panel, Layout › Pages › Delete Page and Properties.+ - **2026-10-15** · A page scrolled or jumped to shows its paper while its render is on its way, as in InDesign, instead of the black of its shadow.+ - **2026-10-15** · Tab, Shift+Tab and Presentation hide the icon column's panel flyout and the classic floating panels too, as InDesign hides floating panels.+ - **2026-10-15** · Layers panel: an object's row is renamed with a slow double-click (a second click on the selected row), as in InDesign; a quick double-click only selects it.+ - **2026-10-15** · New Workspace is InDesign's: Name, and Capture › Panel Locations and Menu Customization (the items hidden with Edit › Menus), both on by default; a workspace saved without panel locations leaves the panels where they are. No readiness percentage change.+ - **2026-10-15** · Presentation shows one spread at a time, as large as the screen allows; the arrow keys, Page Up/Down, Home, End, a click and Shift-click go through the spreads.+ - **2026-10-15** · Layout › First Page, Previous Page, Next Page, Last Page, Next Spread and Previous Spread, with InDesign's shortcuts (Shift+Page Up/Down, Shift+Cmd+Page Up/Down, Alt+Page Up/Down).+ - **2026-10-15** · A panel tab's context menu (and the end of its panel menu) has InDesign's Close, Close Tab Group, Minimize and Collapse to Icons, before Float Panel and Group with; `window.panel.closeGroup` and `window.collapseToIcons` are commands. No readiness percentage change.+ - **2026-10-15** · Window › Styles › Paragraph Styles (or Character Styles) opens InDesign's floating Character Styles | Paragraph Styles group, which stays open while other panels open; it was a flyout that the next panel replaced. No readiness percentage change.+ - **2026-10-15** · Double-clicking the status bar's preflight count or its light shows the Preflight panel, as in InDesign.+ - **2026-10-15** · A tool group's flyout closes on Esc and on a click anywhere outside it (a panel, the Fill swatch), as InDesign's; it only closed on a click on the canvas.+ - **2026-10-15** · Pages panel › Panel Options…, as InDesign's: page and parent sizes from Extra Small to Jumbo, Show Thumbnails, parents shown vertically or side by side, Pages or Parents on Top, and how the two parts share a resize; in the panel menu, the page menu and the right-click menu on the panel's empty part.+ - **2026-10-15** · The Pages panel is laid out as InDesign's: parents and pages scroll on their own, a divider between them shows more or fewer parents, and the footer (page count, Edit page size, Create new page, Delete) stays at the bottom. It scrolled away with the pages.- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.diff --cc crates/doc/src/build.rsindex 43e0c7be0,db61e5869..f8ae0ec19--- a/crates/doc/src/build.rs+++ b/crates/doc/src/build.rs@@@ -1,8 -1,8 +1,8 @@@//! Creating documents (File → New → Document), presets, and page/spread structure edits//! (insert/delete/move pages, repagination into spreads, parents).- use std::collections::{BTreeMap, HashSet};- use std::sync::Arc;+ use std::collections::BTreeMap;-use std::sync::Arc;++use std::{collections::HashSet, sync::Arc};use designcraft_geom::{Affine, Unit, units};use serde::{Deserialize, Serialize};@@@ -251,53 -258,18 +258,65 @@@ impl Documentid}+ /// Delete a parent spread and unapply it wherever it is used. Local overrides survive as+ /// ordinary items; the deleted parent's own items leave their text threads normally.+ pub fn delete_parent(&mut self, id: SpreadId) -> Result<()> {+ let index = self.parent_index(id).ok_or_else(|| DocError::Invalid(format!("no parent {id}")))?;+ let parent = self.parents.get(index).ok_or_else(|| DocError::Invalid(format!("no parent {id}")))?;+ let roots: Vec<_> = parent.items.iter().map(|item| item.id).collect();+ let mut deleted = HashSet::new();+ for item in &parent.items {+ item.walk(&mut |item| {+ deleted.insert(item.id);+ });+ }+ for item in roots {+ self.remove_item(item)?;+ }+ self.parents.remove(index);++ let mut detached = Vec::new();+ for spread in self.spreads.iter_mut().chain(self.parents.iter_mut()) {+ let spread = Arc::make_mut(spread);+ if let Some(parent) = &mut spread.parent+ && parent.based_on == Some(id)+ {+ parent.based_on = None;+ }+ for page in &mut spread.pages {+ if page.parent == Some(id) {+ page.parent = None;+ }+ page.overridden.retain(|item| !deleted.contains(item));+ }+ for item in &spread.items {+ item.walk(&mut |item| {+ if item.overrides.is_some_and(|source| deleted.contains(&source)) {+ detached.push(item.id);+ }+ });+ }+ }+ for item in detached {+ if let Some(item) = self.item_mut(item) {+ item.overrides = None;+ }+ }+ Ok(())+ }++ /// List the pages of each facing parent spread in binding order: left then right, or right+ /// then left when bound right to left. Positions stay, so the parent items keep their pages.+ pub fn order_parent_pages(&mut self) {+ let first = if self.settings.right_to_left_binding { PageSide::Right } else { PageSide::Left };+ for sp in &mut self.parents {+ let pair = matches!(sp.pages.as_slice(), [a, b] if a.side != b.side && a.side != PageSide::Single && b.side != PageSide::Single);+ if pair && sp.pages.first().is_some_and(|p| p.side != first) {+ Arc::make_mut(sp).pages.reverse();+ }+ }+ }+pub fn parent_index(&self, id: SpreadId) -> Option<usize> {self.parents.iter().position(|p| p.id == id)}diff --cc crates/engine/src/cmd/layout.rsindex f1313dc4e,6a4e7f054..615e7c1df--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@@ -246,34 -257,51 +257,72 @@@ pub fn specs() -> Vec<CommandSpec>Ok(json!({"id": id.0, "prefix": prefix}))})}),+ cmd!(+ "layout.parents.delete",+ "Delete Parent",+ [],+ None,+ "{id: parent spread id} — unapply the parent and keep local overrides as ordinary items",+ has_doc,+ |s, p| {+ let id = p.get("id").and_then(Value::as_u64).map(SpreadId).ok_or_else(|| bad("layout.parents.delete", "missing parent id"))?;+ s.edit(|d, sel| {+ d.delete_parent(id)?;+ *sel = Default::default();+ ok()+ })?;+ let st = s.doc_mut()?;+ if st.doc.parents.is_empty() {+ st.editing_parents = false;+ }+ ok()+ }+ ),- cmd!(noundo "layout.parents.edit", "Edit Parents", [], None, "{on: bool} — show parent spreads on the canvas", has_doc, |s, p| {- let st = s.doc_mut()?;- st.editing_parents = p.get("on").and_then(Value::as_bool).unwrap_or(!st.editing_parents);- st.selection = Default::default();- st.revision += 1;- ok()- }),+ cmd!(+ noundo "layout.parents.edit",+ "Edit Parents",+ [],+ None,+ "{on?: bool, parent?: id|\"A-Parent\"|\"A\"} — show parent spreads on the canvas; `parent` shows that parent (and implies on). Turning on without `parent` shows the first parent",+ has_doc,+ |s, p| {+ const ID: &str = "layout.parents.edit";+ let doc = s.doc()?.doc.clone();+ let parent = match p.get("parent") {+ None | Some(Value::Null) => None,+ v => match parent_ref(ID, &doc, v)? {+ Some(Some(id)) => Some(id),+ _ => return Err(bad(ID, "`parent` names a parent to show")),+ },+ };+ let st = s.doc_mut()?;+ let was = st.editing_parents;+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(parent.is_some() || !was);+ st.editing_parents = on;+ st.selection = Default::default();+ st.bump_revision();+ // The parent to show: the one asked for, or the first when editing starts.+ let index = match parent {+ Some(id) => doc.parent_index(id),+ None if !was && !doc.parents.is_empty() => Some(0),+ None => None,+ };+ let shown = index.filter(|_| on);+ if let Some(i) = shown {+ s.ui_requests.push(crate::UiRequest::View { params: json!({"showSpread": designcraft_doc::SpreadRef::Parent(i)}) });+ }+ Ok(json!({"on": on, "parent": shown.and_then(|i| doc.parents.get(i)).map(|x| x.id.0)}))+ }+ ),+ cmd!(+ "layout.parents.options",+ "Parent Options…",+ [],+ None,+ "{parent: id|\"B-Parent\"|\"B\", basedOn: id|\"A-Parent\"|\"A\"|null (= [None])} — the parent shows its base's items under its own, and so do the pages that use it → {parent, basedOn}",+ has_doc,+ parent_options+ ),cmd!("layout.marginsAndColumns","Margins and Columns…",@@@ -1286,6 -1741,292 +1762,296 @@@ mod spread_rotation_input_tests}}+ #[cfg(test)]+ mod layer_options_tests {+ use serde_json::json;++ #[test]+ fn layer_set_sets_every_field_and_rejects_bad_names() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let first = s.doc().unwrap().doc.layers[0].id.0;+ let id = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap();+ let all = json!({"id": id, "name": " Artwork ", "color": "Gold", "visible": false, "locked": true, "printable": false,+ "showGuides": false, "suppressWrapWhenHidden": true});+ s.execute("layer.set", &all).unwrap();+ let l = s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).cloned().unwrap();+ assert_eq!(l.name, "Artwork");+ assert_eq!(l.color, [255, 153, 0]);+ assert!(!l.visible && l.locked && !l.printable && !l.show_guides && l.suppress_wrap_when_hidden);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).unwrap().name, "Art", "one undo step");+ let first_name = s.doc().unwrap().doc.layers.iter().find(|l| l.id.0 == first).unwrap().name.clone();+ let before = s.doc().unwrap().doc.layers.clone();+ for p in [+ json!({"id": id, "name": ""}),+ json!({"id": id, "name": " "}),+ json!({"id": id, "name": first_name}),+ json!({"id": id, "name": "Fine", "color": "Plaid"}),+ json!({"id": id, "color": [300, 0, 0]}),+ json!({"id": id, "visible": "yes"}),+ json!({"id": 999_999, "name": "Ghost"}),+ ] {+ assert!(s.execute("layer.set", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().doc.layers, before);+ // Keeping its own name is fine.+ s.execute("layer.set", &json!({"id": id, "name": "Art", "color": [1, 2, 3]})).unwrap();+ }+ }++ #[cfg(test)]+ mod parent_margin_tests {+ use designcraft_doc::{Document, Margins};+ use serde_json::json;++ use crate::Session;++ fn margins(d: &Document) -> Vec<(Margins, u32, bool)> {+ (0..d.page_count()).filter_map(|i| d.page(i)).map(|p| (p.margins, p.columns.count, p.local_margins)).collect()+ }++ #[test]+ fn document_setup_margins_let_pages_follow_their_parent_page_again() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [1], "margins": 100})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100, "columns": 3})).unwrap();+ s.execute("layout.documentSetup", &json!({"margins": 20})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ let twenty = Margins::uniform(20.0);+ assert_eq!(m, vec![(twenty, 1, false), (twenty, 1, false), (twenty, 3, true)], "own columns stay local");+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (Margins::uniform(50.0), 1, false), "page 2 follows the parent page again");+ assert_eq!(m[2], (twenty, 3, true));+ }++ #[test]+ fn pages_follow_their_parent_pages_margins_unless_set_locally() {+ let mut s = Session::new();+ // Facing: [1] [2 3]; page 3 gets its own margins.+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100})).unwrap();+ // A's left page: only the left document page follows.+ let left = json!({"top": 10, "bottom": 20, "inside": 30, "outside": 40});+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "pages": [0], "margins": left, "columns": 2})).unwrap();+ let l = Margins { top: 10.0, bottom: 20.0, inside: 30.0, outside: 40.0 };+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(36.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A's right page: page 1 follows, page 3 keeps its own.+ s.execute("layout.marginsAndColumns", &json!({"parent": "A-Parent", "pages": [1], "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(50.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A page inserted after page 1 pushes page 2 to the right: it takes the right parent page's.+ s.execute("layout.pages.insert", &json!({"after": 0, "count": 1, "parent": "A"})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (l, 2, false), "the new left page");+ assert_eq!(m[2], (Margins::uniform(50.0), 1, false), "old page 2, now a right page");+ assert_eq!(m[3], (Margins::uniform(100.0), 1, true));+ assert!(s.execute("layout.marginsAndColumns", &json!({"parent": "Z", "margins": 10})).is_err());+ }++ #[test]+ fn applying_a_parent_gives_its_margins_and_local_margins_stay_local() {+ let mut s = Session::new();+ // Facing: [1] [2 3].+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"parent": "B", "margins": 70, "columns": 3})).unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (Margins::uniform(70.0), 3, false), "the page takes B's margins");+ // Page 3 is given margins equal to A's: they are its own all the same.+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 36})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "margins": 20})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[0], (Margins::uniform(20.0), 1, false));+ assert_eq!(m[1], (Margins::uniform(70.0), 3, false), "B's page is not A's");+ assert_eq!(m[2], (Margins::uniform(36.0), 1, true));+ // Back to A: page 2 follows A again.+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "A"})).unwrap();+ assert_eq!(margins(&s.doc().unwrap().doc)[1], (Margins::uniform(20.0), 1, false));+ }++ #[test]+ fn parent_guides_show_on_pages_but_stay_on_the_parent() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ // A vertical guide 100 pt into A's right page (x = 612 in the parent spread).+ s.execute("guide.add", &json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712})).unwrap();+ let d = &s.doc().unwrap().doc;+ let right = d.page(0).unwrap();+ let shown: Vec<f64> = d.parent_guides(right).map(|g| g.position).collect();+ assert_eq!(shown, vec![100.0], "moved to the document page's place");+ assert_eq!(d.parent_guides(d.page(1).unwrap()).count(), 0, "the left page shows A's left page's guides");+ // Not the document page's own: not listed, moved or deleted from there.+ assert_eq!(s.execute("guide.list", &json!({"spread": 0})).unwrap(), json!([]));+ assert!(s.execute("guide.move", &json!({"spread": 0, "page": 0, "index": 0, "position": 50})).is_err());+ assert!(s.execute("guide.delete", &json!({"spread": 0, "page": 0, "index": 0})).is_err());+ }+ }++ #[cfg(test)]+ mod parent_tests {+ use serde_json::json;++ fn parent_of(s: &crate::Session, page: usize) -> Option<u64> {+ s.doc().unwrap().doc.page(page).unwrap().parent.map(|p| p.0)+ }++ #[test]+ fn parents_with_one_prefix_stay_distinct() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let a = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Parent"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Half"})).unwrap()["id"].as_u64().unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": b})).unwrap();+ assert_eq!(parent_of(&s, 0), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Half"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Parent"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(a));+ // A prefix two parents share, or a name no parent has, is an error and changes nothing.+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "Nope"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": 999_999})).is_err());+ assert_eq!(parent_of(&s, 1), Some(a));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "[None]"})).unwrap();+ assert_eq!(parent_of(&s, 1), None);+ }++ #[test]+ fn edit_parents_shows_the_named_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let ids: Vec<u64> =+ ["B", "C", "D"].iter().map(|p| s.execute("layout.parents.new", &json!({"prefix": p})).unwrap()["id"].as_u64().unwrap()).collect();+ s.ui_requests.clear();+ let r = s.execute("layout.parents.edit", &json!({"parent": ids[2]})).unwrap();+ assert_eq!(r, json!({"on": true, "parent": ids[2]}));+ assert!(s.doc().unwrap().editing_parents);+ let n = s.doc().unwrap().doc.parent_index(designcraft_doc::SpreadId(ids[2])).unwrap();+ let shown: Vec<_> = s+ .ui_requests+ .iter()+ .filter_map(|r| match r {+ crate::UiRequest::View { params } => params.get("showSpread").cloned(),+ _ => None,+ })+ .collect();+ assert_eq!(shown, vec![json!({"kind": "parent", "index": n})]);+ let r = s.execute("layout.parents.edit", &json!({"on": true, "parent": "C-Parent"})).unwrap();+ assert_eq!(r["parent"], ids[1]);+ assert!(s.execute("layout.parents.edit", &json!({"parent": "Z-Parent"})).is_err());+ let r = s.execute("layout.parents.edit", &json!({"on": false})).unwrap();+ assert_eq!(r, json!({"on": false, "parent": null}));+ assert!(!s.doc().unwrap().editing_parents);+ }+ }++ #[cfg(test)]+ mod parent_base_tests {+ use serde_json::{Value, json};++ fn rect(s: &mut crate::Session, spread: Value, r: [f64; 4], swatch: &str) -> u64 {+ let id = s.execute("frame.create", &json!({"spread": spread, "rect": r, "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.fill", &json!({"ids": [id], "swatch": swatch})).unwrap();+ id+ }++ fn page(s: &crate::Session, abs: usize) -> designcraft_render::Rendered {+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ rr.render_page(&s.doc().unwrap().doc, &s.cache, abs, 1.0, false, &Default::default()).unwrap()+ }++ /// Parent A (black), parent B based on A (cyan, half over A's square), and a page item (paper)+ /// over B's: the page draws A, then B, then its own items.+ #[test]+ fn based_on_parent_draws_base_items_under_parent_items() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"width": 400, "height": 400, "pages": 2, "facingPages": false, "margins": 0})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B", "name": "Opening"})).unwrap();+ rect(&mut s, json!({"kind": "parent", "index": 0}), [0.0, 0.0, 200.0, 200.0], "[Black]");+ rect(&mut s, json!({"kind": "parent", "index": 1}), [100.0, 0.0, 300.0, 200.0], "C=100 M=0 Y=0 K=0");+ rect(&mut s, json!(1), [150.0, 0.0, 190.0, 40.0], "[Paper]");+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();+ let black = |p: [u8; 4]| p[0] < 80 && p[1] < 80 && p[2] < 80;+ let cyan = |p: [u8; 4]| p[0] < 80 && p[1] > 120 && p[2] > 180;+ let paper = |p: [u8; 4]| p[0] > 240 && p[1] > 240 && p[2] > 240;+ assert!(paper(page(&s, 1).pixel(50, 100)), "B alone does not show A's items");++ let r = s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "A"})).unwrap();+ assert_eq!(r, json!({"parent": "B-Opening", "basedOn": "A-Parent"}));+ let img = page(&s, 1);+ assert!(black(img.pixel(50, 100)), "A's item: {:?}", img.pixel(50, 100));+ assert!(cyan(img.pixel(150, 150)), "B's item over A's: {:?}", img.pixel(150, 150));+ assert!(paper(img.pixel(170, 20)), "the page's item over B's: {:?}", img.pixel(170, 20));+ assert!(black(page(&s, 0).pixel(50, 100)) && !cyan(page(&s, 0).pixel(250, 100)), "page 1 uses A only");+ // Parent B itself shows A's items under its own.+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ let placed = [designcraft_render::Placed { spread: designcraft_doc::SpreadRef::Parent(1), xf: designcraft_geom::Affine::IDENTITY }];+ let opts = designcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };+ let img = rr.render(&s.doc().unwrap().doc, &s.cache, &placed, 400, 400, designcraft_geom::Affine::IDENTITY, &opts);+ assert!(black(img.pixel(50, 100)) && cyan(img.pixel(150, 150)), "{:?} {:?}", img.pixel(50, 100), img.pixel(150, 150));+ let inspect = s.execute("document.inspect", &json!({})).unwrap();+ assert_eq!(inspect["parents"][1]["basedOn"], "A-Parent");+ assert_eq!(inspect["parents"][0]["basedOn"], Value::Null);++ // Cycles are refused.+ assert!(s.execute("layout.parents.options", &json!({"parent": "A", "basedOn": "B"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "B-Opening"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "Z"})).is_err());++ s.execute("edit.undo", &json!({})).unwrap();+ assert!(paper(page(&s, 1).pixel(50, 100)), "undo clears Based on Parent");+ s.execute("edit.redo", &json!({})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": null})).unwrap();+ assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["parents"][1]["basedOn"], Value::Null);+ }++ /// A's page-number marker shown on parent XYZ (based on A) reads XYZ, as markers on XYZ's own items do.+ #[test]+ fn base_parent_markers_read_the_showing_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "XYZ"})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "XYZ", "basedOn": "A"})).unwrap();+ let marker = designcraft_doc::story::PAGE_NUMBER.to_string();+ let r = s+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": marker}))+ .unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let glyphs = |on| -> usize {+ let cs = s.cache.get_on(&d, sid, on);+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()+ };+ assert_eq!(glyphs(designcraft_compose::ShownOn::Own), 1, "A");+ assert_eq!(glyphs(designcraft_compose::ShownOn::Parent(1)), 3, "XYZ");+ }++ /// A file whose parents are based on each other opens, with the cycle broken and reported.+ #[test]+ fn opening_a_parent_cycle_breaks_it_with_a_warning() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ let mut d = s.doc().unwrap().doc.as_ref().clone();+ let (a, b) = (d.parents[0].id, d.parents[1].id);+ std::sync::Arc::make_mut(&mut d.parents[0]).parent.as_mut().unwrap().based_on = Some(b);+ std::sync::Arc::make_mut(&mut d.parents[1]).parent.as_mut().unwrap().based_on = Some(a);+ let b64 = crate::cmd::base64_encode(&crate::cmd::to_bytes(&d).unwrap());+ let r = s.execute("file.openBytes", &json!({"name": "cycle", "base64": b64})).unwrap();+ assert!(r["warnings"].to_string().contains("cycle"), "{r}");+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None);+ assert_eq!(d.parents[1].parent.as_ref().unwrap().based_on, Some(a));+ }+ }+++#[cfg(test)]+#[path = "parent_delete_tests.rs"]+mod parent_delete_tests;diff --cc crates/engine/src/cmd/parent_delete_tests.rsindex 0bfd89e7a,000000000..133381973mode 100644,000000..100644--- a/crates/engine/src/cmd/parent_delete_tests.rs+++ b/crates/engine/src/cmd/parent_delete_tests.rs@@@ -1,127 -1,0 +1,131 @@@+//! Regression coverage for deleting parent spreads through the command boundary.++use std::sync::Arc;++use designcraft_doc::{ItemId, Selection, SpreadId, TextSel};+use serde_json::{Value, json};++use crate::Session;++fn frame(s: &mut Session, parent: usize, text: Option<&str>) -> ItemId {+ let mut p = json!({"spread": {"kind": "parent", "index": parent}, "rect": [36, 36, 200, 100]});+ if let Some(text) = text {+ p["content"] = json!("text");+ p["text"] = json!(text);+ }+ ItemId(s.execute("frame.create", &p).unwrap()["id"].as_u64().unwrap())+}++#[test]+fn parent_delete_rejects_invalid_ids_without_editing_or_adding_history() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("layout.parents.edit", &json!({"on": true})).unwrap();+ let before = s.doc().unwrap().doc.clone();+ let history = s.doc().unwrap().history.undo.len();+ for params in [json!({}), json!({"id": null}), json!({"id": "A"}), json!({"id": -1}), json!({"id": 999999})] {+ assert!(s.execute("layout.parents.delete", ¶ms).is_err(), "{params}");+ let st = s.doc().unwrap();+ assert!(Arc::ptr_eq(&st.doc, &before));+ assert_eq!(st.history.undo.len(), history);+ assert!(st.editing_parents);+ }+}++#[test]+fn parent_delete_preserves_local_copies_cleans_references_and_roundtrips_undo() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();+ let a = s.doc().unwrap().doc.parents[0].id;+ let text = frame(&mut s, 0, Some("Parent folio"));+ let story = s.doc().unwrap().doc.item(text).unwrap().text_frame().unwrap().story;+ let shape = frame(&mut s, 0, None);+ let group = ItemId(s.execute("object.group", &json!({"ids": [text.0, shape.0]})).unwrap()["id"].as_u64().unwrap());+ let local = ItemId(s.execute("layout.overrideParentItems", &json!({"page": 0})).unwrap()["ids"][0].as_u64().unwrap());+ let local_text = s.doc().unwrap().doc.item(local).unwrap().children().iter().find(|i| i.text_frame().is_some()).unwrap().id;+ let local_story = s.doc().unwrap().doc.item(local_text).unwrap().text_frame().unwrap().story;+ assert_ne!(story, local_story);++ let b = SpreadId(s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap()["id"].as_u64().unwrap());+ let c = SpreadId(s.execute("layout.parents.new", &json!({"prefix": "C"})).unwrap()["id"].as_u64().unwrap());+ let inherited = frame(&mut s, 1, Some("Local parent edit"));+ s.edit(|d, _| {+ // Imported parents can base themselves on another parent and carry local overrides.+ let bp = Arc::make_mut(&mut d.parents[1]);+ bp.parent.as_mut().unwrap().based_on = Some(a);+ bp.pages[0].parent = Some(a);+ bp.pages[0].overridden.push(text);+ Arc::make_mut(&mut d.parents[2]).parent.as_mut().unwrap().based_on = Some(b);+ d.item_mut(inherited).unwrap().overrides = Some(text);+ Ok(())+ })+ .unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();- let other_local = ItemId(s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap()["ids"][0].as_u64().unwrap());++ let other_local = ItemId(s.execute("layout.overrideParentItems", &json!({"page": 1, "ids": [inherited.0]})).unwrap()["ids"][0].as_u64().unwrap());+ s.execute("layout.parents.edit", &json!({"on": true})).unwrap();+ s.doc_mut().unwrap().selection = Selection::text(TextSel::caret(story, 0));+ let before = s.doc().unwrap().doc.clone();+ let history = s.doc().unwrap().history.undo.len();+ before.check().unwrap();++ s.execute("layout.parents.delete", &json!({"id": a.0})).unwrap();+ let st = s.doc().unwrap();+ assert_eq!(st.history.undo.len(), history + 1);+ assert_eq!(st.selection, Selection::default());+ assert!(st.editing_parents, "other parents remain editable");+ let d = &st.doc;+ assert_eq!(d.parents.iter().map(|p| p.id).collect::<Vec<_>>(), [b, c]);+ assert_eq!(d.page(0).unwrap().parent, None);+ assert_eq!(d.page(1).unwrap().parent, Some(b));+ assert_eq!(d.page(2).unwrap().parent, None);+ assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None);+ assert_eq!(d.parents[1].parent.as_ref().unwrap().based_on, Some(b));+ assert_eq!(d.parents[0].pages[0].parent, None);+ assert!(d.parents[0].pages[0].overridden.is_empty());+ assert!([group, text, shape].iter().all(|id| d.item(*id).is_none()));+ assert!(d.story(story).is_none(), "nested text frames leave no dangling story");+ assert_eq!(d.item(local).unwrap().overrides, None);+ assert_eq!(d.story(local_story).unwrap().text, "Parent folio");+ assert!(d.page(0).unwrap().overridden.is_empty());+ assert_eq!(d.item(inherited).unwrap().overrides, None);+ assert_eq!(d.item(other_local).unwrap().overrides, Some(inherited));+ assert_eq!(d.page(1).unwrap().overridden, [inherited]);+ d.check().unwrap();+ let after = d.clone();++ s.execute("edit.undo", &Value::Null).unwrap();+ assert_eq!(s.doc().unwrap().doc, before);+ s.doc().unwrap().doc.check().unwrap();+ s.execute("edit.redo", &Value::Null).unwrap();+ assert_eq!(s.doc().unwrap().doc, after);+ s.doc().unwrap().doc.check().unwrap();+}++#[test]+fn parent_delete_last_parent_returns_to_document_pages() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let id = s.doc().unwrap().doc.parents[0].id;+ s.execute("layout.parents.edit", &json!({"on": true})).unwrap();+ frame(&mut s, 0, Some("Last parent"));++ let selection_before = s.doc().unwrap().selection.clone();++ assert!(selection_before.text.is_some(), "creating the text frame leaves a caret");+ s.execute("layout.parents.delete", &json!({"id": id.0})).unwrap();+ let st = s.doc().unwrap();+ assert!(st.doc.parents.is_empty());+ assert!(!st.editing_parents);++ assert_eq!(st.selection, Selection::default());+ assert_eq!(st.doc.page_count(), 2);+ assert!(st.doc.spreads.iter().flat_map(|sp| &sp.pages).all(|page| page.parent.is_none()));+ s.execute("edit.undo", &Value::Null).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents[0].id, id);- assert_eq!(s.doc().unwrap().selection, Selection::default());++ assert_eq!(s.doc().unwrap().selection, selection_before);+ s.execute("edit.redo", &Value::Null).unwrap();+ assert!(s.doc().unwrap().doc.parents.is_empty());+ assert!(!s.doc().unwrap().editing_parents);++ assert_eq!(s.doc().unwrap().selection, Selection::default());+ // A parent-free document still supports creating another parent.+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ assert_eq!(s.doc().unwrap().doc.parents.len(), 1);+ s.doc().unwrap().doc.check().unwrap();+}diff --cc crates/ui-egui/src/panels/pages.rsindex c3d60b07b,0562b4eda..4b2360f8f--- a/crates/ui-egui/src/panels/pages.rs+++ b/crates/ui-egui/src/panels/pages.rs@@@ -80,46 -268,131 +268,142 @@@ pub fn show(app: &mut DesignApp, ui: &mlet aspect = (doc.settings.page_width / doc.settings.page_height.max(1.0)) as f32;let mut drop: Option<(PageDrag, usize)> = None;ui.spacing_mut().item_spacing.y = 0.0;- // ---- Parents: [None] and each parent, 29 pt rows with a blank thumbnail at the right.- let mut rows = vec![("[None]".to_string(), None, 1, None)];- for p in &doc.parents {- let label = p.parent.as_ref().map(|i| i.label()).unwrap_or_default();- rows.push((label, p.parent.as_ref().map(|i| i.prefix.clone()), p.pages.len(), Some(p.id)));- }- for (label, prefix, n, id) in rows {- let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click_and_drag());- let active = editing_parents && prefix.is_some();- if active {- ui.painter().rect_filled(r, 0.0, t.row_selected);- } else if resp.hovered() {- ui.painter().rect_filled(r, 0.0, t.hover);- }- ui.painter().text(r.left_center() + vec2(3.0, 0.0), egui::Align2::LEFT_CENTER, &label, egui::FontId::proportional(11.5), t.text_strong);- blank_spread(ui.painter(), egui::pos2(r.max.x - 10.0, r.center().y), n, aspect, &t);- resp.dnd_set_drag_payload(PageDrag::Parent(prefix.clone()));- if resp.double_clicked() && prefix.is_some() {- let _ = app.run("layout.parents.edit", json!({"on": true}));- app.views.clear();- }- if resp.dragged() {- drag_ghost(ui, &label, &t);+ // ---- Parents: [None] and each parent, rows with the parent's thumbnail at the right.+ // While parents are edited, the row of the parent the canvas shows is selected.+ let cur_parent = if editing_parents {+ let layout = designcraft_tools::CanvasLayout::new(&doc, true);+ crate::canvas::current_slot(app, &layout).and_then(|i| layout.slots.get(i)).and_then(|s| match s.spread {+ SpreadRef::Parent(i) => Some(i),+ SpreadRef::Doc(_) => None,+ })+ } else {+ None+ };+ let mut rows = vec![ParentRow::none(aspect)];+ rows.extend(doc.parents.iter().enumerate().map(|(i, p)| ParentRow::new(i, p, aspect)));+ // As in InDesign: parents and pages each scroll on their own (parents on top unless Panel+ // Options says pages), a divider between them resizes them, the footer stays at the bottom.+ let opts = app.ui.pages_panel.clone();+ let total = {+ let h = ui.available_height();+ if h.is_finite() && h < 4000.0 { h } else { 480.0 }+ }+ .max(160.0);+ let row_h = opts.parent_size.row_h();+ let icon_h = row_h - 5.0;+ // Extra Small has no room for a thumbnail; Show Thumbnails off draws blank pages.+ let parent_thumbnails = opts.parent_thumbnails && opts.parent_size != IconSize::ExtraSmall;+ // Parents side by side (Show Vertically off): tiles of the icon and the prefix, wrapping.+ let tile_w = |unit_w: f32| (icon_h * unit_w + 16.0).max(44.0);+ let natural = if opts.parents_vertical {+ rows.len() as f32 * row_h+ } else {+ let width = (ui.available_width() - 4.0).max(1.0);+ let (mut lines, mut x) = (1.0_f32, 0.0_f32);+ for row in &rows {+ let w = tile_w(row.unit_w) + 6.0;+ if x > 0.0 && x + w > width {+ lines += 1.0;+ x = 0.0;+ }+ x += w;}- if let Some(id) = id {- resp.context_menu(|ui| {- let label = crate::i18n::tr(&app.ui.language, "Delete Parent");- if ui.button(crate::rtl::widget(ui, label)).clicked() {- if app.run("layout.parents.delete", json!({"id": id.0})).is_ok() {- app.views.clear();+ lines * (icon_h + 22.0)+ };+ let space = (total - FOOTER_H - DIVIDER_H).max(2.0 * ROW_H);+ let parents_max = (space - 2.0 * ROW_H).max(ROW_H);+ // A row taller than the room left (large icons in a short panel) gets that room.+ // A row taller than the room left (large icons in a short panel) gets that room.+ let parents_min = row_h.min(natural).min(parents_max);+ // The divider's place as last dragged, and how a change of the panel's height is shared.+ let parents_h = match app.ui.pages_parents_height {+ None => natural.min(PARENTS_DEFAULT_ROWS * ROW_H),+ Some([h, at]) => match opts.resize {+ PanelResize::ParentsFixed => h,+ PanelResize::PagesFixed => h + (space - at),+ PanelResize::Proportional => h * space / at.max(1.0),+ },+ }+ .clamp(parents_min, parents_max)+ .min(natural);+ let pages_h = (space - parents_h).max(ROW_H);+ let parents_part = |app: &mut DesignApp, ui: &mut egui::Ui| {+ egui::ScrollArea::vertical().id_salt("pages_parents").max_height(parents_h).min_scrolled_height(parents_h).auto_shrink([false, true]).show(+ ui,+ |ui| {+ ui.spacing_mut().item_spacing = vec2(6.0, 0.0);+ let each = |app: &mut DesignApp, ui: &mut egui::Ui, row: &ParentRow| {+ let label = row.label.as_str();+ let (r, resp) = if opts.parents_vertical {+ ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click_and_drag())+ } else {+ ui.allocate_exact_size(vec2(tile_w(row.unit_w), icon_h + 22.0), Sense::click_and_drag())+ };+ let active = row.parent.is_some_and(|(i, _)| cur_parent == Some(i));+ if active {+ ui.painter().rect_filled(r, 0.0, t.row_selected);+ } else if resp.hovered() {+ ui.painter().rect_filled(r, 0.0, t.hover);}- ui.close();+ if opts.parents_vertical {+ ui.painter().text(+ r.left_center() + vec2(3.0, 0.0),+ egui::Align2::LEFT_CENTER,+ label,+ egui::FontId::proportional(11.5),+ t.text_strong,+ );+ parent_icon(app, ui, egui::pos2(r.max.x - 10.0, r.center().y), row, icon_h, parent_thumbnails, &t);+ } else {+ let w = icon_h * row.unit_w;+ parent_icon(app, ui, egui::pos2(r.center().x + w / 2.0, r.min.y + 3.0 + icon_h / 2.0), row, icon_h, parent_thumbnails, &t);+ let short = row.prefix.clone().unwrap_or_else(|| label.to_string());+ ui.painter().text(+ egui::pos2(r.center().x, r.max.y - 9.0),+ egui::Align2::CENTER_CENTER,+ short,+ egui::FontId::proportional(11.0),+ t.text_strong,+ );+ }+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, active, label));+ let resp = if opts.parents_vertical { resp } else { resp.on_hover_text(label) };+ resp.dnd_set_drag_payload(PageDrag::Parent(row.parent.map(|(_, id)| id)));+ if resp.double_clicked()+ && let Some((_, id)) = row.parent+ {+ let _ = app.run("layout.parents.edit", json!({"on": true, "parent": id.0}));+ }+ if resp.dragged() {+ drag_ghost(ui, label, &t);+ }++ if let Some((_, id)) = row.parent {++ resp.context_menu(|ui| {++ let label = crate::i18n::tr(&app.ui.language, "Delete Parent");++ if ui.button(crate::rtl::widget(ui, label)).clicked() {++ if app.run("layout.parents.delete", json!({"id": id.0})).is_ok() {++ app.views.clear();++ }++ ui.close();++ }++ });++ }+ };+ if opts.parents_vertical {+ for row in &rows {+ each(app, ui, row);+ }+ } else {+ ui.horizontal_wrapped(|ui| {+ ui.spacing_mut().item_spacing = vec2(6.0, 0.0);+ for row in &rows {+ each(app, ui, row);+ }+ });}- });- }- }- ui.add_space(4.0);- let r = ui.available_rect_before_wrap();- ui.painter().rect_filled(egui::Rect::from_min_size(egui::pos2(r.min.x - 10.0, r.min.y), vec2(r.width() + 20.0, 1.5)), 0.0, t.section_divider);- ui.add_space(12.0);+ },+ );+ };// ---- Document spreads.let cur = crate::canvas::current_page(app).unwrap_or(0);let cur_spread = doc.page_loc(cur).map(|l| l.0);@@@ -383,13 -769,58 +780,82 @@@ pub(crate) fn drag_ghost(ui: &egui::Ui#[cfg(test)]mod tests {- use egui_kittest::{Harness, kittest::Queryable};- use serde_json::json;+ use egui::{Event, Modifiers, PointerButton};+ use egui_kittest::{+ Harness,+ kittest::{NodeT, Queryable},+ };use super::*;+ use crate::test_window;+++ #[test]++ fn parent_context_menu_deletes_the_clicked_id_even_with_a_shared_prefix() {++ for vertical in [true, false] {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({"pages": 2, "facingPages": false})).unwrap();++ app.ui.pages_panel.parents_vertical = vertical;++ let original = app.session.doc().unwrap().doc.parents[0].id;++ let added = app.run("layout.parents.new", json!({"prefix": "A", "name": "Other"})).unwrap()["id"].as_u64().unwrap();++ let mut h = harness(app);++ // Target the actual parent row in either panel layout, not a menu helper.++ h.get_by_label("A-Other").click_secondary();++ h.run_steps(3);++ h.get_by_label("Delete Parent").click();++ h.run_steps(3);++ let doc = &h.state().session.doc().unwrap().doc;++ assert_eq!(doc.parents.len(), 1);++ assert_eq!(doc.parents[0].id, original);++ assert!(doc.parents.iter().all(|p| p.id.0 != added));++ assert_eq!(doc.page_count(), 2, "document pages are not deleted");++ h.state_mut().run("edit.undo", json!({})).unwrap();++ assert_eq!(h.state().session.doc().unwrap().doc.parents.len(), 2);++ }++ }+++ #[test]+ fn double_clicking_a_parent_shows_that_parent() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ for prefix in ["B", "C", "D"] {+ app.run("layout.parents.new", json!({"prefix": prefix})).unwrap();+ }+ app.ui.dock_tab = "pages".into();+ let mut h = test_window::open(app, vec2(1400.0, 900.0));+ let names = ["A-Parent", "B-Parent", "C-Parent", "D-Parent"];+ for name in names {+ assert_ne!(h.get_by_label(name).accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "{name} is not selected yet");+ }+ // Both clicks in one frame: the harness's event queue spaces events too far apart for a+ // double click.+ let at = h.get_by_label("C-Parent").rect().center();+ h.input_mut().events.push(Event::PointerMoved(at));+ for pressed in [true, false, true, false] {+ h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });+ }+ h.run_steps(4);+ let app = &h.state().app;+ assert!(app.session.active().unwrap().editing_parents);+ let st = app.session.active().unwrap();+ let layout = designcraft_tools::CanvasLayout::new(&st.doc, true);+ let slot = crate::canvas::current_slot(app, &layout).unwrap();+ assert_eq!(layout.slots[slot].spread, designcraft_doc::SpreadRef::Parent(2));+ for name in names {+ assert_eq!(h.get_by_label(name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True), name == "C-Parent", "{name}");+ }+ // Parent rows show a rendered thumbnail.+ let id = st.doc.parents[2].id;+ let rev = (st.uid, st.revision);+ let thumbs = super::THUMBS.lock().unwrap();+ assert!(thumbs.as_ref().unwrap().keys().any(|k| (k.0, k.1) == rev && k.2 == super::ThumbOf::Parent(id)));+ }fn harness(app: DesignApp) -> Harness<'static, DesignApp> {- let mut h = Harness::builder().with_size(vec2(280.0, 520.0)).build_ui_state(+ sized_harness(app, vec2(280.0, 520.0))+ }++ fn sized_harness(app: DesignApp, size: egui::Vec2) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(size).build_ui_state(|ui, app: &mut DesignApp| {let key = egui::Id::new("test_fonts");if ui.data(|d| d.get_temp::<bool>(key)).is_none() {