Skip to content

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

Merge PR #1100: Placed greyscale and bitmap images take the swatch applied to them (IDML, screen, PDF)

aiongg6e4f122b8c8a
diff --cc ROADMAP.md
index a5bfd64e2,d297d1cdd..5dd5488b4
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -345,100 -343,11 +345,101 @@@ list) · [roadmap.md](docs/roadmap.md)
## Progress log
-- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.
-
Newest first.
+- **2026-10-14** · 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-15** · Define Lists… is listed under Type › Bulleted & Numbered Lists in command search and Edit › Menus, matching the menu, and the parity doc no longer lists a Type › Paragraph Rules… menu item that does not exist. No readiness percentage change.
+- **2026-10-15** · Pressing Enter in the Layers panel's rename field without typing leaves an unnamed object unnamed, so it keeps following its automatic label instead of taking it as a fixed name. No readiness percentage change.
+- **2026-10-15** · Apply Gradient (.) with the Stroke box in front puts a new default gradient on the stroke in one undo step and leaves the fill's swatch and tint as they were. No readiness percentage change.
+- **2026-10-15** · In a facing-pages document, two odd-numbered pages in a row after a section restart (page 2 starting at 1) each get their own spread and stay right pages, instead of sharing a spread with an odd page on the left. No readiness percentage change.
+- **2026-10-15** · Character formatting set at a caret on a blank line (an empty paragraph) applies to the line's paragraph mark and to the text typed there, also after the caret has left the line and come back; typed text used to take the previous paragraph's format. No readiness percentage change.
+- **2026-10-15** · Very wide effects stay sharp at high zoom: a wide Basic Feather draws the object itself at full resolution, with only the soft mask at a reduced one, and wide inner shadows, inner glows, satin and bevels are clipped to the shape at full resolution, so they no longer blur the object or bleed past its edge. No readiness percentage change.
+- **2026-10-15** · The Typography panel controls every OpenType feature a character format carries: Other Features lists Proportional Metrics, Horizontal Kana, Localized Forms, Mark Positioning, Justification Alternates and Roman Italics. Lining, Oldstyle, Tabular or Proportional chosen alone also sets the other figure axis, so IDML export keeps the figure style instead of writing Default. Standard Ligatures follows and sets Character › Ligatures. No readiness percentage change.
+- **2026-10-15** · Join Path and Convert Point leave a path on a locked layer or inside a locked group unchanged, as the other path edits do. No readiness percentage change.
+- **2026-10-15** · A kerning value chosen in the Character panel or Properties at a caret kerns the pair at the caret (the character before it takes the value, in one undo step), and the field shows that pair's kerning; at the start of a story or paragraph it is kept for the next typing, and a selection is kerned as before (`type.kernPair`). No readiness percentage change.
+- **2026-10-15** · Japanese, Chinese and Korean input methods type into stories with the Type tool: the marked text shows in place, underlined (the clause being converted twice), with the candidate window at the caret, and the commit is one undo step. Keys, shortcuts, the clipboard and Undo wait while the input method composes; a click, a tool switch or another command keeps the marked text as typed. Not yet checked by hand with a system input method. No readiness percentage change.
+- **2026-10-15** · IDML placed PDFs keep their page and Crop to box (`PDFAttribute` `PageNumber` and `PDFCrop`, written for every placed PDF); two crops of one PDF page stay two assets; a page the PDF lacks is left out of PDF export with a warning instead of failing it; `$ID/` font names resolve; the IDML in a package links the images in its Links folder without embedding them. No readiness percentage change.
+- **2026-10-15** · The CJK leading model and character alignment take effect only in paragraphs set with a Japanese composer (`HL Composer J`, `HL Single J`), which IDML import and export keep: Western and Arabic paragraphs set baseline to baseline on the Roman baseline, a paragraph switched to a Japanese composer gets the file's Aki Below spacing, and under Aki Below a line's leading is the space below it. No readiness percentage change.
+- **2026-10-15** · Document pages follow their parent page's margins and columns unless margins were set on the page itself (`Page::local_margins`): applying a different parent gives a page that parent's margins, a page that changes side after an insert takes the other parent page's, and a page given margins equal to its parent's keeps them when the parent changes. IDML import and older files mark pages whose margins differ from their parent as their own. No readiness percentage change.
+- **2026-10-15** · Start-up picks the GPU that drives the display (or the kind `WGPU_POWER_PREF` or the adapter `WGPU_ADAPTER_NAME` names), and when a start-up fails or hangs it restarts on the next adapter, then the next backend, then a software renderer, keeping recovered documents; start-up errors are logged to standard error and the log file (#273, #334). No readiness percentage change.
+- **2026-10-15** · IDML: liquid guides keep their type on document and parent pages instead of reopening as ordinary ruler guides. Positions, orientation, Fit to Page, locks and layers are preserved; object liquid constraints remain unmapped (#872). No readiness percentage change.
+ - **2026-10-16** · A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign: IDML's `<Image FillColor>` is read and written, greyscale pixels become a tint of the swatch on opaque white and a bitmap's white lets the frame show through, on screen and in PDF (spot swatches print on their plate). Colour images keep their colours. Applying the swatch from the Swatches panel comes next. No readiness percentage change.
- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
diff --cc apps/designcraft-cli/src/perf.rs
index aa259ce24,c1b798cc7..bed57cfcc
--- a/apps/designcraft-cli/src/perf.rs
+++ b/apps/designcraft-cli/src/perf.rs
@@@ -246,7 -246,7 +246,8 @@@ pub fn synthetic(spec: &Spec) -> Result
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
if k == 0 && pi == 0 {
it.effects.drop_shadow.on = true;
diff --cc crates/compose/src/tests.rs
index d6344f521,97eeb8cd4..9347a7a9a
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -489,259 -396,46 +489,262 @@@ fn doc_with_ellipse(mode: WrapMode, sid
(d, sid)
}
-/// A text-wrap object elsewhere on the spread doesn't affect a frame it doesn't overlap: the small
-/// frame's one character is set (it was overset: every frame took every wrap object on the
-/// spread, and then no gap narrower than 1.5 em of the paragraph's size was used).
#[test]
-fn small_single_character_frame_sets_beside_unrelated_text_wrap() {
- let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 310.5), Rect::new(0.0, 0.0, 120.0, 60.0));
+fn wrap_on_both_sides_sets_text_left_then_right_of_the_object() {
+ let (d, sid) = doc_with_ellipse(WrapMode::Contour, WrapSide::BothSides);
let cs = compose_story(&d, sid, &ComposeOptions::default());
- assert!(!cs.is_overset(), "the tombstone is set");
- assert_eq!(cs.line_count(), 1);
+ let lines = &cs.frames[0].lines;
+ let pairs: Vec<(&Line, &Line)> = lines.windows(2).filter(|w| w[0].baseline == w[1].baseline).map(|w| (&w[0], &w[1])).collect();
+ assert!(pairs.len() >= 4, "{} lines share a baseline", pairs.len());
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ for (l, r) in &pairs {
+ // Left segment, then the right one; the text runs on from one to the other.
+ assert!(l.x1 < 150.0 && r.x0 > 150.0, "{} {}", l.x1, r.x0);
+ assert_eq!(l.range.end, r.range.start);
+ // No glyph inside the wrapped outline at its line.
+ let (a, b) = ex.contour.as_ref().unwrap().band_extent(l.baseline - l.ascent, l.baseline).unwrap();
+ let n = l.glyphs.len().saturating_sub(1);
+ // The left segment's last glyph may be the space the line breaks at.
+ for g in l.glyphs.iter().take(n).chain(&r.glyphs).filter(|g| g.visible) {
+ assert!(g.x + g.adv <= a + 0.5 || g.x >= b - 0.5, "glyph at {}..{} in {a}..{b}", g.x, g.x + g.adv);
+ }
+ }
+ // Lines beside the narrow top of the ellipse reach closer to its centre than those at its middle.
+ let mid = pairs.iter().map(|(l, _)| l.x1).fold(f64::INFINITY, f64::min);
+ let top = pairs.first().unwrap().0.x1;
+ assert!(top > mid + 5.0, "top {top}, middle {mid}");
+ assert!(!cs.is_overset());
}
-/// A narrow frame that a text-wrap object overlaps further down sets the lines the object doesn't
-/// reach: the minimum gap width only applies to gaps a wrap object cuts.
+/// Same As Clipping follows a placed graphic's clipping path: beside a triangle that widens
+/// downwards, text reaches further in at the narrow top than at the wide bottom.
#[test]
-fn narrow_frame_sets_lines_no_wrap_object_reaches() {
- let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 340.0), Rect::new(290.0, 330.0, 330.0, 360.0));
+fn same_as_clipping_wrap_follows_the_clipping_path() {
+ use designcraft_geom::{PathData, Point, SubPath};
+ let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(
+ id,
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)),
+ );
+ let triangle = PathData::single(SubPath::polyline(&[Point::new(75.0, 0.0), Point::new(150.0, 200.0), Point::new(0.0, 200.0)], true));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (150.0, 200.0),
+ xf: designcraft_geom::Affine::translate((150.0, 100.0)),
+ clip: Some(std::sync::Arc::new(designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, triangle))),
+ auto_fit: Default::default(),
+ fit_align: 0,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::LeftSide;
+ it.wrap.contour = designcraft_doc::ContourType::SameAsClipping;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
let cs = compose_story(&d, sid, &ComposeOptions::default());
- assert!(!cs.is_overset(), "the first line is above the wrap object");
- assert_eq!(cs.line_count(), 1);
- let (top, baseline) = (cs.frames[0].columns[0].y0, cs.frames[0].lines[0].baseline);
- assert!(baseline - top < 20.0, "on the first line: {baseline} (text area from {top})");
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 100.0 && l.baseline + l.descent < 300.0).collect();
+ let (top, bottom) = (beside.first().unwrap().x1, beside.last().unwrap().x1);
+ assert!(top > bottom + 40.0, "top {top}, bottom {bottom}");
+ assert!(bottom < 160.0, "the bottom lines stop near the triangle's base: {bottom}");
+}
+
+/// LOREM beside an ellipse wrapped on both sides along its contour that leaves a sliver (about
+/// 20 pt at its middle) between it and the frame's right edge.
+fn sliver_wrap(para: ParaAttrs) -> (Document, StoryId, String) {
+ let text = [LOREM; 4].join(" ");
+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 800.0), para);
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut it =
+ designcraft_doc::Item::new(id, lid, designcraft_doc::Shape::Oval, designcraft_geom::shapes::ellipse(Rect::new(150.0, 100.0, 276.0, 220.0)));
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::BothSides;
+ it.wrap.offsets = [4.0; 4];
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ (d, sid, text)
+}
+
+#[test]
+fn words_stay_whole_beside_a_wrap_sliver() {
+ for align in [Align::Left, Align::LeftJustified] {
+ for hyphenate in [true, false] {
+ let (d, sid, text) = sliver_wrap(ParaAttrs { align: Some(align), hyphenate: Some(hyphenate), ..Default::default() });
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let word = |i: usize| text.as_bytes().get(i).is_some_and(u8::is_ascii_alphanumeric);
+ let mut empty_slivers = 0;
+ for (i, l) in lines.iter().enumerate() {
+ let line = &text[l.range.clone()];
+ // A line ends inside a word only at a hyphenation point.
+ assert!(l.hyphenated || !(word(l.range.end - 1) && word(l.range.end)), "{align:?} {hyphenate}: split word in {line:?}");
+ // Every word fits its segment whole.
+ for g in l.glyphs.iter().filter(|g| g.visible) {
+ assert!(g.x + g.adv <= l.x1 + 0.5, "{align:?} {hyphenate}: {line:?} overflows its {}..{} segment", l.x0, l.x1);
+ }
+ // A left segment beside the object whose sliver stays empty: the next word doesn't fit it.
+ let Some((_, b)) = ex.contour.as_ref().unwrap().band_extent(l.baseline - l.ascent, l.baseline) else { continue };
+ let next = lines.get(i + 1);
+ if l.x1 > b || 300.0 - b < 18.0 || next.is_some_and(|n| n.baseline == l.baseline) {
+ continue;
+ }
+ let Some(next) = next else { continue };
+ let first = text[next.range.clone()].split(' ').next().unwrap_or_default();
+ let w: f64 = next.glyphs.iter().filter(|g| g.byte < next.range.start + first.len()).map(|g| g.adv).sum();
+ assert!(w > 300.0 - b, "{align:?} {hyphenate}: {first:?} ({w}) fits the {} pt sliver beside {line:?}", 300.0 - b);
+ empty_slivers += 1;
+ }
+ if !hyphenate {
+ assert!(empty_slivers > 0, "{align:?}: no sliver stays empty");
+ }
+ assert!(!cs.is_overset());
+ }
+ }
}
-/// In a frame of narrow columns, a wrap object beside column 2 leaves column 1 alone: only a gap
-/// the object cuts in its own column is held to the minimum width (it was dropped, as the object
-/// overlapped the line's band, and the text went past column 1).
#[test]
-fn wrap_object_beside_one_narrow_column_leaves_the_other_alone() {
- // Two 18 pt columns (12 pt gutter): narrower than 1.5 em of the 14 pt paragraph.
- let (mut d, sid) = tombstone(Rect::new(300.0, 300.0, 348.0, 340.0), Rect::new(336.0, 300.0, 380.0, 340.0));
- let fid = d.spreads[0].items.iter().find(|i| i.text_frame().is_some_and(|t| t.story == sid)).unwrap().id;
- d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+fn one_sided_wrap_leaves_the_other_side_empty() {
+ for (side, right) in [(WrapSide::RightSide, true), (WrapSide::LeftSide, false), (WrapSide::LargestArea, false)] {
+ let (d, sid) = doc_with_ellipse(WrapMode::BoundingBox, side);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent < 200.0 && l.baseline + l.descent > 100.0).collect();
+ assert!(!beside.is_empty());
+ let mut rows: Vec<f64> = beside.iter().map(|l| l.baseline).collect();
+ rows.dedup();
+ assert_eq!(rows.len(), beside.len(), "{side:?}: one segment per line");
+ for l in beside {
+ assert!(if right { l.x0 >= 194.0 - 1e-6 } else { l.x1 <= 106.0 + 1e-6 }, "{side:?}: {}..{}", l.x0, l.x1);
+ }
+ }
+}
+
+#[test]
+fn contour_wrap_follows_the_outline_band_by_band() {
+ let (d, sid) = doc_with_ellipse(WrapMode::Contour, WrapSide::BothSides);
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ let c = ex.contour.as_ref().unwrap();
+ let width = |y0: f64, y1: f64| c.band_extent(y0, y1).map_or(0.0, |(a, b)| b - a);
+ let (top, mid, bottom) = (width(100.0, 104.0), width(146.0, 154.0), width(196.0, 200.0));
+ // 80 wide plus the 4 pt offset each side at the middle; much narrower at the ends.
+ assert!((mid - 88.0).abs() < 0.5, "{mid}");
+ assert!(top < mid - 20.0 && bottom < mid - 20.0, "{top} {mid} {bottom}");
+ // The band is the line's height, not its baseline: a band reaching the middle is full width.
+ assert!((width(120.0, 150.0) - 88.0).abs() < 0.5);
+ // Outside the outline and its offset: no block.
+ assert!(c.band_extent(205.0, 210.0).is_none());
+ // A bounding-box wrap blocks the rectangle at every band.
+ let (d, sid) = doc_with_ellipse(WrapMode::BoundingBox, WrapSide::BothSides);
+ let ex = &frame_specs(&d, sid)[0].exclusions[0];
+ assert!(ex.contour.is_none());
+ assert_eq!(ex.rect, Rect::new(106.0, 96.0, 194.0, 204.0));
+}
+
+/// A contour wrap with a slanted right edge, x = 100 + 2(y − 50) for y in 50..100, text to its right.
+fn doc_with_slant(contour: designcraft_geom::path::PathData) -> (Document, StoryId) {
+ let (mut d, sid, _) = doc_with(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, contour);
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::RightSide;
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ (d, sid)
+}
+
+#[test]
+fn a_line_meets_the_wrap_from_its_top_to_its_baseline() {
+ let pts = [Point::new(0.0, 50.0), Point::new(100.0, 50.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)];
+ let path = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true));
+ let (d, sid) = doc_with_slant(path);
let cs = compose_story(&d, sid, &ComposeOptions::default());
- let f = &cs.frames[0];
- assert_eq!(f.columns.len(), 2);
- assert!(f.columns[0].width() < 21.0, "column 1 is narrower than 1.5 em: {}", f.columns[0].width());
- assert!(!cs.is_overset());
- let l = &f.lines[0];
- assert_eq!(l.column, 0, "set in column 1");
- assert!(l.baseline - f.columns[0].y0 < 20.0, "on its first line: {}", l.baseline);
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 50.0 && l.baseline < 100.0).collect();
+ assert!(beside.len() >= 2, "{} lines beside the slant", beside.len());
+ for l in beside {
+ // The edge at the baseline, not at the bottom of the descenders (about 6 pt further out).
+ let edge = 100.0 + 2.0 * (l.baseline - 50.0);
+ assert!((l.x0 - edge).abs() < 0.5, "line at {} starts at {}, edge {edge}", l.baseline, l.x0);
+ }
+}
+
+#[test]
+fn an_image_contour_stops_at_its_frame() {
+ let (mut d, sid, _) = doc_with(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ // An L-shaped frame: its right edge is at x = 150 down to y = 150, then at 250 below.
+ let pts = [(0.0, 50.0), (150.0, 50.0), (150.0, 150.0), (250.0, 150.0), (250.0, 200.0), (0.0, 200.0)].map(|(x, y)| Point::new(x, y));
+ let frame = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(&pts, true));
+ let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Polygon, frame);
+ // The image overhangs the frame on every side.
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(d.alloc()),
+ size: (300.0, 250.0),
+ xf: designcraft_geom::Affine::IDENTITY,
+ clip: None,
+ auto_fit: designcraft_doc::Fitting::None,
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::RightSide;
+ it.wrap.contour = designcraft_doc::ContourType::BoundingBox;
+ it.wrap.offsets = [4.0; 4];
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 54.0 && l.baseline < 146.0).collect();
+ assert!(beside.len() >= 3, "{} lines beside the frame", beside.len());
+ for l in beside {
+ assert!((l.x0 - 154.0).abs() < 0.5, "line at {} starts at {}", l.baseline, l.x0);
+ }
+ // Below the step the frame is wider.
+ let low = cs.frames[0].lines.iter().find(|l| l.baseline - l.ascent > 154.0 && l.baseline < 196.0).unwrap();
+ assert!((low.x0 - 254.0).abs() < 0.5, "{}", low.x0);
+}
+
+/// A clipping path (Detect Edges with a large inset) that overhangs its frame: a Same As
+/// Clipping wrap follows it only within the frame.
+#[test]
+fn a_clipping_path_contour_stops_at_its_frame() {
+ let (mut d, sid, _) = doc_with(&[LOREM; 4].join(" "), Rect::new(0.0, 0.0, 300.0, 800.0), ParaAttrs::default());
+ let lid = d.default_layer();
+ let mut it = designcraft_doc::Item::new(
+ ItemId(d.alloc()),
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(150.0, 100.0, 300.0, 300.0)),
+ );
+ // The clip path reaches 100 pt left of the frame.
+ let wide = designcraft_geom::path::PathData::single(designcraft_geom::path::SubPath::polyline(
+ &[Point::new(-100.0, 0.0), Point::new(150.0, 0.0), Point::new(150.0, 200.0), Point::new(-100.0, 200.0)],
+ true,
+ ));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (150.0, 200.0),
+ xf: designcraft_geom::Affine::translate((150.0, 100.0)),
+ clip: Some(std::sync::Arc::new(designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, wide))),
+ auto_fit: Default::default(),
+ fit_align: 0,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ it.wrap.mode = WrapMode::Contour;
+ it.wrap.side = WrapSide::LeftSide;
+ it.wrap.contour = designcraft_doc::ContourType::SameAsClipping;
+ it.wrap.offsets = [4.0; 4];
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let beside: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.baseline - l.ascent > 104.0 && l.baseline < 296.0).collect();
+ assert!(beside.len() >= 5, "{} lines beside the frame", beside.len());
+ for l in beside {
+ assert!(l.x1 > 140.0 && l.x1 <= 146.0 + 1e-6, "line at {} ends at {}", l.baseline, l.x1);
+ }
}
#[test]
diff --cc crates/doc/src/assets.rs
index b111da724,834b36e49..0be5604c3
--- a/crates/doc/src/assets.rs
+++ b/crates/doc/src/assets.rs
@@@ -363,7 -349,7 +363,8 @@@ mod tests
auto_fit: Default::default(),
fit_align: 4,
crop: [crop; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it
}
diff --cc crates/doc/src/item.rs
index e063b712e,ca6af050f..456fb8783
--- a/crates/doc/src/item.rs
+++ b/crates/doc/src/item.rs
@@@ -616,9 -520,10 +616,13 @@@ pub struct Graphic
/// Frame Fitting Options › Crop Amount: top, left, bottom, right (negative adds space).
#[serde(default)]
pub crop: [f64; 4],
+ /// Text wrap set on the graphic itself (Direct Selection), around the part its frame shows.
+ #[serde(default, skip_serializing_if = "TextWrap::is_default")]
+ pub wrap: TextWrap,
+ /// The swatch applied to the image itself: InDesign colours a greyscale or bitmap image with
+ /// it, colour images ignore it. `None` (the default, like InDesign's Black) leaves it as is.
+ #[serde(default, skip_serializing_if = "Fill::is_none")]
+ pub fill: Fill,
}
fn center_ref() -> u8 {
@@@ -1622,28 -1304,6 +1626,29 @@@ mod tests
use super::*;
use designcraft_geom::shapes;
+ #[test]
+ fn graphics_without_a_clipping_path_load_and_save_as_before() {
+ let g = Graphic {
+ asset: AssetId(3),
+ size: (40.0, 30.0),
+ xf: Affine::translate((5.0, 5.0)),
+ clip: None,
+ auto_fit: Fitting::None,
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ };
+ let v = serde_json::to_value(&g).unwrap();
+ assert!(v.get("clip").is_none(), "{v}");
+ assert_eq!(serde_json::from_value::<Graphic>(v.clone()).unwrap(), g);
+ // A clip written with only its type and path gets the default options.
+ let mut v = v;
+ v["clip"] = serde_json::json!({"kind": "alphaChannel", "path": {"subpaths": []}});
+ let c = serde_json::from_value::<Graphic>(v).unwrap().clip.unwrap();
+ assert_eq!(*c, ClippingPath::new(ClippingKind::AlphaChannel, PathData::default()));
+ }
+
#[test]
fn bounds_and_text_area() {
let mut it = Item::new(ItemId(1), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)));
diff --cc crates/engine/src/cmd/datamerge/fill.rs
index 3538e8b05,f5b032534..55db5d2a5
--- a/crates/engine/src/cmd/datamerge/fill.rs
+++ b/crates/engine/src/cmd/datamerge/fill.rs
@@@ -388,8 -388,7 +388,9 @@@ fn place_image
auto_fit: mode,
fit_align: 0,
crop: [0.0; 4],
+ wrap: Default::default(),
+ clip: None,
+ fill: Default::default(),
};
if let Some(xf) = g.fitted(inner, mode) {
g.xf = xf;
diff --cc crates/engine/src/cmd/export.rs
index 90df6e21c,64329fff2..9816e693b
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -395,7 -385,7 +395,8 @@@ fn flatten(d: &designcraft_doc::Documen
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it.stroke.weight = 0.0;
it
@@@ -563,7 -551,7 +564,8 @@@ fn rasterize_where
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
img_item.stroke.weight = 0.0;
img_item.alt_text = it.alt_text.clone();
diff --cc crates/engine/src/cmd/file.rs
index 26ae6dcff,c3c4db2d9..13463ad36
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -708,7 -400,7 +708,8 @@@ fn file_place(s: &mut Session, p: &Valu
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
fid
} else {
@@@ -730,7 -419,7 +731,8 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(spread, it, None)?;
id
@@@ -851,7 -527,7 +853,8 @@@ fn place_drop(s: &mut Session, p: &Valu
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
fid
}
@@@ -878,7 -552,7 +881,8 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(sr, it, None)?;
id
diff --cc crates/engine/src/cmd/links.rs
index 69c9d8073,667d655f3..9e06a566d
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@@ -626,7 -605,7 +626,8 @@@ mod shared_asset_tests
auto_fit: Default::default(),
fit_align: 4,
crop: [1.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
src.insert_item(SpreadRef::Doc(0), it, None).unwrap();
let ids = super::super::object::duplicate_from(&mut dst, &src, &[iid], SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap();
@@@ -670,7 -648,7 +671,8 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [1.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
src.insert_item(SpreadRef::Doc(0), it, None).unwrap();
let ids = super::super::object::duplicate_from(&mut dst, &src, &[iid], SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap();
@@@ -678,40 -656,6 +680,41 @@@
assert_ne!(g.asset, missing);
assert!(!dst.assets.contains_key(&g.asset));
}
+
+ #[test]
+ fn pasted_missing_graphic_never_takes_an_asset_placed_later() {
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{Graphic, Item, ItemId, Shape, SpreadRef};
+ let mut src = Document::new(&NewDocument::default());
+ let mut dst = Document::new(&NewDocument::default());
+ // The source's missing id is ahead of the target's counter: the target would allocate it to its next image.
+ for _ in 0..50 {
+ src.alloc();
+ }
+ let missing = AssetId(src.alloc());
+ let iid = ItemId(src.alloc());
+ let mut it = Item::new(
+ iid,
+ src.default_layer(),
+ Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(0.0, 0.0, 9.0, 9.0)),
+ );
+ it.content = Content::Graphic(Graphic {
+ asset: missing,
+ size: (4.0, 4.0),
+ xf: designcraft_geom::Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [1.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ src.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let ids = super::super::object::duplicate_from(&mut dst, &src, &[iid], SpreadRef::Doc(0), designcraft_geom::Vec2::ZERO).unwrap();
+ let g = dst.item(ids[0]).and_then(|i| i.graphic()).unwrap().asset;
+ assert!((0..100).all(|_| AssetId(dst.alloc()) != g), "a later image in the target takes the pasted graphic's id");
+ }
}
#[cfg(test)]
diff --cc crates/engine/src/cmd/mathexpr.rs
index 48550d846,ebeb35381..e0ec7a56b
--- a/crates/engine/src/cmd/mathexpr.rs
+++ b/crates/engine/src/cmd/mathexpr.rs
@@@ -25,8 -33,7 +25,9 @@@ fn math_item(d: &mut designcraft_doc::D
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ clip: None,
+ fill: Default::default(),
});
it.alt_text = latex.to_string();
it.name = "Math".into();
diff --cc crates/engine/src/cmd/media.rs
index f331c0f18,3c3af87f2..43c6cfacf
--- a/crates/engine/src/cmd/media.rs
+++ b/crates/engine/src/cmd/media.rs
@@@ -39,7 -38,7 +39,8 @@@ pub(crate) fn place_media(s: &mut Sessi
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it.media = Some(MediaOptions { controls: true, ..Default::default() });
fid
@@@ -57,7 -55,7 +58,8 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it.media = Some(MediaOptions { controls: true, ..Default::default() });
d.insert_item(spread, it, None)?;
diff --cc crates/engine/src/cmd/table.rs
index 5c8fb16d7,93c07e383..7f8b90e51
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@@ -1883,7 -1422,7 +1883,8 @@@ fn place_graphic(s: &mut Session, p: &V
auto_fit: if fill { designcraft_doc::Fitting::FillProportionally } else { designcraft_doc::Fitting::FitProportionally },
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
clamp_selection(d, sel);
Ok(json!({"asset": aid.0, "row": r, "col": c}))
diff --cc crates/engine/src/sample.rs
index 7964a43ff,448a64da0..0009b4adb
--- a/crates/engine/src/sample.rs
+++ b/crates/engine/src/sample.rs
@@@ -86,7 -85,7 +86,8 @@@ fn graphic_frame(d: &mut Document, sr:
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it.object_style = designcraft_doc::BASIC_GRAPHICS_FRAME.into();
d.insert_item(sr, it, None)?;
diff --cc crates/epub/src/lib.rs
index 15dfcfd40,5e62efbbc..84bf56f1e
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -1541,8 -1538,7 +1541,9 @@@ mod tests
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ clip: None,
+ wrap: Default::default(),
+ fill: Default::default(),
});
item
};
@@@ -1940,8 -1893,7 +1941,9 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ clip: None,
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
aid.0
@@@ -2056,7 -2008,7 +2058,8 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
diff --cc crates/epub/tests/grouped_reading_order.rs
index 5e1f570b1,000000000..fe2223091
mode 100644,000000..100644
--- a/crates/epub/tests/grouped_reading_order.rs
+++ b/crates/epub/tests/grouped_reading_order.rs
@@@ -1,171 -1,0 +1,172 @@@
+use std::io::{Cursor, Read};
+use std::sync::Arc;
+
+use designcraft_doc::build::NewDocument;
+use designcraft_doc::geom::{Affine, PathData, Rect, shapes};
+use designcraft_doc::{Article, Asset, AssetId, Content, Document, Graphic, Item, ItemId, ParaFormat, Shape, SpreadRef, StoryId};
+use designcraft_epub::{Block, EpubOptions, HtmlOptions, export_epub, export_html, reading_order};
+
+fn text(doc: &mut Document, spread: usize, x: f64, y: f64, value: &str) -> (ItemId, StoryId) {
+ doc.add_text_frame(SpreadRef::Doc(spread), Rect::new(x, y, x + 100.0, y + 10.0), doc.default_layer(), value, ParaFormat::default()).unwrap()
+}
+
+fn group(doc: &mut Document, spread: usize, ids: &[ItemId], xf: Affine) -> ItemId {
+ let children = {
+ let sp = doc.spread_mut(SpreadRef::Doc(spread)).unwrap();
+ let children: Vec<_> = ids.iter().map(|id| sp.items.iter().find(|it| it.id == *id).unwrap().clone()).collect();
+ sp.items.retain(|it| !ids.contains(&it.id));
+ children
+ };
+ let id = ItemId(doc.alloc());
+ let mut item = Item::new(id, doc.default_layer(), Shape::Group, PathData::default());
+ item.content = Content::Group { items: children };
+ item.xf = xf;
+ doc.insert_item(SpreadRef::Doc(spread), item, None).unwrap()
+}
+
+fn outputs(doc: &Document) -> [String; 2] {
+ let html = export_html(doc, &HtmlOptions::default());
+ let bytes = export_epub(doc, &EpubOptions::default()).unwrap();
+ let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
+ let mut xhtml = String::new();
+ zip.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut xhtml).unwrap();
+ [html, xhtml]
+}
+
+fn assert_output_order(doc: &Document, values: &[&str]) {
+ let positions: Vec<_> = ["HTML", "EPUB"]
+ .into_iter()
+ .zip(outputs(doc))
+ .map(|(format, output)| {
+ let positions: Vec<_> =
+ values.iter().map(|value| output.find(value).unwrap_or_else(|| panic!("{value} missing from {format}"))).collect();
+ for value in values {
+ assert_eq!(output.matches(value).count(), 1, "{value} should occur once in {format}");
+ }
+ (format, positions)
+ })
+ .collect();
+ assert!(positions.iter().all(|(_, p)| p.windows(2).all(|p| p[0] < p[1])), "wrong export order for {values:?}: {positions:?}");
+}
+
+#[test]
+fn translated_group_uses_its_spread_y_position_in_both_exports() {
+ let mut doc = Document::new(&NewDocument::default());
+ let (child, _) = text(&mut doc, 0, 36.0, 50.0, "Grouped second");
+ group(&mut doc, 0, &[child], Affine::translate((0.0, 300.0)));
+ text(&mut doc, 0, 36.0, 200.0, "Ungrouped first");
+ assert_output_order(&doc, &["Ungrouped first", "Grouped second"]);
+}
+
+#[test]
+fn translated_group_uses_its_spread_x_position_on_the_same_line() {
+ let mut doc = Document::new(&NewDocument::default());
+ let (child, _) = text(&mut doc, 0, 10.0, 200.0, "Grouped right");
+ group(&mut doc, 0, &[child], Affine::translate((350.0, 0.0)));
+ text(&mut doc, 0, 200.0, 200.0, "Ungrouped left");
+ assert_output_order(&doc, &["Ungrouped left", "Grouped right"]);
+}
+
+#[test]
+fn translated_group_uses_the_page_at_its_spread_position() {
+ let mut doc = Document::new(&NewDocument { pages: 3, facing_pages: true, ..Default::default() });
+ assert_eq!(doc.spreads[1].pages.len(), 2);
+ let width = doc.spreads[1].pages[0].width;
+ let (child, _) = text(&mut doc, 1, 36.0, 36.0, "Grouped right page");
+ group(&mut doc, 1, &[child], Affine::translate((width, 0.0)));
+ text(&mut doc, 1, 36.0, 400.0, "Ungrouped left page");
+ assert_output_order(&doc, &["Ungrouped left page", "Grouped right page"]);
+}
+
+#[test]
+fn nested_and_item_rotations_are_combined_before_measuring_graphics() {
+ let mut doc = Document::new(&NewDocument::default());
+ let aid = AssetId(doc.alloc());
+ // Original one-pixel SVG, constructed in the test rather than copied from a fixture.
+ doc.assets.insert(
+ aid,
+ Arc::new(Asset {
+ id: aid,
+ name: "Grouped image".into(),
+ mime: "image/svg+xml".into(),
+ link: None,
+ data: Arc::new(br#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"><rect width="1" height="1" fill="red"/></svg>"#.to_vec()),
+ pixels: None,
+ page: 0,
+ pdf_crop: Default::default(),
+ pdf_box: None,
+ }),
+ );
+ let image = ItemId(doc.alloc());
+ let mut item = Item::new(image, doc.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 10.0)));
+ item.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (1.0, 1.0),
+ xf: Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ // The export writes the alt text, not the file name.
+ item.alt_text = "Grouped image".into();
+ item.xf = Affine::rotate(std::f64::consts::FRAC_PI_4);
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ let inner = group(&mut doc, 0, &[image], Affine::rotate(-std::f64::consts::FRAC_PI_4));
+ group(&mut doc, 0, &[inner], Affine::translate((50.0, 100.0)));
+ text(&mut doc, 0, 50.0, 75.0, "Text above image");
+ // The two rotations cancel: the image's top is y=100, not the y=50 obtained
+ // by rotating the already axis-aligned bounds of its rotated local path.
+ assert_output_order(&doc, &["Text above image", "Grouped image"]);
+}
+
+#[test]
+fn a_threaded_story_keeps_the_position_of_its_first_frame() {
+ let mut doc = Document::new(&NewDocument::default());
+ let (head, sid) = text(&mut doc, 0, 36.0, 50.0, "Threaded story");
+ let (tail, _) = text(&mut doc, 0, 36.0, 10.0, "");
+ doc.thread(head, tail).unwrap();
+ group(&mut doc, 0, &[head], Affine::translate((0.0, 300.0)));
+ let (_, first) = text(&mut doc, 0, 36.0, 200.0, "Standalone first");
+ assert_output_order(&doc, &["Standalone first", "Threaded story"]);
+ assert_eq!(reading_order(&doc), vec![Block::Story(first), Block::Story(sid)]);
+}
+
+#[test]
+fn articles_keep_their_explicit_order_and_exclusions() {
+ let mut doc = Document::new(&NewDocument::default());
+ let (a, _) = text(&mut doc, 0, 36.0, 50.0, "Article first");
+ let (b, _) = text(&mut doc, 0, 36.0, 30.0, "Article second");
+ let grouped = group(&mut doc, 0, &[a, b], Affine::translate((0.0, 300.0)));
+ let (c, _) = text(&mut doc, 0, 36.0, 10.0, "Article third");
+ let (omitted, _) = text(&mut doc, 0, 36.0, 5.0, "Excluded story");
+ doc.articles.push(Article { name: "Unused".into(), items: vec![omitted], export: false });
+ doc.articles.push(Article { name: "Chosen".into(), items: vec![grouped, c, grouped], export: true });
+ assert_output_order(&doc, &["Article first", "Article second", "Article third"]);
+ for output in outputs(&doc) {
+ assert!(!output.contains("Excluded story"));
+ }
+}
+
+#[test]
+fn stable_ties_and_the_existing_item_hidden_filter_are_preserved() {
+ let mut doc = Document::new(&NewDocument::default());
+ let (a, _) = text(&mut doc, 0, 36.0, 100.0, "First tie");
+ let (hidden, _) = text(&mut doc, 0, 36.0, 100.0, "Hidden child");
+ doc.item_mut(hidden).unwrap().hidden = true;
+ group(&mut doc, 0, &[a, hidden], Affine::IDENTITY);
+ text(&mut doc, 0, 36.0, 100.0, "Second tie");
+ let (hidden, _) = text(&mut doc, 0, 36.0, 50.0, "Hidden root");
+ doc.item_mut(hidden).unwrap().hidden = true;
+ text(&mut doc, 0, 36.0, 5.0, "");
+ let parent = doc.default_layer();
+ doc.add_text_frame(SpreadRef::Parent(0), Rect::new(36.0, 0.0, 136.0, 10.0), parent, "Parent text", ParaFormat::default()).unwrap();
+ assert_output_order(&doc, &["First tie", "Second tie"]);
+ for output in outputs(&doc) {
+ for omitted in ["Hidden child", "Hidden root", "Parent text"] {
+ assert!(!output.contains(omitted), "{omitted} should remain excluded");
+ }
+ }
+}
diff --cc crates/format/src/lib.rs
index 3fc4ea8a2,7c87dd9e6..50d48fb21
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@@ -385,7 -336,7 +385,8 @@@ mod tests
auto_fit: Default::default(),
fit_align: 4,
crop: [crop; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
id
diff --cc crates/idml/src/import.rs
index 078e3ed13,84d2d3de0..014524386
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -2958,7 -2507,11 +2958,11 @@@ impl<'r> Importer<'r>
_ => {
if let Some(g) = e.elements().find(|c| matches!(c.local(), "Image" | "PDF" | "EPS" | "ImportedPage" | "WMF" | "PICT" | "SVG")) {
it.content = self.graphic(g);
+ let fill = self.image_fill(g);
+ if let Content::Graphic(gr) = &mut it.content {
+ gr.fill = fill;
+ }
- if let (Some(ff), Content::Graphic(gr)) = (e.elements().find(|c| c.local() == "FrameFittingOption"), &mut it.content) {
+ if let (Some(ff), Content::Graphic(gr)) = (self.with_style(e, "FrameFittingOption"), &mut it.content) {
gr.crop = [ff.num("TopCrop"), ff.num("LeftCrop"), ff.num("BottomCrop"), ff.num("RightCrop")].map(|v| v.unwrap_or(0.0));
gr.fit_align = ff.get("FittingAlignment").map_or(4, names::anchor_in);
if ff.get("AutoFit") == Some("true") {
@@@ -3009,9 -2569,7 +3025,10 @@@
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ // A wrap set on the placed graphic (Direct Selection) is stored on the graphic element,
+ // over the graphic's own object style when it names one.
+ wrap,
+ fill: Default::default(),
})
};
let mut data = g.prop_el("Contents").map(|c| base64_decode(&c.text_content())).unwrap_or_default();
diff --cc crates/idml/src/tests/assets.rs
index b72a1f9e3,f15af1777..23ec31f34
--- a/crates/idml/src/tests/assets.rs
+++ b/crates/idml/src/tests/assets.rs
@@@ -198,24 -192,53 +198,75 @@@ fn a_pdf_placement_reads_its_page_numbe
}
}
+/// Two crops of one linked PDF page are two assets, so each frame keeps its own crop; the same
+/// page and crop placed again shares an asset, and the file is read once per page and crop.
+#[test]
+fn a_pdf_page_placed_with_two_crops_imports_as_two_assets() {
+ let bytes = b"%PDF-1.7\n% fixture".to_vec();
+ let reads = Cell::new(0);
+ let reader = |p: &str| {
+ reads.set(reads.get() + 1);
+ p.ends_with("insert.pdf").then(|| bytes.clone())
+ };
+ let frames = vec![pdf_frame(1, 0.0, 1, "CropTrim"), pdf_frame(2, 100.0, 1, "CropMedia"), pdf_frame(3, 200.0, 1, "CropTrim")];
+ let d = import_idml_with(&package(&frames), &reader).unwrap();
+ let p = placements(&d);
+ let crop = |id| d.assets.get(&id).map(|a| (a.page, a.pdf_crop));
+ assert_eq!(crop(p[0].0), Some((0, PdfCrop::Trim)));
+ assert_eq!(crop(p[1].0), Some((0, PdfCrop::Media)));
+ assert_ne!(p[0].0, p[1].0, "another crop of the same page is another asset");
+ assert_eq!(p[0].0, p[2].0, "the same page and crop share one asset");
+ assert_eq!(d.assets.len(), 2);
+ assert_eq!(reads.get(), 2);
+}
++
+ /// The swatch applied to a placed image (`<Image FillColor FillTint>`) colours a greyscale or
+ /// bitmap image in InDesign (#1094). Black at 100%, InDesign's own value for an image nobody
+ /// coloured, and None leave the image as it is, like a missing attribute.
+ #[test]
+ fn the_swatch_applied_to_an_image_is_kept() {
+ let bytes = vec![42u8; 300];
+ let reader = |p: &str| p.ends_with("couple.jpg").then(|| bytes.clone());
+ let coloured = |n: usize, attrs: &str| image(n, PHOTO, None).replacen(&format!(r#"Self="im{n}""#), &format!(r#"Self="im{n}" {attrs}"#), 1);
+ let frames = vec![
+ frame(1, 0.0, 0.0, &coloured(1, r#"FillColor="Color/Brand" FillTint="50""#)),
+ frame(2, 100.0, 0.0, &coloured(2, r#"FillColor="Color/Black" FillTint="-1""#)),
+ frame(3, 200.0, 0.0, &coloured(3, r#"FillColor="Swatch/None""#)),
+ frame(4, 300.0, 0.0, &image(4, PHOTO, None)),
+ frame(5, 400.0, 0.0, &coloured(5, r#"FillColor="Color/u9""#)),
+ frame(6, 500.0, 0.0, &coloured(6, r#"FillColor="Color/Black" FillTint="40""#)),
+ ];
+ let fills = |d: &Document| {
+ let mut v: Vec<(f64, (String, f32))> = d.spreads[0]
+ .items
+ .iter()
+ .filter_map(|i| match &i.content {
+ Content::Graphic(g) => Some((i.xf.translation().x, (g.fill.swatch.clone(), g.fill.tint))),
+ _ => None,
+ })
+ .collect();
+ v.sort_by(|a, b| a.0.total_cmp(&b.0));
+ v.into_iter().map(|(_, f)| f).collect::<Vec<_>>()
+ };
+ let none = || (designcraft_color::swatch::NONE.to_string(), 1.0);
+ let want = vec![
+ ("Brand".to_string(), 0.5),
+ none(),
+ none(),
+ none(),
+ ("C=10 M=20 Y=30 K=40".to_string(), 1.0),
+ (designcraft_color::swatch::BLACK.to_string(), 0.4),
+ ];
+ let d = import_idml_with(&package(&frames), &reader).unwrap();
+ assert_eq!(fills(&d), want);
+
+ let out = export_idml_with(&d, &ExportOptions::default());
+ let spreads = zip_text(&out, "Spreads/");
+ let images: Vec<&str> = spreads.split("<Image ").skip(1).map(|s| s.split('>').next().unwrap_or("")).collect();
+ assert_eq!(images.len(), 6);
+ // Only an image with a swatch says so; none of them gets an invented `Swatch/None`.
+ assert_eq!(images.iter().filter(|e| e.contains("FillColor=")).count(), 3, "{images:?}");
+ assert!(images.iter().any(|e| e.contains(r#"FillColor="Color/Brand""#) && e.contains(r#"FillTint="50""#)), "{images:?}");
+ assert!(!images.iter().any(|e| e.contains("Swatch/None")), "{images:?}");
+ assert_eq!(fills(&import_idml_with(&out, &reader).unwrap()), want);
+ }
diff --cc crates/images/src/lib.rs
index db9a197e3,daa508297..24eeedb5f
--- a/crates/images/src/lib.rs
+++ b/crates/images/src/lib.rs
@@@ -8,11 -8,11 +8,13 @@@ use std::sync::{Arc, OnceLock}
pub use resvg::usvg;
+pub mod colour;
mod eps;
+mod jpeg;
mod psd;
+ mod tone;
pub use eps::{bounding_box as eps_bounding_box, eps_proxy, is_eps};
+ pub use tone::{Tone, tone};
/// CSS pixels (SVG user units) → points.
pub const PT_PER_PX: f64 = 0.75;
diff --cc crates/pdf/src/export.rs
index d72e74fe1,c7b91f903..5eae34a77
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@@ -1474,6 -1381,83 +1477,83 @@@ impl Exporter<'_>
s.draw_image(img, size);
s.pop();
}
+
+ /// A greyscale or bitmap image coloured by the swatch applied to it (#1094): the swatch is
+ /// painted through the image's ink coverage (its darkness), over 0% ink for a greyscale
+ /// image, whose white is opaque. `false`, drawing nothing, when the image keeps its own
+ /// colours: no swatch, one that no longer exists, a colour image.
+ fn colorized(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic) -> bool {
+ if g.fill.is_none() {
+ return false;
+ }
+ let Some(asset) = self.doc.assets.get(&g.asset) else { return false };
+ let Some(tone) = designcraft_images::tone(&asset.data) else { return false };
+ let Some(paint) = self.swatch_color(&g.fill.swatch, g.fill.tint) else { return false };
+ let Some(coverage) = designcraft_images::decode_rgba(&asset.data).and_then(|img| CoverageImage::new(&img)) else { return false };
- let interpolate = RasterMode::for_standard(self.opts.standard).interpolate && self.interpolate;
++ let interpolate = RasterMode::for_standard(self.opts.standard).interpolate;
+ let Ok(mask) = Image::from_custom(coverage, interpolate) else { return false };
+ let size = Size::from_wh(g.size.0.max(1e-3) as f32, g.size.1.max(1e-3) as f32);
+ let (Some(size), Some(rect)) = (size, to_path(&Rect::new(0.0, 0.0, g.size.0, g.size.1).to_path(0.1))) else { return false };
+ s.push_transform(&tf(g.xf));
+ if tone == designcraft_images::Tone::Gray {
+ let blank =
+ self.swatch_color(designcraft_color::swatch::PAPER, 1.0).unwrap_or_else(|| device(&Color::cmyk(0.0, 0.0, 0.0, 0.0), self.rgb_only));
+ s.set_fill(Some(Fill { paint: blank.into(), ..Default::default() }));
+ s.draw_path(&rect);
+ }
+ let mut sb = s.stream_builder();
+ let mut ms = sb.surface();
+ ms.draw_image(mask, size);
+ ms.finish();
+ let stream = sb.finish();
+ s.push_mask(krilla::mask::Mask::new(stream, krilla::mask::MaskType::Luminosity));
+ s.set_fill(Some(Fill { paint: paint.into(), ..Default::default() }));
+ s.draw_path(&rect);
+ s.pop();
+ s.set_fill(None);
+ s.pop();
+ true
+ }
+ }
+
+ /// The ink coverage of a greyscale or bitmap image (255 = black, 0 = white or transparent) as a
+ /// DeviceGray image, painted into a luminosity mask.
+ #[derive(Clone, Hash)]
+ struct CoverageImage {
+ grey: Arc<Vec<u8>>,
+ size: (u32, u32),
+ }
+
+ impl CoverageImage {
+ fn new(rgba: &image::RgbaImage) -> Option<Self> {
+ let size = rgba.dimensions();
+ if size.0 == 0 || size.1 == 0 {
+ return None;
+ }
+ let grey = rgba.pixels().map(|p| ((u16::from(255 - p[0]) * u16::from(p[3]) + 127) / 255) as u8).collect();
+ Some(Self { grey: Arc::new(grey), size })
+ }
+ }
+
+ impl krilla::image::CustomImage for CoverageImage {
+ fn color_channel(&self) -> &[u8] {
+ &self.grey
+ }
+ fn alpha_channel(&self) -> Option<&[u8]> {
+ None
+ }
+ fn bits_per_component(&self) -> krilla::image::BitsPerComponent {
+ krilla::image::BitsPerComponent::Eight
+ }
+ fn size(&self) -> (u32, u32) {
+ self.size
+ }
+ fn icc_profile(&self) -> Option<&[u8]> {
+ None
+ }
+ fn color_space(&self) -> krilla::image::ImageColorspace {
+ krilla::image::ImageColorspace::Luma
+ }
}
/// `data` with its `%PDF-x.y` header (within the first 1024 bytes, where readers look for it)
diff --cc crates/pdf/src/pdfx.rs
index ff03e9a32,99978e5ee..75d661cf8
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@@ -482,7 -481,7 +482,8 @@@ mod tests
auto_fit: Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
}
diff --cc crates/pdf/src/tests.rs
index bfa6c4032,47534b34c..ed6a1ac1f
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@@ -250,7 -248,7 +250,8 @@@ fn place(d: &mut Document, data: Vec<u8
auto_fit: designcraft_doc::Fitting::FillProportionally,
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
}
diff --cc crates/pdf/tests/support/image_content_cache_contract.rs
index d81bc3abf,dfcd1ad75..2442c33a0
--- a/crates/pdf/tests/support/image_content_cache_contract.rs
+++ b/crates/pdf/tests/support/image_content_cache_contract.rs
@@@ -37,7 -36,7 +37,8 @@@ fn place_named(d: &mut Document, data:
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
}
diff --cc crates/pptx/src/tests.rs
index d8eed869b,f116d46d9..ba97a67b8
--- a/crates/pptx/src/tests.rs
+++ b/crates/pptx/src/tests.rs
@@@ -218,8 -218,7 +218,9 @@@ fn pictures_are_cropped_to_their_frames
auto_fit: designcraft_doc::Fitting::None,
fit_align: 0,
crop: [0.0; 4],
+ clip: None,
+ wrap: Default::default(),
+ fill: Default::default(),
});
});
let mut z = export(&d, &PptxOptions::default());
diff --cc crates/render/src/lib.rs
index 7f2ce3999,64b416112..297e8dab4
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -24,9 -24,9 +24,10 @@@ use vello_cpu::{Pixmap, RenderContext,
pub use vello_cpu;
mod blendspace;
+ mod colorize;
pub mod damage;
mod fx;
+mod grid;
/// How far (points) an object's soft effects reach outside its geometry.
pub fn effect_outset(it: &Item) -> f64 {
@@@ -875,21 -818,17 +876,23 @@@ impl Renderer
let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen };
let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone());
let data = if !hidden.is_empty() && is_pdf(&asset.data) { pdf_layers::layered(&asset.data, &hidden) } else { asset.data.clone() };
- let Some(pm) = images::mip(&data, asset.page, g.size.0, on_screen) else { return };
+ // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space.
+ let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]);
+ let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t));
+ let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h);
+ let Some(pm) = images::mip(&data, asset.page, page_w, on_screen) else { return };
- let pm = match PLATE.with(|p| p.get()) {
- Some(plate) => plate_pixmap(&pm, plate),
- None => pm,
+ // A coloured image is already in the plate's inks (its colours come from `color_of`).
+ let pm = match (colorize::colorized(f.doc, &g.fill, &asset.data, &pm), PLATE.with(|p| p.get())) {
+ (Some(coloured), _) => coloured,
+ (None, Some(plate)) => plate_pixmap(&pm, plate),
+ (None, None) => pm,
};
- let rect = Rect::new(0.0, 0.0, g.size.0, g.size.1);
+ // Only where the page is: a box reaching past it (a media box larger than the crop box)
+ // shows nothing there.
+ let rect = Rect::new(0.0, 0.0, g.size.0, g.size.1).intersect(page);
ctx.set_transform(f.view * xf * g.xf);
- let sx = g.size.0 / pm.width().max(1) as f64;
- let sy = g.size.1 / pm.height().max(1) as f64;
+ let sx = page_w / pm.width().max(1) as f64;
+ let sy = page_h / pm.height().max(1) as f64;
ctx.set_paint(vello_cpu::Image {
image: vello_cpu::ImageSource::Pixmap(pm),
sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium),
@@@ -1848,7 -1663,7 +1851,8 @@@ mod tests
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
let cache = Cache::new();
@@@ -1862,65 -1677,6 +1866,66 @@@
assert_eq!(px(DisplayQuality::Fast, &mut r)[..3], [178, 178, 178]);
}
+ #[test]
+ fn clipping_path_hides_the_image_outside_it() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let mut png = Vec::new();
+ image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))
+ .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
+ .unwrap();
+ let aid = designcraft_doc::AssetId(d.alloc());
+ d.assets.insert(
+ aid,
+ Arc::new(designcraft_doc::Asset {
+ page: 0,
+ id: aid,
+ name: "red.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(png),
+ pixels: Some((4, 4)),
+ ..Default::default()
+ }),
+ );
+ // A 100 pt image at 100,100 clipped by a triangle with its apex at the top middle.
+ let triangle = designcraft_geom::PathData::single(designcraft_geom::path::SubPath::polyline(
+ &[designcraft_geom::Point::new(0.0, 100.0), designcraft_geom::Point::new(50.0, 0.0), designcraft_geom::Point::new(100.0, 100.0)],
+ true,
+ ));
+ let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::PhotoshopPath, triangle);
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut it =
+ Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: aid,
+ size: (100.0, 100.0),
+ xf: Affine::translate((100.0, 100.0)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ clip: Some(Arc::new(clip.clone())),
++ fill: Default::default(),
+ });
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let cache = Cache::new();
+ let mut r = Renderer::new();
+ r.threads = 0;
+ let page = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();
+ assert_eq!(page.pixel(150, 170)[..3], [255, 0, 0], "inside the triangle");
+ assert_eq!(page.pixel(110, 110)[..3], [255, 255, 255], "inside the frame, outside the triangle: paper");
+ // Inverted: the corners show and the triangle is paper.
+ clip.invert = true;
+ if let Some(designcraft_doc::Content::Graphic(g)) = d.item_mut(id).map(|it| &mut it.content) {
+ g.clip = Some(Arc::new(clip));
+ }
+ let cache = Cache::new();
+ let page = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();
+ assert_eq!(page.pixel(150, 170)[..3], [255, 255, 255]);
+ assert_eq!(page.pixel(110, 110)[..3], [255, 0, 0]);
+ }
+
#[test]
fn missing_fonts_are_highlighted_on_screen_only() {
let mut d = Document::new(&NewDocument::default());
diff --cc crates/render/tests/colorize.rs
index 000000000,6ac0256c9..d00683b7c
mode 000000,100644..100644
--- a/crates/render/tests/colorize.rs
+++ b/crates/render/tests/colorize.rs
@@@ -1,0 -1,102 +1,104 @@@
+ //! A swatch applied to a placed greyscale or bitmap image colours it, as in InDesign (#1094):
+ //! a greyscale pixel is a tint of the swatch as strong as the pixel is dark, and white stays
+ //! opaque; a bitmap's black takes the swatch and its white lets the frame's fill show through.
+ //! Colour images, and swatches that no longer exist, leave the image as it is.
+
+ use std::sync::Arc;
+
+ use designcraft_color::swatch::apply_tint;
+ use designcraft_compose::Cache;
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{Asset, AssetId, Content, Document, Fill, Graphic, Item, ItemId, Shape, SpreadRef, Stroke};
+ use designcraft_geom::{Affine, Rect, shapes};
+ use designcraft_render::{RenderOptions, Renderer, color_of};
+ use image::{ExtendedColorType, ImageEncoder};
+
+ const RED: &str = "C=0 M=100 Y=100 K=0";
+ const CYAN: &str = "C=100 M=0 Y=0 K=0";
+
+ fn encode(px: &[u8], w: u32, ct: ExtendedColorType, gif: bool) -> Vec<u8> {
+ let mut b = Vec::new();
+ let c = std::io::Cursor::new(&mut b);
+ if gif {
+ image::codecs::gif::GifEncoder::new(c).encode(px, w, 1, ct).unwrap();
+ } else {
+ image::codecs::png::PngEncoder::new(c).write_image(px, w, 1, ct).unwrap();
+ }
+ b
+ }
+
+ /// The pixels at the centres of the image's three columns, placed 150 × 50 pt at (100, 100) in a
+ /// cyan frame, with `fill` applied to the image.
+ fn shown(file: Vec<u8>, fill: Fill) -> Vec<[u8; 4]> {
+ let mut d = Document::new(&NewDocument::default());
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
- Arc::new(Asset { page: 0, id: aid, name: "a".into(), mime: "image/png".into(), link: None, data: Arc::new(file), pixels: Some((3, 1)) }),
++ Arc::new(Asset { page: 0, id: aid, name: "a".into(), mime: "image/png".into(), link: None, data: Arc::new(file), pixels: Some((3, 1)), pdf_crop: Default::default(), pdf_box: None }),
+ );
+ let id = ItemId(d.alloc());
+ let mut it = Item::new(id, d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 250.0, 150.0)));
+ it.fill = Fill::swatch(CYAN);
+ it.stroke = Stroke::default();
+ it.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (150.0, 50.0),
+ xf: Affine::translate((100.0, 100.0)),
++ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
++ wrap: Default::default(),
+ fill,
+ });
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let mut r = Renderer::new();
+ r.threads = 0;
+ let img = r.render_page(&d, &Cache::new(), 0, 1.0, false, &RenderOptions::default()).unwrap();
+ [125, 175, 225].iter().map(|&x| img.pixel(x, 125)).collect()
+ }
+
+ /// The swatch `name` at `tint` on screen.
+ fn swatch_rgb(name: &str, tint: f32) -> [u8; 4] {
+ let d = Document::new(&NewDocument::default());
+ let [r, g, b, a] = color_of(&apply_tint(d.resolve_color(name, 1.0).unwrap(), tint), 1.0).to_rgba8().to_u8_array();
+ [r, g, b, a]
+ }
+
+ fn near(a: [u8; 4], b: [u8; 4]) -> bool {
+ a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 4)
+ }
+
+ #[test]
+ fn a_greyscale_image_is_a_tint_of_the_swatch_on_opaque_white() {
+ let grey = encode(&[0, 128, 255], 3, ExtendedColorType::L8, false);
+ let got = shown(grey.clone(), Fill::swatch(RED));
+ assert!(near(got[0], swatch_rgb(RED, 1.0)), "black is the swatch: {got:?}");
+ assert!(near(got[1], swatch_rgb(RED, 127.0 / 255.0)), "mid grey is half the swatch: {got:?}");
+ // White is 0% of the swatch, opaque: the cyan frame does not show through.
+ assert!(near(got[2], swatch_rgb(RED, 0.0)), "white stays white: {got:?}");
+ assert!(got[2][0] > 240, "{got:?}");
+
+ // The swatch's tint scales every pixel's.
+ let half = shown(grey, Fill { tint: 0.5, ..Fill::swatch(RED) });
+ assert!(near(half[0], swatch_rgb(RED, 0.5)), "{half:?}");
+ }
+
+ #[test]
+ fn a_bitmap_image_shows_the_frame_through_its_white() {
+ let bw = [[0u8, 0, 0, 255], [255, 255, 255, 255], [0, 0, 0, 255]].concat();
+ let got = shown(encode(&bw, 3, ExtendedColorType::Rgba8, true), Fill::swatch(RED));
+ assert!(near(got[0], swatch_rgb(RED, 1.0)) && near(got[2], got[0]), "{got:?}");
+ assert!(near(got[1], swatch_rgb(CYAN, 1.0)), "the frame's cyan through the white: {got:?}");
+ }
+
+ #[test]
+ fn colour_images_and_missing_swatches_are_left_alone() {
+ let rgb = encode(&[0, 0, 0, 200, 40, 40, 255, 255, 255], 3, ExtendedColorType::Rgb8, false);
+ assert_eq!(shown(rgb.clone(), Fill::swatch(RED)), shown(rgb, Fill::none()));
+ // A swatch that was deleted (or never imported): the image as it is.
+ let grey = encode(&[0, 128, 255], 3, ExtendedColorType::L8, false);
+ let plain = shown(grey.clone(), Fill::none());
+ assert_eq!(shown(grey, Fill::swatch("Gone")), plain);
+ assert!(plain[0][0] < 10, "the image is drawn: {plain:?}");
+ }
diff --cc crates/render/tests/placed_pdf.rs
index 0a7431a7d,3aac49adf..234e43ba7
--- a/crates/render/tests/placed_pdf.rs
+++ b/crates/render/tests/placed_pdf.rs
@@@ -85,7 -85,7 +85,8 @@@ fn placed(size: f64, pdf: Vec<u8>) -> R
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
let mut renderer = Renderer::new();
diff --cc crates/tools/src/tests.rs
index 17148be92,c069ee60c..57f94c9f5
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -1066,492 -1032,6 +1066,494 @@@ fn clicks_in_a_row_edit_and_select_text
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());
}
+/// A 100×100 frame at (100, 100) holding a 200×100 graphic that overhangs it.
+fn graphic_frame(doc: &mut Document) -> ItemId {
+ let id = ItemId(doc.alloc());
+ let mut item = Item::new(id, doc.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ item.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (200.0, 100.0),
+ xf: designcraft_geom::Affine::translate((50.0, 100.0)),
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ id
+}
+
+fn preview_params(a: &[Action]) -> serde_json::Value {
+ match a.last() {
+ Some(Action::Preview(cmd, p)) if cmd == "transform.move" => p.clone(),
+ other => panic!("{other:?}"),
+ }
+}
+
+#[test]
+fn direct_selection_drags_content_inside_its_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let none = Selection::default();
+ let mut t = create("directSelection");
+ let at = spread_pt(&l, 120.0, 130.0);
+ let a = t.pointer(&ctx(&d, &none, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let sel = Selection { content: true, ..Selection::items(vec![f]) };
+ let cx = ctx(&d, &sel, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0));
+ assert_eq!(a.first(), Some(&Action::Begin("Move Content".into())));
+ let p = preview_params(&a);
+ assert_eq!(
+ (p["dx"].as_f64(), p["dy"].as_f64(), &p["content"], &p["ids"]),
+ (Some(15.0), Some(-4.0), &serde_json::json!(true), &serde_json::json!([f.0]))
+ );
+ assert_eq!(t.cursor(&cx, at, Mods::default()), Cursor::HandGrab);
+ assert!(t.overlays(&cx).contains(&Overlay::ContentGhost(f)));
+ // Shift keeps the drag on one axis.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, at.x + 15.0, at.y - 4.0).with_mods(Mods { shift: true, ..Default::default() }));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64()), (Some(15.0), Some(0.0)));
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x + 15.0, at.y)), vec![Action::Commit]);
+}
+
+#[test]
+fn selection_tool_grabber_moves_content_elsewhere_moves_the_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let centre = spread_pt(&l, 150.0, 150.0);
+ let mut t = create("selection");
+ // Hovering the grabber shows the hand; it is there on hover before any click, too.
+ assert_eq!(t.cursor(&ctx(&d, &Selection::default(), &c, &l), centre, Mods::default()), Cursor::Hand);
+ let g = select::grabbers(&ctx(&d, &Selection::default(), &c, &l), Some(centre));
+ assert!(matches!(g.as_slice(), [(id, p)] if *id == f && near(*p, centre)), "{g:?}");
+ // Press on the grabber: the content is selected; the drag moves it.
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, centre.x, centre.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": true}))]);
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, centre.x - 20.0, centre.y + 10.0));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p["dy"].as_f64(), &p["content"]), (Some(-20.0), Some(10.0), &serde_json::json!(true)));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, centre.x - 20.0, centre.y + 10.0)), vec![Action::Commit]);
+ // A press elsewhere in the frame keeps the content selection; dragging selects and moves the frame.
+ let edge = spread_pt(&l, 115.0, 185.0);
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y)).is_empty());
+ let a = t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x + 30.0, edge.y));
+ assert_eq!(a[0], Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0]})));
+ assert_eq!(a[1], Action::Begin("Move".into()));
+ let p = preview_params(&a);
+ assert_eq!((p["dx"].as_f64(), p.get("content"), p.get("ids")), (Some(30.0), None, None));
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, edge.x + 30.0, edge.y));
+ // With the frame selected, a drag away from the grabber moves the frame.
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, edge.x, edge.y));
+ let a = t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Drag, edge.x, edge.y + 30.0));
+ assert_eq!(a[0], Action::Begin("Move".into()));
+ assert_eq!(preview_params(&a).get("content"), None);
+}
+
+#[test]
+fn double_click_toggles_frame_and_content() {
+ let mut d = Document::new(&NewDocument::default());
+ let f = graphic_frame(&mut d);
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let at = spread_pt(&l, 120.0, 180.0);
+ let mut t = create("selection");
+ let frame = Selection::items(vec![f]);
+ let content = Selection { content: true, ..Selection::items(vec![f]) };
+ let set = |content: bool| vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": content}))];
+ // The canvas's presses in a row: the first selects the frame, the second its content.
+ let a = t.pointer(&ctx(&d, &Selection::default(), &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y));
+ assert_eq!(a, vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": [f.0], "content": false}))]);
+ t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(true));
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y)).is_empty());
+ // With the content selected, the first press keeps it and the second selects the frame.
+ assert!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty());
+ t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Up, at.x, at.y));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &PointerEvent::new(PointerKind::Down, at.x, at.y).with_clicks(2)), set(false));
+ // A double click sent as such (control channel) toggles too.
+ let dbl = PointerEvent::new(PointerKind::DoubleClick, at.x, at.y);
+ assert_eq!(t.pointer(&ctx(&d, &frame, &c, &l), &dbl), set(true));
+ assert_eq!(t.pointer(&ctx(&d, &content, &c, &l), &dbl), set(false));
+}
+
+/// A 200 × 150 pt rectangle frame, selected.
+fn live_corner_doc() -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0));
+ (d, id)
+}
+
+fn corner_preview(a: &[Action]) -> Vec<(String, f64)> {
+ let p = match a {
+ [Action::Preview(cmd, p)] | [Action::Exec(cmd, p)] if cmd == "object.cornerOptions" => p,
+ other => panic!("{other:?}"),
+ };
+ p["corners"].as_array().unwrap().iter().map(|c| (c["shape"].as_str().unwrap().to_string(), c["size"].as_f64().unwrap())).collect()
+}
+
+fn diamonds(o: &[Overlay]) -> Vec<Point> {
+ o.iter().filter_map(|o| if let Overlay::LiveCornerDiamond(p) = o { Some(*p) } else { None }).collect()
+}
+
+#[test]
+fn live_corners_click_widget_then_drag_rounds_all_corners() {
+ let (d, id) = live_corner_doc();
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ // The widget sits on the right edge, a little below the top-right corner.
+ let w = at(300.0, 111.5);
+ assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(p) if near(*p, w))));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)), vec![Action::Handled]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y)).is_empty());
+ // Without corner sizes the diamonds sit 12 px along the top and bottom edges.
+ let want = [at(112.0, 100.0), at(288.0, 100.0), at(288.0, 250.0), at(112.0, 250.0)];
+ let got = diamonds(&t.overlays(&cx));
+ assert!(got.len() == 4 && got.iter().zip(want).all(|(g, w)| near(*g, w)), "{got:?}");
+ assert!(!t.overlays(&cx).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+ // Drag the top-left diamond 20 pt toward the centre.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, want[0].x, want[0].y));
+ assert_eq!(a, vec![Action::Begin("Corner Options".into())]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 20.0, want[0].y + 3.0));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 20.0); 4]);
+ // The size stops at half the shorter side.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, want[0].x + 500.0, want[0].y));
+ assert_eq!(corner_preview(&a), vec![("rounded".to_string(), 75.0); 4]);
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, want[0].x + 500.0, want[0].y)), vec![Action::Commit]);
+}
+
+#[test]
+fn live_corners_shift_drag_and_alt_click_change_one_corner() {
+ let (mut d, id) = live_corner_doc();
+ d.item_mut(id).unwrap().corners = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let at = |x, y| spread_pt(&l, x, y);
+ let mut t = create("selection");
+ let w = at(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ // With 30 pt corners the diamonds sit 30 pt along the edges.
+ let tr = at(270.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tr)));
+ let shift = Mods { shift: true, ..Default::default() };
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tr.x, tr.y).with_mods(shift));
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, tr.x - 10.0, tr.y).with_mods(shift));
+ let r = |n: f64| ("rounded".to_string(), n);
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(40.0), r(30.0), r(30.0)]);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, tr.x - 10.0, tr.y));
+ // Alt-click steps the bottom-right corner's shape; Shift+Alt steps every corner.
+ let br = at(270.0, 250.0);
+ let alt = Mods { alt: true, ..Default::default() };
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(alt));
+ assert_eq!(corner_preview(&a), vec![r(30.0), r(30.0), ("inverseRounded".to_string(), 30.0), r(30.0)]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, br.x - 30.0, br.y).with_mods(alt)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, br.x - 30.0, br.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, br.x, br.y).with_mods(Mods { alt: true, shift: true, ..Default::default() }));
+ assert_eq!(corner_preview(&a), vec![("inverseRounded".to_string(), 30.0); 4]);
+}
+
+#[test]
+fn live_corners_end_on_escape_empty_click_and_other_selection() {
+ let (mut d, id) = live_corner_doc();
+ let other = add_rect(&mut d, Rect::new(400.0, 100.0, 500.0, 200.0));
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let w = spread_pt(&l, 300.0, 111.5);
+ let mut t = create("selection");
+ let enter = |t: &mut Box<dyn Tool>| {
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ assert_eq!(diamonds(&t.overlays(&cx)).len(), 4);
+ };
+ // Escape leaves corner editing and keeps the selection; the next Escape deselects.
+ enter(&mut t);
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Handled]);
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]);
+ // A click on empty canvas.
+ enter(&mut t);
+ let e = spread_pt(&l, 350.0, 400.0);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, e.x, e.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, e.x, e.y));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // Another selection.
+ enter(&mut t);
+ let s2 = Selection { items: vec![other], ..Default::default() };
+ let cx2 = ctx(&d, &s2, &c, &l);
+ assert!(diamonds(&t.overlays(&cx2)).is_empty());
+ t.pointer(&cx2, &PointerEvent::new(PointerKind::Move, 0.0, 0.0));
+ assert!(diamonds(&t.overlays(&cx)).is_empty());
+ // A frame too small on screen has no widget.
+ let mut far = ctx(&d, &s, &c, &l);
+ far.zoom = 0.1;
+ assert!(!t.overlays(&far).iter().any(|o| matches!(o, Overlay::LiveCornerWidget(_))));
+}
+
+#[test]
+fn live_corner_diamonds_follow_a_rotated_frame() {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rotated(&mut d, Rect::new(100.0, 100.0, 300.0, 250.0), 30.0);
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let m = l.xf(SpreadRef::Doc(0)) * d.item(id).unwrap().xf;
+ let mut t = create("selection");
+ // The widget: 11.5 pt from the top-right corner along the turned right edge.
+ let w = m * Point::new(300.0, 111.5);
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y));
+ let tl = m * Point::new(112.0, 100.0);
+ assert!(diamonds(&t.overlays(&cx)).iter().any(|p| near(*p, tl)), "{:?}", t.overlays(&cx));
+ // Dragging along the turned top edge sets the size.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, tl.x, tl.y));
+ let to = m * Point::new(137.0, 100.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.x, to.y));
+ let got = corner_preview(&a);
+ assert!(got.iter().all(|(shape, size)| shape == "rounded" && (size - 25.0).abs() < 1e-6), "{got:?}");
+}
+
+#[test]
+fn pen_cursor_shows_add_delete_and_close() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 200.0, 200.0), lid, "", ParaFormat::default()).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let selected = Selection::items(vec![fid]);
+ let none = Selection::default();
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);
+ let mut t = create("pen");
+ let m = Mods::default();
+
+ let cx = ctx(&d, &selected, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::PenDelete, "on a selected path's anchor");
+ assert_eq!(t.cursor(&cx, at(150.0, 101.0), m), Cursor::PenAdd, "on a selected path's outline");
+ assert_eq!(t.cursor(&cx, at(150.0, 150.0), m), Cursor::Pen, "inside, away from the outline");
+ let click = |t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point| {
+ let down = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y));
+ let up = t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y));
+ (down, up)
+ };
+ let (down, up) = click(&mut t, &cx, at(200.0, 100.0));
+ assert_eq!(down, vec![Action::Exec("path.deleteAnchor".into(), serde_json::json!({"id": fid.0, "subpath": 0, "anchor": 1}))]);
+ assert!(up.is_empty() && !t.busy(), "deleting starts no path");
+ let (down, _) = click(&mut t, &cx, at(150.0, 101.0));
+ assert!(matches!(&down[..], [Action::Exec(cmd, p)] if cmd == "path.addAnchor" && p["id"] == fid.0), "{down:?}");
+
+ // Unselected paths are drawn over; the first anchor of the path being drawn closes it.
+ let cx = ctx(&d, &none, &c, &l);
+ assert_eq!(t.cursor(&cx, at(200.0, 100.0), m), Cursor::Pen, "unselected path");
+ click(&mut t, &cx, at(300.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(300.0, 300.0), m), Cursor::Pen, "one anchor cannot close yet");
+ click(&mut t, &cx, at(400.0, 300.0));
+ assert_eq!(t.cursor(&cx, at(301.0, 301.0), m), Cursor::PenClose, "on the first anchor");
+ assert_eq!(t.cursor(&cx, at(350.0, 350.0), m), Cursor::Pen, "elsewhere while drawing");
+}
+
+#[test]
+fn anchor_tools_show_pen_state_cursors() {
+ let d = Document::new(&NewDocument::default());
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let p = Point::new(10.0, 10.0);
+ let cursor = |id: &str| create(id).cursor(&cx, p, Mods::default());
+ assert_eq!(cursor("addAnchor"), Cursor::PenAdd);
+ assert_eq!(cursor("deleteAnchor"), Cursor::PenDelete);
+ assert_eq!(cursor("convertDirection"), Cursor::PenConvert);
+}
+
+/// A text frame holding a 3×3 table of 80 pt columns, optionally rotated about its centre.
+fn table_frame(degrees: f64) -> (Document, ItemId) {
+ let mut d = Document::new(&NewDocument::default());
+ let layer = d.default_layer();
+ let (id, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 400.0), layer, "", ParaFormat::default()).unwrap();
+ let tid = d.alloc();
+ d.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(tid, 3, 3, 0, 0, 240.0));
+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate_about(degrees.to_radians(), Point::new(250.0, 250.0));
+ (d, id)
+}
+
+#[test]
+fn type_tool_drags_a_table_column_border() {
+ for degrees in [0.0, 90.0] {
+ let (d, id) = table_frame(degrees);
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let it = d.item(id).unwrap();
+ let sid = it.text_frame().unwrap().story;
+ let cs = c.get(&d, sid, None);
+ let cell = cs.frames[0].tables[0].cell(1, 0).unwrap();
+ let xf = cx.item_canvas_xf(id).unwrap() * d.text_xf(it);
+ let on_border = xf * Point::new(cell.rect.x1 + 1.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let dragged = xf * Point::new(cell.rect.x1 + 21.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let mut t = create("type");
+ let expected = if degrees == 0.0 { Cursor::ResizeH } else { Cursor::ResizeV };
+ assert_eq!(t.cursor(&cx, on_border, Mods::default()), expected);
+ // A click with a 1 px wobble on the border changes nothing.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, on_border.x + 1.0, on_border.y)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, on_border.x + 1.0, on_border.y)).is_empty());
+ // A press on the border starts a resize, not a text selection.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y)).is_empty());
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(a[0], Action::Begin("Resize Column".into()));
+ let Action::Preview(cmd, p) = &a[1] else { panic!("{a:?}") };
+ assert_eq!(
+ (cmd.as_str(), &p["axis"], &p["index"], &p["frame"]),
+ ("table.resizeBorder", &serde_json::json!("column"), &serde_json::json!(0), &serde_json::json!(id.0))
+ );
+ assert!((p["delta"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}");
+ assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)), vec![Action::Commit]);
+ // Esc cancels a drag in progress.
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, on_border.x, on_border.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, dragged.x, dragged.y));
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, dragged.x, dragged.y)).is_empty());
+ // Inside the cell the Type tool places the caret as usual.
+ let inside = xf * Point::new(cell.rect.x0 + 20.0, (cell.rect.y0 + cell.rect.y1) / 2.0);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, inside.x, inside.y));
+ assert!(matches!(&a[..], [Action::Exec(cmd, _)] if cmd == "text.placeCaret"), "{a:?}");
+ }
+}
+
+#[test]
+fn eyedropper_samples_a_placed_image_and_matches_other_objects() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let photo = ItemId(d.alloc());
+ let mut it = Item::new(photo, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)));
+ it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic {
+ asset: designcraft_doc::AssetId(1),
+ size: (100.0, 100.0),
+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
++ fill: Default::default(),
+ });
+ d.assets.insert(
+ designcraft_doc::AssetId(1),
+ std::sync::Arc::new(designcraft_doc::Asset {
+ id: designcraft_doc::AssetId(1),
+ name: "photo.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(vec![]),
+ pixels: Some((100, 100)),
+ page: 0,
+ pdf_crop: Default::default(),
+ pdf_box: None,
+ }),
+ );
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ // An unfilled text frame over part of the photo lets it show through.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(150.0, 150.0, 250.0, 250.0), lid, "x", ParaFormat::default()).unwrap();
+ let swatch = add_rect(&mut d, Rect::new(300.0, 100.0, 350.0, 150.0));
+ d.item_mut(swatch).unwrap().fill.swatch = "[Black]".into();
+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));
+ // The photo's layer is locked: sampling it still works.
+ d.layers.iter_mut().for_each(|l| l.locked = true);
+ let s = Selection { items: vec![target], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("eyedropper");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ let sample = |x: f64, y: f64| Action::Exec("color.sample".into(), serde_json::json!({"at": [x, y], "spread": {"kind": "doc", "index": 0}}));
+ assert_eq!(a, vec![sample(120.0, 130.0)]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 180.0 + off.x, 180.0 + off.y));
+ assert_eq!(a, vec![sample(180.0, 180.0)], "through the text frame");
+ // With the toolbox's Stroke box in front, the colour goes to the stroke (a line has no fill).
+ let mut cx_stroke = ctx(&d, &s, &c, &l);
+ cx_stroke.stroke_in_front = true;
+ let a = t.pointer(&cx_stroke, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(
+ a,
+ vec![Action::Exec(
+ "color.sample".into(),
+ serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "target": "stroke"})
+ )]
+ );
+ // A filled object is matched as before (here on a locked layer: not reachable, so nothing).
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y)).is_empty());
+ let mut d2 = d.clone();
+ d2.layers.iter_mut().for_each(|l| l.locked = false);
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 320.0 + off.x, 120.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": swatch.0}))]);
+ // An image the pointer can reach names its frame, whose attributes apply where no pixel shows.
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ let sampled = serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}, "matchFrom": photo.0});
+ assert_eq!(a, vec![Action::Exec("color.sample".into(), sampled)]);
+ // Vector graphics and missing assets must retain the ordinary attribute-matching path.
+ for mime in ["application/pdf", "application/postscript", "image/svg+xml", "application/octet-stream"] {
+ std::sync::Arc::make_mut(d2.assets.get_mut(&designcraft_doc::AssetId(1)).unwrap()).mime = mime.into();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))], "{mime}");
+ }
+ d2.assets.clear();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a, vec![Action::Exec("object.matchAttributes".into(), serde_json::json!({"from": photo.0}))]);
+}
+
+#[test]
+fn double_clicking_a_handle_fits_the_frame_to_its_content_along_that_side() {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("selection");
+ for ((x, y), axis) in [((300.0, 200.0), "both"), ((200.0, 200.0), "height"), ((300.0, 150.0), "width")] {
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x + off.x, y + off.y));
+ assert_eq!(a, vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))], "{axis}");
+ }
+}
+
+#[test]
+fn fitting_handle_axes_follow_spread_and_frame_rotation() {
+ for spread_turn in 0..4 {
+ for frame_turn in 0..4 {
+ let mut d = Document::new(&NewDocument::default());
+ let id = add_rect(&mut d, Rect::new(100.0, 100.0, 300.0, 200.0));
+ d.item_mut(id).unwrap().xf = designcraft_geom::Affine::rotate(f64::from(frame_turn) * std::f64::consts::FRAC_PI_2);
+ Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = spread_turn;
+ let s = Selection { items: vec![id], ..Default::default() };
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let b = cx.selection_bounds().unwrap();
+ let mut t = create("selection");
+ let swapped = (spread_turn + frame_turn) % 2 == 1;
+ for (index, axis) in [(1, if swapped { "width" } else { "height" }), (3, if swapped { "height" } else { "width" }), (4, "both")] {
+ let p = select::handles(b)[index];
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, p.x, p.y));
+ assert_eq!(
+ a,
+ vec![Action::Exec("object.fit".into(), serde_json::json!({"mode": "fitFrameToContent", "axis": axis}))],
+ "spread={spread_turn}, frame={frame_turn}, handle={index}"
+ );
+ }
+ }
+ }
+}
+
#[test]
fn pen_continues_an_open_path_from_either_end_point() {
let mut d = Document::new(&NewDocument::default());
@@@ -1793,7 -1242,7 +1795,8 @@@ fn eyedropper_ignores_inactive_states_o
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
it
};
diff --cc crates/ui-egui/src/panels/properties.rs
index 6b4526f08,b7ac40dbc..6c33cbe77
--- a/crates/ui-egui/src/panels/properties.rs
+++ b/crates/ui-egui/src/panels/properties.rs
@@@ -2676,7 -2516,7 +2676,8 @@@ mod tests
auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
});
items.push(id);
assets.push(aid);
diff --cc docs/gaps.md
index 601469e13,a9b5d1c2d..2e04c7cb5
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -1,6 -1,6 +1,6 @@@
# Where DesignCraft falls short of InDesign
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input) · **Target:** Adobe InDesign 2026 (21.6)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (.indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6)
Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops an
InDesign professional from doing real work. This is the work list: agents pick from the top.
@@@ -189,10 -177,10 +189,12 @@@ Kind: **F** feature · **U** UI/UX · *
### 19. Placed graphics depth (FF)
- **Missing:** EPS is shown through its preview only (no PostScript interpreter); PSD layer
- comps beyond visibility; Edit Original / Edit With; PDF placed as editable vectors (#227, #24);
+ comps beyond visibility; the Clipping Path Options dialog (tracing into a clip that keeps the
+ frame, Threshold/Tolerance/Inset Frame preview, picking an alpha channel or a path saved in a
+ TIFF/PSD); Text Wrap › Same As Clipping following an imported clipping path; Edit Original / Edit With; PDF placed as editable vectors (#227, #24);
- QuarkXPress import (#73).
+ QuarkXPress import (#73); applying a swatch to a selected greyscale or bitmap image (Direct
+ Selection + Swatches). A swatch already on the image (IDML `<Image FillColor>`) colours it on
+ screen and in PDF and IDML export (#1094).
- **Estimate:** 30–60 h (PostScript interpreter is a large separate project: +80–150 h).
### 20. Performance on large documents (P)
diff --cc docs/target-app-parity.md
index e2f405fa5,25ff4a347..b7cb74c0b
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@@ -1,6 -1,6 +1,6 @@@
# DesignCraft parity with Adobe InDesign
- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent; object styles carry effects; colour management on craft-cms, Coated FOGRA39 default CMYK; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)
The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)
summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature