Skip to content

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

Merge #84 (final head 9b7a0ec6): Text editing, snapping and text threading

aiongg2f6b62a8314e
diff --cc ROADMAP.md
index dd6195f45,abcd4990b..a84578bb7
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -128,82 -128,6 +128,83 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
++- **2026-10-14** · Threading keeps generated and linked stories, text that refers to a story, local IDs and locked frames intact; a colour chosen at a caret waits for the typing, Swap Fill and Stroke on text keeps each run's colours, control-channel input never reads or writes the system clipboard, and IDML frame preferences given as properties import with bounded column counts (#84). No readiness percentage change.
+- **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.
+- **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.
+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.
+- **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.
+- **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.
+- **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page (and Delete Spread for a spread of several pages), New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.
+- **2026-10-14** · Pages panel: Alt-drag copies a page that is a spread of its own (one undo step; `layout.pages.duplicateSpread` takes `to`), 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** · IDML: an anchored object takes each anchor setting it leaves unset from its object style, the styles that one is based on, then `[None]`; other item attributes read through the same chain. A left-aligned anchored object's X offset reads in the layout's direction. A rotated group's bounds follow its children's outlines instead of the box of their rotated boxes. 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
diff --cc crates/compose/src/lib.rs
index 667cfa0f6,4ed599b04..adad658f5
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -4558,3 -3674,47 +4559,49 @@@ pub fn path_glyphs
}
runs
}
+
+ #[cfg(test)]
+ mod column_allocation_safety_tests {
+ use super::*;
+
+ fn frame(kind: designcraft_doc::ColumnsKind) -> FrameSpec {
+ FrameSpec {
+ id: ItemId(1),
+ area: Rect::new(0., 0., 300., 100.),
+ opts: TextFrameOptions { columns: 217, columns_kind: kind, column_width: 20., gutter: 12., ..Default::default() },
+ vertical: false,
+ exclusions: vec![],
+ page_name: None,
+ page: None,
+ grid: None,
+ left_page: false,
+ page_rect: None,
++ outline: None,
++ section_marker: None,
+ }
+ }
+ fn check(kind: designcraft_doc::ColumnsKind) {
+ let mut f = frame(kind);
+ // Fail safely at a small boundary before exercising hostile native options.
+ assert_eq!(f.columns().len(), 216);
+ f.opts.columns = u32::MAX;
+ assert_eq!(f.columns().len(), 216);
+ f.opts.columns = 0;
+ assert_eq!(f.columns().len(), 1);
+ f.opts.columns = 2;
+ let expected = if kind == designcraft_doc::ColumnsKind::FixedWidth {
+ vec![Rect::new(0., 0., 20., 100.), Rect::new(32., 0., 52., 100.)]
+ } else {
+ vec![Rect::new(0., 0., 144., 100.), Rect::new(156., 0., 300., 100.)]
+ };
+ assert_eq!(f.columns(), expected);
+ }
+ #[test]
+ fn column_allocation_caps_equal_width_frame_count() {
+ check(designcraft_doc::ColumnsKind::FixedNumber);
+ }
+ #[test]
+ fn column_allocation_caps_fixed_width_frame_count() {
+ check(designcraft_doc::ColumnsKind::FixedWidth);
+ }
+ }
diff --cc crates/doc/src/edit.rs
index ee249b12b,7b2168e30..5d86d4036
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@@ -328,8 -245,9 +331,9 @@@ impl Document
for (k, f) in after.iter().enumerate() {
st.frames.insert(at + k, *f);
}
- st.rev += 1;
+ st.rev = st.rev.wrapping_add(1);
}
+ self.remap_thread_story_refs(ts, fs, offset);
for f in &after {
if let Some(t) = self.item_mut(*f).and_then(Item::text_frame_mut) {
t.story = fs;
diff --cc crates/engine/src/cmd/edit.rs
index 43e9e4f90,0885d1554..c6779e3d4
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@@ -172,22 -166,21 +172,25 @@@ pub fn specs() -> Vec<CommandSpec>
let st = s.doc_mut()?;
let e = st.history.undo.pop().ok_or_else(|| super::bad("edit.undo", "nothing to undo"))?;
st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
- st.doc = e.doc;
+ let mut doc = e.doc;
+ super::rulers::keep_zero_point(&st.doc, &mut doc);
+ st.doc = doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
+ // Pending typing overrides belong to the current edit state, not a restored snapshot.
+ s.typing_format = None;
Ok(json!({"undone": e.label}))
}),
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| {
let st = s.doc_mut()?;
let e = st.history.redo.pop().ok_or_else(|| super::bad("edit.redo", "nothing to redo"))?;
st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
- st.doc = e.doc;
+ let mut doc = e.doc;
+ super::rulers::keep_zero_point(&st.doc, &mut doc);
+ st.doc = doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
+ s.typing_format = None;
Ok(json!({"redone": e.label}))
}),
cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| {
diff --cc crates/engine/src/cmd/style.rs
index 06f51edf7,0280612d1..0548b5daa
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -224,8 -180,8 +224,8 @@@ pub fn specs() -> Vec<CommandSpec>
"Apply Color",
[],
None,
- "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",
+ "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255)|{model: rgb|cmyk|gray, r,g,b|c,m,y,k|k}(0..1), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",
- |s| super::has_text(s).or_else(|_| super::has_selection(s)),
+ has_text_or_selection,
apply_color
),
cmd!(
@@@ -233,8 -189,8 +233,8 @@@
"Sample Color (Eyedropper)",
[],
None,
- "{at: [x,y] (spread coords), spread?, target?: fill|stroke, ids?} → {color: \"#rrggbb\", swatch, from: image id} — the Eyedropper on a placed image: the image's colour at the point (an unnamed colour) fills the selected text, else the selected objects",
+ "{at: [x,y] (spread coords), spread?, target?: fill|stroke, ids?, matchFrom?: id} → {color: \"#rrggbb\", swatch, from: image id} — the Eyedropper on a placed image: the image's colour at the point (an unnamed colour) fills the selected text, else the selected objects. With no opaque image pixel there, `matchFrom` gives the object whose attributes apply instead (object.matchAttributes)",
- |s| super::has_text(s).or_else(|_| super::has_selection(s)),
+ has_text_or_selection,
sample_color
),
cmd!(
@@@ -1450,6 -1011,47 +1406,58 @@@ fn apply_color(s: &mut Session, p: &Val
Ok(r)
}
-/// A process swatch holding exactly `color`, else a new unnamed one (hidden from the Swatches
-/// panel until Add to Swatches).
++/// A process swatch holding this colour to the precision its name shows (whole CMYK percents,
++/// 0-255 RGB), else a new unnamed one (hidden from the Swatches panel until Add to Swatches):
++/// values a fraction of a percent apart would otherwise add hidden "C=0 M=50 Y=100 K=0 2" twins.
+ fn color_swatch(d: &mut designcraft_doc::Document, color: designcraft_color::Color) -> String {
++ let shown = value_name(color);
++ let process = |w: &&Swatch| match &w.value {
++ SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } => Some(*c),
++ _ => None,
++ };
+ let existing = d
+ .swatches
+ .iter()
- .find(|w| matches!(&w.value, SwatchValue::Color { color: c, color_type: designcraft_color::ColorType::Process } if *c == color))
++ .find(|w| process(w) == Some(color))
++ .or_else(|| {
++ d.swatches
++ .iter()
++ .find(|w| process(w).is_some_and(|c| std::mem::discriminant(&c) == std::mem::discriminant(&color) && value_name(c) == shown))
++ })
+ .map(|w| w.name.clone());
+ if let Some(n) = existing {
+ return n;
+ }
- let name = Styles::unique_name(|n| d.swatch(n).is_some(), &value_name(color));
++ let name = Styles::unique_name(|n| d.swatch(n).is_some(), &shown);
+ d.swatches.push(Swatch {
+ name: name.clone(),
+ value: SwatchValue::Color { color, color_type: designcraft_color::ColorType::Process },
+ locked: false,
+ named: false,
+ hidden: true,
+ });
+ name
+ }
+
+ fn color_items(d: &mut designcraft_doc::Document, ids: &[designcraft_doc::ItemId], name: &str, stroke: bool) {
+ for id in ids {
+ if let Some(it) = d.item_mut(*id) {
+ if stroke {
+ it.stroke.swatch = name.to_string();
+ it.stroke.tint = 1.0;
+ } else {
+ it.fill.swatch = name.to_string();
+ it.fill.tint = 1.0;
+ }
+ }
+ }
+ }
+
+ fn has_text_or_selection(s: &Session) -> std::result::Result<(), String> {
+ has_doc(s)?;
+ if s.active().is_some_and(|d| d.selection.text.is_some() || d.selection.cells.is_some()) { Ok(()) } else { super::has_selection(s) }
+ }
+
/// The Eyedropper on a placed image (InDesign samples the pixel under the pointer): that colour,
/// as an unnamed colour, fills the selected text (characters), or the selected objects.
fn sample_color(s: &mut Session, p: &Value) -> Result<Value> {
@@@ -1568,150 -1148,112 +1576,158 @@@ fn add_to_swatches(s: &mut Session, p:
let w = d.swatches.iter_mut().find(|w| w.name == name).ok_or_else(|| bad("swatch.addToSwatches", format!("no swatch `{name}`")))?;
w.name = new.clone();
w.named = true;
- for g in &mut d.color_groups {
- for w in &mut g.swatches {
- if *w == name {
- *w = new.clone();
+ d.rename_swatch_refs(&name, &new);
+ Ok(json!({"name": new}))
- })
++ })?;
++ if let Some(new) = result.get("name").and_then(Value::as_str) {
++ super::text::rename_typing_swatch(s, &name, new);
++ }
++ Ok(result)
+}
+
+/// Swatch Options: rename, Name with Color Value, colour type and value, a tint swatch's tint
+/// and base — one undo step. Every use of the swatch follows a rename.
+fn swatch_options(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "swatch.options";
+ let name = str_param(p, "name").ok_or_else(|| bad(ID, "missing name"))?.to_string();
+ let to = str_param(p, "to").map(|n| n.trim().to_string());
+ let with_value = p.get("nameWithValue").and_then(Value::as_bool);
+ let color = match p.get("color") {
+ Some(c) => Some(parse_color(c).ok_or_else(|| bad(ID, "bad color"))?),
+ None => None,
+ };
+ let spot = p.get("spot").and_then(Value::as_bool);
+ let tint = match p.get("tint") {
+ Some(v) => Some(v.as_f64().filter(|t| t.is_finite() && (0.0..=1.0).contains(t)).ok_or_else(|| bad(ID, "tint is 0–1"))? as f32),
+ None => None,
+ };
+ let base = str_param(p, "base").map(str::to_string);
- s.edit(|d, _| {
++ let result = s.edit(|d, _| {
+ let w = d.swatch(&name).cloned().ok_or_else(|| bad(ID, format!("no swatch `{name}`")))?;
+ let mut w2 = w.clone();
+ if w.locked {
+ if to.as_ref().is_some_and(|t| *t != name) || with_value == Some(true) {
+ return Err(bad(ID, format!("`{name}` can't be renamed")));
+ }
+ match (&mut w2.value, color) {
+ (_, None) => {}
+ (SwatchValue::Paper { color: c }, Some(new)) => *c = new,
+ _ => return Err(bad(ID, format!("`{name}` can't be edited"))),
+ }
+ if spot.is_some() || tint.is_some() || base.is_some() {
+ return Err(bad(ID, format!("`{name}` can't be edited")));
+ }
+ } else {
+ match &mut w2.value {
+ SwatchValue::Color { color: c, color_type } => {
+ if let Some(new) = color {
+ *c = new;
+ }
+ if let Some(sp) = spot {
+ *color_type = if sp { designcraft_color::ColorType::Spot } else { designcraft_color::ColorType::Process };
+ }
+ if tint.is_some() || base.is_some() {
+ return Err(bad(ID, "only tint swatches have a tint"));
+ }
+ }
+ SwatchValue::Tint { base: b, tint: t } => {
+ if color.is_some() || spot.is_some() {
+ return Err(bad(ID, "a tint swatch takes its colour from its base"));
+ }
+ if let Some(v) = tint {
+ *t = v;
+ }
+ if let Some(nb) = &base {
+ if !d.swatch(nb).is_some_and(|x| matches!(x.value, SwatchValue::Color { .. })) || *nb == name {
+ return Err(bad(ID, format!("`{nb}` isn't a colour swatch")));
+ }
+ *b = nb.clone();
+ }
+ }
+ _ => {
+ if color.is_some() || spot.is_some() || tint.is_some() || base.is_some() {
+ return Err(bad(ID, format!("`{name}` only takes a name here")));
+ }
}
}
- }
- // Everything using the colour follows the rename.
- for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {
- let sp = std::sync::Arc::make_mut(sp);
- for top in &mut sp.items {
- rename_in(std::sync::Arc::make_mut(top), &name, &new);
+ // Name with Color Value: the name is the colour's values and tracks later edits.
+ let auto = with_value.unwrap_or(!w.named && to.as_ref().is_none_or(|t| *t == name));
+ let derived = match (&w2.value, auto) {
+ (SwatchValue::Color { color, .. }, true) => Some(value_name(*color)),
+ _ => None,
+ };
+ match derived {
+ Some(n) => {
+ w2.name = n;
+ w2.named = false;
+ }
+ None => {
+ if let Some(t) = &to {
+ if t.is_empty() {
+ return Err(bad(ID, "a swatch needs a name"));
+ }
+ w2.name = t.clone();
+ }
+ if with_value == Some(false) || w2.name != name {
+ w2.named = true;
+ }
+ }
}
- }
- for st in d.stories.values_mut() {
- let mut copy = (**st).clone();
- if rename_in_story(&mut copy, &name, &new, 0)? {
- *st = std::sync::Arc::new(copy);
+ if w2.name != name && d.swatch(&w2.name).is_some() {
+ return Err(bad(ID, format!("a swatch named `{}` exists", w2.name)));
}
}
+ let new = w2.name.clone();
+ let slot = d.swatches.iter_mut().find(|x| x.name == name).ok_or_else(|| bad(ID, format!("no swatch `{name}`")))?;
+ *slot = w2;
+ d.rename_swatch_refs(&name, &new);
Ok(json!({"name": new}))
- })
+ })?;
+ if let Some(new) = result.get("name").and_then(Value::as_str) {
+ super::text::rename_typing_swatch(s, &name, new);
+ }
+ Ok(result)
}
-/// Point text colours (character fill, stroke, underline and strikethrough; paragraph shading,
-/// border and rules; table cells, borders and alternating fills) at a renamed swatch, in a story
-/// and the texts inside it (table cells, footnotes, endnotes). Returns whether anything changed.
-fn rename_in_story(st: &mut designcraft_doc::Story, from: &str, to: &str, depth: usize) -> Result<bool> {
- // Refuse the whole edit instead of leaving deeper references pointing at a removed name.
- if depth > 32 {
- return Err(bad("swatch.addToSwatches", "story nesting exceeds 32 levels"));
- }
- fn fix(s: &mut String, from: &str, to: &str) -> bool {
- let hit = s == from;
- if hit {
- *s = to.to_string();
- }
- hit
- }
- let mut n = 0;
- let mut f = |s: &mut String| n += usize::from(fix(s, from, to));
- for r in &mut st.chars {
- let o = &mut r.format.over;
- for c in [&mut o.fill, &mut o.stroke, &mut o.underline_color, &mut o.strikethrough_color].into_iter().flatten() {
- f(c);
- }
- }
- for pf in &mut st.paras {
- let a = &mut pf.para;
- for c in [&mut a.shading_color, &mut a.border_color].into_iter().flatten() {
- f(c);
- }
- for r in [&mut a.rule_above, &mut a.rule_below].into_iter().flatten() {
- f(&mut r.color);
- }
- }
- let mut nested = false;
- for t in st.tables.values_mut() {
- let t = std::sync::Arc::make_mut(t);
- let o = &mut t.options;
- f(&mut o.border.color);
- for b in o.borders.iter_mut().flatten() {
- f(&mut b.color);
- }
- for a in [&mut o.alt_rows, &mut o.alt_cols].into_iter().flatten() {
- f(&mut a.first_color);
- f(&mut a.next_color);
- }
- for k in [&mut o.row_strokes, &mut o.column_strokes].into_iter().flatten() {
- f(&mut k.first_stroke.color);
- f(&mut k.next_stroke.color);
- }
- for c in &mut t.cells {
- f(&mut c.fill);
- for k in &mut c.strokes {
- f(&mut k.color);
- }
- nested |= rename_in_story(&mut c.text, from, to, depth + 1)?;
- }
- }
- for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {
- nested |= rename_in_story(&mut std::sync::Arc::make_mut(note).text, from, to, depth + 1)?;
- }
- let changed = n > 0 || nested;
- if changed {
- st.rev = st.rev.wrapping_add(1);
- }
- Ok(changed)
-}
+/// #777: the params descriptions name the attributes, and a wrong one is the command's error.
+#[cfg(test)]
+mod attribute_error_tests {
+ use super::*;
+ use crate::cmd::find_command;
-/// Point fills and strokes of an item (and its children) at a renamed swatch.
-fn rename_in(it: &mut designcraft_doc::Item, from: &str, to: &str) {
- if it.fill.swatch == from {
- it.fill.swatch = to.to_string();
- }
- if it.stroke.swatch == from {
- it.stroke.swatch = to.to_string();
- }
- if let Some(kids) = it.children_mut() {
- for k in kids {
- rename_in(std::sync::Arc::make_mut(k), from, to);
+ #[test]
+ fn a_wrong_attribute_names_the_command_and_the_right_attribute() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let err = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_err().to_string();
+ assert_eq!(
+ err(&mut s, "style.paragraph.create", json!({"name": "H", "chars": {"font": "Source Sans 3"}})),
+ "invalid parameters for `style.paragraph.create`: chars: unknown attribute `font`; did you mean `fontFamily`?"
+ );
+ assert_eq!(
+ err(&mut s, "style.paragraph.create", json!({"name": "H", "para": {"spaceBefor": 6}})),
+ "invalid parameters for `style.paragraph.create`: para: unknown attribute `spaceBefor`; did you mean `spaceBefore`?"
+ );
+ assert!(
+ err(&mut s, "style.character.create", json!({"name": "C", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.character.create`: chars:")
+ );
+ assert!(err(&mut s, "style.paragraph.create", json!({"name": "H", "chars": "bold"})).contains("chars must be an object of attributes"));
+ s.execute("style.paragraph.create", &json!({"name": "H", "chars": {"fontFamily": "Source Sans 3", "size": 14}})).unwrap();
+ assert!(
+ err(&mut s, "style.paragraph.edit", json!({"name": "H", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.paragraph.edit`: chars:")
+ );
+ s.execute("style.character.create", &json!({"name": "C", "chars": {"fontStyle": "Bold"}})).unwrap();
+ assert!(
+ err(&mut s, "style.character.edit", json!({"name": "C", "chars": {"font": "X"}}))
+ .starts_with("invalid parameters for `style.character.edit`: chars:")
+ );
+ for id in ["style.paragraph.create", "style.paragraph.edit", "style.character.create", "style.character.edit"] {
+ let doc = find_command(id).unwrap().params;
+ assert!(doc.contains("as type.char names them: fontFamily"), "{id}: {doc}");
}
+ assert!(find_command("style.paragraph.create").unwrap().params.contains("as type.para names them: align"));
}
}
@@@ -2737,12 -1806,9 +2753,14 @@@ mod sample_color_tests
let fid = ItemId(f["id"].as_u64().unwrap());
let story = s.doc().unwrap().doc.item(fid).unwrap().text_frame().unwrap().story;
s.execute("text.select", &json!({"story": story.0, "anchor": 1, "focus": 1})).unwrap();
- let sampled = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap();
- assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], sampled["swatch"]);
+ // A caret: the sampled colour is for the next typing.
+ let r = s.execute("color.sample", &json!({"at": [100, 100]})).unwrap();
++ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fill"], r["swatch"]);
+ assert_eq!(s.doc().unwrap().doc.story(story).unwrap().text, "Hi", "caret color waits for typing");
+ s.execute("text.insert", &json!({"text": "X"})).unwrap();
+ let st = s.doc().unwrap().doc.story(story).unwrap().clone();
+ assert_eq!(st.format_after(1).over.fill.as_deref(), r["swatch"].as_str(), "{r}");
+ assert_eq!(st.format_after(0).over.fill, None, "the text before the caret keeps its colour");
let undo = s.doc().unwrap().history.undo.len();
s.execute("text.select", &json!({"story": story.0, "anchor": 0, "focus": 2})).unwrap();
let none = s.execute("color.sample", &json!({"at": [600, 600]})).unwrap_err().to_string();
@@@ -2814,218 -1843,8 +2832,222 @@@
assert_eq!(text.format_after(0).over.stroke.as_deref(), r["swatch"].as_str(), "selected text stroke: {command}");
}
}
+
+ #[test]
+ fn sampling_with_the_stroke_in_front_colours_a_lines_stroke() {
+ let (mut s, _) = session_with_image();
+ let line = s.execute("line.create", &json!({"a": [300, 300], "b": [500, 300]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("selection.set", &json!({"ids": [line]})).unwrap();
+ let r = s.execute("color.sample", &json!({"at": [100, 100], "target": "stroke"})).unwrap();
+ let it = s.doc().unwrap().doc.item(ItemId(line)).unwrap().clone();
+ assert_eq!(it.stroke.swatch, r["swatch"].as_str().unwrap(), "{r}");
+ assert!(it.fill.is_none(), "the fill stays empty");
+ }
+}
+
+#[cfg(test)]
+mod radial_gradient_tests {
+ use serde_json::json;
+
+ /// White at the side and the top of a 100×200 radial (black → white) rectangle at (50, 20) on
+ /// a 200×240 page, rendered at 1 px/pt.
+ fn sides(img: &designcraft_render::Rendered) -> (u8, u8, u8) {
+ (img.pixel(100, 120)[0], img.pixel(52, 120)[0], img.pixel(100, 22)[0])
+ }
+
+ #[test]
+ fn a_radial_gradient_is_the_objects_ellipse_on_screen_and_in_pdf() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"width": 200, "height": 240, "facingPages": false})).unwrap();
+ let id = s.execute("frame.create", &json!({"rect": [50, 20, 150, 220], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
+ s.execute("object.stroke", &json!({"ids": [id], "swatch": "[None]"})).unwrap();
+ s.execute(
+ "object.gradient",
+ &json!({"ids": [id], "kind": "radial", "stops": [{"location": 0, "color": "#000000"}, {"location": 100, "color": "#ffffff"}]}),
+ )
+ .unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let mut r = designcraft_render::Renderer::new();
+ let (c, side, top) = sides(&r.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap());
+ assert!(c < 30 && side > 220 && top > 220, "screen: centre {c}, side {side}, top {top}");
+ // The PDF, placed back and drawn: the same ellipse.
+ let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
+ let mut p = crate::Session::new();
+ p.execute("file.new", &json!({"width": 200, "height": 240, "facingPages": false})).unwrap();
+ p.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&pdf), "name": "radial.pdf", "x": 0, "y": 0, "width": 200}))
+ .unwrap();
+ let d = p.doc().unwrap().doc.clone();
+ let (c, side, top) = sides(&r.render_page(&d, &p.cache, 0, 1.0, false, &Default::default()).unwrap());
+ assert!(c < 30 && side > 220 && top > 220, "pdf: centre {c}, side {side}, top {top}");
+ }
+}
+
+#[cfg(test)]
+mod gradient_swatch_tests {
+ use designcraft_color::SwatchValue;
+ use serde_json::json;
+
+ fn doc() -> crate::Session {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s
+ }
+
+ #[test]
+ fn a_gradient_swatch_from_colour_swatches() {
+ let mut s = doc();
+ // As the Gradient panel's stops take swatches dragged onto them.
+ let r = s
+ .execute(
+ "swatch.create",
+ &json!({"gradient": {"stops": [{"location": 100, "swatch": "C=100 M=0 Y=0 K=0"}, {"location": 0, "swatch": "C=0 M=100 Y=0 K=0"}]}}),
+ )
+ .unwrap();
+ assert_eq!(r["name"], "New Gradient Swatch");
+ let d = &s.doc().unwrap().doc;
+ let w = d.swatch("New Gradient Swatch").unwrap();
+ assert!(w.named && !w.hidden);
+ let SwatchValue::Gradient { gradient } = &w.value else { panic!("{w:?}") };
+ assert_eq!(gradient.stops[0].color, d.resolve_color("C=0 M=100 Y=0 K=0", 1.0).unwrap(), "sorted: magenta first");
+ assert_eq!(gradient.stops[1].color, d.resolve_color("C=100 M=0 Y=0 K=0", 1.0).unwrap());
+ // A second one gets its own name; bad stops are refused.
+ let r = s
+ .execute(
+ "swatch.create",
+ &json!({"gradient": {"kind": "radial", "stops": [{"color": "#ff0000"}, {"location": 100, "color": "#0000ff"}]}}),
+ )
+ .unwrap();
+ assert_eq!(r["name"], "New Gradient Swatch 2");
+ for bad in [
+ json!({"stops": [{"swatch": "C=0 M=100 Y=0 K=0"}]}),
+ json!({"stops": [{"swatch": "Nope"}, {"swatch": "[Black]"}]}),
+ json!({"stops": [{"swatch": "New Gradient Swatch"}, {"swatch": "[Black]"}]}),
+ json!({"kind": "conic", "stops": [{"color": "#000000"}, {"color": "#ffffff"}]}),
+ ] {
+ assert!(s.execute("swatch.create", &json!({"gradient": bad})).is_err(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn new_swatch_names_the_selections_gradient_or_duplicates_a_swatch() {
+ let mut s = doc();
+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();
+ // A gradient made in the Gradient panel is unnamed (and not listed) …
+ s.execute("object.gradient", &json!({"ids": [id], "stops": [{"location": 0, "color": {"c": 0, "m": 100, "y": 0, "k": 0}}, {"location": 100, "color": {"c": 100, "m": 0, "y": 0, "k": 0}}]})).unwrap();
+ let fill = |s: &crate::Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch.clone();
+ assert!(s.doc().unwrap().doc.swatch(&fill(&s)).unwrap().hidden);
+ // … until New Swatch: "New Gradient Swatch", listed, still the object's fill.
+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();
+ assert_eq!(s.execute("swatch.new", &json!({})).unwrap()["name"], "New Gradient Swatch");
+ assert_eq!(fill(&s), "New Gradient Swatch");
+ let w = s.doc().unwrap().doc.swatch("New Gradient Swatch").unwrap().clone();
+ assert!(w.named && !w.hidden && matches!(w.value, SwatchValue::Gradient { .. }));
+ // A named swatch: a copy.
+ assert_eq!(s.execute("swatch.new", &json!({})).unwrap()["name"], "New Gradient Swatch copy");
+ assert_eq!(s.execute("swatch.new", &json!({"swatch": "C=100 M=0 Y=0 K=0"})).unwrap()["name"], "C=100 M=0 Y=0 K=0 copy");
+ assert!(s.execute("swatch.new", &json!({"swatch": "[None]"})).is_err());
+ // The stroke in front: the stroke's swatch.
+ s.execute("object.stroke", &json!({"ids": [id], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();
+ assert_eq!(s.execute("swatch.new", &json!({"target": "stroke"})).unwrap()["name"], "C=100 M=0 Y=0 K=0 copy 2");
+ // Nothing selected, no swatch given: a new colour swatch.
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ let n = s.execute("swatch.new", &json!({})).unwrap()["name"].as_str().unwrap().to_string();
+ let w = s.doc().unwrap().doc.swatch(&n).unwrap();
+ assert!(w.named && !w.hidden && matches!(w.value, SwatchValue::Color { .. }), "{w:?}");
+ }
+}
+
+#[cfg(test)]
+mod gradient_stroke_tests {
+ use serde_json::json;
+
+ /// Grey along a 20 pt line from (20, 60) to (180, 60): near its start, middle and end.
+ fn along(img: &designcraft_render::Rendered) -> (u8, u8, u8) {
+ (img.pixel(26, 60)[0], img.pixel(100, 60)[0], img.pixel(174, 60)[0])
+ }
+
+ #[test]
+ fn a_gradient_on_a_stroke_runs_across_the_path_on_screen_and_in_pdf() {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"width": 200, "height": 120, "facingPages": false})).unwrap();
+ let id = s.execute("line.create", &json!({"a": [20, 60], "b": [180, 60]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("object.stroke", &json!({"ids": [id], "weight": 20})).unwrap();
+ let r = s
+ .execute(
+ "object.gradient",
+ &json!({"ids": [id], "target": "stroke", "stops": [{"location": 0, "color": "#000000"}, {"location": 100, "color": "#ffffff"}]}),
+ )
+ .unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let it = d.item(designcraft_doc::ItemId(id)).unwrap();
+ assert_eq!(it.stroke.swatch, r["swatch"].as_str().unwrap());
+ assert_eq!(it.fill.swatch, designcraft_color::swatch::NONE, "the fill is left alone");
+ let mut rr = designcraft_render::Renderer::new();
+ let (a, m, b) = along(&rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap());
+ assert!(a < 40 && (90..170).contains(&m) && b > 215, "screen: {a} {m} {b}");
+ // The PDF, placed back and drawn: the same.
+ let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
+ let mut p = crate::Session::new();
+ p.execute("file.new", &json!({"width": 200, "height": 120, "facingPages": false})).unwrap();
+ p.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&pdf), "name": "stroke.pdf", "x": 0, "y": 0, "width": 200}))
+ .unwrap();
+ let pd = p.doc().unwrap().doc.clone();
+ let (a, m, b) = along(&rr.render_page(&pd, &p.cache, 0, 1.0, false, &Default::default()).unwrap());
+ assert!(a < 40 && (90..170).contains(&m) && b > 215, "pdf: {a} {m} {b}");
+ // The Gradient Swatch tool's drag on the stroke: reversed by dragging right to left.
+ s.execute("object.gradient", &json!({"ids": [id], "target": "stroke", "from": [180, 60], "to": [20, 60]})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let (a, _, b) = along(&rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap());
+ assert!(a > 215 && b < 40, "dragged: {a} {b}");
+ assert!(s.execute("object.gradient", &json!({"ids": [id], "target": "gap"})).is_err());
+ }
+
+ /// A 20 pt horizontal line with a gradient on its stroke, drawn on screen and from its PDF.
+ fn line_with_stroke_gradient(g: serde_json::Value) -> (designcraft_render::Rendered, designcraft_render::Rendered) {
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({"width": 200, "height": 120, "facingPages": false})).unwrap();
+ let id = s.execute("line.create", &json!({"a": [20, 60], "b": [180, 60]})).unwrap()["id"].as_u64().unwrap();
+ s.execute("object.stroke", &json!({"ids": [id], "weight": 20})).unwrap();
+ let mut g = g;
+ g["ids"] = json!([id]);
+ g["target"] = json!("stroke");
+ s.execute("object.gradient", &g).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let mut rr = designcraft_render::Renderer::new();
+ let screen = rr.render_page(&d, &s.cache, 0, 1.0, false, &Default::default()).unwrap();
+ let pdf = designcraft_pdf::export_pdf(&d, &s.cache, &Default::default()).unwrap();
+ let mut p = crate::Session::new();
+ p.execute("file.new", &json!({"width": 200, "height": 120, "facingPages": false})).unwrap();
+ p.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&pdf), "name": "line.pdf", "x": 0, "y": 0, "width": 200})).unwrap();
+ let pd = p.doc().unwrap().doc.clone();
+ let placed = rr.render_page(&pd, &p.cache, 0, 1.0, false, &Default::default()).unwrap();
+ (screen, placed)
+ }
+
+ #[test]
+ fn a_radial_gradient_on_a_straight_lines_stroke_shows_all_its_stops() {
+ // The line's box has no height: the gradient is a circle across the line's length.
+ let (screen, pdf) = line_with_stroke_gradient(
+ json!({"kind": "radial", "stops": [{"location": 0, "color": "#000000"}, {"location": 100, "color": "#ffffff"}]}),
+ );
+ for (what, img) in [("screen", &screen), ("pdf", &pdf)] {
+ let (a, m, b) = along(img);
+ assert!(m < 40 && a > 180 && b > 180, "{what}: {a} {m} {b}");
+ }
+ }
+
+ #[test]
+ fn a_linear_gradient_across_a_straight_line_paints_its_stroke_alike_on_screen_and_in_pdf() {
+ let (screen, pdf) =
+ line_with_stroke_gradient(json!({"angle": 90, "stops": [{"location": 0, "color": "#ff0000"}, {"location": 100, "color": "#0000ff"}]}));
+ let (s, p) = (screen.pixel(100, 60), pdf.pixel(100, 60));
+ // The line's box has no height: the gradient runs across the line's length, so the stroke
+ // shows its middle.
+ assert!(s[1] < 60 && s[0] > 80 && s[2] > 80, "screen: the stroke is painted, {s:?}");
+ assert!((0..3).all(|i| s[i].abs_diff(p[i]) < 40), "screen {s:?}, pdf {p:?}");
+ }
}
+
+ #[cfg(test)]
+ #[path = "text_color_tests.rs"]
+ mod text_color_tests;
diff --cc crates/engine/src/cmd/text.rs
index ef808fbef,e928ce472..ea8d60ffb
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@@ -34,15 -34,24 +34,15 @@@ pub fn specs() -> Vec<CommandSpec>
has_doc,
|s, p| select_at(s, p, str_param(p, "unit").unwrap_or("word"))
),
- cmd!(noundo "text.selectSentence", "Select Sentence", [], None, "{frame, point} — the sentence under the point", has_doc, |s, p| {
- select_around(s, p, "text.selectSentence", sentence_bounds)
- }),
- cmd!(noundo "text.selectParagraph", "Select Paragraph", [], None, "{frame, point} — the paragraph under the point, without its paragraph return", has_doc, |s, p| {
- select_around(s, p, "text.selectParagraph", para_bounds)
- }),
- cmd!(noundo "text.selectStory", "Select Story", [], None, "{frame, point} — all the text of the story under the point, threaded frames included", has_doc, |s, p| {
- select_around(s, p, "text.selectStory", |t, _| (0, t.len()))
- }),
cmd!(noundo "text.select", "Select Text", [], None, "{story, anchor, focus} (UTF-8 byte offsets into the story text, as find.find reports them: á or — counts 2 or 3)", has_doc, |s, p| {
let sid = StoryId(p.get("story").and_then(Value::as_u64).unwrap_or(0));
- s.typing_format = None;
let st = s.doc_mut()?;
let text = &st.doc.story(sid).ok_or_else(|| bad("text.select", "no such story"))?.text;
let a = floor_char_boundary(text, p.get("anchor").and_then(Value::as_u64).unwrap_or(0) as usize);
let f = floor_char_boundary(text, p.get("focus").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(a));
st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: f, frame: None, cell: None });
- st.revision += 1;
+ st.bump_revision();
+ s.typing_format = None;
ok()
}),
cmd!("text.insert", "Type", [], None, "{text, raw?: bool (no typographer's quotes)} — replaces the selected text", has_text, insert),
@@@ -630,7 -581,11 +635,12 @@@ fn insert(s: &mut Session, p: &Value) -
let pos = r.start + text.len() - trail;
sel.text = Some(TextSel { anchor: pos, focus: pos, ..t });
Ok(json!({"pos": pos}))
- })
+ });
- if result.is_ok() {
++ // A preview (IME marked text) leaves the typing format to the text typed in the end.
++ if result.is_ok() && s.active().is_none_or(|d| d.interaction.is_none()) {
+ s.typing_format = None;
+ }
+ result
}
fn smart_quotes(s: &Session, text: &str) -> String {
@@@ -1554,45 -1211,115 +1564,139 @@@ fn selection_attrs(s: &mut Session, p:
let pi = story.para_at(r.start);
let pf = &story.paras[pi];
let (pp, base) = st.doc.styles.resolve_para(pf);
- let mut cf = if r.is_empty() { story.char_format_at(r.start) } else { story.format_after(r.start) }.clone();
- if let Some(f) = typing_format(s) {
- apply_typing_format(&mut cf, f);
- }
+ let cf = effective_char_format(s, &Target { story: sid, cell, range: r.clone() })?;
let cp = st.doc.styles.resolve_char(&base, &cf);
+ // The selected text (its start, on one line), for previews such as the font menu's.
let selected = selected_text_preview(story.text.get(r.start..r.end).unwrap_or_default().chars());
- Ok(json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,
- "paraOverrides": pf.para.count(), "charOverrides": cf.over.count(), "selectedText": selected.trim()}))
+ let mut out = json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,
+ "paraOverrides": pf.para.count(), "charOverrides": cf.over.count(), "selectedText": selected.trim()});
+ if bool_or(p, "mixed", false) {
+ out["paraMixed"] = json!(mixed_para_attrs(&st.doc, &targets));
+ }
+ Ok(out)
+}
+
+/// The paragraph attributes whose resolved values differ across the paragraphs of `targets`.
+fn mixed_para_attrs(doc: &designcraft_doc::Document, targets: &[Target]) -> Vec<String> {
+ let mut first: Option<serde_json::Map<String, Value>> = None;
+ let mut mixed = std::collections::BTreeSet::new();
+ for t in targets {
+ let Some(story) = doc.text_story(t.story, t.cell) else { continue };
+ let a = story.para_at(t.range.start);
+ let b = story.para_at(t.range.end.max(t.range.start));
+ for pf in story.paras.get(a..=b).unwrap_or(&[]) {
+ let Ok(Value::Object(v)) = serde_json::to_value(doc.styles.resolve_para(pf).0) else { continue };
+ match &first {
+ None => first = Some(v),
+ Some(f) => mixed.extend(v.into_iter().filter(|(k, x)| f.get(k) != Some(x)).map(|(k, _)| k)),
+ }
+ }
+ }
+ mixed.into_iter().collect()
}
- /// `cf` with the typing format chosen at the active document's caret, if any.
- pub(crate) fn with_typing_format(s: &Session, cf: &mut designcraft_doc::CharFormat) {
- if let Some(f) = typing_format(s) {
- apply_typing_format(cf, f);
+ /// The first target character, with any pending caret overrides. Keep character-style
+ /// inheritance separate from paragraph defaults for style creation from the selection.
+ pub(crate) fn effective_char_format(s: &Session, target: &Target) -> Result<designcraft_doc::CharFormat> {
+ let story = s.doc()?.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;
+ let mut format = if target.range.is_empty() { story.char_format_at(target.range.start) } else { story.format_after(target.range.start) }.clone();
+ if let Some(pending) = typing_format(s)
+ && target.story == pending.at.story
+ && target.cell == pending.at.cell
+ && target.range == pending.at.range()
+ {
+ apply_typing_format(&mut format, pending);
+ }
+ Ok(format)
+ }
+
+ /// A swatch promoted to a named color keeps any not-yet-inserted text pointing at it.
+ pub(crate) fn rename_typing_swatch(s: &mut Session, from: &str, to: &str) {
+ let Some(uid) = s.active().map(|st| st.uid) else { return };
+ if let Some(pending) = &mut s.typing_format
+ && pending.doc == uid
+ {
+ for name in [&mut pending.attrs.fill, &mut pending.attrs.stroke, &mut pending.attrs.underline_color, &mut pending.attrs.strikethrough_color]
+ .into_iter()
+ .flatten()
+ {
+ if name == from {
+ *name = to.to_string();
+ }
+ }
+ }
+ }
+
+ fn swapped_colors(cp: &designcraft_doc::CharProps) -> CharAttrs {
+ CharAttrs {
+ fill: Some(cp.stroke.clone()),
+ fill_tint: Some(cp.stroke_tint),
+ stroke: Some(cp.fill.clone()),
+ stroke_tint: Some(cp.fill_tint),
+ ..Default::default()
+ }
+ }
+
+ /// Resolve each paragraph/run before editing: a mixed selection must not take the first run's colors.
+ fn swap_fill_stroke(s: &mut Session, _p: &Value) -> Result<Value> {
+ const ID: &str = "type.swapFillStroke";
+ let targets = format_targets(s);
+ if let [target] = targets.as_slice()
+ && target.range.is_empty()
+ && s.doc()?.selection.text.is_some()
+ {
+ let st = s.doc()?;
+ let story = st.doc.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;
+ let pf = story.paras.get(story.para_at(target.range.start)).ok_or_else(|| bad(ID, "missing paragraph"))?;
+ let (_, base) = st.doc.styles.resolve_para(pf);
+ let cp = st.doc.styles.resolve_char(&base, &effective_char_format(s, target)?);
+ return format_chars(s, &json!({"fill": cp.stroke, "fillTint": cp.stroke_tint, "stroke": cp.fill, "strokeTint": cp.fill_tint}));
+ }
+ let mut edits = Vec::new();
+ let d = &s.doc()?.doc;
+ for target in targets {
+ let story = d.text_story(target.story, target.cell).ok_or(designcraft_doc::DocError::NoStory(target.story))?;
+ if story.is_empty() {
+ let pf = story.paras.first().ok_or_else(|| bad(ID, "missing paragraph"))?;
+ let (_, base) = d.styles.resolve_para(pf);
+ let attrs = swapped_colors(&d.styles.resolve_char(&base, story.char_format_at(0)));
+ validate_char_fill(d, &attrs, ID)?;
+ edits.push((target, attrs));
+ continue;
+ }
+ let mut runs = story.runs().peekable();
+ for (pi, para) in story.para_ranges().into_iter().enumerate() {
+ let start = para.start.max(target.range.start);
+ let end = para.end.saturating_add(1).min(story.len()).min(target.range.end);
+ if start >= end {
+ continue;
+ }
+ let pf = story.paras.get(pi).ok_or_else(|| bad(ID, "missing paragraph"))?;
+ let (_, base) = d.styles.resolve_para(pf);
+ while let Some((range, format)) = runs.peek() {
+ if range.end <= start {
+ runs.next();
+ continue;
+ }
+ if range.start >= end {
+ break;
+ }
+ let attrs = swapped_colors(&d.styles.resolve_char(&base, format));
+ validate_char_fill(d, &attrs, ID)?;
+ edits.push((Target { range: start.max(range.start)..end.min(range.end), ..target.clone() }, attrs));
+ if range.end > end {
+ break;
+ }
+ runs.next();
+ }
+ }
}
+ s.edit(|d, _| {
+ for (target, attrs) in &edits {
+ apply_char_attrs(d, std::slice::from_ref(target), attrs, &[]);
+ }
+ ok()
+ })
}
fn apply_typing_format(cf: &mut designcraft_doc::CharFormat, f: &TypingFormat) {
diff --cc crates/idml/src/import.rs
index 8e4e1f2bd,1a4fa65e3..a87c65f22
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2820,10 -2255,10 +2820,10 @@@ impl<'r> Importer<'r>
let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();
let mut options = text_frame_options(&prefs);
// `prefs` borrows the object styles, so the rule colour's swatch is resolved after it.
- if let Some(r) = Prefs(&prefs).get("ColumnRuleStrokeColor").map(str::to_string) {
+ if let Some(r) = Prefs(&prefs).prop("ColumnRuleStrokeColor") {
options.column_rule_color = self.swatch_ref(&r);
}
- if let Some(g) = e.find("BaselineFrameGridOption")
+ if let Some(g) = self.with_style(e, "BaselineFrameGridOption")
&& g.get("UseCustomBaselineFrameGrid") == Some("true")
{
options.baseline_grid =
@@@ -3290,23 -2577,11 +3290,23 @@@ fn ace_char(v: &str) -> Option<char>
}
}
+/// `HL Composer` and `HL Single`, their World-Ready (`… Optyca`) and Japanese (`… J`) forms.
+fn composer_in(name: &str) -> designcraft_doc::Composer {
+ use designcraft_doc::Composer as C;
+ let name = name.trim().trim_start_matches("$ID/");
+ match (name.contains("Single"), name.ends_with(" J") || name.contains("Japanese")) {
+ (false, false) => C::Paragraph,
+ (true, false) => C::SingleLine,
+ (false, true) => C::Japanese,
+ (true, true) => C::JapaneseSingleLine,
+ }
+}
+
fn margins_of(m: &El) -> (Margins, Columns) {
- let g = |k: &str, d: f64| m.num(k).unwrap_or(d);
+ let g = |k: &str, d: f64| m.num(k).filter(|v| v.is_finite()).unwrap_or(d);
(
Margins { top: g("Top", 36.0), bottom: g("Bottom", 36.0), inside: g("Left", 36.0), outside: g("Right", 36.0) },
- Columns { count: g("ColumnCount", 1.0).max(1.0) as u32, gutter: g("ColumnGutter", 12.0), positions: None },
+ Columns { count: g("ColumnCount", 1.0).clamp(1.0, 216.0) as u32, gutter: g("ColumnGutter", 12.0), positions: None },
)
}
@@@ -3350,21 -2625,15 +3350,21 @@@ fn text_frame_options(prefs: &[&El]) -
if let Some(v) = e.num("MinimumFirstBaselineOffset") {
o.first_baseline_min = v;
}
- o.ignore_wrap = e.get("IgnoreWrap") == Some("true");
- if let Some(v) = e.get("AutoSizingType") {
- o.auto_size = names::auto_size_in(v);
+ o.ignore_wrap = e.prop("IgnoreWrap").as_deref().map(str::trim) == Some("true");
+ if let Some(v) = e.prop("AutoSizingType") {
+ o.auto_size = names::auto_size_in(v.trim());
}
- if let Some(v) = e.get("AutoSizingReferencePoint") {
- o.auto_size_ref = names::REF_POINTS.iter().position(|p| *p == v).unwrap_or(1) as u8;
+ if let Some(v) = e.prop("AutoSizingReferencePoint") {
+ o.auto_size_ref = names::REF_POINTS.iter().position(|p| *p == v.trim()).unwrap_or(1) as u8;
}
+ let size = |k: &str| e.num(k).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 10_000.0));
- o.auto_size_use_min_height = e.get("UseMinimumHeightForAutoSizing") == Some("true");
++ o.auto_size_use_min_height = e.prop("UseMinimumHeightForAutoSizing").as_deref().map(str::trim) == Some("true");
+ o.auto_size_min_height = size("MinimumHeightForAutoSizing").unwrap_or(0.0);
- o.auto_size_use_min_width = e.get("UseMinimumWidthForAutoSizing") == Some("true");
++ o.auto_size_use_min_width = e.prop("UseMinimumWidthForAutoSizing").as_deref().map(str::trim) == Some("true");
+ o.auto_size_min_width = size("MinimumWidthForAutoSizing").unwrap_or(0.0);
- o.auto_size_no_line_breaks = e.get("UseNoLineBreaksForAutoSizing") == Some("true");
++ o.auto_size_no_line_breaks = e.prop("UseNoLineBreaksForAutoSizing").as_deref().map(str::trim) == Some("true");
// Column rules (the colour is a swatch reference: see `Importer::frame_options`).
- o.column_rule = e.get("ColumnRuleOverride") == Some("true");
+ o.column_rule = e.prop("ColumnRuleOverride").as_deref().map(str::trim) == Some("true");
let finite = |k: &str| e.num(k).filter(|v| v.is_finite());
if let Some(v) = finite("ColumnRuleStrokeWidth") {
o.column_rule_weight = v.clamp(0.0, 1000.0);
@@@ -3573,61 -2764,243 +3574,302 @@@ pub(crate) fn uri_to_path(uri: &str) -
percent_decode(rest)
}
+/// Auto tate-chu-yoko, Japanese composition and grid settings of a paragraph range or style.
+fn cjk_settings_para(e: &El, a: &mut ParaAttrs) {
+ let count = |k: &str| e.num(k).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1000.0) as u32);
+ a.auto_tcy = count("AutoTcy");
+ a.auto_tcy_include_roman = e.boolean("AutoTcyIncludeRoman");
+ a.rotate_roman = e.boolean("RotateSingleByteCharacters");
+ // 欧文泣き別れ: the name is inferred (it follows TreatIdeographicSpaceAsSpace).
+ a.roman_word_break = e.boolean("AllowArbitraryHyphenation");
+ a.grid_gyoudori = count("GridGyoudori");
+ a.paragraph_gyoudori = e.boolean("ParagraphGyoudori");
+}
+
+impl Importer<'_> {
+ /// Kenten Settings, Kenten Color and Shatai of a character range or style.
+ fn cjk_settings_chars(&mut self, e: &El, a: &mut CharAttrs) {
+ let finite = |k: &str| e.num(k).filter(|v| v.is_finite());
+ if let Some(kind) = e.get("KentenKind").and_then(crate::cjk::kenten_kind_in) {
+ a.kenten_kind = Some(kind);
+ if a.kenten_character.as_deref().is_none_or(str::is_empty)
+ && let Some(mark) = kind.mark()
+ {
+ a.kenten_character = Some(mark.to_string());
+ }
+ }
+ if let Some(f) = e.prop("KentenFont") {
+ let f = f.trim();
+ a.kenten_font = Some(if f == "$ID/" { String::new() } else { f.to_string() });
+ }
+ if let Some(st) = e.prop("KentenFontStyle") {
+ let st = st.trim();
+ a.kenten_font_style = Some(if st == "Nothing" { String::new() } else { st.to_string() });
+ }
+ a.kenten_size = finite("KentenFontSize").map(|v| (v > 0.0).then_some(v));
+ a.kenten_x_scale = finite("KentenXScale").map(|v| v / 100.0);
+ a.kenten_y_scale = finite("KentenYScale").map(|v| v / 100.0);
+ a.kenten_distance = finite("KentenPlacement");
+ a.kenten_position = e.prop("KentenPosition").and_then(|v| crate::cjk::kenten_position_in(&v));
+ a.kenten_alignment = e.prop("KentenAlignment").and_then(|v| crate::cjk::kenten_alignment_in(&v));
+ a.kenten_character_set = e.prop("KentenCharacterSet");
+ // "Text Color" is the text's own colour; it resets an inherited swatch.
+ if let Some(r) = e.prop("KentenFillColor") {
+ a.kenten_fill = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) });
+ }
+ if let Some(r) = e.prop("KentenStrokeColor") {
+ a.kenten_stroke = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) });
+ }
+ // Tints and weight: -1 is the text's.
+ a.kenten_fill_tint = finite("KentenTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32));
+ a.kenten_stroke_tint = finite("KentenStrokeTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32));
+ a.kenten_stroke_weight = finite("KentenWeight").map(|v| (v >= 0.0).then_some(v));
+ a.kenten_overprint_fill = e.prop("KentenOverprintFill").and_then(|v| crate::cjk::overprint_in(&v));
+ a.kenten_overprint_stroke = e.prop("KentenOverprintStroke").and_then(|v| crate::cjk::overprint_in(&v));
+ a.shatai_magnification = finite("ShataiMagnification");
+ a.shatai_angle = finite("ShataiDegreeAngle").map(|v| v / crate::cjk::SHATAI_ANGLE_UNITS);
+ a.shatai_adjust_rotation = e.boolean("ShataiAdjustRotation");
+ a.shatai_adjust_tsume = e.boolean("ShataiAdjustTsume");
+ }
+}
++
+ #[cfg(test)]
+ mod numeric_property_tests {
+ use super::*;
+
+ fn pref(attrs: &[(&str, &str)], props: &[(&str, &str)]) -> El {
+ let mut e = El::new("TextFramePreference");
+ for (key, value) in attrs {
+ e.set(key, *value);
+ }
+ let mut p = El::new("Properties");
+ for (key, value) in props {
+ p.push(El::new(key).text(*value));
+ }
+ e.push(p);
+ e
+ }
+
+ #[test]
+ fn numeric_property_forms_import_every_frame_option() {
+ let local = pref(
+ &[("UseFixedColumnWidth", "true")],
+ &[
+ ("TextColumnCount", "3"),
+ ("TextColumnGutter", "17"),
+ ("TextColumnFixedWidth", "123"),
+ ("VerticalThreshold", "19"),
+ ("MinimumFirstBaselineOffset", "8"),
+ ("ColumnRuleStrokeWidth", "2"),
+ ("ColumnRuleStrokeTint", "25"),
+ ("ColumnRuleOffset", "3"),
+ ("ColumnRuleTopInset", "4"),
+ ("ColumnRuleBottomInset", "5"),
+ ],
+ );
+ let o = text_frame_options(&[&local]);
+ assert_eq!((o.columns, o.gutter, o.column_width), (3, 17., 123.));
+ assert_eq!((o.vj_paragraph_spacing_limit, o.first_baseline_min), (19., 8.));
+ assert_eq!(
+ (o.column_rule_weight, o.column_rule_tint, o.column_rule_offset, o.column_rule_top_inset, o.column_rule_bottom_inset),
+ (2., 0.25, 3., 4., 5.)
+ );
+ }
+
+ #[test]
+ fn numeric_property_precedence_is_nearest_level_then_attribute() {
+ let local = pref(&[("TextColumnCount", "4")], &[("TextColumnCount", "5"), ("TextColumnGutter", "17")]);
+ let child = pref(
+ &[("TextColumnGutter", "90"), ("MinimumFirstBaselineOffset", "8")],
+ &[("MinimumFirstBaselineOffset", "9"), ("VerticalThreshold", "19")],
+ );
+ let base = pref(&[("VerticalThreshold", "99")], &[("ColumnRuleStrokeWidth", "2")]);
+ let o = text_frame_options(&[&local, &child, &base]);
+ assert_eq!((o.columns, o.gutter, o.first_baseline_min, o.vj_paragraph_spacing_limit, o.column_rule_weight), (4, 17., 8., 19., 2.));
+ // An explicit invalid value still masks inherited values, as attribute lookup did.
+ let invalid = pref(&[("TextColumnCount", "bad")], &[("TextColumnCount", "6")]);
+ assert_eq!(text_frame_options(&[&invalid, &local]).columns, TextFrameOptions::default().columns);
+ }
+ }
+
+ #[cfg(test)]
+ mod frame_preference_safety_tests {
+ use super::*;
+
+ fn pref(attrs: &[(&str, &str)], props: &[(&str, &str)]) -> El {
+ let mut e = El::new("TextFramePreference");
+ for (key, value) in attrs {
+ e.set(key, *value);
+ }
+ let mut p = El::new("Properties");
+ for (key, value) in props {
+ p.push(El::new(key).text(*value));
+ }
+ e.push(p);
+ e
+ }
+
+ #[test]
+ fn frame_preference_nonfinite_numbers_keep_finite_defaults() {
+ const KEYS: [&str; 10] = [
+ "TextColumnCount",
+ "TextColumnGutter",
+ "TextColumnFixedWidth",
+ "VerticalThreshold",
+ "MinimumFirstBaselineOffset",
+ "ColumnRuleStrokeWidth",
+ "ColumnRuleStrokeTint",
+ "ColumnRuleOffset",
+ "ColumnRuleTopInset",
+ "ColumnRuleBottomInset",
+ ];
+ let fallback = pref(&[("UseFixedColumnWidth", "true")], &[]);
+ let expected = text_frame_options(&[&fallback]);
+ for value in ["NaN", "inf", "-inf", "1e309"] {
+ for attribute in [true, false] {
+ let values: Vec<_> = KEYS.iter().map(|key| (*key, value)).collect();
+ let mut invalid = if attribute { pref(&values, &[]) } else { pref(&[], &values) };
+ invalid.set("UseFixedColumnWidth", "true");
+ let inherited = pref(&[], &[("TextColumnCount", "7"), ("TextColumnGutter", "9")]);
+ assert_eq!(text_frame_options(&[&invalid, &inherited]), expected, "{value}, attribute={attribute}");
+ }
+ }
+ }
+
+ #[test]
+ fn frame_preference_property_booleans_enums_and_precedence() {
+ let base = pref(
+ &[
+ ("UseFixedColumnWidth", "true"),
+ ("UseFlexibleColumnWidth", "false"),
+ ("VerticalBalanceColumns", "false"),
+ ("IgnoreWrap", "false"),
+ ("ColumnRuleOverride", "false"),
+ ("VerticalJustification", "TopAlign"),
+ ("FirstBaselineOffset", "AscentOffset"),
+ ("AutoSizingType", "Off"),
+ ("AutoSizingReferencePoint", "TopCenterPoint"),
+ ],
+ &[],
+ );
+ let local = pref(
+ &[],
+ &[
+ ("UseFixedColumnWidth", "false"),
+ ("UseFlexibleColumnWidth", "true"),
+ ("VerticalBalanceColumns", "true"),
+ ("IgnoreWrap", "true"),
+ ("ColumnRuleOverride", "true"),
+ ("VerticalJustification", "BottomAlign"),
+ ("FirstBaselineOffset", "FixedHeight"),
+ ("AutoSizingType", "HeightAndWidth"),
+ ("AutoSizingReferencePoint", "BottomRightPoint"),
+ ],
+ );
+ let o = text_frame_options(&[&local, &base]);
+ assert_eq!(o.columns_kind, ColumnsKind::FlexibleWidth);
+ assert!(o.balance_columns && o.ignore_wrap && o.column_rule);
+ assert_eq!(o.vertical_justification, designcraft_doc::VerticalJustification::Bottom);
+ assert_eq!(o.first_baseline, designcraft_doc::FirstBaseline::Fixed);
+ assert_eq!(o.auto_size, designcraft_doc::AutoSize::HeightAndWidth);
+ assert_eq!(o.auto_size_ref, 8);
+ let fixed = pref(&[], &[("UseFixedColumnWidth", "true")]);
+ assert_eq!(text_frame_options(&[&fixed, &local, &base]).columns_kind, ColumnsKind::FixedWidth);
+ // At one level an attribute wins over a conflicting property child, for every key.
+ let mut same_level = local.clone();
+ for (key, value) in &base.attrs {
+ same_level.set(key, value);
+ }
+ assert_eq!(text_frame_options(&[&same_level, &local]), text_frame_options(&[&base]));
+ // Malformed nearer values mask ancestors and use the normal per-field fallback.
+ let mut malformed = El::new("TextFramePreference");
+ for (key, _) in &base.attrs {
+ malformed.set(key, "invalid");
+ }
+ assert_eq!(text_frame_options(&[&malformed, &local]), TextFrameOptions { auto_size_ref: 1, ..Default::default() });
+ }
+ }
+
+ #[cfg(test)]
+ mod page_column_import_safety_tests {
+ use super::*;
+
+ #[test]
+ fn frame_preference_page_columns_are_bounded_and_finite() {
+ for (raw, expected) in [("4000000000", 216), ("1e300", 216), ("-10", 1), ("NaN", 1), ("inf", 1)] {
+ let m = El::new("MarginPreference")
+ .attr("ColumnCount", raw)
+ .attr("ColumnGutter", "NaN")
+ .attr("Top", "inf")
+ .attr("Bottom", "-inf")
+ .attr("Left", "NaN")
+ .attr("Right", "1e309");
+ let (margins, columns) = margins_of(&m);
+ assert_eq!(columns.count, expected);
+ assert_eq!(columns.gutter, 12.);
+ assert_eq!(margins, Margins::uniform(36.));
+ }
+ }
+ }
+
+ #[cfg(test)]
+ mod frame_preference_scalar_tests {
+ use super::*;
+
+ #[test]
+ fn frame_preference_scalar_whitespace() {
+ let values = [
+ ("UseFixedColumnWidth", "true"),
+ ("UseFlexibleColumnWidth", "false"),
+ ("VerticalBalanceColumns", "true"),
+ ("IgnoreWrap", "true"),
+ ("ColumnRuleOverride", "true"),
+ ("VerticalJustification", "BottomAlign"),
+ ("FirstBaselineOffset", "FixedHeight"),
+ ("AutoSizingType", "HeightAndWidth"),
+ ("AutoSizingReferencePoint", "BottomRightPoint"),
+ ];
+ let preference = |properties: bool, padded: bool, fixed: bool| {
+ let mut e = El::new("TextFramePreference");
+ let mut props = El::new("Properties");
+ for (key, raw) in values {
+ let raw = match key {
+ "UseFixedColumnWidth" if !fixed => "false",
+ "UseFlexibleColumnWidth" if !fixed => "true",
+ _ => raw,
+ };
+ let value = if padded { format!("\n {raw}\t ") } else { raw.to_string() };
+ if properties {
+ props.push(El::new(key).text(value));
+ } else {
+ e.set(key, value);
+ }
+ }
+ e.push(props);
+ e
+ };
+ for fixed in [false, true] {
+ let clean = preference(false, false, fixed);
+ let expected = text_frame_options(&[&clean]);
+ assert_eq!(expected.columns_kind, if fixed { ColumnsKind::FixedWidth } else { ColumnsKind::FlexibleWidth });
+ assert!(expected.balance_columns && expected.ignore_wrap && expected.column_rule);
+ assert_eq!(expected.vertical_justification, designcraft_doc::VerticalJustification::Bottom);
+ assert_eq!(expected.first_baseline, designcraft_doc::FirstBaseline::Fixed);
+ assert_eq!(expected.auto_size, designcraft_doc::AutoSize::HeightAndWidth);
+ assert_eq!(expected.auto_size_ref, 8);
+ for properties in [false, true] {
+ let padded = preference(properties, true, fixed);
+ assert_eq!(text_frame_options(&[&padded]), expected);
+ }
+ // A malformed nearest attribute masks both its own valid child and farther values.
+ let mut invalid = preference(true, true, fixed);
+ for (key, _) in values {
+ invalid.set(key, " invalid ");
+ }
+ assert_eq!(text_frame_options(&[&invalid, &clean]), TextFrameOptions { auto_size_ref: 1, ..Default::default() });
+ }
+ // Object identities use the raw property lookup, not scalar whitespace normalization.
+ let exact = El::new("TextFramePreference").child(El::new("Properties").child(El::new("ColumnRuleStrokeColor").text(" Color/Named ")));
+ assert_eq!(Prefs(&[&exact]).prop("ColumnRuleStrokeColor").as_deref(), Some(" Color/Named "));
+ }
+ }
diff --cc crates/idml/src/tests.rs
index a97461491,57801e34f..6de2985b0
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -3488,240 -2127,45 +3488,283 @@@ fn type_on_a_path_keeps_its_start_and_e
}
}
+/// Based on Parent travels as the parent pages' `AppliedMaster`; a cycle in a file is broken on
+/// import with a warning.
+#[test]
+fn parent_based_on_round_trips_and_cycles_are_broken() {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let a = d.parents[0].id;
+ let b = d.add_parent("B", "Opening", 2, 12.0, designcraft_doc::Margins::uniform(36.0));
+ d.add_parent("C", "Closing", 2, 12.0, designcraft_doc::Margins::uniform(36.0));
+ let set = |d: &mut Document, pi: usize, on| std::sync::Arc::make_mut(&mut d.parents[pi]).parent.as_mut().unwrap().based_on = on;
+ set(&mut d, 1, Some(a));
+ set(&mut d, 2, Some(b));
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let base_of = |d: &Document, pi: usize| {
+ let b = d.parents[pi].parent.as_ref().unwrap().based_on?;
+ d.parents.iter().find(|p| p.id == b).and_then(|p| p.parent.as_ref()).map(|i| i.prefix.clone())
+ };
+ assert_eq!((base_of(&back, 0), base_of(&back, 1), base_of(&back, 2)), (None, Some("A".into()), Some("B".into())));
+
+ set(&mut d, 0, Some(b));
+ let r = import_idml_report(&export_idml(&d), &|_| None).unwrap();
+ assert!(r.warnings.iter().any(|w| w.contains("A-Parent") && w.contains("cycle")), "{:?}", r.warnings);
+ assert_eq!((base_of(&r.document, 0), base_of(&r.document, 1)), (None, Some("A".into())));
+}
+
+#[test]
+fn object_style_effects_round_trip() {
+ use designcraft_doc::{DropShadow, Effects, ObjectStyle};
+ let mut d = Document::new(&NewDocument::default());
+ let fx = Effects {
+ drop_shadow: DropShadow { on: true, distance: 5.0, size: 12.0, opacity: 0.28, ..Default::default() },
+ feather: 3.0,
+ ..Default::default()
+ };
+ d.styles_mut().object.push(ObjectStyle { name: "Photo".into(), effects: Some(fx.clone()), ..Default::default() });
+ d.styles_mut().object.push(ObjectStyle { name: "Plain".into(), fill: Some(Fill::swatch("Black")), ..Default::default() });
+ let lid = d.default_layer();
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)));
+ it.object_style = "Photo".into();
+ it.effects = fx.clone();
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ // A frame that turned the style's effects off writes them off, so it doesn't take the style's.
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut off = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(200.0, 40.0, 300.0, 140.0)));
+ off.object_style = "Photo".into();
+ d.insert_item(SpreadRef::Doc(0), off, None).unwrap();
+
+ let bytes = export_idml(&d);
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut spreads = String::new();
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ if f.name().starts_with("Spreads/") {
+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();
+ }
+ }
+ assert!(spreads.contains(r#"<DropShadowSetting Mode="None""#) && spreads.contains(r#"<FeatherSetting Mode="None""#), "{spreads}");
+ let back = import_idml(&bytes).unwrap();
+ let style = |n: &str| back.styles.object.iter().find(|s| s.name == n).unwrap();
+ let got = style("Photo").effects.clone().unwrap();
+ let ds = &got.drop_shadow;
+ assert!(ds.on && ds.size == 12.0 && (ds.opacity - 0.28).abs() < 1e-6, "{ds:?}");
+ assert!((ds.distance - 5.0).abs() < 1e-6 && (ds.angle - DropShadow::default().angle).abs() < 1e-6, "{ds:?}");
+ assert_eq!(got.feather, 3.0);
+ assert!(style("Plain").effects.is_none());
+ // The frame's effects are the style's, so it follows later edits of the style.
+ let frames: Vec<_> = back.spreads[0].items.iter().filter(|i| i.object_style == "Photo").collect();
+ assert_eq!(frames[0].effects, got);
+ assert_eq!(frames[1].effects, Effects::default());
+}
+
+#[test]
+fn object_style_effects_import_by_category_and_based_on() {
+ let styles = r#"
+ <ObjectStyle Self="ObjectStyle/Base" Name="Base">
+ <TransparencySetting>
+ <DropShadowSetting Mode="Drop" XOffset="3" YOffset="4" Size="9" Opacity="50"/>
+ <FeatherSetting Mode="Standard" Width="6"/>
+ </TransparencySetting>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="false"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Child" Name="Child">
+ <Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="true"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Off" Name="Off">
+ <TransparencySetting><DropShadowSetting Mode="Drop" Size="9"/></TransparencySetting>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="false" EnableFeather="false"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Loop" Name="Loop">
+ <Properties><BasedOn type="object">ObjectStyle/Loop</BasedOn></Properties>
+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true"/>
+ </ObjectStyle>"#;
+ let d = inset_fixture("", styles);
+ let fx = |n: &str| d.styles.object.iter().find(|s| s.name == n).unwrap().effects.clone();
+ let base = fx("Base").unwrap();
+ assert!(base.drop_shadow.on && base.drop_shadow.size == 9.0 && (base.drop_shadow.distance - 5.0).abs() < 1e-9);
+ assert_eq!(base.feather, 0.0, "EnableFeather=false");
+ let child = fx("Child").unwrap();
+ assert_eq!((child.drop_shadow.size, child.feather), (9.0, 6.0), "settings from the BasedOn style");
+ assert!(fx("Off").is_none());
+ assert!(!fx("Loop").unwrap().drop_shadow.on);
+}
+
+#[test]
+fn a_strokes_gradient_vector_round_trips() {
+ let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(
+ id,
+ d.default_layer(),
+ designcraft_doc::Shape::Path,
+ designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(10.0, 10.0, 110.0, 60.0)),
+ );
+ it.stroke.gradient_vector = Some([10.0, 35.0, 110.0, 35.0]);
+ d.insert_item(designcraft_doc::SpreadRef::Doc(0), it, None).unwrap();
+ let back = crate::import_idml(&crate::export_idml(&d)).unwrap();
+ let v = back.spreads[0].items[0].stroke.gradient_vector.unwrap();
+ assert!(v.iter().zip([10.0, 35.0, 110.0, 35.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{v:?}");
+}
+
+#[test]
+fn feather_choke_and_corners_round_trip() {
+ use designcraft_doc::{Effects, FeatherCorners, FeatherOptions, Item, ItemId, ObjectStyle};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let feathers = [(6.0, 40.0, FeatherCorners::Sharp), (4.0, 0.0, FeatherCorners::Rounded), (3.0, 12.5, FeatherCorners::Diffused)];
+ let fx = |(w, choke, corners): (f64, f64, FeatherCorners)| Effects {
+ feather: w,
+ feather_options: FeatherOptions { choke, corners },
+ ..Default::default()
+ };
+ for (i, f) in feathers.into_iter().enumerate() {
+ let x = 40.0 + 120.0 * i as f64;
+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, 40.0, x + 100.0, 140.0)));
+ it.effects = fx(f);
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ }
+ let styled = fx((5.0, 25.0, FeatherCorners::Rounded));
+ d.styles_mut().object.push(ObjectStyle { name: "Soft".into(), effects: Some(styled.clone()), ..Default::default() });
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let got: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();
+ assert_eq!(got, feathers.map(fx));
+ let style = back.styles.object.iter().find(|s| s.name == "Soft").and_then(|s| s.effects.clone()).unwrap();
+ assert_eq!((style.feather, style.feather_options), (styled.feather, styled.feather_options));
+}
+
+#[test]
+fn style_names_ending_in_a_space_and_partial_rule_overrides_import() {
+ // Nested style "Decimals " (a name with a trailing space, as InDesign allows) and a label
+ // style that only recolours the rule of the style it is based on.
+ let styles = STYLES
+ .replace(
+ r#" </RootCharacterStyleGroup>"#,
+ r#" <CharacterStyle Self="CharacterStyle/Decimals " Name="Decimals " Position="Superscript"/>
+ </RootCharacterStyleGroup>"#,
+ )
+ .replace(
+ r#" </RootParagraphStyleGroup>"#,
+ r#" <ParagraphStyle Self="ParagraphStyle/Price" Name="Price">
+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn>
+ <AllNestedStyles type="list"><ListItem type="record"><AppliedCharacterStyle type="object">CharacterStyle/Decimals </AppliedCharacterStyle><Delimiter type="enumeration">AnyCharacter</Delimiter><Repetition type="long">2</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles>
+ </Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Label white" Name="Label white" RuleAbove="true" RuleAboveLineWeight="16" RuleAboveOffset="-3">
+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><RuleAboveColor type="object">Color/Paper</RuleAboveColor></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Label black" Name="Label black">
+ <Properties><BasedOn type="object">ParagraphStyle/Label white</BasedOn><RuleAboveColor type="object">Color/Black</RuleAboveColor></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>"#,
+ );
+ let d = import_idml(&fixture_with_table_styles(&styles, STORY)).unwrap();
+ let style = |n: &str| d.styles.paragraph.iter().find(|s| s.name == n).unwrap();
+ let nested = style("Price").para.nested_styles.clone().unwrap();
+ assert_eq!(nested[0].style, "Decimals ", "the trailing space is part of the name");
+ let white = style("Label white").para.rule_above.clone().unwrap();
+ let black = style("Label black").para.rule_above.clone().unwrap();
+ assert!(black.on, "the rule stays on");
+ assert_eq!((black.weight, black.offset), (16.0, -3.0), "weight and offset come from the base style");
+ assert_ne!(black.color, white.color, "only the colour is overridden");
+}
+
+#[test]
+fn missing_linked_graphics_show_their_preview_and_keep_their_link() {
+ // InDesign's preview of the missing photo (a PNG header is all the importer reads: 4 × 3).
+ let png: Vec<u8> = [b"\x89PNG\r\n\x1a\n".as_slice(), &[0, 0, 0, 13], b"IHDR", &4u32.to_be_bytes(), &3u32.to_be_bytes()].concat();
+ let previews = std::collections::HashMap::from([("im".to_string(), std::sync::Arc::new(png.clone()))]);
+ let d = crate::import_idml_report_with_previews(&fixture(), &|_| None, &previews).unwrap().document;
+ let img = d.spreads.iter().flat_map(|sp| sp.items.iter()).find(|i| i.graphic().is_some()).unwrap();
+ let a = &d.assets[&img.graphic().unwrap().asset];
+ assert_eq!(a.data.as_slice(), png.as_slice(), "the preview shows");
+ assert_eq!(a.mime, "image/jpeg", "the link's format, not the preview's");
+ assert_eq!(a.link.as_deref(), Some("/definitely/missing dir/photo.jpg"), "relinking still finds the file");
+ // Without a preview it stays empty, as before.
+ let d = import_idml(&fixture()).unwrap();
+ assert!(d.assets.values().all(|a| a.data.is_empty() || a.link.is_none()));
+}
+
+#[test]
+fn a_preview_keeps_the_links_format_and_pixel_size_and_is_shared() {
+ let png: std::sync::Arc<Vec<u8>> =
+ std::sync::Arc::new([b"\x89PNG\r\n\x1a\n".as_slice(), &[0, 0, 0, 13], b"IHDR", &4u32.to_be_bytes(), &3u32.to_be_bytes()].concat());
+ let spread = SPREAD
+ .replace(r#"<Image Self="im" ItemTransform="1 0 0 1 0 0">"#, r#"<Image Self="im" ItemTransform="1 0 0 1 0 0" ActualPpi="300 300">"#)
+ .replace(
+ " </Spread>",
+ r#" <Rectangle Self="pf" ItemLayer="L1" ItemTransform="1 0 0 1 300 100" ContentType="GraphicType">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 30"/><PathPointType Anchor="40 30"/><PathPointType Anchor="40 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <PDF Self="pd" ItemTransform="1 0 0 1 0 0">
+ <Properties><GraphicBounds Left="0" Top="0" Right="40" Bottom="30"/></Properties>
+ <Link Self="lp" LinkResourceURI="file:/definitely/missing%20dir/logo.pdf" StoredState="Normal"/>
+ </PDF>
+ </Rectangle>
+ </Spread>"#,
+ );
+ let idml = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", STORY),
+ ]);
+ // One preview for both graphics, as indd-utils groups them.
+ let previews = std::collections::HashMap::from([("im".to_string(), png.clone()), ("pd".to_string(), png.clone())]);
+ let d = crate::import_idml_report_with_previews(&idml, &|_| None, &previews).unwrap().document;
+ let asset = |name: &str| d.assets.values().find(|a| a.name == name).unwrap();
+ let (photo, logo) = (asset("photo.jpg"), asset("logo.pdf"));
+ // 40 × 30 pt at 300 ppi, from the link, not the preview's 4 × 3.
+ assert_eq!((photo.mime.as_str(), photo.pixels), ("image/jpeg", Some((167, 125))));
+ assert_eq!(logo.mime, "application/pdf", "a placed PDF stays a PDF, for IDML export");
+ assert!(std::sync::Arc::ptr_eq(&photo.data, &png) && std::sync::Arc::ptr_eq(&logo.data, &png), "the preview's bytes are not copied");
+}
++
+ #[test]
+ fn frame_preference_import_caps_column_count_without_composition() {
+ for (raw, expected) in [("4000000000", 216), ("1e300", 216), ("-100", 1), ("0", 1), ("NaN", 1), ("inf", 1), ("-inf", 1)] {
+ for attribute in [true, false] {
+ let preference = if attribute {
+ format!(r#"<TextFramePreference TextColumnCount="{raw}"/>"#)
+ } else {
+ format!(
+ r#"<TextFramePreference><Properties><TextColumnCount type="number">{raw}</TextColumnCount></Properties></TextFramePreference>"#
+ )
+ };
+ let document = format!(
+ r#"<Document><Story Self="s"/><Spread Self="spread"><Page Self="page"/><TextFrame Self="frame" ParentStory="s">{preference}</TextFrame></Spread></Document>"#
+ );
+ let d = import_idml_with(&zip_files(&[("designmap.xml", &document)]), &|_| None).unwrap();
+ let frame = d.spreads[0].items[0].text_frame().unwrap();
+ // Inspect imported data only: never compose an unbounded input value.
+ assert_eq!(frame.options.columns, expected, "{raw}, attribute={attribute}");
+ }
+ }
+ }
+
+ #[test]
+ fn frame_preference_property_color_resolves_for_frames_and_object_styles() {
+ let document = r#"<Document>
+ <Color Self="Color/Near" Model="Process" Space="RGB" ColorValue="255 0 0" Name="Near" Visible="true"/>
+ <Color Self="Color/Far" Model="Process" Space="RGB" ColorValue="0 0 255" Name="Far" Visible="true"/>
+ <RootObjectStyleGroup Self="root">
+ <ObjectStyle Self="ObjectStyle/Base" Name="Base" EnableTextFrameGeneralOptions="true"><TextFramePreference ColumnRuleStrokeColor="Color/Far"/></ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" EnableTextFrameGeneralOptions="true"><Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></ObjectStyle>
+ </RootObjectStyleGroup>
+ <Story Self="s"/><Spread Self="spread"><Page Self="page"/>
+ <TextFrame Self="local" ParentStory="s" AppliedObjectStyle="ObjectStyle/Base"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ <TextFrame Self="inherited" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"/>
+ <TextFrame Self="attribute" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference ColumnRuleStrokeColor="Color/Far"><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ <TextFrame Self="invalid" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">missing</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ </Spread></Document>"#;
+ let d = import_idml_with(&zip_files(&[("designmap.xml", document)]), &|_| None).unwrap();
+ let colors: Vec<_> = d.spreads[0].items.iter().map(|it| it.text_frame().unwrap().options.column_rule_color.as_str()).collect();
+ assert_eq!(colors, vec!["Near", "Near", "Far", designcraft_color::swatch::NONE]);
+ assert_eq!(d.styles.object_style("Child").unwrap().text_frame.as_ref().unwrap().column_rule_color, "Near");
+ }
diff --cc crates/ui-egui/src/control.rs
index 57020755e,15da79df8..ce6ed3673
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@@ -113,29 -100,9 +113,30 @@@ fn key_from(name: &str) -> Option<egui:
})
}
+// Retain room for the existing maximum drag (10,000 moves plus move/down/up), but
+// bound the whole gesture and already queued input before generating any events.
+const MAX_PENDING_POINTER_EVENTS: usize = 10_003;
+
+fn pointer_counts(p: &Value, drag: bool, pending: usize) -> Result<(u64, u64), String> {
+ let positive = |name: &str, default: u64| match p.get(name) {
+ None => Ok(default),
+ Some(v) => v.as_u64().filter(|n| *n > 0).ok_or_else(|| format!("`{name}` must be a positive integer")),
+ };
+ let count = positive("count", 1)?;
+ let steps = if drag { positive("steps", 8)? } else { 0 };
+ // One initial move, two button events per click, and each drag step. Check the
+ // arithmetic too: hostile counts must never overflow into a small budget.
+ let events = count.checked_mul(2).and_then(|n| n.checked_add(steps)).and_then(|n| n.checked_add(1));
+ let available = MAX_PENDING_POINTER_EVENTS.saturating_sub(pending) as u64;
+ if events.is_none_or(|n| n > available) {
+ return Err(format!("pointer input would exceed the {MAX_PENDING_POINTER_EVENTS} pending-event limit"));
+ }
+ Ok((count, steps))
+}
+
/// Handle one control request. Commands it runs leave the user's system clipboard alone.
pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
+ app.install_clipboard_guard(ctx);
let was = std::mem::replace(&mut app.in_control, true);
let out = handle_request(app, ctx, req);
app.in_control = was;
@@@ -226,26 -189,21 +227,33 @@@ fn handle_request(app: &mut DesignApp,
ctx.request_repaint();
ok(Value::Null)
}
+ // What Ctrl/Cmd+V delivers from the system clipboard: text, or SVG markup copied in an
+ // illustration app (pasted as editable paths when no text is being edited).
+ "ui.paste" => {
+ let Some(text) = s("text") else { return err("missing `text`") };
+ app.synthetic.push(egui::Event::Paste(text.to_string()));
+ ctx.request_repaint();
+ ok(Value::Null)
+ }
"ui.move" => {
let pos = egui::pos2(p.get("x").and_then(Value::as_f64).unwrap_or(0.0) as f32, p.get("y").and_then(Value::as_f64).unwrap_or(0.0) as f32);
- app.synthetic.push(egui::Event::PointerMoved(pos));
+ app.control_synthetic.push(egui::Event::PointerMoved(pos));
ctx.request_repaint();
ok(Value::Null)
}
"ui.click" | "ui.drag" => {
+ let count = match p.get("count") {
+ None => 1,
+ Some(v) => match v.as_u64().filter(|n| (1..=255).contains(n)) {
+ Some(n) => n,
+ None => return err("`count` must be an integer from 1 through 255"),
+ },
+ };
// Screen-space (egui points) pointer input through egui itself: reaches every widget.
+ let (count, steps) = match pointer_counts(p, req.method == "ui.drag", app.synthetic.len()) {
+ Ok(counts) => counts,
+ Err(e) => return err(e),
+ };
let f = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0) as f32;
let button = match s("button") {
Some("right") | Some("secondary") => egui::PointerButton::Secondary,
@@@ -262,18 -220,20 +270,18 @@@
};
let a = egui::pos2(f("x"), f("y"));
let end = if req.method == "ui.drag" { egui::pos2(f("toX"), f("toY")) } else { a };
- app.synthetic.push(egui::Event::PointerMoved(a));
- app.synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
+ app.control_synthetic.push(egui::Event::PointerMoved(a));
+ app.control_synthetic.push(egui::Event::PointerButton { pos: a, button, pressed: true, modifiers });
if req.method == "ui.drag" {
- // From the caller: a huge count would queue events until memory runs out.
- let steps = p.get("steps").and_then(Value::as_u64).unwrap_or(8).clamp(1, 10_000);
for i in 1..=steps {
let t = i as f32 / steps as f32;
- app.synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));
+ app.control_synthetic.push(egui::Event::PointerMoved(a + (end - a) * t));
}
}
- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
for _ in 1..count {
- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });
- app.synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: true, modifiers });
+ app.control_synthetic.push(egui::Event::PointerButton { pos: end, button, pressed: false, modifiers });
}
ctx.request_repaint();
ok(Value::Null)
diff --cc crates/ui-egui/src/lib.rs
index f69325e12,1db2f591d..fec7d92e3
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -544,8 -504,12 +544,12 @@@ pub struct DesignApp
pub color_applied: bool,
pub perf: Perf,
pub synthetic: Vec<egui::Event>,
+ /// Control input stays separate from native-menu input until its frame is processed.
+ pub(crate) control_synthetic: Vec<egui::Event>,
+ control_input_frame: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ clipboard_guard_installed: bool,
/// Story open in the Story Editor.
- pub story_editor: Option<designcraft_doc::StoryId>,
+ pub story_editor: Option<story_editor::Target>,
control_rx: Option<Receiver<ControlRequest>>,
pending_shots: Vec<(u64, Option<String>, Sender<ControlResponse>, f64)>,
queued_shots: Vec<(u64, f64, u32)>,
@@@ -726,27 -638,8 +733,27 @@@ impl DesignApp
return r;
}
// Only user-initiated runs touch the system clipboard, never the control channel's.
- let system_clipboard = !self.in_control;
+ let system_clipboard = !self.in_control && !self.control_input_frame.load(std::sync::atomic::Ordering::Relaxed);
- let params = if system_clipboard { self.with_system_clipboard(id, params) } else { params };
+ let mut params = if system_clipboard { self.with_system_clipboard(id, params) } else { params };
+ // Vector art copied in another app (Illustrator, VectorCraft, Figma) is SVG markup on the
+ // system clipboard: with no insertion point it pastes as editable paths where text would go.
+ let typing = self.session.active().is_some_and(|d| d.selection.text.is_some());
+ let id = match params.as_object_mut() {
+ Some(o) if id == "edit.paste" && !typing && o.get("text").and_then(Value::as_str).is_some_and(designcraft_engine::cmd::is_svg_markup) => {
+ if let Some(svg) = o.remove("text") {
+ o.insert("svg".into(), svg);
+ }
+ "edit.pasteSvg"
+ }
+ _ => id,
+ };
+ // Copied objects paste on the spread in view.
+ if matches!(id, "edit.paste" | "edit.pasteInPlace" | "edit.pasteSvg")
+ && let Some(spread) = canvas::current_spread(self)
+ && let Some(p) = params.as_object_mut()
+ {
+ p.entry("spread").or_insert(json!(spread));
+ }
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.after_engine();
match &r {
@@@ -1091,12 -922,10 +1098,12 @@@
}
self.last_time = now;
self.drain_control(ctx);
+ new_document::end_stale_preview(self);
if self.fonts_ready {
self.drain_inbox();
+ self.open_os_documents();
}
- if !self.synthetic.is_empty() {
+ if !self.synthetic.is_empty() || !self.control_synthetic.is_empty() {
ctx.request_repaint();
}
self.collect_screenshots(ctx);
@@@ -1336,26 -1123,39 +1343,46 @@@
r
}
+ /// Deliver window actions to the host without persisting them in UI preferences.
+ pub(crate) fn flush_window_commands(&mut self, ctx: &egui::Context) {
+ for command in std::mem::take(&mut self.pending_window_commands) {
+ ctx.send_viewport_cmd(command);
+ }
+ }
+
- /// Inject synthetic events (one pointer event per frame).
- pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) {
- if self.synthetic.is_empty() {
+ /// Keep widget clipboard output private while a queued control event is running.
+ pub(crate) fn install_clipboard_guard(&mut self, ctx: &egui::Context) {
+ if self.clipboard_guard_installed {
return;
}
- let n = match self.synthetic[0] {
+ let private = self.control_input_frame.clone();
+ ctx.on_end_pass(
+ "control clipboard",
+ std::sync::Arc::new(move |ui| {
+ if private.load(std::sync::atomic::Ordering::Relaxed) {
+ ui.ctx().output_mut(|o| {
+ o.commands.retain(|cmd| !matches!(cmd, egui::OutputCommand::CopyText(_) | egui::OutputCommand::CopyImage(_)))
+ });
+ }
+ }),
+ );
+ self.clipboard_guard_installed = true;
+ }
+
+ /// Inject synthetic events (one pointer event per frame), retaining control provenance.
+ pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) {
+ let private = !self.control_synthetic.is_empty();
+ self.control_input_frame.store(private, std::sync::atomic::Ordering::Relaxed);
+ let events = if private { &mut self.control_synthetic } else { &mut self.synthetic };
+ let Some(first) = events.first() else { return };
+ let n = match first {
egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } => 1,
- _ => self.synthetic.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(self.synthetic.len(), |i| i + 1),
+ _ => events.iter().position(|e| matches!(e, egui::Event::Key { pressed: false, .. })).map_or(events.len(), |i| i + 1),
};
- if let Some(egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. }) = self.synthetic.first() {
+ if let egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } = first {
raw.events.push(egui::Event::PointerMoved(*p));
}
- raw.events.extend(self.synthetic.drain(..n));
+ raw.events.extend(events.drain(..n));
}
/// Lay out the whole window.
diff --cc crates/ui-egui/src/toolbar.rs
index 7676ad8ea,6e7d98487..5572924c8
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@@ -416,25 -424,18 +416,20 @@@ fn tool_button(ui: &mut egui::Ui, icon
})
}
-/// Default Fill and Stroke (D): no fill, a black stroke.
+/// Default Fill and Stroke (D): text gets a black fill and no stroke, objects no fill and a black
+/// stroke. Colour keys act on what the proxy shows (see `panels::colors_affect_text`).
pub(crate) fn default_fill_stroke(app: &mut DesignApp) -> Result<Value, String> {
if crate::panels::colors_affect_text(app) {
- app.run("type.char", json!({"fill": "[Black]", "fillTint": 1.0, "stroke": "[None]", "strokeTint": 1.0}))
- } else {
- app.run("object.defaultFillStroke", json!({}))
+ let attrs = json!({"fill": "[Black]", "fillTint": 1.0, "stroke": "[None]", "strokeTint": 1.0});
+ return app.run("type.char", json!({ "attrs": attrs }));
}
+ app.run("object.defaultFillStroke", json!({}))
}
-/// Swap Fill and Stroke (Shift+X): each selected object's fill and stroke trade places.
+/// Swap Fill and Stroke (Shift+X): the text's fill and stroke, or each selected object's, trade
+/// places, tints included.
pub(crate) fn swap_fill_stroke(app: &mut DesignApp) -> Result<Value, String> {
- if crate::panels::colors_affect_text(app) {
- let (fill, fill_tint, stroke, stroke_tint) = crate::panels::color_target(app).ok_or("no text to color")?;
- let attrs = json!({"fill": stroke, "fillTint": stroke_tint, "stroke": fill, "strokeTint": fill_tint});
- return app.run("type.char", json!({ "attrs": attrs }));
- }
- app.run("object.swapFillStroke", json!({}))
+ if crate::panels::colors_affect_text(app) { app.run("type.swapFillStroke", json!({})) } else { app.run("object.swapFillStroke", json!({})) }
}
/// Fill/Stroke toggle (X): brings the other of fill and stroke to the front of the proxy.
@@@ -636,8 -585,87 +631,88 @@@ mod tests
app.session.execute("text.select", &json!({"story": f["story"], "anchor": 5})).unwrap();
app.select_tool("type");
assert!(app.session.wants_text());
+ let front = app.ui.stroke_front;
press(&mut app, &ctx, Key::X, Modifiers::NONE);
- assert!(app.ui.stroke_front, "X while typing leaves the proxy alone");
+ assert_eq!(app.ui.stroke_front, front, "X while typing leaves the proxy alone");
}
}
+
+ #[cfg(test)]
+ mod text_color_tests {
+ use super::*;
+ use designcraft_doc::{ItemId, StoryId};
+
+ #[test]
+ fn integration_color_swap_preserves_each_run_and_frame() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let mut frames = vec![];
+ let mut stories = vec![];
+ for text in ["abcd", "efgh"] {
+ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":text})).unwrap();
+ frames.push(f["id"].clone());
+ stories.push(f["story"].as_u64().unwrap());
+ }
+ let pairs = [("[Paper]", "[Black]", 0.2, 0.8), ("[Black]", "[Paper]", 0.4, 0.6)];
+ for (i, sid) in stories.iter().enumerate() {
+ for j in 0..2 {
+ let (fill, stroke, ft, st) = pairs[(i + j) % 2];
+ app.run("text.select", json!({"story":sid,"anchor":j*2,"focus":j*2+2})).unwrap();
+ app.run("type.char", json!({"fill":fill,"stroke":stroke,"fillTint":ft,"strokeTint":st})).unwrap();
+ }
+ }
+ app.run("selection.set", json!({"ids":frames})).unwrap();
+ app.run("app.formattingAffectsText", json!({"on":true})).unwrap();
+ let before = serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap();
+ let n = app.session.doc().unwrap().history.undo.len();
+ swap_fill_stroke(&mut app).unwrap();
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1);
+ for (i, sid) in stories.iter().enumerate() {
+ let story = app.session.doc().unwrap().doc.story(StoryId(*sid)).unwrap();
+ for j in 0..2 {
+ let (fill, stroke, ft, st) = pairs[(i + j) % 2];
+ let a = &story.format_after(j * 2).over;
+ assert_eq!((a.fill.as_deref(), a.stroke.as_deref(), a.fill_tint, a.stroke_tint), (Some(stroke), Some(fill), Some(st), Some(ft)));
+ }
+ }
+ let swapped = serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap();
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap(), before);
+ app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(serde_json::to_value(app.session.doc().unwrap().doc.as_ref()).unwrap(), swapped);
+ }
+
+ #[test]
+ fn integration_color_toolbar_picker_targets_selected_frame_text() {
+ use egui_kittest::kittest::Queryable;
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let f = app.run("frame.create", json!({"rect":[36,36,300,200],"content":"text","text":"hello"})).unwrap();
+ app.run("selection.set", json!({"ids":[f["id"]]})).unwrap();
+ app.run("app.formattingAffectsText", json!({"on":true})).unwrap();
+ let before = app.session.doc().unwrap().doc.item(ItemId(f["id"].as_u64().unwrap())).unwrap().fill.clone();
+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(0.001).build_ui_state(
+ |ui, app: &mut DesignApp| {
+ app.logic(&ui.ctx().clone());
+ app.ui(ui);
+ },
+ app,
+ );
+ h.run_steps(6);
+ let at = h.get_by_label("Fill (X)").rect().center();
+ h.hover_at(at);
+ h.step();
+ for pressed in [true, false, true, false] {
+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
+ h.step();
+ }
+ h.run_steps(3);
+ let d = h.state().ui.dialog.clone().unwrap();
+ assert_eq!(d.id, "colorPicker");
+ assert_eq!(d.fields["text"], true);
+ h.state_mut().run("object.color", json!({"color":"#123456","target":"fill","text":d.fields["text"]})).unwrap();
+ let doc = &h.state().session.doc().unwrap().doc;
+ assert_eq!(doc.item(ItemId(f["id"].as_u64().unwrap())).unwrap().fill, before);
+ assert!(doc.story(StoryId(f["story"].as_u64().unwrap())).unwrap().format_after(0).over.fill.is_some());
+ }
+ }