Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #869: Pages panel: Alt-drag copies a page, drop a page on Create new page, Edit page size; duplicates keep their size

aiongg2036194de68e
diff --cc ROADMAP.md
index 865d9fb1e,cf4d92cff..216351199
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -128,94 -129,9 +128,95 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+ - **2026-10-14** · Pages panel: Alt-drag copies a page, a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.
+- **2026-10-13** · Control-channel clicks and drags validate positive counts and the complete pending-event budget before queuing input (#732). Oversized requests leave pending gestures intact, preventing unbounded click-count allocation. No readiness percentage change.
+- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
+- **2026-10-13** · Placed PDFs are drawn through pdfcraft's patched hayro crates: calculator functions whose `idiv` divides by zero or overflows, chains of stitching functions a hundred thousand deep, and mesh shadings with points far off the page, ten thousand overlapping triangles or forty thousand patches no longer panic, overflow the stack, run for over a minute or use more than 2 GiB of memory. A page with a `/UserUnit`, and its trim, bleed and art boxes, are sized in points. No readiness percentage change.
+- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.
+- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.
+- **2026-10-13** · Commands refuse parameter keys their params description doesn't name (#776): the control channel, MCP (`-32602`, every `batch` step checked before the first runs) and `designcraft-cli --cmd` answer with an “unknown parameter” error naming the nearest or the accepted keys instead of running with defaults; journals still replay. Descriptions of the table, anchored-object, data-merge and placing commands now name every key they read. No readiness percentage change.
+- **2026-10-13** · File ▸ Open Recent lists the documents last opened or saved (newest first, no duplicates; Save a Copy and exports don't count), with Clear Recent Files; the start screen shows the last eight, below the community card, as cards with a picture of the first page: saving puts one in the file (`preview.png`), so the start screen reads it without opening the document. A file that is gone is dimmed and says so when chosen, and stays listed. Preferences ▸ File Handling sets how many are kept (default 20, 0–100). `file.openRecent {index}`, `file.recentFiles`, `file.clearRecent` (#706). No readiness percentage change.
+- **2026-10-13** · Dropping an `.ase` file on the window loads its swatches, as Load Swatches does (the drop failed with "Can't Place the File"). No readiness percentage change.
+- **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.
+- **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.
+- **2026-10-13** · The Gradient panel follows InDesign's layout (thumbnail, Type, Location, Angle, Reverse, ramp with midpoint diamonds) and takes swatches dragged from the Swatches panel: dropped on a stop they colour it, elsewhere they add a stop. Stops keep their CMYK through panel edits; `object.gradient` stops accept a `swatch`. No readiness percentage change.
+- **2026-10-13** · New Swatch works as InDesign's: a gradient made in the Gradient panel becomes "New Gradient Swatch" (still applied), an unnamed colour a listed swatch, a named swatch a "copy" (`swatch.new`); `swatch.create {gradient}` makes a gradient swatch from colour swatches. No readiness percentage change.
+- **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.
+- **2026-10-13** · Inner Glow takes a blend mode (Screen by default) and a Technique (Softer or Precise); Basic Feather takes Choke and Corners (Sharp, Rounded, Diffused), in the Effects dialog and `object.effects`. Inner glow and bevel blend modes now mix with the object below them instead of an empty layer. Noise isn't drawn. No readiness percentage change.
+- **2026-10-13** · Text Frame Options is laid out as InDesign's: General (Columns: Fixed Number or Fixed Width with Number, Width and Gutter; Balance Columns; Inset Spacing with the link button; Vertical Justification; Ignore Text Wrap), Baseline Options (First Baseline Offset and Min) and Column Rules. `object.textFrameOptions` takes `columnWidth` and `firstBaselineMin`. No readiness percentage change.
+- **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.
+- **2026-10-13** · `.indd` and `.indt` documents open through File › Open, drop, the web inbox, `file.open`, `file.openBytes`, `file.openIdml` and the CLI: [storytold/indd-utils](https://github.com/storytold/indd-utils) converts them to IDML in memory and the IDML importer reads the result, on desktop and web. Converter warnings come first in the open result; an unreadable file is an open error (#21, #114). No readiness percentage change until a real-file corpus measures it.
+- **2026-10-13** · macOS: a command chosen with the mouse in the menu bar runs at once. It used to wait for the next mouse move or key press over the window, so File › Open, Place and Save As seemed to take 10–20 seconds to open their dialogs. No readiness percentage change.
+- **2026-10-13** · An explicit recovery folder (`file.recovery.save` with `dir`) never overwrites or deletes another running app's checkpoints. Document uids start at 1 in every process, so two apps saving recovery to one chosen folder replaced or removed each other's `<uid>.designcraft`. A run replaces or removes only the entries it wrote or recovered there, refuses an occupied uid, and refuses a folder whose run lock another app holds. No readiness percentage change.
+- **2026-10-13** · PDF export leaves out form fields, buttons and video or sound that don't print: inside a hidden group, on a hidden or non-printing layer, or marked non-printing. Page content and interactive elements follow one inclusion rule. No readiness percentage change.
+- **2026-10-13** · IDML export keeps parent item overrides: each page lists its overridden parent items and the local copy keeps its link to the parent item, so a reopened IDML file shows only the local copy (#725). No readiness percentage change.
+- **2026-10-13** · Reflowable EPUB and HTML export include tables (header and footer rows, merged cells), footnotes (a linked note after the paragraph that refers to it) and endnotes (a linked section at the end of the book). No readiness percentage change.
+- **2026-10-13** · Word import: table cells read text by the same rules as body text, so deleted text, moved-away text and field codes stay out (#721). Word's Normal comes in as its own paragraph style "Normal" over the document defaults, so text formatted only by Normal keeps its look; it conflicts only with a document's own Normal, and the style map can send it to [Basic Paragraph] (#722). No readiness percentage change.
+- **2026-10-13** · Text recomposes when the document baseline grid changes, when a layer holding a text-wrap object is shown or hidden, or when a section's start number, numbering style, prefix or marker changes; the composition cache keyed only on the section count and item identities and kept the old layout. No readiness percentage change.
+- **2026-10-13** · Path edits (`path.setAnchor`, `path.moveAnchors`, `path.appendAnchor`, `path.reverse`, `path.close`, anchor add/delete/convert, Erase, Smooth and Scissors) refuse a path that is locked, sits in a locked group or on a locked layer (#735). Properties links to the Stroke, Character, Paragraph, Effects, Text Wrap and Info panels open them in a customized panel layout too (#736). No readiness percentage change.
+- **2026-10-13** · The Story Editor stays with the document its story belongs to: it hides while another document is active and closes with its document, so its edits never reach another document's story with the same id (#729). Undo restores the selection from before the command and Redo the one after it (#716). No readiness percentage change.
+- **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, 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-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. 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/tests.rs
index a38d75337,f896ab3cd..1dd7e230f
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -859,402 -570,28 +859,428 @@@ fn commands_take_non_object_params_with
}
}
+/// Load the text from a frame's out port with the Selection tool and click on the pasteboard:
+/// a new frame is threaded there and the overset text flows into it.
+#[test]
+fn threading_with_the_loaded_text_cursor_on_the_sample() {
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let mut s = Session::new();
+ s.execute("file.newSample", &json!({})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let (sid, first) = d.stories.values().find(|st| st.frames.len() >= 2).map(|st| (st.id, st.frames[0])).expect("a threaded story");
+ // Break the thread so the first frame is overset, and select it.
+ s.execute("text.unthread", &json!({"frame": first.0})).unwrap();
+ assert!(s.cache.get(&s.doc().unwrap().doc, sid, None).is_overset());
+ s.execute("selection.set", &json!({"ids": [first.0]})).unwrap();
+ s.set_tool("selection");
+ let v = ViewInfo::at_zoom(1.0);
+ let layout = s.layout();
+ let port = designcraft_tools::thread::port_center(&s.doc().unwrap().doc, &layout, first, true, v.zoom).unwrap();
+ let ev = |k, p: designcraft_geom::Point| PointerEvent::new(k, p.x, p.y);
+ s.pointer(&ev(PointerKind::Down, port), v).unwrap();
+ s.pointer(&ev(PointerKind::Up, port), v).unwrap();
+ assert_eq!(s.cursor(port + designcraft_geom::Vec2::new(-2000.0, 0.0), Default::default(), v), designcraft_tools::Cursor::LoadedText);
+ // On the pasteboard left of the first spread.
+ let b = layout.slots[0].bounds;
+ let at = designcraft_geom::Point::new(b.x0 - 300.0, b.y0 + 100.0);
+ let undo = s.doc().unwrap().history.undo.len();
+ s.pointer(&ev(PointerKind::Down, at), v).unwrap();
+ s.pointer(&ev(PointerKind::Up, at), v).unwrap();
+ let st = s.doc().unwrap();
+ assert_eq!(st.history.undo.len(), undo + 1, "one undo step");
+ let frames = st.doc.story(sid).unwrap().frames.clone();
+ assert_eq!(frames.len(), 2);
+ let new = frames[1];
+ assert_eq!(st.selection.items, [new]);
+ let cs = s.cache.get(&s.doc().unwrap().doc, sid, None);
+ assert!(cs.frames.iter().any(|f| f.frame == new && !f.range.is_empty()), "the text flows into the new frame");
+ let nb = s.doc().unwrap().doc.item(new).unwrap().bounds();
+ assert!((nb.y0 - layout.to_spread(designcraft_doc::SpreadRef::Doc(0), at).y).abs() < 1e-6, "{nb:?}");
+}
+
+/// Drag a selection handle of item 0 on spread 0 from the edge point `at` by `by` (canvas units).
+fn drag_handle(s: &mut Session, at: designcraft_geom::Point, by: designcraft_geom::Vec2, v: ViewInfo) {
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let p = s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), at);
+ s.pointer(&PointerEvent::new(PointerKind::Down, p.x, p.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, p.x + by.x / 2.0, p.y + by.y / 2.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, p.x + by.x, p.y + by.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, p.x + by.x, p.y + by.y), v).unwrap();
+}
+
+#[test]
+fn text_frame_resize_snaps_to_the_margins() {
+ use designcraft_geom::{Point, Vec2};
+ for zoom in [1.0, 0.5] {
+ let mut s = Session::new();
+ s.execute("file.newSample", &json!({})).unwrap();
+ let margin = s.doc().unwrap().doc.spreads[0].pages[0].margin_rect();
+ let (x0, y0) = (margin.x0 + 40.0, margin.y0 + 40.0);
+ s.execute("frame.create", &json!({"rect": [x0, y0, x0 + 200.0, y0 + 200.0], "content": "text"})).unwrap();
+ s.set_tool("selection");
+ let v = ViewInfo::at_zoom(zoom);
+ let b0 = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
+ // Right handle to 1.5 pt short of the right margin.
+ drag_handle(&mut s, Point::new(b0.x1, b0.center().y), Vec2::new(margin.x1 - 1.5 - b0.x1, 0.0), v);
+ let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
+ assert!((b.x1 - margin.x1).abs() < 1e-6, "zoom {zoom}: right edge {} not on the margin {}", b.x1, margin.x1);
+ // Bottom handle to 1.5 pt past the bottom margin.
+ drag_handle(&mut s, Point::new(b.center().x, b.y1), Vec2::new(0.0, margin.y1 + 1.5 - b.y1), v);
+ let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
+ assert!((b.y1 - margin.y1).abs() < 1e-6, "zoom {zoom}: bottom edge {} not on the margin {}", b.y1, margin.y1);
+ // Top-left corner handle onto the top and left margins.
+ drag_handle(&mut s, Point::new(b.x0, b.y0), Vec2::new(margin.x0 + 1.0 - b.x0, margin.y0 - 1.0 - b.y0), v);
+ let b = s.doc().unwrap().doc.spreads[0].items.last().unwrap().bounds();
+ assert!((b.x0 - margin.x0).abs() < 1e-6 && (b.y0 - margin.y0).abs() < 1e-6, "zoom {zoom}: corner {b:?} not on the margins {margin:?}");
+ }
+}
+
+#[test]
+fn type_tool_frames_snap_to_the_margins() {
+ use designcraft_geom::Point;
+ use designcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let margin = s.doc().unwrap().doc.spreads[0].pages[0].margin_rect();
+ s.set_tool("type");
+ let v = ViewInfo::at_zoom(1.0);
+ let c = |s: &Session, x: f64, y: f64| s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), Point::new(x, y));
+ // From 1.5 pt off the top-left margin corner to 1.5 pt off the right margin.
+ let a = c(&s, margin.x0 + 1.5, margin.y0 + 1.5);
+ let b = c(&s, margin.x1 - 1.5, margin.y0 + 101.5);
+ let before = s.doc().unwrap().doc.spreads[0].items.len();
+ s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, (a.x + b.x) / 2.0, b.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();
+ let items = &s.doc().unwrap().doc.spreads[0].items;
+ assert_eq!(items.len(), before + 1, "a frame was drawn");
+ let r = items.last().unwrap().bounds();
+ assert!((r.x0 - margin.x0).abs() < 1e-6 && (r.y0 - margin.y0).abs() < 1e-6, "press point {r:?} vs {margin:?}");
+ assert!((r.x1 - margin.x1).abs() < 1e-6, "right edge {} vs {}", r.x1, margin.x1);
+}
+
+#[test]
+fn preflight_distinguishes_unplaced_stories_and_locates_footnote_overset() {
+ use designcraft_doc::{AnchorPosition, AnchoredObject, ParaFormat, SpreadRef, Story, StoryId};
+ use designcraft_geom::Rect;
+ let mut s = session();
+ let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+ let layer = doc.default_layer();
+ let (host, body) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(20.0, 20.0, 400.0, 600.0), layer, "Body", ParaFormat::default()).unwrap();
+ let (frame, _) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 5.0, 2.0), layer, "Overflow", ParaFormat::default()).unwrap();
+ let item = doc.item(frame).unwrap().clone();
+ doc.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != frame);
+ let story = doc.story_mut(body).unwrap();
+ story.insert_note(4, "Note", ParaFormat::default());
+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 }));
+ let unplaced = StoryId(doc.alloc());
+ doc.stories.insert(unplaced, Arc::new(Story::with_text(unplaced, "Unplaced", ParaFormat::default())));
+ doc.check().unwrap();
+ let issues = s.execute("preflight.run", &json!({})).unwrap();
+ let issues = issues["issues"].as_array().unwrap();
+ let overset: Vec<_> = issues.iter().filter(|i| i["kind"] == "overset").collect();
+ assert_eq!(overset.len(), 1, "{issues:?}");
+ assert_eq!(overset[0]["item"], host.0);
+ assert_eq!(overset[0]["page"], 0);
+ let unplaced = issues.iter().find(|i| i["kind"] == "unplacedStory").unwrap();
+ assert_eq!(unplaced["severity"], "warning");
+ assert!(unplaced.get("page").is_none());
+}
+
+#[test]
+fn preflight_mojikumi_uses_the_same_supported_rules_as_composition() {
+ let mut s = session();
+ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "中文 A1"})).unwrap();
+ let story = s.doc().unwrap().doc.stories.keys().next().unwrap().0;
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 1})).unwrap();
+ for (name, unsupported) in [
+ ("SimpChineseDefault", false),
+ ("LineEndAllOneHalfEmEnum", false),
+ ("LineEndAllOneEmEnum", false),
+ ("UnknownPreset", true),
+ ("Nothing", false),
+ ] {
+ s.execute("type.para", &json!({"attrs": {"mojikumi": name, "kinsokuType": "KinsokuPushInFirst"}})).unwrap();
+ let result = s.execute("preflight.run", &json!({})).unwrap();
+ let warnings: Vec<_> = result["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "unsupportedTypography").collect();
+ assert_eq!(!warnings.is_empty(), unsupported, "{name}: {warnings:?}");
+ }
+}
+
+#[test]
+fn paragraph_style_edit_persists_attrs_and_rename() {
+ let mut s = session();
+ let name =
+ s.execute("style.paragraph.create", &json!({"name": "Body Copy", "para": {"align": "left"}})).unwrap()["name"].as_str().unwrap().to_string();
+ s.execute("style.paragraph.edit", &json!({"name": name, "para": {"align": "center"}})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let style = st.doc.styles.para(&name).expect("style still exists");
+ assert_eq!(style.para.align, Some(designcraft_doc::Align::Center), "edited attribute persisted");
+ }
+ // Renaming updates the style definition itself, and every place it's referenced.
+ s.execute("style.paragraph.edit", &json!({"name": name, "rename": "Body Text"})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.para("Body Text").is_some(), "renamed style exists under the new name");
+ assert!(st.doc.styles.para(&name).is_none(), "old name is gone");
+}
+
+#[test]
+fn paragraph_style_edit_rejects_based_on_cycle() {
+ let mut s = session();
+ let a = s.execute("style.paragraph.create", &json!({"name": "A"})).unwrap()["name"].as_str().unwrap().to_string();
+ let b = s.execute("style.paragraph.create", &json!({"name": "B", "basedOn": a})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("style.paragraph.edit", &json!({"name": a, "basedOn": b}));
+ assert!(r.is_err(), "A based on B based on A must be rejected");
+}
+
+#[test]
+fn paragraph_style_delete_reassigns_affected_text() {
+ let mut s = session();
+ let name = s.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();
+ let sid = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap()["story"].as_u64().unwrap();
+ s.execute("text.insert", &json!({"text": "Hello, world"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 0})).unwrap();
+ s.execute("style.paragraph.apply", &json!({"name": name})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.paras[0].style, name, "style applied before delete");
+ }
+ s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": designcraft_doc::BASIC_PARAGRAPH})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.para(&name).is_none(), "deleted style is gone");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.paras[0].style, designcraft_doc::BASIC_PARAGRAPH, "affected paragraph reassigned to the replacement style");
+}
+
+#[test]
+fn paragraph_style_delete_rejects_builtin_styles() {
+ let mut s = session();
+ let r = s.execute("style.paragraph.delete", &json!({"name": designcraft_doc::BASIC_PARAGRAPH}));
+ assert!(r.is_err(), "built-in styles can't be deleted");
+}
+
+#[test]
+fn character_style_edit_persists_attrs_and_rename() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term", "chars": {"fontStyle": "Bold"}})).unwrap()["name"]
+ .as_str()
+ .unwrap()
+ .to_string();
+ s.execute("style.character.edit", &json!({"name": name, "chars": {"tracking": 20.0}})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let style = st.doc.styles.char_style(&name).expect("style still exists");
+ assert_eq!(style.chars.tracking, Some(20.0), "edited attribute persisted");
+ }
+ // Renaming updates the style definition itself, and every place it's referenced.
+ s.execute("style.character.edit", &json!({"name": name, "rename": "Emphasis"})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.char_style("Emphasis").is_some(), "renamed style exists under the new name");
+ assert!(st.doc.styles.char_style(&name).is_none(), "old name is gone");
+}
+
+#[test]
+fn character_style_edit_rejects_based_on_cycle() {
+ let mut s = session();
+ let a = s.execute("style.character.create", &json!({"name": "A"})).unwrap()["name"].as_str().unwrap().to_string();
+ let b = s.execute("style.character.create", &json!({"name": "B", "basedOn": a})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("style.character.edit", &json!({"name": a, "basedOn": b}));
+ assert!(r.is_err(), "A based on B based on A must be rejected");
+}
+
+#[test]
+fn character_style_delete_reassigns_affected_text() {
+ let mut s = session();
+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.insert", &json!({"text": "Hello, world"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();
+ s.execute("style.character.apply", &json!({"name": name})).unwrap();
+ {
+ let st = s.doc().unwrap();
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.chars[0].format.style, name, "style applied before delete");
+ }
+ s.execute("style.character.delete", &json!({"name": name, "replaceWith": designcraft_doc::NO_CHAR_STYLE})).unwrap();
+ let st = s.doc().unwrap();
+ assert!(st.doc.styles.char_style(&name).is_none(), "deleted style is gone");
+ let story = st.doc.stories.get(&designcraft_doc::StoryId(sid)).expect("story exists");
+ assert_eq!(story.chars[0].format.style, designcraft_doc::NO_CHAR_STYLE, "affected run reassigned to the replacement style");
+}
+
+#[test]
+fn character_style_delete_rejects_builtin_styles() {
+ let mut s = session();
+ let r = s.execute("style.character.delete", &json!({"name": designcraft_doc::NO_CHAR_STYLE}));
+ assert!(r.is_err(), "built-in styles can't be deleted");
+}
+
+#[test]
+fn direct_selection_drag_and_arrow_keys_move_placed_content() {
+ use designcraft_tools::{Mods, PointerEvent, PointerKind, SnapView, ToolKey};
+ let mut s = session();
+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();
+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("place.load", &json!({"base64": cmd::base64_encode(&png)})).unwrap();
+ s.execute("place.drop", &json!({"frame": f})).unwrap();
+ let xfs = |s: &Session| {
+ let it = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();
+ (it.xf, it.graphic().unwrap().xf.translation())
+ };
+ let (frame0, g0) = xfs(&s);
+ let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };
+ let at = s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(150.0, 150.0));
+ s.set_tool("directSelection");
+ s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 10.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 30.0, at.y + 10.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, at.x + 30.0, at.y + 10.0), v).unwrap();
+ assert!(s.doc().unwrap().selection.content);
+ let (frame1, g1) = xfs(&s);
+ assert_eq!(frame1, frame0, "the frame stays");
+ assert_eq!(g1 - g0, designcraft_geom::Vec2::new(30.0, 10.0));
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(xfs(&s).1, g0, "one undo step");
+ // Arrow keys nudge the selected content; Shift nudges ten times as far.
+ s.set_tool("selection");
+ s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();
+ s.tool_key(ToolKey::Down, Mods { shift: true, ..Default::default() }, v).unwrap();
+ let (frame2, g2) = xfs(&s);
+ assert_eq!(frame2, frame0);
+ assert_eq!(g2 - g0, designcraft_geom::Vec2::new(1.0, 10.0));
+}
+
+#[test]
+fn preflight_notes_an_assumed_mojikumi_base_set_without_calling_the_table_unapplied() {
+ let mut s = session();
+ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "中文 A1"})).unwrap();
+ let story = s.doc().unwrap().doc.stories.keys().next().unwrap().0;
+ let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+ std::sync::Arc::make_mut(&mut d.styles)
+ .mojikumi_tables
+ .push(designcraft_doc::cjk::MojikumiTable { name: "Baseless".into(), ..Default::default() });
+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 1})).unwrap();
+ s.execute("type.para", &json!({"attrs": {"mojikumi": "MojikumiTable/Baseless"}})).unwrap();
+ let result = s.execute("preflight.run", &json!({})).unwrap();
+ let messages: Vec<_> =
+ result["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "unsupportedTypography").filter_map(|i| i["message"].as_str()).collect();
+ assert!(messages.iter().any(|m| m.contains("Baseless") && m.contains("no base set")), "{messages:?}");
+ assert!(!messages.iter().any(|m| m.contains("not applied")), "{messages:?}");
+}
+
+#[test]
+fn live_corner_gestures_are_one_undo_step_each() {
+ use designcraft_geom::corners::CornerShape;
+ use designcraft_tools::{Mods, PointerEvent, PointerKind};
+ let mut s = session();
+ s.execute("frame.create", &json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap();
+ let id = s.doc().unwrap().doc.spreads[0].items[0].id;
+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();
+ s.set_tool("selection");
+ let v = ViewInfo::at_zoom(1.0);
+ let undo = |s: &Session| s.doc().unwrap().history.undo.len();
+ let corners = |s: &Session| s.doc().unwrap().doc.item(id).unwrap().corners.corners;
+ let before = undo(&s);
+ // Click the widget, then drag the top-left diamond 20 pt toward the centre.
+ s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 111.5), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 111.5), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Down, 112.0, 100.0), v).unwrap();
+ for x in [116.0, 124.0, 132.0] {
+ s.pointer(&PointerEvent::new(PointerKind::Drag, x, 100.0), v).unwrap();
+ }
+ s.pointer(&PointerEvent::new(PointerKind::Up, 132.0, 100.0), v).unwrap();
+ assert_eq!(undo(&s), before + 1);
+ assert!(corners(&s).iter().all(|c| c.shape == CornerShape::Rounded && (c.size - 20.0).abs() < 1e-9), "{:?}", corners(&s));
+ // Alt-click the top-left diamond, now 20 pt along the edge.
+ let alt = Mods { alt: true, ..Default::default() };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 100.0).with_mods(alt), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 120.0, 100.0).with_mods(alt), v).unwrap();
+ assert_eq!(undo(&s), before + 2);
+ assert_eq!(corners(&s)[0].shape, CornerShape::InverseRounded);
+ assert_eq!(corners(&s)[1].shape, CornerShape::Rounded);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(corners(&s)[0].shape, CornerShape::Rounded);
+ // Malformed per-corner parameters are errors, not silent defaults.
+ let c = json!({"shape": "rounded", "size": 5});
+ assert!(s.execute("object.cornerOptions", &json!({"corners": [c, c, c]})).is_err());
+ assert!(s.execute("object.cornerOptions", &json!({"corners": [c, c, c, {"shape": "rounded", "size": -1}]})).is_err());
+ assert!(s.execute("object.cornerOptions", &json!({"corners": "rounded"})).is_err());
+}
+
+#[test]
+fn alt_arrows_kern_at_the_caret_and_track_a_selection() {
+ use designcraft_doc::{Kerning, StoryId};
+ use designcraft_tools::{Mods, ToolKey};
+ let mut s = session();
+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello world"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.set_tool("type");
+ let v = ViewInfo::at_zoom(1.0);
+ let alt = Mods { alt: true, ..Default::default() };
+ let story = |s: &Session| s.doc().unwrap().doc.story(StoryId(sid)).unwrap().clone();
+ let caret = |s: &mut Session, at: usize| s.execute("text.select", &json!({"story": sid, "anchor": at, "focus": at})).unwrap();
+ // Caret between "e" and "l": Alt+Right kerns the pair by the increment; the caret stays.
+ caret(&mut s, 2);
+ assert!(s.tool_key(ToolKey::Right, alt, v).unwrap());
+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(20.0)));
+ assert_eq!(s.doc().unwrap().selection.text.unwrap().focus, 2);
+ s.tool_key(ToolKey::Right, alt, v).unwrap();
+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(40.0)));
+ // One undo step per press.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(20.0)));
+ // Alt+Cmd (Alt+Ctrl elsewhere) steps five increments.
+ caret(&mut s, 4);
+ s.tool_key(ToolKey::Left, Mods { cmd: true, ..alt }, v).unwrap();
+ assert_eq!(story(&s).format_after(3).over.kerning, Some(Kerning::Manual(-100.0)));
+ // The increment is the document's Kerning/Tracking preference.
+ s.execute("document.preferences", &json!({"kerningIncrement": 10})).unwrap();
+ caret(&mut s, 2);
+ s.tool_key(ToolKey::Right, alt, v).unwrap();
+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(30.0)));
+ // A selection: tracking of the selected text.
+ s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 11})).unwrap();
+ s.tool_key(ToolKey::Right, alt, v).unwrap();
+ let st = story(&s);
+ assert_eq!((st.format_after(6).over.tracking, st.format_after(10).over.tracking), (Some(10.0), Some(10.0)));
+ assert_eq!(st.format_after(4).over.tracking, None);
+ s.tool_key(ToolKey::Left, Mods { cmd: true, ctrl: true, ..alt }, v).unwrap();
+ assert_eq!(story(&s).format_after(8).over.tracking, Some(-40.0));
+ // Words: Cmd+Right (Ctrl+Right elsewhere); Alt+Shift+Right extends by a word.
+ caret(&mut s, 0);
+ s.tool_key(ToolKey::Right, Mods { cmd: true, ..Default::default() }, v).unwrap();
+ assert_eq!(s.doc().unwrap().selection.text.unwrap().focus, 5);
+ caret(&mut s, 0);
+ s.tool_key(ToolKey::Right, Mods { alt: true, shift: true, ..Default::default() }, v).unwrap();
+ let t = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.anchor, t.focus), (0, 5));
+}
++
+ #[test]
+ fn duplicating_a_page_keeps_its_own_size_rule_guides_and_objects() {
+ // Chris Cicchino's Page Tool video (2:06): the letterhead page is duplicated, then resized.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 252, "height": 144, "facingPages": false})).unwrap();
+ s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
+ s.execute("layout.pageSize", &json!({"pages": [2], "width": 612, "height": 792})).unwrap();
+ s.execute("liquid.pageRule", &json!({"rule": "scale", "pages": [2]})).unwrap();
+ s.execute("guide.add", &json!({"spread": 1, "page": 0, "orientation": "vertical", "position": 300})).unwrap();
+ s.execute("frame.create", &json!({"spread": 1, "rect": [100, 100, 200, 200]})).unwrap();
+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 1})).unwrap();
+ assert_eq!(r["page"], 2);
+ let d = s.doc().unwrap().doc.clone();
+ let (si, pi) = d.page_loc(2).unwrap();
+ let pg = &d.spreads[si].pages[pi];
+ assert_eq!((pg.width, pg.height, pg.liquid), (612.0, 792.0, designcraft_doc::LiquidRule::Scale));
+ assert_eq!(pg.guides.len(), 1);
+ assert_eq!(d.spreads[si].items.len(), 1);
+ // At the end of the document (the New Page button): the business card, not the last page's size.
+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "atEnd": true})).unwrap();
+ assert_eq!(r["page"], 3);
+ let d = s.doc().unwrap().doc.clone();
+ let (si, pi) = d.page_loc(3).unwrap();
+ assert_eq!((d.spreads[si].pages[pi].width, d.spreads[si].pages[pi].height), (252.0, 144.0));
+ }
diff --cc crates/ui-egui/src/i18n.rs
index 74e80c367,93728dde5..218b440bb
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@@ -1064,89 -577,70 +1064,105 @@@ const TABLE: &[(&str, [&str; 5])] = &
"跟踪所有文章中的更改",
],
),
- ("Trim", ["Trim", "Trim", "Trim", "Trim", "裁切"]),
- ("Type:", ["Type:", "Type:", "Type:", "Type:", "类型:"]),
- ("Typical", ["Typical", "Typical", "Typical", "Typical", "典型"]),
- ("UI Size:", ["UI Size:", "UI Size:", "UI Size:", "UI Size:", "UI 大小:"]),
- ("Ungroup Color Group", ["Ungroup Color Group", "Ungroup Color Group", "Ungroup Color Group", "Ungroup Color Group", "取消颜色组"]),
- ("Unmerge", ["Unmerge", "Unmerge", "Unmerge", "Unmerge", "取消合并"]),
- ("Update", ["Update", "Update", "Update", "Update", "更新"]),
- ("Update Numbering", ["Update Numbering", "Update Numbering", "Update Numbering", "Update Numbering", "更新编号"]),
- ("Use Global Light", ["Use Global Light", "Use Global Light", "Use Global Light", "Use Global Light", "使用全局光"]),
- ("User Dictionary", ["User Dictionary", "User Dictionary", "User Dictionary", "User Dictionary", "用户词典"]),
+ ("Trim", ["Trim", "Rognage", "Trim", "Trim", "裁切"]),
+ (
+ "Bounding Box (Visible Layers Only)",
+ [
+ "Begrenzungsrahmen (nur sichtbare Ebenen)",
+ "Cadre de sélection (calques visibles uniquement)",
+ "Cuadro delimitador (solo capas visibles)",
+ "バウンディングボックス(表示レイヤーのみ)",
+ "边界框(仅可见图层)",
+ ],
+ ),
+ (
+ "Bounding Box (All Layers)",
+ [
+ "Begrenzungsrahmen (alle Ebenen)",
+ "Cadre de sélection (tous les calques)",
+ "Cuadro delimitador (todas las capas)",
+ "バウンディングボックス(すべてのレイヤー)",
+ "边界框(所有图层)",
+ ],
+ ),
+ ("Type:", ["Type:", "Type :", "Type:", "Type:", "类型:"]),
+ ("Typical", ["Typical", "Standard", "Typical", "Typical", "典型"]),
+ ("UI Size:", ["UI Size:", "Taille de l'interface :", "UI Size:", "UI Size:", "UI 大小:"]),
+ ("Ungroup Color Group", ["Ungroup Color Group", "Dissocier le groupe de couleurs", "Ungroup Color Group", "Ungroup Color Group", "取消颜色组"]),
+ ("Unmerge", ["Unmerge", "Annuler la fusion", "Unmerge", "Unmerge", "取消合并"]),
+ ("Update", ["Update", "Mettre à jour", "Update", "Update", "更新"]),
+ ("Update Numbering", ["Update Numbering", "Mettre à jour la numérotation", "Update Numbering", "Update Numbering", "更新编号"]),
+ ("Use Global Light", ["Use Global Light", "Utiliser la lumière globale", "Use Global Light", "Use Global Light", "使用全局光"]),
+ ("User Dictionary", ["User Dictionary", "Dictionnaire utilisateur", "User Dictionary", "User Dictionary", "用户词典"]),
(
"Vertical Gridline Every:",
- ["Vertical Gridline Every:", "Vertical Gridline Every:", "Vertical Gridline Every:", "Vertical Gridline Every:", "垂直网格线间隔:"],
+ [
+ "Vertical Gridline Every:",
+ "Ligne de grille verticale tous les :",
+ "Vertical Gridline Every:",
+ "Vertical Gridline Every:",
+ "垂直网格线间隔:",
+ ],
),
- ("Vertical Margins:", ["Vertical Margins:", "Vertical Margins:", "Vertical Margins:", "Vertical Margins:", "垂直边距:"]),
- ("Vertical justification", ["Vertical justification", "Vertical justification", "Vertical justification", "Vertical justification", "垂直对齐"]),
- ("View Threshold:", ["View Threshold:", "View Threshold:", "View Threshold:", "View Threshold:", "视图阈值:"]),
+ ("Vertical Margins:", ["Vertical Margins:", "Marges verticales :", "Vertical Margins:", "Vertical Margins:", "垂直边距:"]),
+ ("Vertical justification", ["Vertical justification", "Justification verticale", "Vertical justification", "Vertical justification", "垂直对齐"]),
+ ("View Threshold:", ["View Threshold:", "Seuil d'affichage :", "View Threshold:", "View Threshold:", "视图阈值:"]),
("Web", ["Web", "Web", "Web", "Web", "Web"]),
- ("Web Hyperlink", ["Web Hyperlink", "Web Hyperlink", "Web Hyperlink", "Web Hyperlink", "Web 超链接"]),
- ("Weight:", ["Weight:", "Weight:", "Weight:", "Weight:", "粗细:"]),
- ("Width", ["Width", "Width", "Width", "Width", "宽度"]),
- ("Width:", ["Width:", "Width:", "Width:", "Width:", "宽度:"]),
- ("Words, one per line:", ["Words, one per line:", "Words, one per line:", "Words, one per line:", "Words, one per line:", "单词,每行一个:"]),
- ("Multiple Objects", ["Multiple Objects", "Multiple Objects", "Multiple Objects", "Multiple Objects", "多个对象"]),
+ ("Web Hyperlink", ["Web Hyperlink", "Hyperlien Web", "Web Hyperlink", "Web Hyperlink", "Web 超链接"]),
+ ("Weight:", ["Weight:", "Épaisseur :", "Weight:", "Weight:", "粗细:"]),
+ ("Width", ["Width", "Largeur", "Width", "Width", "宽度"]),
+ ("Width:", ["Width:", "Largeur :", "Width:", "Width:", "宽度:"]),
+ ("Words, one per line:", ["Words, one per line:", "Mots, un par ligne :", "Words, one per line:", "Words, one per line:", "单词,每行一个:"]),
+ ("Multiple Objects", ["Multiple Objects", "Plusieurs objets", "Multiple Objects", "Multiple Objects", "多个对象"]),
("Ellipse", ["Ellipse", "Ellipse", "Ellipse", "Ellipse", "椭圆"]),
- ("Polygon", ["Polygon", "Polygon", "Polygon", "Polygon", "多边形"]),
- ("Characters", ["Characters", "Characters", "Characters", "Characters", "字符"]),
+ ("Polygon", ["Polygon", "Polygone", "Polygon", "Polygon", "多边形"]),
+ ("Characters", ["Characters", "Caractères", "Characters", "Characters", "字符"]),
("Image", ["Image", "Image", "Image", "Image", "图像"]),
- ("Line", ["Line", "Line", "Line", "Line", "直线"]),
- ("Path", ["Path", "Path", "Path", "Path", "路径"]),
- ("No Selection", ["No Selection", "No Selection", "No Selection", "No Selection", "未选择"]),
- ("Adjust Layout", ["Adjust Layout", "Adjust Layout", "Adjust Layout", "Adjust Layout", "调整版面"]),
- ("Edit Page", ["Edit Page", "Edit Page", "Edit Page", "Edit Page", "编辑页面"]),
- ("Import File", ["Import File", "Import File", "Import File", "Import File", "导入文件"]),
- ("Insert Page", ["Insert Page", "Insert Page", "Insert Page", "Insert Page", "插入页面"]),
+ ("Line", ["Line", "Trait", "Line", "Line", "直线"]),
+ ("Path", ["Path", "Tracé", "Path", "Path", "路径"]),
+ ("No Selection", ["No Selection", "Aucune sélection", "No Selection", "No Selection", "未选择"]),
+ ("Adjust Layout", ["Adjust Layout", "Ajuster la mise en page", "Adjust Layout", "Adjust Layout", "调整版面"]),
+ ("Edit Page", ["Edit Page", "Modifier la page", "Edit Page", "Edit Page", "编辑页面"]),
+ ("Import File", ["Import File", "Importer un fichier", "Import File", "Import File", "导入文件"]),
+ ("Insert Page", ["Insert Page", "Insérer une page", "Insert Page", "Insert Page", "插入页面"]),
+ (
+ "Delete selected pages",
+ ["Ausgewählte Seiten löschen", "Supprimer les pages sélectionnées", "Eliminar páginas seleccionadas", "選択したページを削除", "删除选定页面"],
+ ),
+ ("Create new page", ["Neue Seite erstellen", "Créer une page", "Crear página nueva", "新規ページを作成", "新建页面"]),
+ ("Edit page size", ["Seitenformat bearbeiten", "Modifier le format de page", "Editar tamaño de página", "ページサイズを編集", "编辑页面大小"]),
+ (
+ "Custom Page Size…",
+ [
+ "Benutzerdefiniertes Seitenformat …",
+ "Format de page personnalisé…",
+ "Tamaño de página personalizado…",
+ "カスタムページサイズ…",
+ "自定页面大小…",
+ ],
+ ),
- ("Hide Bar", ["Hide Bar", "Hide Bar", "Hide Bar", "Hide Bar", "隐藏栏"]),
- ("Properties Panel", ["Properties Panel", "Properties Panel", "Properties Panel", "Properties Panel", "属性面板"]),
- ("New Workspace…", ["New Workspace…", "New Workspace…", "New Workspace…", "New Workspace…", "新建工作区…"]),
- ("Float panel", ["Float panel", "Float panel", "Float panel", "Float panel", "浮动面板"]),
- ("Dock panel", ["Dock panel", "Dock panel", "Dock panel", "Dock panel", "停靠面板"]),
+ ("Hide Bar", ["Hide Bar", "Masquer la barre", "Hide Bar", "Hide Bar", "隐藏栏"]),
+ ("Properties Panel", ["Properties Panel", "Panneau Propriétés", "Properties Panel", "Properties Panel", "属性面板"]),
+ ("New Workspace…", ["New Workspace…", "Nouvel espace de travail…", "New Workspace…", "New Workspace…", "新建工作区…"]),
+ ("Float panel", ["Float panel", "Détacher le panneau", "Float panel", "Float panel", "浮动面板"]),
+ ("Dock panel", ["Dock panel", "Ancrer le panneau", "Dock panel", "Dock panel", "停靠面板"]),
(
"Fit frame height to text",
- ["Fit frame height to text", "Fit frame height to text", "Fit frame height to text", "Fit frame height to text", "适合框架高度到文本"],
+ [
+ "Fit frame height to text",
+ "Ajuster la hauteur du bloc au texte",
+ "Fit frame height to text",
+ "Fit frame height to text",
+ "适合框架高度到文本",
+ ],
),
- ("More Options", ["More Options", "More Options", "More Options", "More Options", "更多选项"]),
- ("Flip Horizontal", ["Flip Horizontal", "Flip Horizontal", "Flip Horizontal", "Flip Horizontal", "水平翻转"]),
- ("Rotate 90° Clockwise", ["Rotate 90° Clockwise", "Rotate 90° Clockwise", "Rotate 90° Clockwise", "Rotate 90° Clockwise", "顺时针旋转90°"]),
- ("Flip Vertical", ["Flip Vertical", "Flip Vertical", "Flip Vertical", "Flip Vertical", "垂直翻转"]),
+ ("More Options", ["More Options", "Plus d'options", "More Options", "More Options", "更多选项"]),
+ ("Flip Horizontal", ["Flip Horizontal", "Retourner horizontalement", "Flip Horizontal", "Flip Horizontal", "水平翻转"]),
+ (
+ "Rotate 90° Clockwise",
+ ["Rotate 90° Clockwise", "Rotation de 90° dans le sens horaire", "Rotate 90° Clockwise", "Rotate 90° Clockwise", "顺时针旋转90°"],
+ ),
+ ("Flip Vertical", ["Flip Vertical", "Retourner verticalement", "Flip Vertical", "Flip Vertical", "垂直翻转"]),
(
"Default Fill and Stroke (D)",
[
diff --cc crates/ui-egui/src/panels/pages.rs
index 1ed0c2cb0,d70b3427e..7405ebf82
--- a/crates/ui-egui/src/panels/pages.rs
+++ b/crates/ui-egui/src/panels/pages.rs
@@@ -357,46 -337,53 +402,94 @@@ pub(crate) fn drag_ghost(ui: &egui::Ui
#[cfg(test)]
mod tests {
- use egui::{Event, Modifiers, PointerButton, vec2};
- use egui_kittest::kittest::{NodeT, Queryable};
- use egui_kittest::{Harness, kittest::Queryable};
-- use serde_json::json;
++ use egui::{Event, Modifiers, PointerButton};
++ use egui_kittest::{
++ Harness,
++ kittest::{NodeT, Queryable},
++ };
+ use super::*;
+ use crate::test_window;
+
+ #[test]
+ fn double_clicking_a_parent_shows_that_parent() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ for prefix in ["B", "C", "D"] {
+ app.run("layout.parents.new", json!({"prefix": prefix})).unwrap();
+ }
+ app.ui.dock_tab = "pages".into();
+ let mut h = test_window::open(app, vec2(1400.0, 900.0));
+ let names = ["A-Parent", "B-Parent", "C-Parent", "D-Parent"];
+ for name in names {
+ assert_ne!(h.get_by_label(name).accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "{name} is not selected yet");
+ }
+ // Both clicks in one frame: the harness's event queue spaces events too far apart for a
+ // double click.
+ let at = h.get_by_label("C-Parent").rect().center();
+ h.input_mut().events.push(Event::PointerMoved(at));
+ for pressed in [true, false, true, false] {
+ h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ }
+ h.run_steps(4);
+ let app = &h.state().app;
+ assert!(app.session.active().unwrap().editing_parents);
+ let st = app.session.active().unwrap();
+ let layout = designcraft_tools::CanvasLayout::new(&st.doc, true);
+ let slot = crate::canvas::current_slot(app, &layout).unwrap();
+ assert_eq!(layout.slots[slot].spread, designcraft_doc::SpreadRef::Parent(2));
+ for name in names {
+ assert_eq!(h.get_by_label(name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True), name == "C-Parent", "{name}");
+ }
+ // Parent rows show a rendered thumbnail.
+ let id = st.doc.parents[2].id;
+ let rev = (st.uid, st.revision);
+ let thumbs = super::THUMBS.lock().unwrap();
+ assert!(thumbs.as_ref().unwrap().keys().any(|k| (k.0, k.1) == rev && k.2 == super::ThumbOf::Parent(id)));
+ }
+
+ fn harness(app: DesignApp) -> Harness<'static, DesignApp> {
+ let mut h = Harness::builder().with_size(vec2(280.0, 520.0)).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ let key = egui::Id::new("test_fonts");
+ if ui.data(|d| d.get_temp::<bool>(key)).is_none() {
+ crate::theme::install_fonts(ui.ctx(), "");
+ ui.data_mut(|d| d.insert_temp(key, true));
+ return;
+ }
+ show(app, ui);
+ },
+ app,
+ );
+ h.run_steps(3);
+ h
+ }
+
+ /// Release a dragged page over `at`.
+ fn drop_page(h: &mut Harness<'_, DesignApp>, page: usize, at: egui::Pos2, alt: bool) {
+ let modifiers = egui::Modifiers { alt, ..Default::default() };
+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers });
+ egui::DragAndDrop::set_payload(&h.ctx, PageDrag::Page(page));
+ h.event(egui::Event::PointerMoved(at));
+ h.run_steps(2);
+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers });
+ h.run_steps(3);
+ }
+
+ #[test]
+ fn a_page_dropped_on_create_new_page_is_duplicated_at_the_end() {
+ // Chris Cicchino's Page Tool video (2:06): "click and drag onto my plus sign I can duplicate that".
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 252, "height": 144, "facingPages": false})).unwrap();
+ app.run("layout.pages.insert", json!({"count": 1})).unwrap();
+ app.run("layout.pageSize", json!({"pages": [2], "width": 612, "height": 792})).unwrap();
+ let mut h = harness(app);
+ let plus = h.get_by_label("Create new page").rect().center();
+ drop_page(&mut h, 1, plus, false);
+ let d = h.state().session.doc().unwrap().doc.clone();
+ assert_eq!(d.page_count(), 3);
+ let (si, pi) = d.page_loc(2).unwrap();
+ assert_eq!(d.spreads[si].pages[pi].width, 612.0, "a copy of the letterhead");
+ let _ = h.get_by_label("Edit page size");
+ }
}