DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge save-result: fix(file): saving never reports success without a file (#741, #708)
aiongg3d3f02e621da
diff --cc ROADMAP.mdindex b7c29f5d7,3c85c1ef9..d5390cce9--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,66 -129,9 +128,67 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-13** · Saving never reports success without a file: a document that can't be written is an error from Save, Save As, Save a Copy, Package, snippet export and the web serializer, leaving the existing file, the unsaved state and the recovery checkpoint as they were. Placed files over 4 GiB are written with zip64 sizes. A web Save whose browser download can't start reports the error and keeps the document unsaved (#741, #708). No readiness percentage change.+- **2026-10-13** · Colour management runs on craft-libs' `craft-cms`. The default CMYK working space is its Coated FOGRA39 profile (Generic CMYK and Device CMYK stay selectable); CMYK swatches show relative colorimetric with the settings' black point compensation, and PDF/X-4 output intents embed the working CMYK profile (FOGRA39 by default). Profile names the built-in stands in for resolve to it; other unknown names are an error, and saved settings naming one start with the default. No readiness percentage change.+- **2026-10-13** · Command scripts look up only a well-formed `$N.path` / `$last.path` reference; other strings starting with `$`, such as a GREP replacement of `$1` and a nonbreaking space, stay as written, and `$$` writes a literal `$` (#749). No readiness percentage change.+- **2026-10-13** · Dialogs and the About window move when you drag their title row, so the page behind them can be seen. A dragged dialog may go partly off-screen, but its title row stays reachable; each dialog opens centred, and again after the window is resized. No readiness percentage change.+- **2026-10-12** · Placed Excel tables and Excel data-merge records keep numeric precision, including small values, and preserve numeric-looking cached formula strings as text. No readiness percentage change.+- **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.+- **2026-10-13** · HTML and reflowable EPUB order grouped stories and graphics by their transformed spread position, including nested groups and rotated frames. Explicit Article order is unchanged. No readiness percentage change.+- **2026-10-13** · A selected placed graphic shows its own brown bounding box with handles: dragging one resizes the graphic inside its frame (Shift keeps proportions, Alt from the centre) and leaves the frame as it is; `transform.set` takes the graphic's new spread `bounds`. Builds on #415 and #550. No readiness percentage change.+- **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.+- **2026-10-13** · Ungroup only takes groups apart: a frame with pasted-in content stays whole (and selected), is named by its shape in the Layers and Properties panels, and offers Convert Shape rather than Ungroup. Non-groups stay selected. No readiness percentage change.+- **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.+- **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.+- **2026-10-13** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.+- **2026-10-12** · The engine's atomic writer, used by saves and exports (documents, snippets, books, libraries, swatches, XML, interchange, MCP, desktop and CLI writes), delegates to craft-libs/craft-atomic. Failed writes retain the original; new files follow the umask and replaced files keep their permissions. Recovery checkpoints and package output keep their own no-follow writers. No readiness percentage change.+- **2026-10-13** · New Document has Preview (off by default, kept for the session): a document with the window's settings shows in the workspace and follows them once typing pauses. Create keeps it with a clean undo history and refuses invalid fields; Close removes it and shows the previous document again. The preview takes no Untitled number and writes no recovery data; one edited by a menu or script stays open as a document. No readiness percentage change.+- **2026-10-13** · Object styles carry effects (drop shadow, feather, inner and outer shadows and glows, bevel, satin, gradient and directional feather). New styles from a selection keep its effects, `style.object.edit` changes a style's effects and every item that follows them, `style.object.clearOverrides` returns items to their style, and new frames take their default style's effects. IDML carries only the drop shadow and feather, for ObjectStyles (with their effects category and BasedOn chain) as for items (#653). No readiness percentage change.+- **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change.+- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.+- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.+- **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.+- **2026-10-12** · Text in oval, polygon and other non-rectangular text frames follows the frame's outline: each line is set in the part of its band inside the shape, one inset away from the outline, in every column and in vertical frames; text wrap still applies on top (#646). No readiness percentage change.+- **2026-10-12** · Colour entry: the Color Picker's hex, R/G/B and C/M/Y/K fields and the Color panel's number fields keep typed text until it is complete; panel and picker values are applied on a fixed scale (`{model, …}` colours in 0..1), so M 1 is 1 %. Picking keeps a CMYK colour CMYK; dialogs leave the page behind them undimmed; colours that round to the same swatch name share one swatch (#323). No readiness percentage change.+- **2026-10-12** · Placed photos show in their own colours: embedded ICC profiles (Adobe RGB, ProPhoto, P3, grey) are converted to sRGB on screen, and CMYK JPEGs (including YCCK), CMYK TIFFs and CMYK PSDs go through their embedded CMYK profile or the working CMYK space with the colour settings' intent and black-point compensation, instead of the profile-free formula. Unreadable profiles are ignored. No readiness percentage change.+- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.+- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.+- **2026-10-12** · Type tool: Option/Alt+Left/Right kerns the pair at the caret (manual kerning) or tracks a selection by the Kerning/Tracking increment (Preferences › Units & Increments, 20/1000 em), five times with Cmd/Ctrl; moving by words is Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere, and Option/Alt+Shift+Left/Right still selects by words (#621). No readiness percentage change.+- **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 f56e3dadf,b2545b5b6..257c81139--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -13,43 -13,21 +13,43 @@@ use crate::{DocState, EngineError, Resupub fn specs() -> Vec<CommandSpec> {vec![cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?}",always, file_new),cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();+ presets.extend(+ s.prefs+ .document_presets+ .iter()+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),+ );+ Ok(Value::Array(presets))+ }),+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,+ "{name, …the settings file.new takes} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",+ always, save_preset),+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();+ let before = s.prefs.document_presets.len();+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if s.prefs.document_presets.len() == before {+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));+ }+ ok()+ }),cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped (and, for .idml, package parts missing)}",+ "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}",always, file_open),- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", always, file_open_bytes),- cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),- cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),- cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {- let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?.to_string();+ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes),+ cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| {+ let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?;+ let path = with_document_extension(path);let mut copy = (*s.doc()?.doc).clone();super::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path));- let bytes = to_bytes(©);+ let bytes = to_bytes(©)?;#[cfg(not(target_arch = "wasm32"))]crate::atomic::write_file(&path, &bytes)?;Ok(json!({"path": path, "bytes": bytes.len()}))@@@ -131,182 -109,30 +131,193 @@@]}- pub fn to_bytes(d: &Document) -> Vec<u8> {- designcraft_format::save(d).unwrap_or_default()+ #[cfg(test)]+ thread_local! {+ /// Makes [`to_bytes`] fail on this thread, standing in for writer errors that need gigabytes to reach.+ pub(crate) static FAIL_TO_BYTES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+ }++ /// The document as `.designcraft` bytes, or an error when it can't be written; never an empty file.+ pub fn to_bytes(d: &Document) -> Result<Vec<u8>> {+ #[cfg(test)]+ if FAIL_TO_BYTES.with(std::cell::Cell::get) {+ return Err(EngineError::Other("could not write the document: injected failure".into()));+ }+ designcraft_format::save(d).map_err(|e| EngineError::Other(format!("could not write the document: {e}")))}+/// `path` ending in `.designcraft`: the extension is added when it is missing or another one, so+/// the file opens from the file manager. A path without a file name is left for the write to fail.+pub fn with_document_extension(path: &str) -> String {+ let p = std::path::Path::new(path);+ let ext = p.extension().and_then(|e| e.to_str());+ if p.file_name().is_none() || ext.is_some_and(|e| e.eq_ignore_ascii_case(designcraft_format::EXTENSION)) {+ return path.to_string();+ }+ format!("{path}.{}", designcraft_format::EXTENSION)+}++/// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package.+pub fn is_document(bytes: &[u8]) -> bool {+ designcraft_idml::is_idml(bytes) || designcraft_format::is_designcraft(bytes)+}+pub fn from_bytes(b: &[u8]) -> Result<Document> {- designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))+ load_bytes(b).map(|(d, _)| d)}-fn file_new(s: &mut Session, p: &Value) -> Result<Value> {+/// Read `.designcraft` bytes and repair what a hand-edited file can get wrong without failing the+/// open, with a warning for each repair.+fn load_bytes(b: &[u8]) -> Result<(Document, Vec<String>)> {+ let mut d = designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))?;+ let warnings = d.fix_parent_bases();+ Ok((d, warnings))+}++/// The longest saved preset name, and how many presets are kept.+const MAX_PRESET_NAME: usize = 100;+const MAX_PRESETS: usize = 500;++/// A built-in document preset or a saved one, by name (case ignored).+fn find_preset(s: &Session, name: &str) -> Option<NewDocument> {+ NewDocument::from_preset(name).or_else(|| s.prefs.document_presets.iter().find(|p| p.title.eq_ignore_ascii_case(name.trim())).cloned())+}++/// The settings `file.new` makes a document with for `p`: its preset, then the settings over it.+fn new_document_settings(s: &Session, p: &Value) -> Result<NewDocument> {let mut nd = match str_param(p, "preset") {- Some(name) => NewDocument::from_preset(name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,+ Some(name) => find_preset(s, name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,None => NewDocument::default(),};+ apply_settings(&mut nd, p);+ check_size("file.new", &nd)?;+ Ok(nd)+}++fn file_new(s: &mut Session, p: &Value) -> Result<Value> {+ let mut nd = new_document_settings(s, p)?;+ s.untitled += 1;+ nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| format!("Untitled-{}", s.untitled));+ let d = Document::new(&nd);+ let i = s.add_document(DocState::new(d, None));+ Ok(json!({"index": i}))+}++impl Session {+ /// New Document's Preview: a document made as `file.new` would make it with `p`, shown while+ /// the New Document window is open. It replaces the previous preview document in its tab and+ /// takes no Untitled number, no undo step and no recovery entry. Settings `file.new` refuses+ /// leave the previous preview as it was. Returns the preview document's uid.+ pub fn preview_new_document(&mut self, p: &Value) -> Result<u64> {+ let mut nd = new_document_settings(self, p)?;+ let previous = match self.new_document_preview {+ Some((_, previous)) => previous,+ None => self.active().map(|d| d.uid),+ };+ let shown = self.new_document_preview.and_then(|(old, _)| self.docs.iter().position(|d| d.uid == old));+ // A preview edited or saved by a menu or script while the window is open has become a+ // document of its own: it stays, and the preview gets a tab of its own.+ let replace = shown.filter(|&i| self.docs.get(i).is_some_and(|d| !d.is_dirty() && d.path.is_none()));+ if replace.is_none() && shown.is_some() {+ self.untitled += 1;+ }+ nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| self.next_untitled_title());+ let st = DocState::new(Document::new(&nd), None);+ let uid = st.uid;+ match replace.and_then(|i| self.docs.get_mut(i).map(|d| (i, d))) {+ Some((i, d)) => {+ *d = st;+ self.active = Some(i);+ }+ None => {+ // Pushed without `add_document`: the document that was active stays as it is.+ self.docs.push(st);+ self.active = Some(self.docs.len() - 1);+ }+ }+ self.new_document_preview = Some((uid, previous));+ Ok(uid)+ }++ /// The uid of New Document's preview document, while one is shown.+ pub fn new_document_preview(&self) -> Option<u64> {+ self.new_document_preview.map(|(uid, _)| uid)+ }++ /// End New Document's preview. Its document goes, and if it was still the active document,+ /// the one that was active before it is active again. A preview that a menu or script has+ /// edited or saved stays open as a document, with an Untitled number. Returns the uid of the+ /// document removed. Without a preview it does nothing.+ pub fn end_new_document_preview(&mut self) -> Option<u64> {+ let (uid, previous) = self.new_document_preview.take()?;+ let i = self.docs.iter().position(|d| d.uid == uid)?;+ let d = self.docs.get(i)?;+ if d.is_dirty() || d.path.is_some() {+ self.untitled += 1;+ return None;+ }+ self.docs.remove(i);+ self.active = match self.active {+ Some(a) if a == i => previous.and_then(|p| self.docs.iter().position(|d| d.uid == p)).or_else(|| self.docs.len().checked_sub(1)),+ Some(a) if a > i => Some(a - 1),+ a => a,+ };+ Some(uid)+ }++ /// Create in the New Document window, with the settings the preview shows: the preview+ /// document becomes the new document, as `file.new` would make it (the next Untitled number,+ /// no undo history). Returns its index, or `None` when there is no unedited preview to keep.+ pub fn keep_new_document_preview(&mut self) -> Option<usize> {+ let (uid, _) = self.new_document_preview?;+ let i = self.docs.iter().position(|d| d.uid == uid && !d.is_dirty() && d.path.is_none())?;+ self.new_document_preview = None;+ self.untitled += 1;+ if let Some(d) = self.docs.get_mut(i) {+ d.history.undo.clear();+ d.history.redo.clear();+ }+ self.active = Some(i);+ Some(i)+ }+}++fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {+ let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("file.savePreset", "missing `name`"))?.to_string();+ if name.chars().count() > MAX_PRESET_NAME {+ return Err(bad("file.savePreset", format!("a preset name has at most {MAX_PRESET_NAME} characters")));+ }+ if NewDocument::from_preset(&name).is_some() {+ return Err(bad("file.savePreset", format!("`{name}` is a built-in preset")));+ }+ let mut nd = NewDocument::default();+ apply_settings(&mut nd, p);+ check_size("file.savePreset", &nd)?;+ nd.title = name.clone();+ let presets = &mut s.prefs.document_presets;+ presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if presets.len() >= MAX_PRESETS {+ return Err(bad("file.savePreset", format!("at most {MAX_PRESETS} saved presets")));+ }+ presets.push(nd);+ Ok(json!({"name": name}))+}++fn check_size(cmd: &str, nd: &NewDocument) -> Result<()> {+ if !(nd.width > 0.0 && nd.height > 0.0 && nd.width <= 15552.0 && nd.height <= 15552.0) {+ return Err(bad(cmd, "page size out of range (0 < size ≤ 216 in)"));+ }+ Ok(())+}++/// The document settings in `p` (as file.new takes them) over `nd`.+fn apply_settings(nd: &mut NewDocument, p: &Value) {+ if let Some(intent) = p.get("intent").and_then(|v| serde_json::from_value(v.clone()).ok()) {+ nd.intent = intent;+ }+ if let Some(units) = p.get("units").and_then(|v| serde_json::from_value(v.clone()).ok()) {+ nd.units = units;+ }nd.width = f64_or(p, "width", nd.width);nd.height = f64_or(p, "height", nd.height);nd.pages = p.get("pages").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(nd.pages).clamp(1, 9999);diff --cc crates/engine/src/cmd/layout.rsindex 8f2488091,bd5320799..2761b17e5--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@@ -1443,295 -921,3 +1443,295 @@@ mod adjust_testsassert_eq!(b, b2);}}++#[cfg(test)]+mod spread_rotation_input_tests {+ use serde_json::json;++ #[test]+ fn quarter_turns_work_and_other_angles_are_rejected_without_mutation() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let rotation = |s: &crate::Session| s.doc().unwrap().doc.spreads[0].pages[0].view_rotation;+ for bad in [json!(45), json!(-45), json!(91), json!("90"), json!(0.5)] {+ assert!(s.execute("layout.rotateSpreadView", &json!({"angle": bad})).is_err(), "{bad}");+ assert_eq!(rotation(&s), 0, "invalid input must not change the view");+ }+ s.execute("layout.rotateSpreadView", &json!({"angle": 90})).unwrap();+ assert_eq!(rotation(&s), 1);+ s.execute("layout.rotateSpreadView", &json!({"angle": -90})).unwrap();+ assert_eq!(rotation(&s), 0);+ s.execute("layout.rotateSpreadView", &json!({"angle": 180})).unwrap();+ assert_eq!(rotation(&s), 2);+ s.execute("layout.rotateSpreadView", &json!({"angle": 0})).unwrap();+ assert_eq!(rotation(&s), 0, "zero resets the spread view");+ }+}++#[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 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));++ 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));+ }+}diff --cc crates/engine/src/cmd/load_styles.rsindex 1e1e1bb6d,000000000..b2893c693mode 100644,000000..100644--- a/crates/engine/src/cmd/load_styles.rs+++ b/crates/engine/src/cmd/load_styles.rs@@@ -1,696 -1,0 +1,696 @@@+//! Load Styles: the paragraph and character styles of another document (`.designcraft` or IDML)+//! come into this one, with the styles, swatches and lists they name.++use std::collections::{BTreeMap, HashMap, HashSet};++use designcraft_color::{Swatch, SwatchValue};+use designcraft_doc::{CharAttrs, Document, NO_CHAR_STYLE, NO_PARA_STYLE, NumberedList, ParaAttrs, ParagraphStyle, Styles};+use serde_json::{Value, json};++use super::{CommandSpec, bad, cmd, has_doc, str_param};+use crate::{Result, Session};++const ID: &str = "style.load";++pub fn specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "style.load",+ "Load Styles…",+ [],+ None,+ "{path | base64, name?: the file's name (`.idml` reads IDML), paragraph?: [name], character?: [name], conflicts?: redefine|useExisting|autoRename} — paragraph and character styles of another document (.designcraft or .idml): all of a kind, or the named ones (`[]`: none). The styles, swatches and lists they name come along where this document has none. A style this document defines differently under the same name takes the loaded definition (redefine, the default), stays as it is (useExisting), or the loaded one gets a new name (autoRename) → {paragraph: {added, replaced, renamed: {name: new name}}, character: {…}, swatches: [name]}",+ has_doc,+ load+ ),+ cmd!(query "style.load.list", "List Styles in File", [], None,+ "{path | base64, name?} → {paragraph: [{name, conflict}], character: [{name, conflict}]} — the styles `style.load` would bring; `conflict`: this document defines a style of that name differently",+ has_doc, list),+ ]+}++/// What happens to a loaded style when the document defines its name differently.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Conflict {+ /// The loaded definition replaces the document's.+ Redefine,+ /// The document's style stays.+ UseExisting,+ /// The loaded style comes in under a free name (`Name 2`).+ AutoRename,+}++/// What loading does with one style of the file.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Action {+ /// The document keeps what it has.+ Skip,+ Add,+ Replace,+ /// Added under a new name.+ Rename,+}++/// The loaded styles of one kind (paragraph or character), by their name in the file.+#[derive(Default)]+struct Kind {+ actions: HashMap<String, Action>,+ renames: HashMap<String, String>,+ added: Vec<String>,+ replaced: Vec<String>,+}++impl Kind {+ /// The name a style of the file has in this document.+ fn follow(&self, name: &mut String) {+ if let Some(new) = self.renames.get(name.as_str()) {+ *name = new.clone();+ }+ }++ fn changes(&self) -> bool {+ !(self.added.is_empty() && self.replaced.is_empty() && self.renames.is_empty())+ }++ fn report(&self) -> Value {+ let renamed: BTreeMap<&String, &String> = self.renames.iter().collect();+ json!({"added": self.added, "replaced": self.replaced, "renamed": renamed})+ }+}++/// The document a command reads styles from.+fn source(p: &Value, id: &str) -> Result<Document> {+ let (bytes, name) = match (str_param(p, "path"), str_param(p, "base64")) {+ (_, Some(b)) => (super::file::base64_decode(b), str_param(p, "name").unwrap_or("").to_string()),+ (Some(path), None) => (std::fs::read(path).map_err(|e| bad(id, format!("{path}: {e}")))?, path.to_string()),+ _ => return Err(bad(id, "give `path` or `base64`")),+ };+ if name.to_lowercase().ends_with(".idml") {+ designcraft_idml::import_idml(&bytes).map_err(|e| bad(id, e.to_string()))+ } else {+ super::file::from_bytes(&bytes).map_err(|e| bad(id, e.to_string()))+ }+}++/// The styles of one kind to load: every one (`None`) or the named ones.+fn names(p: &Value, key: &str) -> Result<Option<Vec<String>>> {+ let list = match p.get(key) {+ None | Some(Value::Null) => return Ok(None),+ Some(v) => v.as_array().and_then(|a| a.iter().map(|n| n.as_str().map(str::to_string)).collect::<Option<Vec<_>>>()),+ };+ list.map(Some).ok_or_else(|| bad(ID, format!("`{key}` must be a list of style names")))+}++/// The styles a paragraph style names: its base, its next style and its nested, line and GREP+/// styles. `true` marks a paragraph style.+fn para_refs(s: &ParagraphStyle) -> Vec<(bool, String)> {+ let p = &s.para;+ let chars = p+ .nested_styles+ .iter()+ .flatten()+ .map(|n| &n.style)+ .chain(p.grep_styles.iter().flatten().map(|g| &g.style))+ .chain(p.nested_line_styles.iter().flatten().map(|l| &l.style));+ s.based_on.iter().chain(&s.next_style).map(|n| (true, n.clone())).chain(chars.map(|n| (false, n.clone()))).collect()+}++fn char_swatches(c: &CharAttrs) -> impl Iterator<Item = &String> {+ [&c.fill, &c.stroke, &c.underline_color, &c.strikethrough_color].into_iter().flatten()+}++fn para_swatches(p: &ParaAttrs) -> impl Iterator<Item = &String> {+ p.rule_above.iter().chain(&p.rule_below).map(|r| &r.color).chain(&p.shading_color).chain(&p.border_color)+}++/// Decide what happens to every asked-for style and to the styles those name. A style the+/// document defines the same way is left alone; one that is only named by another is added when+/// the document has none, and never replaces one.+fn plan(doc: &Document, src: &Document, paragraph: Option<&[String]>, character: Option<&[String]>, conflict: Conflict) -> Result<(Kind, Kind)> {+ let (theirs, mine) = (&src.styles, &doc.styles);+ let mut todo: Vec<(bool, String)> = Vec::new();+ match paragraph {+ Some(names) => {+ for n in names {+ if n == NO_PARA_STYLE || theirs.para(n).is_none() {+ return Err(bad(ID, format!("the file has no paragraph style `{n}`")));+ }+ todo.push((true, n.clone()));+ }+ }+ None => todo.extend(theirs.paragraph.iter().filter(|s| s.name != NO_PARA_STYLE).map(|s| (true, s.name.clone()))),+ }+ match character {+ Some(names) => {+ for n in names {+ if n == NO_CHAR_STYLE || theirs.char_style(n).is_none() {+ return Err(bad(ID, format!("the file has no character style `{n}`")));+ }+ todo.push((false, n.clone()));+ }+ }+ None => todo.extend(theirs.character.iter().filter(|s| s.name != NO_CHAR_STYLE).map(|s| (false, s.name.clone()))),+ }+ let asked: HashSet<(bool, String)> = todo.iter().cloned().collect();+ let (mut para, mut chars) = (Kind::default(), Kind::default());+ while let Some(key) = todo.pop() {+ let (is_para, name) = (key.0, key.1.as_str());+ let kind = if is_para { &mut para } else { &mut chars };+ if kind.actions.contains_key(name) {+ continue;+ }+ // Is the document's style of that name the same, and which styles does the file's name?+ let (same, refs) = if is_para {+ let Some(s) = theirs.para(name).filter(|s| s.name != NO_PARA_STYLE) else { continue };+ (mine.para(name).map(|m| m == s), para_refs(s))+ } else {+ let Some(s) = theirs.char_style(name).filter(|s| s.name != NO_CHAR_STYLE) else { continue };+ (mine.char_style(name).map(|m| m == s), s.based_on.iter().map(|b| (false, b.clone())).collect())+ };+ let action = match same {+ None => Action::Add,+ Some(false) if asked.contains(&key) => match conflict {+ Conflict::Redefine => Action::Replace,+ Conflict::UseExisting => Action::Skip,+ Conflict::AutoRename => Action::Rename,+ },+ Some(_) => Action::Skip,+ };+ if action != Action::Skip {+ todo.extend(refs);+ }+ kind.actions.insert(key.1, action);+ }+ // Free names for the renamed styles, in the file's order.+ let order = theirs.paragraph.iter().map(|s| (true, &s.name)).chain(theirs.character.iter().map(|s| (false, &s.name)));+ for (is_para, name) in order {+ let kind = if is_para { &mut para } else { &mut chars };+ if kind.actions.get(name) != Some(&Action::Rename) || kind.renames.contains_key(name) {+ continue;+ }+ // A built-in style comes in as an ordinary one, without its brackets.+ let base = name.strip_prefix('[').and_then(|n| n.strip_suffix(']')).filter(|n| !n.is_empty()).unwrap_or(name);+ let taken = |n: &str| {+ (if is_para { mine.para(n).is_some() } else { mine.char_style(n).is_some() })+ || kind.actions.get(n).is_some_and(|a| *a != Action::Skip)+ || kind.renames.values().any(|r| r == n)+ };+ let new = Styles::unique_name(taken, base);+ kind.renames.insert(name.clone(), new);+ }+ Ok((para, chars))+}++fn load(s: &mut Session, p: &Value) -> Result<Value> {+ let src = source(p, ID)?;+ let conflict = match p.get("conflicts") {+ None | Some(Value::Null) => Conflict::Redefine,+ Some(v) => match v.as_str() {+ Some("redefine") => Conflict::Redefine,+ Some("useExisting") => Conflict::UseExisting,+ Some("autoRename") => Conflict::AutoRename,+ _ => return Err(bad(ID, "`conflicts` must be redefine, useExisting or autoRename")),+ },+ };+ let (paragraph, character) = (names(p, "paragraph")?, names(p, "character")?);+ let doc = s.doc()?.doc.clone();+ let (mut para, mut chars) = plan(&doc, &src, paragraph.as_deref(), character.as_deref(), conflict)?;++ let mut styles = (*doc.styles).clone();+ let (mut swatches, mut lists): (HashSet<String>, HashSet<String>) = Default::default();+ // (kind, name here) of every style that came in, for the based-on check.+ let mut loaded: Vec<(bool, String)> = Vec::new();+ for theirs in &src.styles.paragraph {+ let Some(action) = para.actions.remove(&theirs.name).filter(|a| *a != Action::Skip) else { continue };+ let mut style = theirs.clone();+ para.follow(&mut style.name);+ style.based_on.iter_mut().chain(&mut style.next_style).for_each(|n| para.follow(n));+ let p = &mut style.para;+ p.nested_styles.iter_mut().flatten().for_each(|n| chars.follow(&mut n.style));+ p.grep_styles.iter_mut().flatten().for_each(|g| chars.follow(&mut g.style));+ p.nested_line_styles.iter_mut().flatten().for_each(|l| chars.follow(&mut l.style));+ swatches.extend(char_swatches(&style.chars).chain(para_swatches(&style.para)).cloned());+ lists.extend(style.para.list_name.iter().cloned());+ let tag = format!("p:{}", style.name);+ match src.styles.export_tags.get(&format!("p:{}", theirs.name)) {+ Some(t) => styles.export_tags.insert(tag, t.clone()),+ None => styles.export_tags.remove(&tag),+ };+ loaded.push((true, style.name.clone()));+ match styles.para_mut(&style.name) {+ Some(m) if action == Action::Replace => {+ *m = style;+ para.replaced.push(theirs.name.clone());+ }+ _ => {+ if action == Action::Add {+ para.added.push(theirs.name.clone());+ }+ styles.paragraph.push(style);+ }+ }+ }+ for theirs in &src.styles.character {+ let Some(action) = chars.actions.remove(&theirs.name).filter(|a| *a != Action::Skip) else { continue };+ let mut style = theirs.clone();+ chars.follow(&mut style.name);+ style.based_on.iter_mut().for_each(|n| chars.follow(n));+ swatches.extend(char_swatches(&style.chars).cloned());+ let tag = format!("c:{}", style.name);+ match src.styles.export_tags.get(&format!("c:{}", theirs.name)) {+ Some(t) => styles.export_tags.insert(tag, t.clone()),+ None => styles.export_tags.remove(&tag),+ };+ loaded.push((false, style.name.clone()));+ match styles.char_style_mut(&style.name) {+ Some(m) if action == Action::Replace => {+ *m = style;+ chars.replaced.push(theirs.name.clone());+ }+ _ => {+ if action == Action::Add {+ chars.added.push(theirs.name.clone());+ }+ styles.character.push(style);+ }+ }+ }+ // A loaded style and one the document keeps can name each other as their base.+ for (is_para, name) in &loaded {+ let looped = if *is_para {+ styles.para(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.para_based_on_cycles(name, b))+ } else {+ styles.char_style(name).and_then(|s| s.based_on.as_deref()).is_some_and(|b| styles.char_based_on_cycles(name, b))+ };+ if looped {+ let kind = if *is_para { "paragraph" } else { "character" };+ return Err(bad(ID, format!("{kind} style `{name}` would be based on itself; load the style it is based on as well")));+ }+ }++ let swatches = missing_swatches(&doc, &src, swatches);+ let lists: Vec<NumberedList> = {+ let mut seen = HashSet::new();+ let has = |n: &str| doc.settings.lists.iter().any(|l| l.name == n);+ src.settings.lists.iter().filter(|l| lists.contains(&l.name) && !has(&l.name) && seen.insert(l.name.as_str())).cloned().collect()+ };+ let report = json!({"paragraph": para.report(), "character": chars.report(), "swatches": swatches.iter().map(|w| &w.name).collect::<Vec<_>>()});+ // Nothing to load leaves no undo step.+ if para.changes() || chars.changes() {+ s.edit(|d, _| {+ *d.styles_mut() = styles;+ d.swatches.extend(swatches);+ d.settings.lists.extend(lists);+ Ok(())+ })?;+ }+ Ok(report)+}++/// The swatches of the file that the loaded styles name and the document lacks, in the file's+/// order; a tint brings its base colour.+fn missing_swatches(doc: &Document, src: &Document, mut used: HashSet<String>) -> Vec<Swatch> {+ let mut todo: Vec<String> = used.iter().cloned().collect();+ while let Some(name) = todo.pop() {+ if let Some(Swatch { value: SwatchValue::Tint { base, .. }, .. }) = src.swatch(&name)+ && used.insert(base.clone())+ {+ todo.push(base.clone());+ }+ }+ let mut seen = HashSet::new();+ src.swatches.iter().filter(|w| used.contains(&w.name) && doc.swatch(&w.name).is_none() && seen.insert(w.name.as_str())).cloned().collect()+}++fn list(s: &mut Session, p: &Value) -> Result<Value> {+ let src = source(p, "style.load.list")?;+ let mine = &s.doc()?.doc.styles;+ let row = |name: &str, conflict: bool| json!({"name": name, "conflict": conflict});+ let paragraph: Vec<Value> =+ src.styles.paragraph.iter().filter(|x| x.name != NO_PARA_STYLE).map(|x| row(&x.name, mine.para(&x.name).is_some_and(|m| m != x))).collect();+ let character: Vec<Value> = src+ .styles+ .character+ .iter()+ .filter(|x| x.name != NO_CHAR_STYLE)+ .map(|x| row(&x.name, mine.char_style(&x.name).is_some_and(|m| m != x)))+ .collect();+ Ok(json!({"paragraph": paragraph, "character": character}))+}++#[cfg(test)]+mod tests {+ use designcraft_color::{Color, Swatch, SwatchValue};+ use designcraft_doc::{CharAttrs, CharacterStyle, ExportTag, GrepStyle, NumberedList, ParaAttrs, ParagraphStyle, Rule, Styles};+ use serde_json::{Value, json};++ use crate::Session;++ const BASIC: &str = "[Basic Paragraph]";++ fn para(name: &str, based_on: Option<&str>, size: f64) -> ParagraphStyle {+ ParagraphStyle {+ name: name.into(),+ based_on: based_on.map(str::to_string),+ next_style: None,+ para: ParaAttrs::default(),+ chars: CharAttrs { size: Some(size), ..Default::default() },+ shortcut: String::new(),+ }+ }++ fn chars(name: &str, based_on: Option<&str>, size: f64) -> CharacterStyle {+ CharacterStyle {+ name: name.into(),+ based_on: based_on.map(str::to_string),+ chars: CharAttrs { size: Some(size), ..Default::default() },+ shortcut: String::new(),+ }+ }++ fn new_doc() -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s+ }++ fn file_of(s: &Session) -> String {- super::super::file::base64_encode(&super::super::file::to_bytes(&s.doc().unwrap().doc))++ super::super::file::base64_encode(&super::super::file::to_bytes(&s.doc().unwrap().doc).unwrap())+ }++ /// A client's document: Body in the brand colour with a GREP style, Head and Quote based on+ /// it, Small characters based on Lead, an 11 pt [Basic Paragraph], and a swatch no style uses.+ fn client() -> Session {+ let mut s = new_doc();+ s.edit(|d, _| {+ d.swatches.push(Swatch::color("Brand Teal", Color::cmyk(0.9, 0.0, 0.4, 0.2)));+ d.swatches.push(Swatch {+ name: "Brand Teal 40%".into(),+ value: SwatchValue::Tint { base: "Brand Teal".into(), tint: 0.4 },+ locked: false,+ named: true,+ hidden: false,+ });+ d.swatches.push(Swatch::color("Unused Red", Color::cmyk(0.0, 1.0, 1.0, 0.0)));+ let st = d.styles_mut();+ st.para_mut(BASIC).unwrap().chars.size = Some(11.0);+ st.character.push(chars("Lead", None, 9.0));+ st.character.push(chars("Small", Some("Lead"), 7.0));+ let mut body = para("Body", Some(BASIC), 10.0);+ body.chars.fill = Some("Brand Teal".into());+ body.para.grep_styles = Some(vec![GrepStyle { style: "Small".into(), pattern: r"\d+".into() }]);+ st.paragraph.push(body);+ let mut head = para("Head", Some("Body"), 20.0);+ head.next_style = Some("Body".into());+ st.paragraph.push(head);+ let mut quote = para("Quote", Some("Body"), 12.0);+ quote.para.rule_above = Some(Rule { on: true, color: "Brand Teal 40%".into(), ..Default::default() });+ st.paragraph.push(quote);+ Ok(())+ })+ .unwrap();+ s+ }++ fn styles(s: &Session) -> Styles {+ (*s.doc().unwrap().doc.styles).clone()+ }++ #[test]+ fn every_style_of_the_file_loads_with_the_swatches_it_uses() {+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"base64": file_of(&client())})).unwrap();+ let d = &s.doc().unwrap().doc;+ let head = d.styles.para("Head").unwrap();+ assert_eq!((head.based_on.as_deref(), head.next_style.as_deref(), head.chars.size), (Some("Body"), Some("Body"), Some(20.0)));+ assert_eq!(d.styles.para("Body").unwrap().chars.fill.as_deref(), Some("Brand Teal"));+ assert_eq!(d.styles.char_style("Small").unwrap().based_on.as_deref(), Some("Lead"));+ assert_eq!(d.swatch("Brand Teal"), client().doc().unwrap().doc.swatch("Brand Teal"));+ assert!(d.swatch("Brand Teal 40%").is_some());+ assert!(d.swatch("Unused Red").is_none(), "a swatch no loaded style uses stays behind");+ assert_eq!(r["paragraph"]["added"], json!(["Body", "Head", "Quote"]));+ assert_eq!(r["character"]["added"], json!(["Lead", "Small"]));+ assert_eq!(r["swatches"], json!(["Brand Teal", "Brand Teal 40%"]));+ }++ #[test]+ fn basic_paragraph_takes_the_definition_of_the_file() {+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"base64": file_of(&client())})).unwrap();+ assert_eq!(s.doc().unwrap().doc.styles.para(BASIC).unwrap().chars.size, Some(11.0));+ assert_eq!(r["paragraph"]["replaced"], json!([BASIC]));+ }++ #[test]+ fn a_named_style_brings_the_styles_it_names() {+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"base64": file_of(&client()), "paragraph": ["Head"], "character": []})).unwrap();+ let st = styles(&s);+ assert_eq!(r["paragraph"]["added"], json!(["Body", "Head"]), "Head is based on Body");+ assert_eq!(r["character"]["added"], json!(["Lead", "Small"]), "Body's GREP style names Small, which is based on Lead");+ assert!(st.para("Quote").is_none());+ assert_eq!(st.para(BASIC).unwrap().chars.size, None, "a style the document has is only replaced when it was asked for");+ assert_eq!(r["paragraph"]["replaced"], json!([]));+ assert_eq!(r["swatches"], json!(["Brand Teal"]));+ }++ /// The document already has a Body and a Lead of its own.+ fn doc_with_body_and_lead() -> Session {+ let mut s = new_doc();+ s.edit(|d, _| {+ let st = d.styles_mut();+ st.paragraph.push(para("Body", None, 8.0));+ st.character.push(chars("Lead", None, 5.0));+ Ok(())+ })+ .unwrap();+ s+ }++ #[test]+ fn a_style_of_the_same_name_takes_the_loaded_definition() {+ let mut s = doc_with_body_and_lead();+ let r = s.execute("style.load", &json!({"base64": file_of(&client())})).unwrap();+ let st = styles(&s);+ assert_eq!((st.para("Body").unwrap().chars.size, st.char_style("Lead").unwrap().chars.size), (Some(10.0), Some(9.0)));+ assert_eq!(r["paragraph"]["replaced"], json!([BASIC, "Body"]));+ assert_eq!(r["character"]["replaced"], json!(["Lead"]));+ assert_eq!(st.paragraph.iter().filter(|p| p.name == "Body").count(), 1);+ }++ #[test]+ fn use_existing_keeps_the_styles_of_the_document() {+ let mut s = doc_with_body_and_lead();+ let r = s.execute("style.load", &json!({"base64": file_of(&client()), "conflicts": "useExisting"})).unwrap();+ let st = styles(&s);+ assert_eq!((st.para("Body").unwrap().chars.size, st.char_style("Lead").unwrap().chars.size), (Some(8.0), Some(5.0)));+ assert_eq!(st.para(BASIC).unwrap().chars.size, None);+ assert_eq!(st.para("Head").unwrap().based_on.as_deref(), Some("Body"));+ assert_eq!((&r["paragraph"]["added"], &r["paragraph"]["replaced"]), (&json!(["Head", "Quote"]), &json!([])));+ }++ #[test]+ fn auto_rename_loads_a_clashing_style_under_a_new_name() {+ let mut s = doc_with_body_and_lead();+ let r = s.execute("style.load", &json!({"base64": file_of(&client()), "conflicts": "autoRename"})).unwrap();+ let st = styles(&s);+ assert_eq!((st.para("Body").unwrap().chars.size, st.para("Body 2").unwrap().chars.size), (Some(8.0), Some(10.0)));+ assert_eq!((st.char_style("Lead").unwrap().chars.size, st.char_style("Lead 2").unwrap().chars.size), (Some(5.0), Some(9.0)));+ let head = st.para("Head").unwrap();+ assert_eq!(+ (head.based_on.as_deref(), head.next_style.as_deref()),+ (Some("Body 2"), Some("Body 2")),+ "the loaded Head follows the loaded Body"+ );+ assert_eq!(st.char_style("Small").unwrap().based_on.as_deref(), Some("Lead 2"));+ assert_eq!(st.para("Body 2").unwrap().based_on.as_deref(), Some("Basic Paragraph"));+ assert_eq!(st.para("Basic Paragraph").unwrap().chars.size, Some(11.0), "a built-in style comes in without its brackets");+ assert_eq!(st.para(BASIC).unwrap().chars.size, None);+ assert_eq!(r["paragraph"]["renamed"], json!({"[Basic Paragraph]": "Basic Paragraph", "Body": "Body 2"}));+ assert_eq!(r["character"]["renamed"], json!({"Lead": "Lead 2"}));+ assert_eq!(r["paragraph"]["replaced"], json!([]));+ }++ #[test]+ fn a_style_that_is_the_same_in_both_is_no_conflict() {+ let mut s = new_doc();+ let file = file_of(&client());+ s.execute("style.load", &json!({"base64": file})).unwrap();+ let loaded = styles(&s);+ for conflicts in ["redefine", "autoRename"] {+ let r = s.execute("style.load", &json!({"base64": file, "conflicts": conflicts})).unwrap();+ let none = json!({"added": [], "replaced": [], "renamed": {}});+ assert_eq!(r, json!({"paragraph": none, "character": none, "swatches": []}), "{conflicts}");+ }+ assert_eq!(styles(&s), loaded);+ // Loading nothing leaves no undo step: one Undo takes back the first load.+ s.execute("edit.undo", &json!({})).unwrap();+ assert!(styles(&s).para("Head").is_none());+ }++ #[test]+ fn loading_is_one_undo_step() {+ let mut s = doc_with_body_and_lead();+ let (before, swatches) = (styles(&s), s.doc().unwrap().doc.swatches.clone());+ s.execute("style.load", &json!({"base64": file_of(&client())})).unwrap();+ assert_ne!(styles(&s), before);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(styles(&s), before);+ assert_eq!(s.doc().unwrap().doc.swatches, swatches);+ }++ #[test]+ fn a_swatch_of_the_document_wins_over_the_one_in_the_file() {+ let mut s = new_doc();+ s.execute("swatch.create", &json!({"name": "Brand Teal", "color": "#ff0000"})).unwrap();+ let mine = s.doc().unwrap().doc.swatch("Brand Teal").cloned();+ let r = s.execute("style.load", &json!({"base64": file_of(&client())})).unwrap();+ assert_eq!(s.doc().unwrap().doc.swatch("Brand Teal").cloned(), mine);+ assert_eq!(r["swatches"], json!(["Brand Teal 40%"]));+ }++ #[test]+ fn a_tint_swatch_brings_its_base_colour() {+ let mut src = client();+ src.edit(|d, _| {+ let mut ruled = para("Ruled", None, 9.0);+ ruled.para.rule_below = Some(Rule { on: true, color: "Brand Teal 40%".into(), ..Default::default() });+ d.styles_mut().paragraph.push(ruled);+ Ok(())+ })+ .unwrap();+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"base64": file_of(&src), "paragraph": ["Ruled"], "character": []})).unwrap();+ assert_eq!(r["paragraph"]["added"], json!(["Ruled"]));+ assert_eq!(r["swatches"], json!(["Brand Teal", "Brand Teal 40%"]));+ }++ #[test]+ fn export_tags_and_named_lists_come_with_their_styles() {+ let mut src = client();+ src.edit(|d, _| {+ d.settings.lists.push(NumberedList { name: "Steps".into(), continue_across_stories: false });+ d.settings.lists.push(NumberedList { name: "Unused".into(), ..Default::default() });+ let st = d.styles_mut();+ st.export_tags.insert("p:Head".into(), ExportTag { tag: "h1".into(), class: "title".into() });+ st.export_tags.insert("c:Lead".into(), ExportTag { tag: "em".into(), class: String::new() });+ st.para_mut("Quote").unwrap().para.list_name = Some("Steps".into());+ Ok(())+ })+ .unwrap();+ let mut s = doc_with_body_and_lead();+ s.execute("style.load", &json!({"base64": file_of(&src), "conflicts": "autoRename"})).unwrap();+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.styles.export_tag("Head", false).map(|t| t.tag.as_str()), Some("h1"));+ assert_eq!(d.styles.export_tag("Lead 2", true).map(|t| t.tag.as_str()), Some("em"), "the tag follows the new name");+ assert_eq!(d.styles.export_tag("Lead", true), None);+ assert_eq!(d.settings.lists.iter().map(|l| (l.name.as_str(), l.continue_across_stories)).collect::<Vec<_>>(), [("Steps", false)]);+ }++ #[test]+ fn styles_load_from_an_idml_file() {+ let idml = client().execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"base64": idml, "name": "Client.IDML", "paragraph": ["Head"]})).unwrap();+ let d = &s.doc().unwrap().doc;+ let head = d.styles.para("Head").unwrap();+ assert_eq!((head.based_on.as_deref(), head.chars.size), (Some("Body"), Some(20.0)));+ assert_eq!(d.styles.para("Body").unwrap().chars.fill.as_deref(), Some("Brand Teal"));+ assert!(d.swatch("Brand Teal").is_some());+ assert_eq!(r["paragraph"]["added"], json!(["Body", "Head"]));+ }++ #[test]+ fn styles_load_from_a_path() {+ let path = std::env::temp_dir().join(format!("dc-load-styles-{}.designcraft", std::process::id()));- std::fs::write(&path, super::super::file::to_bytes(&client().doc().unwrap().doc)).unwrap();++ std::fs::write(&path, super::super::file::to_bytes(&client().doc().unwrap().doc).unwrap()).unwrap();+ let mut s = new_doc();+ let r = s.execute("style.load", &json!({"path": path.to_str().unwrap(), "paragraph": [], "character": ["Small"]}));+ std::fs::remove_file(&path).unwrap();+ assert_eq!(r.unwrap()["character"]["added"], json!(["Lead", "Small"]));+ assert!(styles(&s).para("Head").is_none());+ }++ #[test]+ fn the_file_lists_its_styles_and_which_ones_clash() {+ let mut s = doc_with_body_and_lead();+ let file = file_of(&client());+ let name = |n: &str, conflict: bool| json!({"name": n, "conflict": conflict});+ let r = s.execute("style.load.list", &json!({"base64": file})).unwrap();+ assert_eq!(r["paragraph"], json!([name(BASIC, true), name("Body", true), name("Head", false), name("Quote", false)]));+ assert_eq!(r["character"], json!([name("Lead", true), name("Small", false)]));+ s.execute("style.load", &json!({"base64": file})).unwrap();+ let r = s.execute("style.load.list", &json!({"base64": file})).unwrap();+ assert!(r["paragraph"].as_array().unwrap().iter().all(|p| p["conflict"] == false), "the same definition is no clash: {r}");+ }++ fn unchanged_after(s: &mut Session, params: Value, why: &str) {+ let before = s.doc().unwrap().doc.clone();+ let e = s.execute("style.load", ¶ms).unwrap_err().to_string();+ assert!(e.contains(why), "{e}");+ assert_eq!(s.doc().unwrap().doc, before);+ }++ #[test]+ fn what_cannot_be_loaded_is_an_error_and_changes_nothing() {+ let mut s = doc_with_body_and_lead();+ let file = file_of(&client());+ unchanged_after(&mut s, json!({}), "`path` or `base64`");+ unchanged_after(&mut s, json!({"base64": "AAAA"}), "");+ unchanged_after(&mut s, json!({"base64": "AAAA", "name": "a.idml"}), "");+ unchanged_after(&mut s, json!({"base64": file, "paragraph": ["Head", "Nope"]}), "no paragraph style `Nope`");+ unchanged_after(&mut s, json!({"base64": file, "character": ["[None]"]}), "no character style `[None]`");+ unchanged_after(&mut s, json!({"base64": file, "paragraph": ["[No Paragraph Style]"]}), "no paragraph style");+ unchanged_after(&mut s, json!({"base64": file, "paragraph": "Head"}), "`paragraph` must be a list of style names");+ unchanged_after(&mut s, json!({"base64": file, "character": [1]}), "`character` must be a list of style names");+ unchanged_after(&mut s, json!({"base64": file, "conflicts": "merge"}), "`conflicts`");+ }++ #[test]+ fn a_style_that_would_be_based_on_itself_is_refused() {+ // In the file B is based on A; in the document A is based on B.+ let mut src = new_doc();+ src.edit(|d, _| {+ let st = d.styles_mut();+ st.paragraph.push(para("A", None, 9.0));+ st.paragraph.push(para("B", Some("A"), 9.0));+ st.character.push(chars("X", None, 9.0));+ st.character.push(chars("Y", Some("X"), 9.0));+ Ok(())+ })+ .unwrap();+ let mut s = new_doc();+ s.edit(|d, _| {+ let st = d.styles_mut();+ st.paragraph.push(para("B", None, 9.0));+ st.paragraph.push(para("A", Some("B"), 9.0));+ st.character.push(chars("Y", None, 9.0));+ st.character.push(chars("X", Some("Y"), 9.0));+ Ok(())+ })+ .unwrap();+ unchanged_after(&mut s, json!({"base64": file_of(&src), "paragraph": ["B"], "character": []}), "`B` would be based on itself");+ unchanged_after(&mut s, json!({"base64": file_of(&src), "paragraph": [], "character": ["Y"]}), "`Y` would be based on itself");+ // With A loaded as well both take the file's order.+ s.execute("style.load", &json!({"base64": file_of(&src), "character": []})).unwrap();+ assert_eq!((styles(&s).para("A").unwrap().based_on.clone(), styles(&s).para("B").unwrap().based_on.clone()), (None, Some("A".to_string())));+ }++ #[test]+ fn a_file_with_a_based_on_loop_of_its_own_does_not_hang() {+ let mut src = new_doc();+ src.edit(|d, _| {+ let st = d.styles_mut();+ st.paragraph.push(para("A", Some("B"), 9.0));+ st.paragraph.push(para("B", Some("A"), 9.0));+ st.paragraph.push(para("Next", None, 9.0));+ st.para_mut("Next").unwrap().next_style = Some("Next".into());+ Ok(())+ })+ .unwrap();+ let mut s = new_doc();+ unchanged_after(&mut s, json!({"base64": file_of(&src), "paragraph": ["A"]}), "would be based on itself");+ let r = s.execute("style.load", &json!({"base64": file_of(&src), "paragraph": ["Next"]})).unwrap();+ assert_eq!(r["paragraph"]["added"], json!(["Next"]));+ }+}diff --cc crates/engine/src/tests_table.rsindex 2412b22e3,0084d76e2..8a91d5f27--- a/crates/engine/src/tests_table.rs+++ b/crates/engine/src/tests_table.rs@@@ -177,43 -177,6 +177,43 @@@ fn file_roundtrip_keeps_tables()assert_eq!(st.tables.values().next().unwrap().cells[0].text.text, "A1");}+#[test]+fn backspace_and_paste_between_tables_keep_both_and_the_file_reopens() {+ let n = designcraft_doc::TABLE_ANCHOR.len_utf8();+ let anchor_of = |s: &Session, sid: u64, tid: u64| s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().table_anchor(tid).unwrap();+ let reopens_with = |s: &Session, sid: u64, ids: &[u64]| {- let back = crate::cmd::file_from(&crate::cmd::file_bytes(&s.doc().unwrap().doc)).unwrap();++ let back = crate::cmd::file_from(&crate::cmd::file_bytes(&s.doc().unwrap().doc).unwrap()).unwrap();+ let st = back.story(doc::StoryId(sid)).unwrap();+ assert!(ids.iter().all(|id| st.table_anchor(*id).is_some()), "{:?}", st.tables.keys());+ assert_eq!(st.tables.len(), ids.len());+ };+ // Backspace at the start of the second of two consecutive tables.+ let (mut s, sid, _) = session_with_frame();+ let t1 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ let len = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().len();+ s.execute("text.select", &json!({"story": sid, "anchor": len})).unwrap();+ let t2 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ let a2 = anchor_of(&s, sid, t2);+ s.execute("text.select", &json!({"story": sid, "anchor": a2})).unwrap();+ s.execute("text.delete", &json!({})).unwrap();+ check(&s);+ reopens_with(&s, sid, &[t1, t2]);+ // Pasting a copy of a table right after its anchor.+ let (mut s, sid, _) = session_with_frame();+ let t1 = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ let a1 = anchor_of(&s, sid, t1);+ s.execute("text.select", &json!({"story": sid, "anchor": a1, "focus": a1 + n})).unwrap();+ s.execute("edit.copy", &json!({})).unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": a1 + n})).unwrap();+ let pasted = s.execute("edit.paste", &json!({})).unwrap();+ check(&s);+ assert_eq!(pasted["pos"], a1 + 2 * n + 1);+ let st = s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().clone();+ let copy = st.tables.keys().copied().find(|id| *id != t1).unwrap();+ assert_eq!((st.table_anchor(t1), st.table_anchor(copy)), (Some(a1), Some(a1 + n + 1)));+ reopens_with(&s, sid, &[t1, copy]);+}+fn table_for(s: &Session, sid: u64, tid: u64) -> &doc::Table {s.doc().unwrap().doc.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap()}@@@ -437,137 -400,6 +437,137 @@@ fn editing_beside_a_merged_cell_only_ch}}+#[test]+fn cell_stroke_gap_colour_on_inner_horizontal_edges_of_a_selection_undoes_and_saves() {+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ s.execute("table.select", &json!({"what": "table"})).unwrap();+ let before = table_for(&s, sid, tid).clone();+ let cyan = "C=100 M=0 Y=0 K=0";+ let stroke = json!({"weight": 3, "type": "dashed", "gapColor": cyan, "gapTint": 0.5, "edges": ["innerHorizontal"]});+ s.execute("table.setCell", &json!({ "stroke": stroke })).unwrap();+ let t = table_for(&s, sid, tid).clone();+ let edge = |r: usize, c: usize, side: usize| t.cell(r, c).unwrap().strokes[side].clone();+ for (r, c, side) in [(0, 0, 2), (0, 1, 2), (1, 0, 0), (1, 1, 0)] {+ let e = edge(r, c, side);+ assert_eq!((e.weight, e.gap_color.as_str(), e.gap_tint), (3.0, cyan, 0.5), "inner horizontal {r},{c} side {side}");+ assert!(matches!(e.kind, doc::StrokeType::Dashed { .. }));+ }+ for (r, c, side) in [(0, 0, 0), (0, 0, 1), (0, 0, 3), (1, 1, 2), (1, 1, 1), (0, 1, 3)] {+ assert_eq!(&edge(r, c, side), &before.cell(r, c).unwrap().strokes[side], "{r},{c} side {side} keeps its stroke");+ }+ // The query reports the chosen edges, and mixed values as null.+ let inner = s.execute("table.getCellStroke", &json!({"edges": "innerHorizontal"})).unwrap();+ assert_eq!((inner["weight"].as_f64(), inner["gapColor"].as_str(), inner["edges"].as_u64()), (Some(3.0), Some(cyan), Some(2)));+ let all = s.execute("table.getCellStroke", &json!({})).unwrap();+ assert!(all["weight"].is_null() && all["gapColor"].is_null());+ // Bad values are errors and change nothing.+ for bad in+ [json!({"gapTint": 2}), json!({"gapColor": "No Such Swatch"}), json!({"weight": -1}), json!({"type": "zigzag"}), json!({"edges": "middle"})]+ {+ assert!(s.execute("table.setCell", &json!({ "stroke": bad })).is_err(), "{bad}");+ assert_eq!(table_for(&s, sid, tid), &t);+ }- let bytes = crate::cmd::file_bytes(&s.doc().unwrap().doc);++ let bytes = crate::cmd::file_bytes(&s.doc().unwrap().doc).unwrap();+ let back = crate::cmd::file_from(&bytes).unwrap();+ assert_eq!(back.story(doc::StoryId(sid)).unwrap().tables.get(&tid).unwrap().as_ref(), &t);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(table_for(&s, sid, tid), &before);+}++#[test]+fn shared_edge_edits_and_queries_start_from_the_drawn_stroke() {+ let cyan = "C=100 M=0 Y=0 K=0";+ let thin = doc::CellStroke { weight: 0.25, color: cyan.into(), ..Default::default() };+ // The higher-priority copy of a shared edge is drawn: 2 pt cyan over 0.5 pt black.+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 1})).unwrap()["table"].as_u64().unwrap();+ s.edit(|d, _| {+ let t = d.story_mut(doc::StoryId(sid)).unwrap().table_mut(tid).unwrap();+ let upper = t.cell_mut(0, 0).unwrap();+ upper.strokes[2] = doc::CellStroke { weight: 2.0, color: cyan.into(), ..Default::default() };+ (upper.stroke_defined[2], upper.stroke_priorities[2]) = (true, 5);+ let lower = t.cell_mut(1, 0).unwrap();+ lower.strokes[0] = doc::CellStroke { weight: 0.5, ..Default::default() };+ (lower.stroke_defined[0], lower.stroke_priorities[0]) = (true, 1);+ Ok(())+ })+ .unwrap();+ let q = s.execute("table.getCellStroke", &json!({"table": tid, "edges": "innerHorizontal"})).unwrap();+ assert_eq!((q["weight"].as_f64(), q["color"].as_str(), q["edges"].as_u64()), (Some(2.0), Some(cyan), Some(1)));+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"color": "[Paper]", "edges": "innerHorizontal"}})).unwrap();+ let t = table_for(&s, sid, tid);+ for e in [&t.cell(0, 0).unwrap().strokes[2], &t.cell(1, 0).unwrap().strokes[0]] {+ assert_eq!((e.weight, e.color.as_str()), (2.0, "[Paper]"));+ }+ let composed = s.cache.get(&s.doc().unwrap().doc, doc::StoryId(sid), None);+ let frag = composed.frames.iter().flat_map(|f| &f.tables).next().unwrap();+ assert!(frag.strokes.iter().any(|x| x.stroke.weight == 2.0 && x.stroke.color == "[Paper]"));+ assert!(!frag.strokes.iter().any(|x| x.stroke.weight == 0.5), "the edge stays 2 pt");++ // An interior edge no cell supplies is drawn from the table's row pattern.+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ s.edit(|d, _| {+ let t = d.story_mut(doc::StoryId(sid)).unwrap().table_mut(tid).unwrap();+ t.options.row_strokes = Some(doc::AltStrokes { first: 1, next: 0, first_stroke: thin.clone(), ..Default::default() });+ for cell in &mut t.cells {+ (cell.stroke_defined, cell.border_overrides, cell.stroke_priorities) = ([false; 4], [false; 4], [0; 4]);+ }+ Ok(())+ })+ .unwrap();+ let q = s.execute("table.getCellStroke", &json!({"table": tid, "edges": "innerHorizontal"})).unwrap();+ assert_eq!((q["weight"].as_f64(), q["color"].as_str(), q["edges"].as_u64()), (Some(0.25), Some(cyan), Some(2)));+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"color": "[Paper]", "edges": "innerHorizontal"}})).unwrap();+ let t = table_for(&s, sid, tid);+ for (r, c, side) in [(0, 0, 2), (0, 1, 2), (1, 0, 0), (1, 1, 0)] {+ let e = &t.cell(r, c).unwrap().strokes[side];+ assert_eq!((e.weight, e.color.as_str()), (0.25, "[Paper]"), "{r},{c} side {side}");+ }+}++#[test]+fn degenerate_dash_patterns_are_rejected() {+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ let before = table_for(&s, sid, tid).clone();+ for pattern in [json!([1e-6, 1e-6]), json!([0.05, 3]), json!([]), json!([0, 0]), json!(vec![1.0; 65]), json!([20000, 1])] {+ let stroke = json!({"table": tid, "stroke": {"type": {"kind": "dashed", "pattern": pattern}}});+ assert!(s.execute("table.setCell", &stroke).is_err(), "{pattern}");+ assert_eq!(table_for(&s, sid, tid), &before);+ assert!(s.execute("strokeStyle.new", &json!({"name": "Fine", "type": "dash", "pattern": pattern})).is_err(), "{pattern}");+ }+ s.execute("table.setCell", &json!({"table": tid, "stroke": {"type": {"kind": "dashed", "pattern": [0.1, 0, 3]}}})).unwrap();+}++#[test]+fn cell_and_table_style_strokes_take_type_and_gap_colour_with_validation() {+ let (mut s, sid, _) = session_with_frame();+ let tid = s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();+ let stroke = json!({"weight": 2, "type": "dotted", "gapColor": "[Paper]", "gapTint": 0.4});+ s.execute("style.cell.create", &json!({"name": "Dotted", "stroke": stroke})).unwrap();+ s.execute("style.cell.apply", &json!({"name": "Dotted", "table": tid})).unwrap();+ let edges = s.execute("table.getCellStroke", &json!({"table": tid})).unwrap();+ assert_eq!((edges["weight"].as_f64(), edges["type"]["kind"].as_str()), (Some(2.0), Some("dotted")));+ assert_eq!((edges["gapColor"].as_str(), edges["gapTint"].as_f64().map(|t| (t * 10.0).round())), (Some("[Paper]"), Some(4.0)));+ s.execute("style.table.create", &json!({"name": "Framed", "border": {"type": "thickThin", "gapSwatch": "[Black]"}})).unwrap();+ let framed = s.doc().unwrap().doc.styles.table.iter().find(|t| t.name == "Framed").unwrap().border.clone().unwrap();+ assert_eq!((framed.kind, framed.gap_color.as_str()), (doc::StrokeType::ThickThin, "[Black]"));+ let styles = s.doc().unwrap().doc.styles.clone();+ let table = table_for(&s, sid, tid).clone();+ for (cmd, p) in [+ ("style.cell.edit", json!({"name": "Dotted", "stroke": {"gapTint": 3}})),+ ("style.cell.create", json!({"name": "Bad", "stroke": {"type": "zigzag"}})),+ ("style.table.edit", json!({"name": "Framed", "border": {"gapColor": "No Such Swatch"}})),+ ("style.table.create", json!({"name": "Bad", "border": {"weight": -2}})),+ ] {+ assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");+ assert_eq!(s.doc().unwrap().doc.styles, styles, "{cmd} changed the styles");+ assert_eq!(table_for(&s, sid, tid), &table);+ }+}+#[test]fn split_selected_row_or_column_splits_both_cells() {for horizontal in [true, false] {diff --cc crates/format/src/lib.rsindex 09deb6056,4d43eca2b..803c72a6a--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -355,122 -302,20 +364,136 @@@ mod testsassert_eq!(back.stories, d.stories);}+ /// `doc` as format 1 wrote it.+ fn save_v1(doc: &Document) -> Vec<u8> {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("meta.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(br#"{"format": "designcraft", "version": 1}"#).unwrap();+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(doc).unwrap()).unwrap();+ z.finish().unwrap().into_inner()+ }++ fn para_style(name: &str, based_on: Option<&str>, keep_all_lines: Option<bool>) -> designcraft_doc::ParagraphStyle {+ designcraft_doc::ParagraphStyle {+ name: name.into(),+ based_on: based_on.map(str::to_string),+ next_style: None,+ para: designcraft_doc::ParaAttrs { keep_lines_together: Some(true), keep_all_lines, ..Default::default() },+ chars: Default::default(),+ shortcut: String::new(),+ }+ }++ /// Format 1 resolved an unset Keep Lines Together mode as all lines: those documents still+ /// do after loading, wherever the mode comes from. New documents keep lines at start/end.+ #[test]+ fn format_1_keep_lines_without_mode_stays_all_lines() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Root", None, None));+ st.paragraph.push(para_style("Child", Some("Root"), None));+ st.paragraph.push(para_style("Explicit", None, Some(false)));+ st.paragraph.push(para_style("Under explicit", Some("Explicit"), None));+ st.paragraph.push(para_style("Loop A", Some("Loop B"), None));+ st.paragraph.push(para_style("Loop B", Some("Loop A"), None));+ let lid = d.default_layer();+ let names = [designcraft_doc::story::BASIC_PARAGRAPH, "Root", "Child", "Explicit", "Under explicit", "Loop A", "Loop B", "Missing"];+ let text = names.join("\n");+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, &text, ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(names) {+ p.style = name.into();+ p.para.keep_lines_together = Some(true);+ }+ s.insert_note(1, "Note", ParaFormat { style: "Missing".into(), ..Default::default() });+ }+ let back = load(&save_v1(&d)).unwrap();+ let resolve = |f: &ParaFormat| back.styles.resolve_para(f).0;+ let story = back.story(sid).unwrap();+ for (p, name) in story.paras.iter().zip(names) {+ let pp = resolve(p);+ assert!(pp.keep_lines_together);+ assert_eq!(pp.keep_all_lines, !name.contains("xplicit"), "{name}");+ }+ assert!(resolve(&story.notes[0].text.paras[0]).keep_all_lines, "footnote with a missing style");+ assert!(back.styles.resolve_para_style("Loop A").0.keep_all_lines && back.styles.resolve_para_style("Loop B").0.keep_all_lines);+ // Pinned where the chains start; explicit and inheriting styles are left as they were.+ assert_eq!(back.styles.para("Root").unwrap().para.keep_all_lines, Some(true));+ assert_eq!(back.styles.para("Child").unwrap().para.keep_all_lines, None);+ assert_eq!(back.styles.para("Under explicit").unwrap().para.keep_all_lines, None);+ // The current format keeps the new default: at start/end of paragraph.+ let now = load(&save(&d).unwrap()).unwrap();+ let p = &now.story(sid).unwrap().paras[0];+ assert!(!now.styles.resolve_para(p).0.keep_all_lines);+ assert!(!designcraft_doc::ParaProps::default().keep_all_lines);+ }++ /// Format 1 wrote paragraph rules, text frame options and numbered lists in full, so their+ /// old defaults (black rules, auto-size from the top centre, lists continuing across stories)+ /// load as saved. New documents take InDesign's.+ #[test]+ fn format_1_rules_frames_and_lists_load_as_saved() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let old_rule = designcraft_doc::Rule { on: true, color: designcraft_doc::color::swatch::BLACK.into(), ..Default::default() };+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "Ruled", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(old_rule.clone());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.auto_size_ref = 1;+ d.settings.lists.push(designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: true });+ let back = load(&save_v1(&d)).unwrap();+ assert_eq!(back.story(sid).unwrap().paras[0].para.rule_above, Some(old_rule));+ assert_eq!(back.item(fid).unwrap().text_frame().unwrap().options.auto_size_ref, 1);+ assert!(back.settings.lists[0].continue_across_stories);+ assert_eq!(designcraft_doc::Rule::default().color, designcraft_doc::TEXT_COLOR);+ assert_eq!(designcraft_doc::TextFrameOptions::default().auto_size_ref, 4);+ assert!(!designcraft_doc::NumberedList::default().continue_across_stories);+ }++ /// Format 1 set drop caps without Align Left Edge: those documents still do where nothing set+ /// it. New documents align the drop cap's left edge.+ #[test]+ fn format_1_drop_caps_stay_unaligned() {+ let mut d = Document::new(&NewDocument::default());+ let st = d.styles_mut();+ st.paragraph.push(para_style("Opener", None, None));+ st.paragraph.push(designcraft_doc::ParagraphStyle {+ para: designcraft_doc::ParaAttrs { drop_cap_align_left: Some(true), ..Default::default() },+ ..para_style("Aligned", None, None)+ });+ let lid = d.default_layer();+ let (_, sid) =+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 200.0, 200.0), lid, "One\nTwo\nThree", ParaFormat::default()).unwrap();+ {+ let s = d.story_mut(sid).unwrap();+ for (p, name) in s.paras.iter_mut().zip(["Opener", "Aligned", "Missing"]) {+ p.style = name.into();+ p.para.drop_cap_lines = Some(2);+ p.para.drop_cap_chars = Some(1);+ }+ }+ let back = load(&save_v1(&d)).unwrap();+ let aligned: Vec<bool> = back.story(sid).unwrap().paras.iter().map(|p| back.styles.resolve_para(p).0.drop_cap_align_left).collect();+ assert_eq!(aligned, [false, true, false]);+ let now = load(&save(&d).unwrap()).unwrap();+ assert!(now.styles.resolve_para(&now.story(sid).unwrap().paras[0]).0.drop_cap_align_left);+ }++ /// Assets over the zip size limit are written with zip64 sizes (scaled down here: the real+ /// threshold is near 4 GiB); smaller ones are written exactly as before.+ #[test]+ fn large_assets_are_written_with_zip64_sizes_and_open_again() {+ let mut d = Document::new(&NewDocument::default());+ let aid = png_asset(&mut d, &[5; 64]);+ place(&mut d, aid, 0.0);+ let normal = save(&d).unwrap();+ assert_eq!(normal, save_with_large_entries_from(&d, 65).unwrap(), "an asset under the threshold is unchanged");+ let large = save_with_large_entries_from(&d, 64).unwrap();+ assert!(large.len() > normal.len(), "the asset entry carries zip64 sizes");+ assert_eq!(*load(&large).unwrap().assets[&aid].data, vec![5; 64]);+ }+#[test]fn saves_hold_each_used_file_once() {let mut d = Document::new(&NewDocument::default());diff --cc crates/ui-egui/src/lib.rsindex 43e52ddde,6d76a6cac..98094e3d6--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -59,8 -52,8 +59,9 @@@ pub struct ImportedFilepub bytes: Vec<u8>,}pub type OpenAsyncFn = Box<dyn FnMut(ImportRequest)>;- pub type DownloadFn = Box<dyn FnMut(&str, &[u8])>;+ /// Starts a browser download; an error means no file was handed to the user.+ pub type DownloadFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;+pub type ClipboardFn = Box<dyn FnMut() -> Option<String>>;/// Files delivered asynchronously with their original operation and document identity.pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<ImportedFile>>>;diff --cc crates/ui-egui/src/menus.rsindex afa149665,e2c2790a0..e66728465--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -4476,40 -3604,30 +4475,67 @@@ mod testsassert!(!open, "an open submenu closes when its row becomes fully clipped");}+ #[test]+ fn mac_settings_follow_about_in_the_app_menu_and_leave_edit() {+ let pos = |command: &str| MAC_APP_MENU.iter().position(|m| matches!(m, AppMenuItem::Cmd { command: c, .. } if *c == command));+ let (Some(about), Some(settings)) = (pos("help.about"), pos("app.preferences")) else { panic!("About and Settings are in the app menu") };+ assert!(about < settings);+ assert_eq!(MAC_APP_MENU.get(settings - 1), Some(&AppMenuItem::Sep));+ assert_eq!(MAC_APP_MENU.get(settings + 1), Some(&AppMenuItem::Sep));+ let label = |command: &str| {+ MAC_APP_MENU.iter().find_map(|m| match m {+ AppMenuItem::Cmd { label, command: c, .. } if *c == command => Some(*label),+ _ => None,+ })+ };+ assert_eq!(label("app.preferences"), Some("Settings…"));+ assert_ne!(crate::i18n::tr("de", "Settings…"), "Settings…");+ let ids = MAC_APP_MENU.iter().filter_map(|m| if let AppMenuItem::Cmd { id, .. } = m { Some(*id) } else { None }).collect::<Vec<_>>();+ assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "native ids are unique: {ids:?}");++ let edit = |tree: Vec<(&'static str, Vec<Item>)>| {+ let mut out = Vec::new();+ walk(&tree.into_iter().find(|(t, _)| *t == "Edit").map(|(_, e)| e).unwrap_or_default(), &mut out);+ out.into_iter().map(|(_, id, _)| id).collect::<Vec<_>>()+ };+ assert!(edit(menu_tree()).iter().any(|id| id == "app.preferences"), "the in-window Edit menu keeps Preferences");+ let native = native_menu_tree();+ let mut all = Vec::new();+ for (_, entries) in &native {+ walk(entries, &mut all);+ }+ assert!(!all.iter().any(|(_, id, _)| id == "app.preferences"), "the macOS menu bar has Settings only in the app menu");+ assert!(edit(native_menu_tree()).iter().any(|id| id == "app.keyboardShortcuts"));+ for (title, entries) in &native {+ assert!(!matches!(entries.first(), Some(Item::Sep)) && !matches!(entries.last(), Some(Item::Sep)), "{title}: separator at an end");+ assert!(entries.windows(2).all(|w| !matches!(w, [Item::Sep, Item::Sep])), "{title}: doubled separator");+ }+ }+++ /// Web save: a download that couldn't start is an error and leaves the document unsaved; one+ /// that started marks it saved.+ #[test]+ fn web_save_marks_the_document_saved_only_after_the_download_starts() {+ let dir = tempfile::tempdir().unwrap();+ // The title names a temporary path: on native, file.saveAs writes where the web build doesn't.+ let title = dir.path().join("doc").to_string_lossy().to_string();+ let fails = std::rc::Rc::new(std::cell::Cell::new(true));+ let f = fails.clone();+ let services = crate::Services {+ download: Some(Box::new(move |_: &str, _: &[u8]| if f.get() { Err("blocked".into()) } else { Ok(()) })),+ ..Default::default()+ };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.run("file.new", json!({"title": title})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 300, 200]})).unwrap();+ assert!(app.session.active().unwrap().is_dirty());++ let e = app.run("app.save", json!({})).unwrap_err();+ assert!(e.contains("blocked"), "{e}");+ assert!(app.session.active().unwrap().is_dirty(), "a failed download leaves the document unsaved");++ fails.set(false);+ app.run("app.save", json!({})).unwrap();+ assert!(!app.session.active().unwrap().is_dirty());+ }}