Skip to content

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

Merge upstream main a930276 into fix/idml-interchange: placed PDF crop on top of main's PDFAttribute page

aionggac524c4e7ac3
diff --cc ROADMAP.md
index a53591ed9,d60a6bf49..f49375a23
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -210,19 -212,285 +212,286 @@@ same references), and from the app's JS
## Milestones
| # | Milestone | State |
+ **Stage: pre-alpha** · next: alpha, ~0% and ~15–25 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%)
+
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes) · **Target:** Adobe InDesign 2026
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (parent canvas refresh) · **Target:** Adobe InDesign 2026
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (bounded control click/drag input) · **Target:** Adobe InDesign 2026
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text stroke behind fill) · **Target:** Adobe InDesign 2026
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Links source paths) · **Target:** Adobe InDesign 2026
+ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (table anchors keep their own paragraphs) · **Target:** Adobe InDesign 2026
+
+ DesignCraft aims at full Adobe InDesign parity, and to be better: faster, open (documented JSON
+ format + IDML), scriptable by agents (MCP), and available on the web.
+
+ ## Headline numbers
+
+ | | Value | Kind |
+ |---|---|---|
+ | **Feature breadth** | **~80%** (69% of InDesign 21.6's in-scope menu items matched; 99% of our 275-row checklist) | measured bounds, estimate between |
+ | **Ready for real work** | **~47%** (range 42–52%) | estimated: weighted sum over the dimensions below |
+ | Mainstream practitioner | **~42%** (weekly core 60.7% × 0.88 interaction × 0.92 stability × 0.85 file exchange) | estimated |
+ | Essentials user | **~54%** (core features 72% × 0.90 launch × 0.88 discoverability × 0.95 files received) | estimated |
+ | Remaining to **beta** | **420–750 Opus 5.5 agent-hours** (~120–200 wall-clock hours with 4–5 agents) | estimated |
+ | Remaining to **full parity** | **1,150–1,950 Opus 5.5 agent-hours** | estimated |
+
+ | Audience | Ready | Opus 5.5 agent-hours to ~95% | Work that dominates |
+ |---|---|---|---|
+ | Full target (ready for real work) | ~47% | 1,150–1,950 (~70% parallel) | depth across all areas, scripting compatibility, localization, typography fidelity, INDD/IDML |
+ | Mainstream practitioner | ~42% | 500–850 (~65% parallel) | INDD import and IDML corpus, composition fidelity, weekly-area depth, PDF/X-1a and printing |
+ | Essentials user | ~54% | 135–250 (~50% parallel) | start-up robustness, context menus and copy/paste, threading, fonts, Windows printing |
+
+ **Why pre-alpha:** it fails one of InDesign's core workflows, the alpha gate in
+ [docs/roadmap.md](docs/roadmap.md#alpha-gate). Text threads by hand (click a port, then click or
+ draw a frame; thread and unthread commands), but Primary Text Frame autoflow adds pages users
+ can't delete (#165). Everything else in the gate works end to end on macOS (document setup,
+ styles, images, object editing, PDF export, save and reopen), and ready for real work (~47%) is
+ above the alpha bar, so the Primary Text Frame page fixes are the whole distance to alpha.
+ Beyond that, beta needs INDD opening, IDML proven on real files, composition compared with
+ InDesign's, and basic editing fixed on Windows and Linux. Details:
+ [docs/target-app-parity.md](docs/target-app-parity.md).
+
+ ## By dimension
+
+ | Dimension | Ready | Hours | Doc |
+ |---|---|---|---|
+ | Features (depth) | 55% | 250–400 | [target-app-parity.md](docs/target-app-parity.md) |
+ | Typography and composition fidelity | 45% | 120–200 | [typography-parity.md](docs/typography-parity.md) |
+ | File formats | 40% | 150–250 + 20–60 (INDD) | [file-format-parity.md](docs/file-format-parity.md) |
+ | UI/UX fidelity | 45% | 120–180 | [ui-parity.md](docs/ui-parity.md) |
+ | Stability | 45% | 60–100 | [gaps.md](docs/gaps.md) |
+ | Performance | 65% | 40–80 | [gaps.md](docs/gaps.md) |
+ | Localization | 45% | 120–180 | [localization-parity.md](docs/localization-parity.md) |
+ | Platforms | 55% | 40–80 | [hardware-parity.md](docs/hardware-parity.md) |
+ | Hardware | 45% | 20–40 | [hardware-parity.md](docs/hardware-parity.md) |
+ | Ecosystem (scripting, plug-ins) | 15% | 150–250 | [gaps.md](docs/gaps.md) |
+ | AI features | 15% | 60–120 | [gaps.md](docs/gaps.md) |
+
+ All "Ready" figures are estimates; the weights and evidence are in target-app-parity.md.
+
+ ## Features
+
+ Breadth from [docs/parity-checklist.md](docs/parity-checklist.md) (`cargo xtask parity`,
+ measured); Ready estimated.
+
+ | Area | Breadth | Ready | Hours |
+ |---|---|---|---|
+ | Application shell & workspace | 99% | 55% | 40–60 |
+ | Documents, pages, spreads | 100% | 65% | 20–35 |
+ | Layers | 100% | 75% | 5–10 |
+ | Frames, shapes & paths | 100% | 60% | 25–40 |
+ | Transform | 100% | 70% | 10–20 |
+ | Fill, stroke, colour | 100% | 60% | 20–35 |
+ | Effects & transparency | 100% | 50% | 20–30 |
+ | Placing & links | 93% | 55% | 20–35 |
+ | Type & text frames | 99% | 45% | 40–60 |
+ | Typography | 100% | 45% | see typography-parity.md |
+ | Styles | 100% | 60% | 15–25 |
+ | Tables | 100% | 55% | 25–40 |
+ | Long documents | 100% | 45% | 30–50 |
+ | Interactivity & digital | 100% | 40% | 30–50 |
+ | Output & production | 92% | 55% | 40–70 |
+ | XML & automation | 100% | 35% | see Ecosystem |
+ | View & navigation | 100% | 65% | 10–20 |
+ | Undo, history, saving | 100% | 70% | 5–10 |
+ | Accessibility | 100% | 50% | 15–25 |
+
+ ## Languages
+
+ Interface strings translated, of 1,724 measured. Detail: [docs/localization-parity.md](docs/localization-parity.md).
+
+ | Language | Code | Status | Translated |
+ |---|---|---|---|
+ | English | en | full | 100% |
+ | Simplified Chinese | zh | partial (no canvas IME) | 83% |
+ | Spanish | es | partial | 83% |
+ | Hindi | hi | none | 0% |
+ | Arabic | ar | partial (RTL UI and composition) | 85% |
+ | French | fr | partial | 83% |
+ | Portuguese (Brazil) | pt-br | partial | 61% |
+ | Indonesian | id | none | 0% |
+ | Japanese | ja | partial (no canvas IME) | 95% |
+ | German | de | partial | 83% |
+ | Korean | ko | none | 0% |
+ | Vietnamese | vi | none | 0% |
+
+ Also shipped: Italian (85%), Ukrainian (83%), Georgian (100%).
+
+ ## Upcoming
+
+ Ranked; detail and estimates in [docs/roadmap.md](docs/roadmap.md), the full list in
+ [docs/gaps.md](docs/gaps.md).
+
+ 1. **Alpha gate:** Primary Text Frame page fixes: autoflow adds pages users can't delete (#165) (5–7 h)
+ 2. Basic editing on every platform: copy/paste, context menus, caret formatting (30–50 h)
+ 3. CI running `cargo xtask ci` on pull requests (4–8 h)
+ 4. Open INDD through a clean-room converter, owner decision on #114 (20–60 h)
+ 5. IDML real-file corpus and fixes (60–100 h)
+ 6. Composition oracle against InDesign; optical kerning; overset rule (80–140 h)
+ 7. Start on any GPU; find every installed font (25–50 h)
+
+ ## Documents
+
+ [target-app-parity.md](docs/target-app-parity.md) (assessment) · [gaps.md](docs/gaps.md) (work
+ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.md](docs/parity-checklist.md)
+ (presence checklist) · [typography-parity.md](docs/typography-parity.md) ·
+ [file-format-parity.md](docs/file-format-parity.md) · [ui-parity.md](docs/ui-parity.md) ·
+ [hardware-parity.md](docs/hardware-parity.md) · [localization-parity.md](docs/localization-parity.md) ·
+ [architecture.md](docs/architecture.md) · agents: [agents.md](docs/agents.md), [mcp.md](docs/mcp.md),
+ [control-protocol.md](docs/control-protocol.md) · CJK: [cjk.md](docs/cjk.md),
+ [cjk-typography.md](docs/cjk-typography.md) · Arabic: [arabic-typography.md](docs/arabic-typography.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-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-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.
+ - **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.
+ - **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.
+ - **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.
+ - **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.
+ - **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.
+ - **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.
+ - **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.
+ - **2026-10-15** · Flex Layout (InDesign 2026): Object › Flex Layout (Add to, Convert to, Remove) and a Flex Layout panel laid out as InDesign's, also in Properties. A container lays out its objects by direction, wrap, justification, the alignment grid, Fixed/Auto width and height, padding and spacing, after every edit; Add detects aligned objects (direction, Auto size, Space Between at their spacing); resizing a container reflows its objects instead of scaling them; dragging an object in one reorders it. Montilla Design's tutorial replays step for step. No readiness percentage change.
+ - **2026-10-14** · Layout › Margins and Columns and Layout › Create Guides are laid out as InDesign's: Margins in Top/Bottom and Inside/Outside pairs with a link button that makes all four the same, Rows and Columns side by side, Fit Guides to Margins or Page, and a Preview checkbox that shows the change on the canvas before OK. A measurement field works out arithmetic when you leave it (`0.4375 in*2` becomes `0.875 in`). No readiness percentage change.
+ - **2026-10-14** · The Pathfinder panel is laid out as InDesign's: Paths (Join, Open, Close, Reverse), Pathfinder, Convert Shape and Convert Point, each a row of icon buttons. Join Path closes an open path or joins two at their nearest ends (`path.join`), and Convert Point makes the selected points plain, corner, smooth or symmetrical (`path.convertPoints`). 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-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change.
+ - **2026-10-14** · Type › Fill with Placeholder Text fills a frame with paragraphs of a few sentences, as InDesign does, so one paragraph can be styled on its own (it was one long paragraph, and the filler ran sentences together, "interit.Ovid"). 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-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. 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 (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. 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** · 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** · 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 (now with Controlled by Parent) and Show Parent Page Overlay, which draws the parent page's size over a resized page. 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/Spread, 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, 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-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. 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** · 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** · The Text Wrap panel is laid out as InDesign's: the wrap buttons with Invert, and the four offsets (Top, Left, Bottom, Right) showing the object's values, with the link button that sets them all the same. It used to show a single offset, always 0. 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** · 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-14** · In a facing document, pages take their side from their section's page numbers, as InDesign shuffles them: a section that starts at 1 on a left page moves it to the right and the pages after it follow, with their objects. No readiness percentage change.
+ - **2026-10-14** · The Type menu follows InDesign's order (Size, Character ⌘T, Paragraph ⌥⌘T, Glyphs, the style panels, Notes, footnotes and endnotes, then the insert submenus and Show Hidden Characters); Current Page Number has ⌥⇧⌘N. No readiness percentage change.
+ - **2026-10-14** · Colour parameters: a bare `{c,m,y,k}` is always read as 0..100, so C 1 is a 1 % tint and no longer
+ solid cyan; fractions take the colour's own `{model: "cmyk", …}` form (#910). No readiness percentage change.
+ - **2026-10-14** · The Tools panel follows InDesign's: Gradient Swatch and Gradient Feather are tools of their own; in two columns Content Collector and Placer, Apply Color / Gradient / None and Normal / Preview each get a button; View Options holds Frame Edges, Rulers, Guides, Smart Guides, Baseline Grid and Hidden Characters; Apply Color (,) and Apply Gradient (.) reuse the last colour and gradient. 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** · 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** · 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-12** · Text threads by hand: click a selected text frame's in or out port to load
+ the text cursor, then click a frame to thread it, click empty space for a column-wide frame or
+ drag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the
+ frame just added; click the linked frame or double-click a port to break the thread.
+ `text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layers
+ refuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). No
+ readiness percentage change.
+ - **2026-10-14** · Georgian interface (`ka`, Edit ▸ Interface Language ▸ ქართული): every catalog key
+ translated, count captions as `noun: n`.
+ - **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change.
+ - **2026-10-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** · 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-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-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** · 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** · 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** · 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** · 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** · 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** · 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-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
+ - **2026-10-12** · 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** · 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** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
+ - **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
+ - **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.
+ - **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.
+ - **2026-10-12** · Save As, library edits and book collection edits persist prospective values before changing live state; failed writes preserve the document and existing collections. Save a Copy rebases data-source paths for its destination without changing the open document. 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** · 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 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** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
+ - **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.
+ - **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.
+ - **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.
+ - **2026-10-12** · 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-11** · Corner Options keep curved sides curved and round every corner point, including where an arc meets a line (a Pathfinder quarter circle with rounded corners stayed a triangle). No readiness percentage change.
+ - **2026-10-11** · `story.replaceRange`, `story.setText`, notes, footnotes, endnotes, type on a path and table cells read `\r` and `\r\n` as paragraph returns, as `frame.create` and `text.insert` already did. No readiness percentage change.
+ - **2026-10-11** · The View menu follows InDesign's: proofing first, then zoom, Rotate Spread, Screen Mode, Display Performance, rulers, Extras, Grids & Guides and Structure; the view items that sat at the end of the Type menu moved there. No readiness percentage change.
+ - **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.
+ - **2026-10-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-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.
+ - **2026-10-12** · 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** · Double-clicking the Fill or Stroke box in the Tools panel opens the Color Picker with the selection's colour, as in InDesign (it opened the Swatches panel). No readiness percentage change.
+ - **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-11** · Properties gains InDesign's Pathfinder section (Add, Subtract, Intersect, Exclude Overlap, Minus Back) with several objects selected; section titles and icon buttons have accessible names. No readiness percentage change.
+ - **2026-10-12** · The Eyedropper samples a placed image: clicking the photo with text (or objects) selected fills them with the image's colour under the pointer, as an unnamed colour (`color.sample`), as in InDesign. Images on locked layers can be sampled. No readiness percentage change.
+ - **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.
+ - **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.
+ - **2026-10-12** · A gradient feather on a group fades the group as one, on screen and in PDF. Before, the screen ignored it, and PDF masked the group with a box of zero size because a group has no path of its own. No readiness percentage change.
+ - **2026-10-12** · In a CMYK transparency blend space (print documents), blend modes blend in CMYK on screen as in InDesign. Color Dodge with 100% K text turns coloured areas under it white and leaves the paper alone, where RGB blending changed almost nothing. PDF export already did this. No readiness percentage change.
+ - **2026-10-11** · Moving a sheared and rotated text frame no longer leaves trails of text behind: canvas repaints cover the frame's whole text box, not just its outline. No readiness percentage change.
+ - **2026-10-12** · Words in capitals hyphenate like capitalized words (FERRUM COM-MODI), as in InDesign; Hyphenate Capitalized Words off keeps them whole. No readiness percentage change.
+ - **2026-10-12** · Load Swatches refuses an `.ase` file with more than 100,000 colors, and `swatch.load` merges a file of 100,000 colors in under 0.1 s (it took 9.6 s of CPU in a test build). No readiness percentage change.
+ - **2026-10-11** · `transform.move {copy}`, Edit › Duplicate and Step and Repeat return the copies' ids, so a script can go on with them. No readiness percentage change.
+ - **2026-10-11** · `object.fill` and `object.stroke` refuse a swatch name the document doesn't have (it painted nothing) and suggest the name meant (`Paper` → `[Paper]`). 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-11 (printing):** `file.printers` and `file.print` use craft-libs/craft-print for CUPS and Windows. DesignCraft retains PDF export, page selection, spreads, marks and bleed; dry runs create no temporary PDF or print job. Windows selects matching or default driver paper and shrinks oversized sheets without enlarging smaller ones; queue duplex defaults are preserved. Headless tests exercise exported bytes, job settings, dry runs and refusals; shared native Windows CI passes, including paused-queue submission and cleanup. PostScript, production print controls and physical output validation remain open. No readiness percentage change.
+
+ - **2026-10-10 (UI.4–UI.5):** Panel tabs can move into other groups, split the dock, float, resize and return to their saved locations through shared docking transactions. Layouts persist in custom workspaces; UI and control commands share the same validated action path. Shared pane geometry and widget-state theme application retain all five palettes and local fonts. Split panes send keyboard input only to the focused canvas and scope contextual toolbar IDs per pane. No readiness percentage change.
+ - **2026-10-10** · Version 0.6.0; releases add a Linux riscv64 tar.gz (cross-compiled, CLI
+ smoke-tested under QEMU).
+ - **2026-10-10** · Readiness per audience: full ~47% (method aligned with the standard, was
+ 42%), mainstream practitioner ~42%, essentials user ~54%, each with hours to ~95%.
+ - **2026-10-10** · Stage re-normalized to **pre-alpha** under craftrules' core-workflow gate: text
+ can't be threaded by hand (no out-port click, no thread command).
+ - **2026-10-10** · Full re-measure against InDesign 2026 21.6 (menu dump, bundle formats and
+ localizations, 124 issues): breadth ~80%, ready ~42% (down from the ~83% "including depth" of
+ 2026-10-04, on user evidence and the INDD gap); progress docs restructured to the craftrules
+ standard (`docs/parity.md` → `docs/parity-checklist.md`; new target-app-parity, gaps, roadmap,
+ architecture, typography, file-format, UI, hardware and localization docs). Landed today:
+ split columns (#295), PDF export options dialog (#196), column rules (#274), Paragraph Rules
+ dialog (#263), Character Style Options (#144), PDF/X-4 RGB handling (#223), Spanish
+ hyphenation (#222), Japanese (#272), Italian (#218) and Ukrainian (#236) interfaces, relocated packages relink (#244), graphics backend chosen
+ before the window (#297), IDML table styles (#288), warichu (#280), list numbering from IDML
+ (#298), security hardening (#153, #155), many text-composition fixes (#282–#293).
+ - **2026-10-09** · Version 0.5.0; many user reports triaged into issues (#160–#265).
+ - **2026-10-08** · Version 0.4.0.
+ - **2026-10-07** · Community PRs: data merge, Brazilian Portuguese, PDF/X-4 flags, Office fonts
+ on macOS; CJK 1.x (Korean line breaking, fallback fonts in Package); PrintCraft renamed PdfCraft.
+ - **2026-10-06** · Snapping to parent items, Windows packaging, ARM64 workflow, control-channel
+ hardening.
+ - **2026-10-05** · FreeBSD build; caret-boundary fixes.
+ - **2026-10-04** · Never-crash pass across importers and the engine; rotate spread view; kashida
+ in styles; previous estimate: breadth 99%, "~83% including depth", ~170 h remaining.
+ - **2026-10-03** · Release 0.1.1; separations, XML tagging, track changes, PDF/X-4 output
+ intent, split window, buttons, menu customization.
+ - **2026-10-02** · Hyperlinks/Bookmarks panels, conditional text, tagged PDF, lists across
+ stories, style groups, Glyphs panel, High Contrast theme.
+ - **2026-10-01** · First commit; skeleton, IDML, PDF, tables, footnotes, cross-references, index,
+ spelling and parallel composition on the first day.
+
+ ## Revision history
+
+ | Date | Change | Summary |
|---|---|---|
- | M0 | Skeleton + vertical slice | ✅ |
- | M1 | Selection, transform, layers, pages, MCP | in progress |
- | M2 | Type I (Type tool, threading, Character/Paragraph, composer) | in progress |
- | M3 | Styles (nested/GREP, bullets, keeps, span columns) | started |
- | M4 | Color & effects | started |
- | M5 | Graphics & links | started |
- | M6 | Files & export (native, IDML, PDF, PNG/JPEG) | in progress (IDML ✅, PDF export) |
- | M7 | Long documents (sections, TOC, index, footnotes, books) | in progress (sections, TOC, text variables/running heads, hyperlinks, bookmarks, footnotes, cross-references, index) |
- | M8 | Tables | ✅ core (table/cell styles, rotation, diagonal lines pending) |
- | M9 | Performance (MT composition, tiles) | in progress (glyph path cache, bounded RTL label layout cache, culling, parallel compose 6.7× faster, perf harness) |
- | M10 | Find/Change, spelling, Preflight | in progress (Find/Change ✅, spelling ✅, Preflight) |
- | M11 | Layout power features (liquid/alternate layouts, data merge) | started (data merge phase 1, step & repeat, snippets) |
- | M12 | Interactive & digital (EPUB, HTML, interactive PDF) | started (EPUB, PDF links/bookmarks) |
- | M13 | Automation (scripts, batch) | |
- | M14 | 1.0 polish & packaging | |
+ | 2026-10-12 | minor | Manual text threading landed; alpha distance 15–25 h → 5–7 h (Primary Text Frame page fixes, #165) |
+ | 2026-10-10 | minor | Full number 42% → 47% (method aligned with the standard: plain weighted sum, no new evidence); readiness table with hours per audience |
+ | 2026-10-10 | minor | Headline adds mainstream practitioner (~42%) and essentials user (~54%); method in docs/target-app-parity.md |
+ | 2026-10-10 | minor | Stage alpha → pre-alpha under the new core-workflow gate: manual text threading is missing; alpha gate table added to docs/roadmap.md |
+ | 2026-10-10 | major | Restructured to the progress-docs standard; full re-measure; the "Working today" inventory moved to docs/target-app-parity.md, milestones to docs/roadmap.md, the CLI/MCP section left to docs/agents.md (which already covered it) |
+ | 2026-10-04 | major | Parity estimate: breadth 99%, depth ~83%, ~170 h |
+ | 2026-10-01 | major | First roadmap: status, milestones |
diff --cc crates/doc/src/assets.rs
index 000000000,cff196fc0..f880001ce
mode 000000,100644..100644
--- a/crates/doc/src/assets.rs
+++ b/crates/doc/src/assets.rs
@@@ -1,0 -1,411 +1,424 @@@
+ //! Placed files (assets): one asset per distinct file, the assets a document uses, and the
+ //! compaction a save applies (duplicates merged, unused assets left out).
+ //!
+ //! An asset holds what is shared by every placement of a file (bytes, link, type, the PDF page
-//! shown); each placement's frame data (transform, crop, fitting) lives on its [`Graphic`].
++//! and crop shown); each placement's frame data (transform, crop, fitting) lives on its [`Graphic`].
+
+ use std::collections::{BTreeMap, BTreeSet, HashMap};
+ use std::hash::BuildHasher;
+ use std::sync::Arc;
+
+ use crate::story::Story;
+ use crate::{Asset, AssetId, Content, Document, Item};
+
+ /// Nesting limit for groups, anchored objects, table cells and notes. A document nested deeper
+ /// is treated as using every asset, so nothing it references is merged away or pruned.
+ const MAX_DEPTH: usize = 64;
+
+ impl Asset {
- /// Whether `other` holds the same file: the same type, page, link and bytes. Files at
++ /// Whether `other` holds the same file: the same type, PDF page and crop, link and bytes. Files at
+ /// different paths stay apart even with identical bytes, since each can be updated or
+ /// relinked on its own. Assets without bytes (a link that couldn't be read) are the same only
+ /// when they link to the same path.
+ pub fn same_file(&self, other: &Asset) -> bool {
- if self.mime != other.mime || self.page != other.page {
++ if self.mime != other.mime || self.page != other.page || self.pdf_crop != other.pdf_crop {
+ return false;
+ }
+ if self.link != other.link {
+ return false;
+ }
+ match (self.data.is_empty(), other.data.is_empty()) {
+ (false, false) => self.same_bytes(other),
+ (true, true) => self.link.is_some(),
+ _ => false,
+ }
+ }
+
+ fn same_bytes(&self, other: &Asset) -> bool {
+ Arc::ptr_eq(&self.data, &other.data) || (self.data.len() == other.data.len() && *self.data == *other.data)
+ }
+ }
+
+ /// The asset in `assets` holding the same file as `asset`.
+ pub fn find_same_asset(assets: &BTreeMap<AssetId, Arc<Asset>>, asset: &Asset) -> Option<AssetId> {
+ assets.values().find(|a| a.same_file(asset)).map(|a| a.id)
+ }
+
+ /// Add `asset` to `assets` unless they already hold the same file; returns the id placements
+ /// should reference. A new asset with the bytes of an existing one shares its buffer.
+ pub fn insert_asset(assets: &mut BTreeMap<AssetId, Arc<Asset>>, mut asset: Asset) -> AssetId {
+ if let Some(id) = find_same_asset(assets, &asset) {
+ return id;
+ }
+ if !asset.data.is_empty()
+ && let Some(a) = assets.values().find(|a| a.same_bytes(&asset))
+ {
+ asset.data = Arc::clone(&a.data);
+ }
+ let id = asset.id;
+ assets.insert(id, Arc::new(asset));
+ id
+ }
+
+ /// Calls `f` with every asset reference in `it` and its children; false when nesting exceeded
+ /// [`MAX_DEPTH`] (some references weren't visited).
+ fn item_refs(it: &Item, f: &mut impl FnMut(AssetId), depth: usize) -> bool {
+ if depth > MAX_DEPTH {
+ return false;
+ }
+ if let Content::Graphic(g) = &it.content {
+ f(g.asset);
+ }
+ if let Some(p) = it.media.as_ref().and_then(|m| m.poster) {
+ f(p);
+ }
+ it.children().iter().all(|c| item_refs(c, f, depth + 1))
+ }
+
+ /// Asset references in a story's anchored objects, graphic cells and notes (recursively).
+ fn story_refs(st: &Story, f: &mut impl FnMut(AssetId), depth: usize) -> bool {
+ if depth > MAX_DEPTH {
+ return false;
+ }
+ let mut complete = st.objects.iter().all(|o| item_refs(&o.item, f, depth + 1));
+ for t in st.tables.values() {
+ for c in &t.cells {
+ if let Some(g) = &c.graphic {
+ f(g.asset);
+ }
+ complete &= story_refs(&c.text, f, depth + 1);
+ }
+ }
+ for n in st.notes.iter().chain(&st.endnotes) {
+ complete &= story_refs(&n.text, f, depth + 1);
+ }
+ complete
+ }
+
+ /// Every asset reference in a story (its anchored objects, graphic cells and notes).
+ pub fn story_asset_refs(st: &Story) -> Vec<AssetId> {
+ let mut out = Vec::new();
+ story_refs(st, &mut |a| out.push(a), 0);
+ out
+ }
+
+ /// Point a story's references to a key of `map` at its value.
+ pub fn remap_story_assets(st: &mut Story, map: &HashMap<AssetId, AssetId>) {
+ if !map.is_empty() {
+ remap_story(st, map, 0);
+ }
+ }
+
+ fn item_uses(it: &Item, map: &HashMap<AssetId, AssetId>) -> bool {
+ let mut hit = false;
+ item_refs(it, &mut |a| hit |= map.contains_key(&a), 0);
+ hit
+ }
+
+ fn story_uses(st: &Story, map: &HashMap<AssetId, AssetId>) -> bool {
+ let mut hit = false;
+ story_refs(st, &mut |a| hit |= map.contains_key(&a), 0);
+ hit
+ }
+
+ fn remap_id(id: &mut AssetId, map: &HashMap<AssetId, AssetId>) {
+ if let Some(n) = map.get(id) {
+ *id = *n;
+ }
+ }
+
+ /// Rewrites the references in `it`, copying only the shared items that change.
+ fn remap_item(it: &mut Arc<Item>, map: &HashMap<AssetId, AssetId>, depth: usize) {
+ if depth > MAX_DEPTH || !item_uses(it, map) {
+ return;
+ }
+ remap_item_in(Arc::make_mut(it), map, depth);
+ }
+
+ fn remap_item_in(it: &mut Item, map: &HashMap<AssetId, AssetId>, depth: usize) {
+ if let Content::Graphic(g) = &mut it.content {
+ remap_id(&mut g.asset, map);
+ }
+ if let Some(p) = it.media.as_mut().and_then(|m| m.poster.as_mut()) {
+ remap_id(p, map);
+ }
+ if let Some(kids) = it.children_mut() {
+ for k in kids {
+ remap_item(k, map, depth + 1);
+ }
+ }
+ }
+
+ fn remap_story(st: &mut Story, map: &HashMap<AssetId, AssetId>, depth: usize) {
+ if depth > MAX_DEPTH {
+ return;
+ }
+ for o in &mut st.objects {
+ if item_uses(&o.item, map) {
+ remap_item_in(&mut Arc::make_mut(o).item, map, depth + 1);
+ }
+ }
+ for t in st.tables.values_mut() {
+ if !t.cells.iter().any(|c| c.graphic.as_ref().is_some_and(|g| map.contains_key(&g.asset)) || story_uses(&c.text, map)) {
+ continue;
+ }
+ for c in &mut Arc::make_mut(t).cells {
+ if let Some(g) = &mut c.graphic {
+ remap_id(&mut g.asset, map);
+ }
+ remap_story(&mut c.text, map, depth + 1);
+ }
+ }
+ for n in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {
+ if story_uses(&n.text, map) {
+ remap_story(&mut Arc::make_mut(n).text, map, depth + 1);
+ }
+ }
+ }
+
+ impl Document {
+ /// Add a placed file, reusing the asset of an identical file already in the document;
+ /// returns the id to reference.
+ pub fn add_asset(&mut self, asset: Asset) -> AssetId {
+ insert_asset(&mut self.assets, asset)
+ }
+
+ /// Copy asset `id` of `src` into this document (or reuse the identical asset it already
+ /// has); returns the id to reference here, `None` when `src` has no such asset.
+ pub fn adopt_asset(&mut self, src: &Document, id: AssetId) -> Option<AssetId> {
+ let a = src.assets.get(&id)?;
+ if let Some(same) = find_same_asset(&self.assets, a) {
+ return Some(same);
+ }
+ let fresh = AssetId(self.alloc());
+ Some(self.add_asset(Asset { id: fresh, ..(**a).clone() }))
+ }
+
+ /// Calls `f` with every asset reference: graphics on document and parent spreads (in
+ /// groups and multi-state objects too), media posters, anchored and inline objects, graphic
+ /// table cells and notes. False when nesting exceeded the depth limit.
+ fn asset_refs(&self, f: &mut impl FnMut(AssetId)) -> bool {
+ let mut complete = true;
+ for sp in self.spreads.iter().chain(&self.parents) {
+ for it in &sp.items {
+ complete &= item_refs(it, f, 0);
+ }
+ }
+ for st in self.stories.values() {
+ complete &= story_refs(st, f, 0);
+ }
+ complete
+ }
+
+ /// The assets something in the document references. When the document nests deeper than
+ /// the traversal limit, every asset counts as used.
+ pub fn used_assets(&self) -> BTreeSet<AssetId> {
+ let mut used = BTreeSet::new();
+ if !self.asset_refs(&mut |a| {
+ used.insert(a);
+ }) {
+ return self.assets.keys().copied().collect();
+ }
+ used
+ }
+
+ /// Point every reference to a key of `map` at its value.
+ pub fn remap_assets(&mut self, map: &HashMap<AssetId, AssetId>) {
+ if map.is_empty() {
+ return;
+ }
+ for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) {
+ if sp.items.iter().any(|it| item_uses(it, map)) {
+ for it in &mut Arc::make_mut(sp).items {
+ remap_item(it, map, 0);
+ }
+ }
+ }
+ for st in self.stories.values_mut() {
+ if story_uses(st, map) {
+ remap_story(Arc::make_mut(st), map, 0);
+ }
+ }
+ }
+
+ /// Merge assets holding the same file into the first of them (lowest id), rewriting the
+ /// references; returns how many assets were removed.
+ pub fn merge_duplicate_assets(&mut self) -> usize {
+ if !self.asset_refs(&mut |_| {}) {
+ return 0;
+ }
+ let fingerprint = std::collections::hash_map::RandomState::new();
+ let mut hashes = HashMap::new();
+ let mut reps: HashMap<_, Vec<&Arc<Asset>>> = HashMap::new();
+ let mut map = HashMap::new();
+ for a in self.assets.values() {
+ // Empty, unlinked assets never compare equal. Don't build a quadratic bucket
+ // of them, and hash a shared immutable buffer only once per compaction.
+ if a.data.is_empty() && a.link.is_none() {
+ continue;
+ }
+ let hash = *hashes.entry(Arc::as_ptr(&a.data)).or_insert_with(|| fingerprint.hash_one(a.data.as_slice()));
+ let bucket = reps.entry((hash, a.mime.as_str(), a.page, a.link.as_deref())).or_default();
+ // A fingerprint only selects candidates; equality still checks the actual file.
+ match bucket.iter().find(|r| r.same_file(a)) {
+ Some(r) => {
+ map.insert(a.id, r.id);
+ }
+ None => bucket.push(a),
+ }
+ }
+ self.remap_assets(&map);
+ self.assets.retain(|id, _| !map.contains_key(id));
+ map.len()
+ }
+
+ /// Merge duplicate assets and drop the ones nothing references (what a saved file holds).
+ pub fn compact_assets(&mut self) {
+ self.merge_duplicate_assets();
+ let used = self.used_assets();
+ self.assets.retain(|id, _| used.contains(id));
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use crate::{Graphic, ItemId, LayerId, Shape, StoryId};
+ use designcraft_geom::{Affine, Rect, shapes};
+
+ fn asset(id: u64, data: &[u8]) -> Asset {
- Asset { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), link: None, data: Arc::new(data.to_vec()), pixels: None, page: 0 }
++ Asset { id: AssetId(id), name: "p.png".into(), mime: "image/png".into(), data: Arc::new(data.to_vec()), ..Default::default() }
+ }
+
+ #[test]
+ fn equal_size_assets_keep_distinct_contents_and_merge_exact_copies() {
+ let mut d = Document::new(&Default::default());
+ for id in 1..=256u64 {
+ let mut bytes = vec![42; 1024];
+ bytes[1016..].copy_from_slice(&id.to_le_bytes());
+ d.assets.insert(AssetId(id), Arc::new(asset(id, &bytes)));
+ d.assets.insert(AssetId(id + 256), Arc::new(asset(id + 256, &bytes)));
+ }
+ assert_eq!(d.merge_duplicate_assets(), 256);
+ assert_eq!(d.assets.len(), 256);
+ for id in 1..=256u64 {
+ assert_eq!(d.assets[&AssetId(id)].data[1016..], id.to_le_bytes());
+ }
+ }
+
+ #[test]
+ fn compaction_preserves_asset_identity_and_missing_data_rules() {
+ let mut d = Document::new(&Default::default());
+ let mut cases = vec![asset(1, b"same"), asset(2, b"same"), asset(3, b"same"), asset(4, b"same")];
+ cases[1].mime = "application/pdf".into();
+ cases[2].page = 1;
+ cases[3].link = Some("/linked.png".into());
+ cases.extend([asset(5, b""), asset(6, b""), asset(7, b""), asset(8, b"")]);
+ cases[6].link = Some("/missing.png".into());
+ cases[7].link = Some("/missing.png".into());
+ for a in cases {
+ d.assets.insert(a.id, Arc::new(a));
+ }
+ assert_eq!(d.merge_duplicate_assets(), 1);
+ assert_eq!(d.assets.keys().copied().collect::<Vec<_>>(), (1..=7).map(AssetId).collect::<Vec<_>>());
+ }
+
++ /// Two crops of one PDF page are two assets: merging them would show one crop in both frames.
++ #[test]
++ fn pdf_assets_with_different_crops_stay_apart() {
++ let mut d = Document::new(&Default::default());
++ let pdf = |id: u64, pdf_crop: crate::PdfCrop| Asset { mime: "application/pdf".into(), pdf_crop, ..asset(id, b"%PDF-") };
++ let crop = d.add_asset(pdf(1, crate::PdfCrop::Crop));
++ let trim = d.add_asset(pdf(2, crate::PdfCrop::Trim));
++ assert_ne!(crop, trim);
++ assert_eq!(d.add_asset(pdf(3, crate::PdfCrop::Trim)), trim);
++ assert_eq!(d.merge_duplicate_assets(), 0);
++ assert_eq!(d.assets.len(), 2);
++ }
++
+ #[test]
+ #[cfg(not(target_arch = "wasm32"))]
+ #[ignore = "manual bounded timing comparison; no timing assertion"]
+ fn equal_size_assets_timing() {
+ for count in [500, 1000, 2000] {
+ let mut d = Document::new(&Default::default());
+ for id in 1..=count as u64 {
+ let mut bytes = vec![42; 8192];
+ bytes[8184..].copy_from_slice(&id.to_le_bytes());
+ d.assets.insert(AssetId(id), Arc::new(asset(id, &bytes)));
+ }
+ let start = std::time::Instant::now();
+ assert_eq!(d.merge_duplicate_assets(), 0);
+ eprintln!("{count} distinct 8 KiB assets: {:?}", start.elapsed());
+ }
+ }
+
+ fn graphic_item(id: u64, asset: u64, crop: f64) -> Item {
+ let mut it = Item::new(ItemId(id), LayerId(1), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
+ it.content = Content::Graphic(Graphic {
+ asset: AssetId(asset),
+ size: (10.0, 10.0),
+ xf: Affine::translate((crop, 0.0)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [crop; 4],
+ });
+ it
+ }
+
+ #[test]
+ fn identical_files_share_one_asset() {
+ let mut d = Document::new(&Default::default());
+ let a = d.add_asset(asset(1, b"same"));
+ let b = d.add_asset(asset(2, b"same"));
+ let c = d.add_asset(asset(3, b"diff"));
+ let p = d.add_asset(Asset { page: 1, ..asset(4, b"same") });
+ assert_eq!(a, b);
+ assert_ne!(a, c);
+ assert_ne!(a, p);
+ assert_eq!(d.assets.len(), 3);
+ // Unreadable links match by path only.
+ let m1 = d.add_asset(Asset { link: Some("/m/1.png".into()), ..asset(5, b"") });
+ let m2 = d.add_asset(Asset { link: Some("/m/2.png".into()), ..asset(6, b"") });
+ let m3 = d.add_asset(asset(7, b""));
+ let m4 = d.add_asset(asset(8, b""));
+ assert_ne!(m1, m2);
+ assert_ne!(m3, m4);
+ }
+
+ #[test]
+ fn files_at_different_paths_stay_separate_assets() {
+ let mut d = Document::new(&Default::default());
+ let linked = |id, path: &str| Asset { link: Some(path.into()), ..asset(id, b"same") };
+ let embedded = d.add_asset(asset(1, b"same"));
+ let a = d.add_asset(linked(2, "/p/a.png"));
+ let b = d.add_asset(linked(3, "/q/b.png"));
+ assert_eq!(d.add_asset(linked(4, "/p/a.png")), a, "the same path placed again");
+ assert_eq!(d.assets.len(), 3);
+ assert!(embedded != a && a != b && embedded != b);
+ assert_eq!(d.assets[&embedded].link, None);
+ assert_eq!(d.assets[&b].link.as_deref(), Some("/q/b.png"));
+ assert!(Arc::ptr_eq(&d.assets[&a].data, &d.assets[&b].data), "identical bytes share one buffer");
+ }
+
+ #[test]
+ fn compaction_merges_duplicates_and_drops_unused_assets() {
+ let mut d = Document::new(&Default::default());
+ for (id, data) in [(1, b"one"), (2, b"one"), (3, b"two"), (4, b"old")] {
+ d.assets.insert(AssetId(id), Arc::new(asset(id, data)));
+ }
+ let sp = Arc::make_mut(d.spreads.first_mut().unwrap());
+ sp.items.push(Arc::new(graphic_item(10, 1, 1.0)));
+ sp.items.push(Arc::new(graphic_item(11, 2, 2.0)));
+ // A graphic cell and an anchored object in a story.
+ let mut st = Story::new(StoryId(20));
+ st.objects.push(Arc::new(crate::AnchoredObject::new(graphic_item(12, 3, 3.0), Default::default())));
+ d.stories.insert(StoryId(20), Arc::new(st));
+ assert_eq!(d.used_assets(), [1, 2, 3].map(AssetId).into_iter().collect());
+
+ d.compact_assets();
+ assert_eq!(d.assets.keys().copied().collect::<Vec<_>>(), vec![AssetId(1), AssetId(3)]);
+ let crops: Vec<(AssetId, f64)> = d.spreads[0].items.iter().filter_map(|i| i.graphic().map(|g| (g.asset, g.crop[0]))).collect();
+ assert_eq!(crops, vec![(AssetId(1), 1.0), (AssetId(1), 2.0)]);
+ }
+ }
diff --cc crates/doc/src/lib.rs
index 440ef6bc9,c0fdc8fe2..cb87bea86
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@@ -448,81 -446,18 +446,91 @@@ pub struct Asset
/// The page shown from a multi-page PDF (0-based; Image Import Options).
#[serde(default, skip_serializing_if = "is_zero")]
pub page: u32,
+ /// Image Import Options › Crop to: the page box a placed PDF shows.
+ #[serde(default, skip_serializing_if = "PdfCrop::is_crop")]
+ pub pdf_crop: PdfCrop,
+ /// Where the `pdf_crop` box sits on the page as rendered (its visible crop box, rotated as it
+ /// displays): left, top, right, bottom as fractions of the page's width and height. Graphic
+ /// space (0,0)-(w,h) spans this box. `None`: the whole page, or a Bounding Box crop not
+ /// measured yet (`designcraft_render::shown_box` measures it when the graphic is drawn).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pdf_box: Option<[f64; 4]>,
+}
+
+impl Asset {
+ /// The part of the page a placed PDF shows, when [`Asset::pdf_box`] holds a usable box.
+ pub fn shown_box(&self) -> Option<[f64; 4]> {
+ self.shown(self.pdf_box?)
+ }
+
+ /// `b` as the part of the page this asset shows: a usable box of a placed PDF.
+ pub fn shown(&self, b: [f64; 4]) -> Option<[f64; 4]> {
+ // A box under 1/10000 of the page, or far outside it, would blow the page up to sizes
+ // nothing can draw.
+ let usable = b.iter().all(|v| v.is_finite() && v.abs() <= 1e3) && b[2] - b[0] >= 1e-4 && b[3] - b[1] >= 1e-4;
+ (usable && self.mime == "application/pdf").then_some(b)
+ }
+
+ /// A Bounding Box crop ([`PdfCrop::ContentVisible`], [`PdfCrop::ContentAll`]) whose box isn't
+ /// stored yet: finding it needs the page's drawing interpreted.
+ pub fn content_box_pending(&self) -> bool {
+ self.pdf_box.is_none() && matches!(self.pdf_crop, PdfCrop::ContentVisible | PdfCrop::ContentAll) && self.mime == "application/pdf"
+ }
+}
+
+/// Image Import Options › Crop to: which box of a PDF page a placed PDF shows.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum PdfCrop {
+ /// The crop box: the page as PDF readers show it.
+ #[default]
+ Crop,
+ Art,
+ Trim,
+ Bleed,
+ Media,
+ /// The bounds of what the page draws, with the layers the PDF shows by default.
+ ContentVisible,
+ /// The bounds of what the page draws, with every layer on.
+ ContentAll,
+}
+
+impl PdfCrop {
+ pub const ALL: [PdfCrop; 7] =
+ [PdfCrop::ContentVisible, PdfCrop::ContentAll, PdfCrop::Crop, PdfCrop::Art, PdfCrop::Trim, PdfCrop::Bleed, PdfCrop::Media];
+
+ /// The name commands and files use (`crop`, `trim`, `contentVisible`…).
+ pub fn name(self) -> &'static str {
+ match self {
+ PdfCrop::Crop => "crop",
+ PdfCrop::Art => "art",
+ PdfCrop::Trim => "trim",
+ PdfCrop::Bleed => "bleed",
+ PdfCrop::Media => "media",
+ PdfCrop::ContentVisible => "contentVisible",
+ PdfCrop::ContentAll => "contentAll",
+ }
+ }
+
+ pub fn from_name(name: &str) -> Option<PdfCrop> {
+ PdfCrop::ALL.into_iter().find(|c| c.name() == name)
+ }
+
+ fn is_crop(&self) -> bool {
+ *self == PdfCrop::Crop
+ }
}
+ impl Asset {
+ /// A raster image (PNG, JPEG, GIF, WebP, TIFF, BMP, PSD), as opposed to a PDF, EPS or SVG.
+ pub fn is_raster(&self) -> bool {
+ matches!(
+ self.mime.as_str(),
+ "image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/tiff" | "image/bmp" | "image/vnd.adobe.photoshop"
+ )
+ }
+ }
+
fn is_zero(v: &u32) -> bool {
*v == 0
}
diff --cc crates/engine/src/cmd/datamerge/fill.rs
index 5628aef2d,6ecb1470d..8071e6931
--- a/crates/engine/src/cmd/datamerge/fill.rs
+++ b/crates/engine/src/cmd/datamerge/fill.rs
@@@ -355,21 -369,18 +369,18 @@@ fn place_image
};
let (nw, nh) = (f64::from(pw), f64::from(ph));
let mode = fitting_of(&options.fitting);
- let aid = AssetId(doc.alloc());
+ let fresh = AssetId(doc.alloc());
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| field.to_string());
let link = options.link_images.then(|| path.to_string_lossy().into_owned());
- doc.assets.insert(
- aid,
- Arc::new(Asset {
- id: aid,
- name,
- mime: designcraft_render::image_mime(&bytes).to_string(),
- link,
- data: Arc::new(bytes),
- pixels: Some((pw, ph)),
- ..Default::default()
- }),
- );
+ let aid = doc.add_asset(Asset {
+ id: fresh,
+ name,
+ mime: designcraft_render::image_mime(&bytes).to_string(),
+ link,
+ data: Arc::new(bytes),
+ pixels: Some((pw, ph)),
- page: 0,
++ ..Default::default()
+ });
let mut g = Graphic { asset: aid, size: (nw, nh), xf: Affine::translate((inner.x0, inner.y0)), auto_fit: mode, fit_align: 0, crop: [0.0; 4] };
if let Some(xf) = g.fitted(inner, mode) {
g.xf = xf;
diff --cc crates/engine/src/cmd/file.rs
index eab036573,f63f0d6e9..bb643634a
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -100,7 -103,7 +103,7 @@@ pub fn specs() -> Vec<CommandSpec>
"Place…",
["File"],
Some("Cmd+D"),
- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",
- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media, loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}",
++ "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor?: with no frame to fill and no x/y, an image loads into the place cursor (File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link?: keep the file linked (Links panel; default: the linkTextFiles preference)}",
has_doc,
file_place
),
@@@ -313,25 -347,19 +347,26 @@@ fn file_place(s: &mut Session, p: &Valu
.map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32))
.ok_or_else(|| bad("file.place", "can't read that PDF page"))?,
};
- // 72 ppi by default unless the file says otherwise; scale so it fits the page when huge.
- let (nw, nh) = eps_size.unwrap_or((pw as f64, ph as f64));
+ // 72 ppi by default unless the file says otherwise; scale so it fits the page when huge. PDF pages
+ // and SVGs keep their exact size: rounding it to whole points would stretch them unevenly.
+ let (nw, nh) = eps_size.or_else(|| designcraft_render::natural_size(&bytes, pdf_page as usize)).unwrap_or((pw as f64, ph as f64));
- // Image Import Options › Crop to: the frame shows that box of the PDF page.
- let crop_box = match str_param(p, "pdfCrop") {
- Some(k) if designcraft_render::is_pdf(&bytes) => {
- if !["crop", "trim", "bleed", "art", "media"].contains(&k) {
- return Err(bad("file.place", format!("unknown pdfCrop `{k}` (crop, trim, bleed, art, media)")));
- }
- designcraft_render::pdf_page_box(&bytes, pdf_page as usize, k).filter(|b| b.2 > 0.0 && b.3 > 0.0)
+ // Image Import Options › Crop to: the graphic spans that box of the PDF page.
+ let is_pdf = designcraft_render::is_pdf(&bytes);
+ let pdf_crop = match str_param(p, "pdfCrop") {
+ Some(k) if is_pdf => PdfCrop::from_name(k)
+ .ok_or_else(|| bad("file.place", format!("unknown pdfCrop `{k}` (crop, art, trim, bleed, media, contentVisible, contentAll)")))?,
+ _ => PdfCrop::Crop,
+ };
+ let mime = designcraft_render::image_mime(&bytes).to_string();
+ let mut asset = Asset { page: pdf_page, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), pdf_crop, ..Default::default() };
+ // The graphic's natural size: the box in points (the whole page when the box can't be found,
+ // and then the document says so).
+ let (bw, bh) = match crop_pdf(&mut asset) {
+ Some(size) => size,
+ None => {
+ asset.pdf_crop = PdfCrop::Crop;
+ (nw, nh)
}
- Some(_) => None,
- None => None,
};
let target_frame = super::id_param(p, "frame").or_else(|| {
let st = s.active()?;
@@@ -342,9 -370,15 +377,12 @@@
let px = p.get("x").and_then(Value::as_f64);
let py = p.get("y").and_then(Value::as_f64);
let want_w = p.get("width").and_then(Value::as_f64);
+ if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) {
- let mime = designcraft_render::image_mime(&bytes).to_string();
- let asset = Asset { page: pdf_page, id: AssetId(0), name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) };
- return load_cursor(s, asset, (nw, nh), crop_box);
++ return load_cursor(s, asset, (bw, bh));
+ }
s.edit(|d, sel| {
- let aid = AssetId(d.alloc());
- d.assets.insert(aid, Arc::new(Asset { id: aid, ..asset }));
+ let fresh = AssetId(d.alloc());
- let mime = designcraft_render::image_mime(&bytes).to_string();
- let aid = d.add_asset(Asset { page: pdf_page, id: fresh, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) });
++ let aid = d.add_asset(Asset { id: fresh, ..asset });
// The width the whole page (or image) gets; the height follows the proportions.
let w = match want_w {
Some(w) => w,
@@@ -356,14 -390,14 +394,14 @@@
let id = if let Some(fid) = target_frame {
let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;
let r = it.inner_bounds();
- // Fill frame proportionally.
+ // Fill the frame proportionally once. Auto-Fit stays off, so resizing the frame crops.
- let k = (r.width() / nw).max(r.height() / nh);
- let (gw, gh) = (nw * k, nh * k);
+ let k = (r.width() / bw).max(r.height() / bh);
+ let (gw, gh) = (bw * k, bh * k);
it.content = Content::Graphic(Graphic {
asset: aid,
- size: (nw, nh),
+ size: (bw, bh),
xf: Affine::translate((r.x0 + (r.width() - gw) / 2.0, r.y0 + (r.height() - gh) / 2.0)) * Affine::scale(k),
- auto_fit: designcraft_doc::Fitting::FillProportionally,
+ auto_fit: Default::default(),
fit_align: 4,
crop: [0.0; 4],
});
@@@ -458,31 -480,34 +496,33 @@@ pub(crate) fn read_source(p: &Value) -
fn place_load(s: &mut Session, p: &Value) -> Result<Value> {
let (bytes, name, link) = read_source(p)?;
let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;
+ let natural = designcraft_render::natural_size(&bytes, 0).unwrap_or((pw as f64, ph as f64));
+ let mime = designcraft_render::image_mime(&bytes).to_string();
- let asset = Asset { page: 0, id: AssetId(0), name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) };
- load_cursor(s, asset, natural, None)
++ let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() };
++ load_cursor(s, asset, natural)
+ }
+
+ /// Adds `asset` to the document (with a fresh id) and loads it into the place cursor.
-fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), crop: Option<(f64, f64, f64, f64)>) -> Result<Value> {
++fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result<Value> {
+ let name = asset.name.clone();
+ let (pw, ph) = asset.pixels.unwrap_or_default();
let aid = s.edit(|d, _| {
- let aid = AssetId(d.alloc());
- let mime = designcraft_render::image_mime(&bytes).to_string();
- d.assets.insert(
- aid,
- Arc::new(Asset {
- id: aid,
- name: name.clone(),
- mime,
- link: link.clone(),
- data: Arc::new(bytes),
- pixels: Some((pw, ph)),
- ..Default::default()
- }),
- );
- Ok(aid)
+ asset.id = AssetId(d.alloc());
+ Ok(d.add_asset(asset))
})?;
- s.loaded = Some((aid, (pw as f64, ph as f64)));
- s.loaded = Some(crate::LoadedGraphic { asset: aid, size, crop });
++ s.loaded = Some(crate::LoadedGraphic { asset: aid, size });
s.set_tool("placeGun");
- Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph}))
+ Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true}))
}
fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
- let (aid, (nw, nh)) = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
- let sr = super::spread_param(p, "spread");
- let crate::LoadedGraphic { asset: aid, size: (nw, nh), crop } =
- s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
++ let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
+ // Undo can remove the loaded graphic's asset.
+ if !s.doc()?.doc.assets.contains_key(&aid) {
+ s.loaded = None;
+ return Err(bad("place.drop", "the loaded graphic is no longer in the document"));
+ }
+ let sr = super::spread_param(p, "place.drop")?;
let lid = s.doc()?.active_layer;
let frame = super::id_param(p, "frame");
let rect = super::rect_param(p, "rect");
@@@ -720,57 -761,23 +774,75 @@@ mod pdf_crop_tests
assert!(t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "nope"})).is_err());
}
+ /// Placing with `trim` stores the choice; the graphic spans the trim box and draws only it,
+ /// even in a frame larger than the graphic.
+ #[test]
+ fn a_pdf_placed_with_its_trim_box_stores_and_draws_that_box() {
+ // Letter with a 9 pt bleed: black in the bleed's top-left corner and a black square inside.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
+ for rect in [[-9, -9, 0, 0], [10, 10, 30, 30]] {
+ let id = s.execute("frame.create", &json!({"rect": rect})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap();
+ }
+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();
+
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ // `width` is the whole page's (630 pt with its bleed): half size.
+ let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "trim", "width": 315, "x": 100, "y": 100})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let d = t.doc().unwrap().doc.clone();
+ let it = d.item(id).unwrap();
+ let g = it.graphic().unwrap().clone();
+ let a = &d.assets[&g.asset];
+ assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::Trim);
+ let b = a.shown_box().unwrap();
+ let want = [9.0 / 630.0, 9.0 / 810.0, 621.0 / 630.0, 801.0 / 810.0];
+ assert!(b.iter().zip(want).all(|(x, y)| (x - y).abs() < 1e-4), "{b:?}");
+ assert!((g.size.0 - 612.0).abs() < 1e-3 && (g.size.1 - 792.0).abs() < 1e-3, "{:?}", g.size);
+ let shown = (it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1));
+ let fb = it.bounds();
+ for (x, y) in [(shown.x0, 100.0), (shown.y0, 100.0), (shown.x1, 406.0), (shown.y1, 496.0), (fb.x1, 406.0), (fb.y1, 496.0)] {
+ assert!((x - y).abs() < 1e-3, "{shown:?} {fb:?}");
+ }
+
+ // A frame larger than the graphic still shows only the trim box.
+ t.edit(|d, _| {
+ d.item_mut(id).unwrap().path = designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(90.0, 90.0, 416.0, 506.0));
+ Ok(())
+ })
+ .unwrap();
+ let d = t.doc().unwrap().doc.clone();
+ let mut rr = designcraft_render::Renderer::new();
+ rr.threads = 0;
+ let img = rr.render_page(&d, &t.cache, 0, 1.0, false, &Default::default()).unwrap();
+ let dark = |x: u32, y: u32| img.pixel(x, y)[0] < 60;
+ // The page sits at 95.5: its bleed corner (95.5–100) is cut off, the square (105–115) shows
+ // where it is on the page.
+ assert!(!dark(97, 97), "the bleed is outside the trim box");
+ assert!(!dark(103, 103), "the page is offset by its bleed");
+ assert!(dark(110, 110), "the square inside the trim box");
+ }
++
+ #[test]
+ fn placed_pdf_keeps_its_exact_page_size() {
+ // A 100.4 x 50.4 pt page placed 100.4 pt wide is 50.4 pt tall, not stretched to whole points.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100.4, "height": 50.4, "pages": 1})).unwrap();
+ let b64 = s.execute("file.exportPdf", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "width": 100.4, "x": 0, "y": 0})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let d = &t.doc().unwrap().doc;
+ let it = d.item(id).unwrap();
+ let b = it.bounds();
+ assert!((b.width() - 100.4).abs() < 1e-3 && (b.height() - 50.4).abs() < 1e-3, "{b:?}");
+ let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("not a graphic") };
+ assert!((g.size.0 - 100.4).abs() < 1e-3 && (g.size.1 - 50.4).abs() < 1e-3, "{:?}", g.size);
+ }
}
#[cfg(test)]
diff --cc crates/engine/src/cmd/interchange.rs
index 3f7f96697,9b9520662..d8daab858
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@@ -32,8 -32,19 +32,21 @@@ fn export_idml(s: &mut Session, p: &Val
}
}
+ /// [`designcraft_idml::import_idml`] with the linked images read through [`crate::io`], so the
-/// automation read root applies to the paths the package names.
++/// automation read root applies to the paths the package names, and its PDF crops resolved.
+ pub(crate) fn import_idml_confined(bytes: &[u8]) -> designcraft_idml::Result<Document> {
- designcraft_idml::import_idml_with(bytes, &|path| crate::io::read_file(path).ok())
++ let mut d = designcraft_idml::import_idml_with(bytes, &|path| crate::io::read_file(path).ok())?;
++ resolve_pdf_crops(&mut d);
++ Ok(d)
+ }
+
/// Import IDML bytes; `dir` is the folder the package came from (for relative link lookup).
pub fn import(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<Document> {
+ import_report(bytes, dir).map(|(document, _)| document)
+ }
+
+ /// [`import`], with the problems that did not stop it (parts missing from the package, …).
+ pub fn import_report(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<(Document, Vec<String>)> {
#[cfg(not(target_arch = "wasm32"))]
let resolved = std::cell::RefCell::new(std::collections::HashMap::new());
let read = |link: &str| -> Option<Vec<u8>> {
@@@ -49,8 -60,8 +62,10 @@@
None
}
};
- let mut document = designcraft_idml::import_idml_with(bytes, &read).map_err(|e| EngineError::Other(e.to_string()))?;
+ let designcraft_idml::Imported { document, warnings } =
+ designcraft_idml::import_idml_report(bytes, &read).map_err(|e| EngineError::Other(e.to_string()))?;
++ let mut document = document;
+ resolve_pdf_crops(&mut document);
#[cfg(not(target_arch = "wasm32"))]
let document = {
let mut document = document;
@@@ -63,85 -74,9 +78,85 @@@
resolve_packaged_links(&mut document, dir);
document
};
- Ok(document)
+ Ok((document, warnings))
}
+/// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page,
+/// which the IDML reader can't (it doesn't parse PDFs). The box spans the graphic's
+/// `GraphicBounds`; a graphic without bounds takes the box's size. Bounding Box crops interpret
+/// the page's drawing to find the box, so they wait for drawing or export ([`designcraft_render::shown_box`],
+/// [`with_pdf_boxes`]) unless a graphic needs the box's size now.
+pub(crate) fn resolve_pdf_crops(d: &mut Document) {
+ use std::collections::{HashMap, HashSet};
+ use std::sync::Arc;
+
+ use designcraft_doc::{AssetId, Content, Item, PdfCrop};
+ let mut no_bounds: HashSet<AssetId> = HashSet::new();
+ for sp in d.spreads.iter().chain(&d.parents) {
+ for it in &sp.items {
+ it.walk(&mut |i| {
+ if let Content::Graphic(g) = &i.content
+ && !(g.size.0 > 0.0 && g.size.1 > 0.0)
+ {
+ no_bounds.insert(g.asset);
+ }
+ });
+ }
+ }
+ let mut sizes: HashMap<AssetId, (f64, f64)> = HashMap::new();
+ for a in d.assets.values_mut() {
+ if a.pdf_crop == PdfCrop::Crop || a.pdf_box.is_some() || (a.content_box_pending() && !no_bounds.contains(&a.id)) {
+ continue;
+ }
+ let a = Arc::make_mut(a);
+ if let Some(size) = super::file::crop_pdf(a) {
+ sizes.insert(a.id, size);
+ }
+ }
+ let no_size = |i: &Item| matches!(&i.content, Content::Graphic(g) if !(g.size.0 > 0.0 && g.size.1 > 0.0) && sizes.contains_key(&g.asset));
+ fn fix(it: &mut Arc<Item>, sizes: &HashMap<AssetId, (f64, f64)>, no_size: &dyn Fn(&Item) -> bool) {
+ let mut any = false;
+ it.walk(&mut |i| any |= no_size(i));
+ if !any {
+ return;
+ }
+ let it = Arc::make_mut(it);
+ if let Content::Graphic(g) = &mut it.content
+ && let Some(size) = sizes.get(&g.asset)
+ && !(g.size.0 > 0.0 && g.size.1 > 0.0)
+ {
+ g.size = *size;
+ }
+ for k in it.children_mut().into_iter().flatten() {
+ fix(k, sizes, no_size);
+ }
+ }
+ if sizes.is_empty() {
+ return;
+ }
+ for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {
+ for it in &mut Arc::make_mut(sp).items {
+ fix(it, &sizes, &no_size);
+ }
+ }
+}
+
+/// `d` with the boxes of its Bounding Box crops measured ([`resolve_pdf_crops`] leaves them for
+/// later), for writers that don't render: PDF export places the page by the box.
+pub(crate) fn with_pdf_boxes(d: &Document) -> std::borrow::Cow<'_, Document> {
+ if !d.assets.values().any(|a| a.content_box_pending()) {
+ return std::borrow::Cow::Borrowed(d);
+ }
+ let mut out = d.clone();
+ for a in out.assets.values_mut() {
+ if a.content_box_pending() {
+ // No usable box: the whole page.
+ std::sync::Arc::make_mut(a).pdf_box = designcraft_render::shown_box(a);
+ }
+ }
+ std::borrow::Cow::Owned(out)
+}
+
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINK_PATH_BYTES: usize = 128 * 1024;
diff --cc crates/engine/src/cmd/links.rs
index 1137a303d,9db6c6cb8..be5b05cd2
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@@ -15,8 -18,9 +18,9 @@@ use crate::{EngineError, Result, Sessio
pub fn specs() -> Vec<CommandSpec> {
vec![
- cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}]", has_doc, |s, _| {
- Ok(Value::Array(list(&s.doc()?.doc)))
- cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, pixels, uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| {
++ cmd!(query "links.list", "Links", [], None, "{} → [{asset, name, path, status: ok|modified|missing|embedded, pixels, pdfCrop (placed PDFs: the box shown), uses: [{id, page, ppi}]}], then linked text files: [{story, name, path, status (also tooLarge: unchanged size, too big to check), edited (the story was changed in the layout), uses: [{id, page}]}]", has_doc, |s, _| {
+ let d = s.doc()?.doc.clone();
+ Ok(Value::Array(list(&d, &mut s.text_link_checks)))
}),
cmd!(
"links.relink",
@@@ -136,9 -255,9 +255,10 @@@ fn list(d: &Document, checks: &mut Text
json!({"id": id.0, "page": page, "ppi": ppi})
})
.collect();
- json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status(a), "pixels": a.pixels, "uses": uses})
+ let pdf_crop = (a.mime == "application/pdf").then(|| a.pdf_crop.name());
+ json!({"asset": a.id.0, "name": a.name, "path": a.link, "status": status(a), "pixels": a.pixels, "pdfCrop": pdf_crop, "uses": uses})
})
+ .chain(texts)
.collect()
}
@@@ -232,10 -412,13 +415,14 @@@ fn update(s: &mut Session, p: &Value) -
let a = Arc::make_mut(a);
a.data = Arc::new(bytes.clone());
a.pixels = Some(*px);
+ super::file::crop_pdf(a);
}
}
- Ok(json!({"updated": n}))
+ let mut warnings = Vec::new();
+ for (sid, path, bytes, before) in &fresh_texts {
+ warnings.extend(reimport(d, *sid, path, bytes, *before)?);
+ }
+ Ok(json!({"updated": n, "warnings": warnings}))
})
}
@@@ -315,3 -498,453 +502,453 @@@ mod relink_folder_tests
let _ = std::fs::remove_dir_all(&dir);
}
}
+
+ #[cfg(test)]
+ mod shared_asset_tests {
+ use super::*;
+
+ fn png(w: u32, h: u32) -> Vec<u8> {
+ designcraft_render::Rendered { width: w, height: h, pixels: vec![200u8; (w * h * 4) as usize] }.to_png()
+ }
+
+ #[test]
+ fn placements_of_one_file_share_an_asset_and_saves_drop_replaced_ones() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let a = super::super::file::base64_encode(&png(10, 10));
+ s.execute("file.place", &json!({"base64": a, "name": "a.png", "x": 72, "y": 72})).unwrap();
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ s.execute("file.place", &json!({"base64": a, "name": "a.png", "x": 200, "y": 72})).unwrap();
+ let l = s.execute("links.list", &json!({})).unwrap();
+ assert_eq!(l.as_array().unwrap().len(), 1);
+ assert_eq!(l[0]["uses"].as_array().unwrap().len(), 2);
+ assert_eq!(s.doc().unwrap().doc.assets.len(), 1);
+
+ // A new image into a frame: the old asset stays in memory (undo) but not in the file.
+ let f = s.execute("frame.create", &json!({"rect": [100, 300, 200, 400]})).unwrap()["id"].as_u64().unwrap();
+ let b = super::super::file::base64_encode(&png(20, 10));
+ let c = super::super::file::base64_encode(&png(30, 10));
+ s.execute("file.place", &json!({"base64": b, "name": "b.png", "frame": f})).unwrap();
+ s.execute("file.place", &json!({"base64": c, "name": "c.png", "frame": f})).unwrap();
+ let d = &s.doc().unwrap().doc;
+ assert_eq!(d.assets.len(), 3);
+ assert_eq!(s.execute("links.list", &json!({})).unwrap().as_array().unwrap().len(), 2);
+ let back = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();
+ let mut names: Vec<&str> = back.assets.values().map(|a| a.name.as_str()).collect();
+ names.sort();
+ assert_eq!(names, ["a.png", "c.png"]);
+ }
+
+ #[test]
+ fn files_with_identical_bytes_at_different_paths_keep_their_own_links() {
+ let dir = std::env::temp_dir().join(format!("dc-same-bytes-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let (a, b) = (dir.join("a.png"), dir.join("b.png"));
+ std::fs::write(&a, png(10, 10)).unwrap();
+ std::fs::write(&b, png(10, 10)).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ for (path, x) in [(&a, 72), (&b, 200)] {
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ s.execute("file.place", &json!({"path": path.to_string_lossy(), "x": x, "y": 72})).unwrap();
+ }
+ assert_eq!(s.doc().unwrap().doc.assets.len(), 2);
+ let rows = |s: &mut Session| -> Vec<(String, Value)> {
+ let l = s.execute("links.list", &json!({})).unwrap();
+ l.as_array().unwrap().iter().map(|r| (r["path"].as_str().unwrap().to_string(), r["pixels"].clone())).collect()
+ };
+ let paths = |r: &[(String, Value)]| r.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>();
+ let before = rows(&mut s);
+ assert_eq!(paths(&before), [a.to_string_lossy(), b.to_string_lossy()]);
+
+ // b.png changes on disk: updating it leaves a.png's placement alone.
+ std::fs::write(&b, png(20, 10)).unwrap();
+ assert_eq!(s.execute("links.update", &json!({})).unwrap()["updated"], 1);
+ let after = rows(&mut s);
+ assert_eq!(paths(&after), paths(&before));
+ assert_eq!((after[0].1.clone(), after[1].1.clone()), (json!([10, 10]), json!([20, 10])));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn pasted_graphics_reuse_the_identical_asset_of_the_target() {
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{Asset, Graphic, Item, ItemId, Shape, SpreadRef};
+ let asset = |id: u64, data: Vec<u8>| Asset {
+ id: AssetId(id),
+ name: "p.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(data),
+ pixels: None,
- page: 0,
++ ..Default::default()
+ };
+ let mut src = Document::new(&NewDocument::default());
+ let mut dst = Document::new(&NewDocument::default());
+ let (pa, pb) = (png(4, 4), png(8, 4));
+ // The source's asset id is taken in the target by a different file.
+ let sid = AssetId(src.alloc());
+ src.assets.insert(sid, Arc::new(asset(sid.0, pa.clone())));
+ dst.assets.insert(sid, Arc::new(asset(sid.0, pb)));
+ dst.alloc();
+ let same = AssetId(dst.alloc());
+ assert_ne!(same, sid);
+ dst.assets.insert(same, Arc::new(asset(same.0, pa)));
+ 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: sid,
+ size: (4.0, 4.0),
+ xf: designcraft_geom::Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [1.0; 4],
+ });
+ 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();
+ assert_eq!((g.asset, g.crop), (same, [1.0; 4]));
+ assert_eq!(dst.assets.len(), 2);
+ }
+
+ #[test]
+ fn pasted_missing_graphic_does_not_show_an_unrelated_target_asset() {
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{Asset, Graphic, Item, ItemId, Shape, SpreadRef};
+ let mut src = Document::new(&NewDocument::default());
+ let mut dst = Document::new(&NewDocument::default());
+ // The source graphic points at an asset the source does not have; the target uses that id for another image.
+ let missing = AssetId(src.alloc());
+ dst.assets.insert(
+ missing,
+ Arc::new(Asset {
+ id: missing,
+ name: "p.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(png(8, 4)),
+ pixels: None,
- page: 0,
++ ..Default::default()
+ }),
+ );
+ 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,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [1.0; 4],
+ });
+ 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();
+ assert_ne!(g.asset, missing);
+ assert!(!dst.assets.contains_key(&g.asset));
+ }
+ }
+
+ #[cfg(test)]
+ mod text_link_tests {
+ use serde_json::{Value, json};
+
+ use crate::Session;
+ use designcraft_doc::{ItemId, StoryId};
+
+ /// A small Word file: a Title paragraph, then Body paragraphs (`body` is WordprocessingML).
+ fn docx(body: &str) -> Vec<u8> {
+ use std::io::Write;
+ const W: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#;
+ let styles = format!(
+ r#"<w:styles {W}><w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:rPr><w:sz w:val="56"/></w:rPr></w:style>
+ <w:style w:type="paragraph" w:styleId="Body"><w:name w:val="Body"/><w:rPr><w:sz w:val="20"/></w:rPr></w:style></w:styles>"#
+ );
+ let doc = format!(
+ r#"<w:document {W}><w:body><w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Head</w:t></w:r></w:p>
+ <w:p><w:pPr><w:pStyle w:val="Body"/></w:pPr>{body}</w:p></w:body></w:document>"#
+ );
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let o = zip::write::SimpleFileOptions::default();
+ for (n, c) in [("word/document.xml", doc), ("word/styles.xml", styles)] {
+ w.start_file(n, o).unwrap();
+ w.write_all(c.as_bytes()).unwrap();
+ }
+ w.finish().unwrap().into_inner()
+ }
+
+ fn text_rows(s: &mut Session) -> Vec<Value> {
+ let l = s.execute("links.list", &json!({})).unwrap();
+ l.as_array().unwrap().iter().filter(|r| r.get("story").is_some()).cloned().collect()
+ }
+
+ fn story(s: &Session, sid: StoryId) -> designcraft_doc::Story {
+ s.doc().unwrap().doc.story(sid).unwrap().clone()
+ }
+
+ fn styles(st: &designcraft_doc::Story) -> Vec<String> {
+ st.paras.iter().map(|p| p.style.clone()).collect()
+ }
+
+ #[test]
+ fn linked_word_file_status_update_relink_and_unlink() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join("moved")).unwrap();
+ let path = dir.join("chapter.docx");
+ std::fs::write(&path, docx("<w:r><w:t>First draft.</w:t></w:r>")).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Body", "chars": {"size": 9}})).unwrap();
+ s.execute("style.paragraph.create", &json!({"name": "Headline", "chars": {"size": 30}})).unwrap();
+ // Two threaded frames.
+ let a = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text"})).unwrap()["id"].as_u64().unwrap();
+ let b = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "spread": 1, "content": "text"})).unwrap()["id"].as_u64().unwrap();
+ s.edit(|d, _| Ok(d.thread(ItemId(a), ItemId(b))?)).unwrap();
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+
+ // Place and link, with a style map and Auto Rename.
+ let r = s
+ .execute(
+ "file.place",
+ &json!({"path": path.to_string_lossy(), "frame": a, "link": true, "styleMap": {"Title": "Headline"}, "styleConflicts": "autoRename"}),
+ )
+ .unwrap();
+ let sid = StoryId(r["story"].as_u64().unwrap());
+ let placed = story(&s, sid);
+ assert_eq!(placed.text, "Head\nFirst draft.");
+ assert_eq!(styles(&placed), ["Headline", "Body_wrd_1"]);
+ let link = placed.file_link.clone().unwrap();
+ assert_eq!(link.path, path.to_string_lossy());
+ assert_eq!(link.style_conflicts, "autoRename");
+ assert_eq!(link.style_map.get("Title").map(String::as_str), Some("Headline"));
+ assert_eq!(link.style_map.get("Body").map(String::as_str), Some("Body_wrd_1"), "Auto Rename's choice is kept");
+ let rows = text_rows(&mut s);
+ assert_eq!(rows.len(), 1);
+ assert_eq!((rows[0]["story"].as_u64(), rows[0]["name"].as_str()), (Some(sid.0), Some("chapter.docx")));
+ assert_eq!((rows[0]["status"].as_str(), rows[0]["edited"].as_bool()), (Some("ok"), Some(false)));
+ assert_eq!(rows[0]["uses"].as_array().unwrap().len(), 2, "both threaded frames");
+
+ // The file changes (with tracked changes): Modified; Update imports it as if accepted, with
+ // the saved style map, into the same frames, without new renamed styles.
+ std::fs::write(
+ &path,
+ docx(r#"<w:r><w:t xml:space="preserve">Second </w:t></w:r><w:ins w:id="1" w:author="A"><w:r><w:t>revised </w:t></w:r></w:ins><w:del w:id="2" w:author="A"><w:r><w:delText>old </w:delText></w:r></w:del><w:r><w:t>draft.</w:t></w:r>"#),
+ )
+ .unwrap();
+ assert_eq!(text_rows(&mut s)[0]["status"], "modified");
+ let r = s.execute("links.update", &json!({"story": sid.0})).unwrap();
+ assert_eq!(r["updated"], 1);
+ assert_eq!(r["warnings"], json!([]), "no edits in the layout to replace");
+ let updated = story(&s, sid);
+ assert_eq!(updated.text, "Head\nSecond revised draft.");
+ assert_eq!(styles(&updated), ["Headline", "Body_wrd_1"]);
+ assert_eq!(updated.frames, [ItemId(a), ItemId(b)], "frames and thread kept");
+ assert!(s.doc().unwrap().doc.styles.para("Body_wrd_2").is_none());
+ assert!(s.doc().unwrap().doc.styles.para("Title").is_none(), "mapped styles aren't imported");
+ assert_eq!(text_rows(&mut s)[0]["status"], "ok");
+
+ // An edit in the layout, then the file changes again: Update replaces the edit and warns.
+ s.execute("story.setText", &json!({"story": sid.0, "text": "Fixed in layout"})).unwrap();
+ assert_eq!(text_rows(&mut s)[0]["edited"], true);
+ std::fs::write(&path, docx("<w:r><w:t>Third draft.</w:t></w:r>")).unwrap();
+ let r = s.execute("links.update", &json!({})).unwrap();
+ assert_eq!(r["updated"], 1);
+ let w = r["warnings"][0].as_str().unwrap();
+ assert!(w.contains("chapter.docx") && w.contains("replaced"), "{w}");
+ assert_eq!(story(&s, sid).text, "Head\nThird draft.");
+ assert_eq!(text_rows(&mut s)[0]["edited"], false);
+ // Undo brings the edit back.
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(story(&s, sid).text, "Fixed in layout");
+ s.execute("edit.redo", &json!({})).unwrap();
+
+ // Saved and opened again: the link and its options are kept.
+ let back = designcraft_format::load(&designcraft_format::save(&s.doc().unwrap().doc).unwrap()).unwrap();
+ assert_eq!(back.story(sid).unwrap().file_link, story(&s, sid).file_link);
+ assert_eq!(super::text_status(back.story(sid).unwrap().file_link.as_ref().unwrap(), &mut Default::default()), "ok");
+
+ // The file moves: Missing; Relink to it imports it into the story.
+ let moved = dir.join("moved").join("chapter.docx");
+ std::fs::write(&moved, docx("<w:r><w:t>Moved draft.</w:t></w:r>")).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ assert_eq!(text_rows(&mut s)[0]["status"], "missing");
+ s.execute("links.relink", &json!({"story": sid.0, "path": moved.to_string_lossy()})).unwrap();
+ let rows = text_rows(&mut s);
+ assert_eq!((rows[0]["status"].as_str(), rows[0]["path"].as_str()), (Some("ok"), Some(moved.to_string_lossy().as_ref())));
+ assert_eq!(story(&s, sid).text, "Head\nMoved draft.");
+
+ // Go To selects the story's frames; Unlink keeps the text and drops the file.
+ let r = s.execute("links.goTo", &json!({"story": sid.0})).unwrap();
+ assert_eq!(r["ids"], json!([a, b]));
+ s.execute("links.embed", &json!({"story": sid.0})).unwrap();
+ assert!(text_rows(&mut s).is_empty());
+ assert_eq!(story(&s, sid).text, "Head\nMoved draft.");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn unchanged_linked_text_files_are_not_read_again() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("dc-text-link-poll-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("note.txt");
+ std::fs::write(&path, "Hello").unwrap();
+ // Unreadable: a status that reads the file would say missing.
+ let readable = |on: bool| std::fs::set_permissions(&path, std::fs::Permissions::from_mode(if on { 0o644 } else { 0o000 })).unwrap();
+ // A time `secs` ago (a file changed in the last two seconds is always read).
+ let touch = |secs: u64| {
+ let f = std::fs::File::options().write(true).open(&path).unwrap();
+ f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(secs)).unwrap();
+ };
+ touch(60);
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("file.place", &json!({"path": path.to_string_lossy(), "link": true})).unwrap();
+ let status = |s: &mut Session| text_rows(s)[0]["status"].as_str().unwrap().to_string();
+
+ // Size and time as placed: not read.
+ readable(false);
+ if std::fs::read(&path).is_ok() {
+ // Running as root: permissions don't stop reads, so this can't be observed.
+ return;
+ }
+ assert_eq!(status(&mut s), "ok");
+ // Saved again unchanged (a new time): read once, then not again.
+ readable(true);
+ touch(30);
+ assert_eq!(status(&mut s), "ok");
+ readable(false);
+ assert_eq!(status(&mut s), "ok", "the second poll doesn't read it");
+ // Changed, same size, new time: modified.
+ readable(true);
+ std::fs::write(&path, "Jello").unwrap();
+ touch(20);
+ assert_eq!(status(&mut s), "modified");
+ // Changed again in the same second, same size: still seen (just-changed files are read).
+ std::fs::write(&path, "Hello").unwrap();
+ assert_eq!(status(&mut s), "ok");
+ std::fs::write(&path, "Jello").unwrap();
+ assert_eq!(status(&mut s), "modified");
+ touch(10);
+ // Updated: the new size and time are kept, so the next poll doesn't read it.
+ s.execute("links.update", &json!({})).unwrap();
+ readable(false);
+ assert_eq!(status(&mut s), "ok");
+ // A time in the future (clock skew): read once, then not on every poll.
+ readable(true);
+ let f = std::fs::File::options().write(true).open(&path).unwrap();
+ f.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)).unwrap();
+ assert_eq!(status(&mut s), "ok");
+ readable(false);
+ assert_eq!(status(&mut s), "ok", "a future time is remembered");
+ readable(true);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn create_links_when_placing_text_files_preference() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-pref-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("notes.txt");
+ std::fs::write(&path, "Plain text").unwrap();
+ let place = |s: &mut Session, extra: Value| {
+ let mut p = json!({"path": path.to_string_lossy(), "rect": [72, 72, 300, 200]});
+ p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ let r = s.execute("file.place", &p).unwrap();
+ (s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap().file_link.is_some(), r)
+ };
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ assert!(!place(&mut s, json!({})).0, "off by default");
+ assert!(place(&mut s, json!({"link": true})).0);
+ s.execute("prefs.set", &json!({"linkTextFiles": true})).unwrap();
+ assert!(place(&mut s, json!({})).0, "the preference links");
+ assert!(!place(&mut s, json!({"link": false})).0, "`link` overrides it");
+ // Placed from bytes: no file to link.
+ let b64 = crate::cmd::base64_encode(b"Plain text");
+ let r = s.execute("file.place", &json!({"base64": b64, "name": "notes.txt", "rect": [72, 300, 300, 400]})).unwrap();
+ assert!(s.doc().unwrap().doc.story(StoryId(r["story"].as_u64().unwrap())).unwrap().file_link.is_none());
+ // Into an insertion point: not linked, with a warning.
+ let fr = s.execute("frame.create", &json!({"rect": [72, 500, 300, 600], "content": "text", "text": "Start end"})).unwrap();
+ let sid = fr["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 6})).unwrap();
+ let r = s.execute("file.place", &json!({"path": path.to_string_lossy()})).unwrap();
+ assert!(r["warnings"][0].as_str().unwrap().contains("not linked"), "{r}");
+ assert!(s.doc().unwrap().doc.story(StoryId(sid)).unwrap().file_link.is_none());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ }
+
+ #[cfg(unix)]
+ #[cfg(test)]
+ mod text_link_read_tests {
+ use std::time::Duration;
+
+ use designcraft_doc::TextFileLink;
+
+ use super::{MAX_TEXT_LINK_BYTES, read_text, text_status};
+
+ /// `f` on another thread: a call that blocks fails the test instead of hanging it.
+ fn promptly<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(f());
+ });
+ // A timeout means the call blocked.
+ rx.recv_timeout(Duration::from_secs(10)).unwrap()
+ }
+
+ fn status_of(path: &std::path::Path, size: u64) -> &'static str {
+ let l = TextFileLink { path: path.to_string_lossy().to_string(), size, hash: "0".into(), ..Default::default() };
+ promptly(move || text_status(&l, &mut Default::default()))
+ }
+
+ fn read(path: &std::path::Path) -> Result<usize, String> {
+ let p = path.to_string_lossy().to_string();
+ promptly(move || read_text(&p).map(|(b, _)| b.len()).map_err(|e| e.to_string()))
+ }
+
+ #[test]
+ fn links_to_fifos_devices_folders_and_huge_files_are_not_read() {
+ let dir = std::env::temp_dir().join(format!("dc-text-link-read-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ // A FIFO with no writer: reading it would block for ever.
+ let fifo = dir.join("pipe.docx");
+ assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
+ assert_eq!(status_of(&fifo, 0), "missing");
+ assert!(read(&fifo).is_err());
+ // A device that never ends, recorded with size 0 (as its metadata reports).
+ let zero = std::path::Path::new("/dev/zero");
+ assert_eq!(status_of(zero, 0), "missing");
+ assert!(read(zero).is_err());
+ // A folder.
+ assert_eq!(status_of(&dir, 0), "missing");
+ assert!(read(&dir).is_err());
+ // Over the limit (sparse, so cheap): not read; the same size is reported as too large
+ // to check rather than OK, another size as modified.
+ let big = dir.join("big.txt");
+ std::fs::File::create(&big).unwrap().set_len(MAX_TEXT_LINK_BYTES + 1).unwrap();
+ assert_eq!(status_of(&big, MAX_TEXT_LINK_BYTES + 1), "tooLarge");
+ assert_eq!(status_of(&big, 10), "modified");
+ assert!(read(&big).unwrap_err().contains("larger than"));
+ assert!(!super::checkable_size(MAX_TEXT_LINK_BYTES as usize + 1), "placing it doesn't link it");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ }
diff --cc crates/engine/src/cmd/mathexpr.rs
index 9f1e3806c,d9ce51148..5b4f07e3a
--- a/crates/engine/src/cmd/mathexpr.rs
+++ b/crates/engine/src/cmd/mathexpr.rs
@@@ -13,9 -13,16 +13,8 @@@ use crate::{Result, Session}
fn math_item(d: &mut designcraft_doc::Document, latex: &str, size: f64, lid: designcraft_doc::LayerId, at: (f64, f64)) -> Item {
let (svg, (w, h)) = crate::math::to_svg(latex, size);
- let aid = AssetId(d.alloc());
- d.assets
- .insert(aid, Arc::new(Asset { id: aid, name: "math.svg".into(), mime: "image/svg+xml".into(), data: Arc::new(svg), ..Default::default() }));
+ let fresh = AssetId(d.alloc());
- let aid = d.add_asset(Asset {
- page: 0,
- id: fresh,
- name: "math.svg".into(),
- mime: "image/svg+xml".into(),
- link: None,
- data: Arc::new(svg),
- pixels: None,
- });
++ let aid = d.add_asset(Asset { id: fresh, name: "math.svg".into(), mime: "image/svg+xml".into(), data: Arc::new(svg), ..Default::default() });
let id = ItemId(d.alloc());
let r = Rect::new(at.0, at.1, at.0 + w, at.1 + h);
let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));
diff --cc crates/engine/src/cmd/media.rs
index 66f1c2899,f6d13ec0b..05da35174
--- a/crates/engine/src/cmd/media.rs
+++ b/crates/engine/src/cmd/media.rs
@@@ -25,8 -25,8 +25,8 @@@ pub(crate) fn place_media(s: &mut Sessi
let (px, py) = (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64));
let mime = mime.to_string();
s.edit(|d, sel| {
- let aid = AssetId(d.alloc());
- d.assets.insert(aid, Arc::new(Asset { id: aid, name, mime, link, data: Arc::new(bytes), ..Default::default() }));
+ let fresh = AssetId(d.alloc());
- let aid = d.add_asset(Asset { page: 0, id: fresh, name, mime, link, data: Arc::new(bytes), pixels: None });
++ let aid = d.add_asset(Asset { id: fresh, name, mime, link, data: Arc::new(bytes), ..Default::default() });
let id = match target {
Some(fid) => {
let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;
@@@ -90,13 -90,9 +90,17 @@@ pub fn specs() -> Vec<CommandSpec>
s.edit(|d, _| {
let poster_id = match poster {
Some(Some((bytes, name, link, px))) => {
- let aid = AssetId(d.alloc());
+ let fresh = AssetId(d.alloc());
let mime = designcraft_render::image_mime(&bytes).to_string();
- d.assets.insert(
- aid,
- Arc::new(Asset { id: aid, name, mime, link, data: Arc::new(bytes), pixels: Some(px), ..Default::default() }),
- );
- Some(Some(aid))
- Some(Some(d.add_asset(Asset { page: 0, id: fresh, name, mime, link, data: Arc::new(bytes), pixels: Some(px) })))
++ Some(Some(d.add_asset(Asset {
++ id: fresh,
++ name,
++ mime,
++ link,
++ data: Arc::new(bytes),
++ pixels: Some(px),
++ ..Default::default()
++ })))
}
Some(None) => Some(None),
None => None,
diff --cc crates/engine/src/cmd/package.rs
index 230e18b57,299c17e2d..d9ec75aa4
--- a/crates/engine/src/cmd/package.rs
+++ b/crates/engine/src/cmd/package.rs
@@@ -475,34 -479,46 +482,76 @@@ mod tests
std::fs::remove_dir_all(dir).unwrap();
}
+ /// The package's IDML links its images to the files in the package's Links folder and embeds
+ /// no copies of them.
+ #[test]
+ fn package_idml_links_the_links_folder_and_embeds_nothing() {
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let dir = std::env::temp_dir().join(format!("dc-package-idml-links-{}-{nonce}", std::process::id()));
+ let png = designcraft_render::Rendered { width: 4, height: 3, pixels: [30, 90, 180, 255].repeat(12) }.to_png();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"title": "LinkedPackage", "width": 72, "height": 72})).unwrap();
+ s.execute("file.place", &json!({"base64": super::super::base64_encode(&png), "name": "my photo.png", "x": 5, "y": 5, "width": 16})).unwrap();
+ s.execute("file.package", &json!({"dir": dir.to_string_lossy(), "idml": true, "pdf": false})).unwrap();
+ let idml = std::fs::read(dir.join("LinkedPackage.idml")).unwrap();
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(idml.as_slice())).unwrap();
+ let mut spreads = String::new();
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ if f.name().starts_with("Spreads/") {
+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();
+ }
+ }
+ let linked = dir.join("Links").join("my photo.png");
+ let uri = format!("file:{}", linked.to_string_lossy().replace(' ', "%20"));
+ assert!(spreads.contains(&format!(r#"LinkResourceURI="{uri}""#)), "{spreads}");
+ assert!(!spreads.contains("<Contents") && !spreads.contains(r#"StoredState="Embedded""#), "no image is embedded");
+ let back = designcraft_idml::import_idml_with(&idml, &|_| None).unwrap();
+ let asset = back.assets.values().next().unwrap();
+ assert!(asset.data.is_empty(), "no image is embedded");
+ assert_eq!(asset.link.as_deref(), linked.to_str());
++ }
++
+ /// A link whose file is gone has no bytes to copy: the package leaves it out of Links/, the
+ /// report lists it as missing, and the packaged document keeps it missing (#908).
+ #[test]
+ fn package_leaves_missing_links_missing() {
+ let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
+ let dir = std::env::temp_dir().join(format!("dc-package-missing-{}-{nonce}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40"/></svg>"##;
+ let (gone, kept) = (dir.join("gone.svg"), dir.join("kept.svg"));
+ std::fs::write(&gone, svg).unwrap();
+ std::fs::write(&kept, svg.replace("<rect", "<circle r=\"9\"/><rect")).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"title": "TwoLinks"})).unwrap();
+ s.execute("file.place", &json!({"path": gone.to_string_lossy(), "x": 10, "y": 10})).unwrap();
+ s.execute("edit.deselectAll", &json!({})).unwrap();
+ s.execute("file.place", &json!({"path": kept.to_string_lossy(), "x": 10, "y": 200})).unwrap();
+ let idml = dir.join("TwoLinks.idml");
+ s.execute("file.exportIdml", &json!({"path": idml.to_string_lossy(), "embedImages": false})).unwrap();
+ std::fs::remove_file(&gone).unwrap();
+ let mut s = Session::new();
+ s.execute("file.openIdml", &json!({"path": idml.to_string_lossy()})).unwrap();
+ let status = |s: &mut Session, name: &str| {
+ let links = s.execute("links.list", &json!({})).unwrap();
+ links.as_array().unwrap().iter().find(|l| l["name"] == name).map(|l| l["status"].clone())
+ };
+ assert_eq!(status(&mut s, "gone.svg"), Some(json!("missing")));
+
+ let out = dir.join("Pkg");
+ let r = s.execute("file.package", &json!({"dir": out.to_string_lossy(), "idml": true})).unwrap();
+ assert!(!out.join("Links").join("gone.svg").exists(), "a missing link is not copied");
+ assert!(out.join("Links").join("kept.svg").exists());
+ assert!(!r["files"].to_string().contains("gone.svg"), "{}", r["files"]);
+ let report = r["report"].as_str().unwrap();
+ assert!(report.contains("gone.svg (missing)"), "{report}");
+ for (command, extension) in [("file.open", "designcraft"), ("file.openIdml", "idml")] {
+ let mut opened = Session::new();
+ opened.execute(command, &json!({"path": out.join(format!("TwoLinks.{extension}")).to_string_lossy()})).unwrap();
+ assert_eq!(status(&mut opened, "gone.svg"), Some(json!("missing")), "{extension}");
+ assert_eq!(status(&mut opened, "kept.svg"), Some(json!("ok")), "{extension}");
+ }
std::fs::remove_dir_all(dir).unwrap();
}
diff --cc crates/engine/src/cmd/print.rs
index cfb953a12,659b520e8..70712321d
--- a/crates/engine/src/cmd/print.rs
+++ b/crates/engine/src/cmd/print.rs
@@@ -85,20 -42,30 +42,30 @@@ fn print(s: &mut Session, p: &Value) -
}
#[cfg(not(target_arch = "wasm32"))]
- fn secure_print_file() -> Result<tempfile::NamedTempFile> {
- let file = tempfile::Builder::new()
- .prefix("designcraft-print-")
- .suffix(".pdf")
- .tempfile()
- .map_err(|e| EngineError::Other(format!("temporary print file: {e}")))?;
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- file.as_file()
- .set_permissions(std::fs::Permissions::from_mode(0o600))
- .map_err(|e| EngineError::Other(format!("{}: {e}", file.path().display())))?;
+ fn print_with(
+ s: &mut Session,
+ p: &Value,
+ submit: impl FnOnce(&[u8], &craft_print::Job) -> std::result::Result<String, craft_print::Error>,
+ ) -> Result<Value> {
+ let d = &s.doc()?.doc;
+ let opts = super::export::options(p, d.page_count())?;
+ let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1).clamp(1, 999) as u32;
+ let job = craft_print::Job {
+ printer: str_param(p, "printer").map(str::to_string),
+ copies,
+ scaling: craft_print::Scaling::ShrinkToFit,
+ title: d.title.clone(),
+ ..craft_print::Job::default()
+ };
+ let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
- let pdf = designcraft_pdf::export_pdf(d, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
++ let pdf = designcraft_pdf::export_pdf(&super::interchange::with_pdf_boxes(d), &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
+ let command = craft_print::command_preview(&job).map_err(|e| bad("file.print", e.to_string()))?;
+ let pages = opts.pages.as_ref().map_or(d.page_count(), |v| v.len());
+ let out = json!({"printer": job.printer, "copies": copies, "pages": pages, "command": command, "bytes": pdf.len()});
+ if !dry {
+ submit(&pdf, &job).map_err(|e| bad("file.print", e.to_string()))?;
}
- Ok(file)
+ Ok(out)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
diff --cc crates/engine/src/cmd/table.rs
index cb75e553f,4b2962b4e..dcfc99bcd
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@@ -1402,20 -1398,10 +1398,17 @@@ fn place_graphic(s: &mut Session, p: &V
let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad(ID, "unsupported or corrupt image"))?;
let fill = p.get("fit").and_then(Value::as_str) == Some("fill");
s.edit(|d, sel| {
- let aid = designcraft_doc::AssetId(d.alloc());
+ let fresh = designcraft_doc::AssetId(d.alloc());
let mime = designcraft_render::image_mime(&bytes).to_string();
- d.assets.insert(
- aid,
- std::sync::Arc::new(designcraft_doc::Asset {
- id: aid,
- name,
- mime,
- link,
- data: std::sync::Arc::new(bytes),
- pixels: Some((pw, ph)),
- ..Default::default()
- }),
- );
- let aid =
- d.add_asset(designcraft_doc::Asset { page: 0, id: fresh, name, mime, link, data: std::sync::Arc::new(bytes), pixels: Some((pw, ph)) });
++ let aid = d.add_asset(designcraft_doc::Asset {
++ id: fresh,
++ name,
++ mime,
++ link,
++ data: std::sync::Arc::new(bytes),
++ pixels: Some((pw, ph)),
++ ..Default::default()
++ });
let st = d.story_mut(g.story).ok_or_else(|| bad(ID, "no story"))?;
let t = st.table_mut(g.table).ok_or_else(|| bad(ID, "no table"))?;
let (r, c) = t.owner(g.range.r0, g.range.c0);
diff --cc crates/engine/src/lib.rs
index 771c89b13,745e45647..a7e708b4b
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -105,6 -112,16 +112,14 @@@ pub struct DocState
#[derive(Debug)]
pub struct FontScope(pub u32);
+ /// A graphic loaded in the place cursor (`place.load`, File › Place with no frame to fill).
+ #[derive(Clone, Copy, Debug)]
+ pub struct LoadedGraphic {
+ pub asset: designcraft_doc::AssetId,
- /// Natural size in points.
++ /// Natural size in points (a placed PDF's: its Crop to box).
+ pub size: (f64, f64),
- /// Image Import Options › Crop to: the box of the graphic a new frame shows (x, y, w, h).
- pub crop: Option<(f64, f64, f64, f64)>,
+ }
+
impl Drop for FontScope {
fn drop(&mut self) {
designcraft_fonts::FontDb::global().close_scope(self.0);
diff --cc crates/engine/src/tests_idml.rs
index 2c85d1434,c6ecc539c..445db68e3
--- a/crates/engine/src/tests_idml.rs
+++ b/crates/engine/src/tests_idml.rs
@@@ -252,137 -338,59 +338,194 @@@ fn named_lists_round_trip_through_idml(
assert_eq!(st.paras[0].para.start_at, Some(Some(5)));
}
+/// IDML says which page of a placed PDF shows and which box its graphic spans, so InDesign opens
+/// it at the same size and position; importing it back gives the same page, crop and geometry.
+#[test]
+fn placed_pdf_page_and_crop_round_trip_through_idml() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).unwrap();
+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ // Page 2, cropped to its trim box: the frame is smaller than the page with its bleed.
+ let place = json!({"base64": b64, "name": "a.pdf", "pdfPage": 2, "pdfCrop": "trim", "width": 315, "x": 20, "y": 30});
+ let r = t.execute("file.place", &place).unwrap();
+ let d = t.doc().unwrap().doc.clone();
+ let item = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap();
+ let (bounds, g) = (item.bounds(), item.graphic().unwrap().clone());
+ assert_eq!(d.assets[&g.asset].page, 1);
+ assert_eq!(d.assets[&g.asset].pdf_crop, designcraft_doc::PdfCrop::Trim);
+
+ let bytes = designcraft_idml::export_idml(&d);
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut spreads = String::new();
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ if f.name().starts_with("Spreads/") {
+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();
+ }
+ }
+ let attr = spreads.split("<PDFAttribute ").nth(1).and_then(|a| a.split("/>").next()).expect("a PDFAttribute");
+ assert!(attr.contains(r#"PageNumber="2""#) && attr.contains(r#"PDFCrop="CropTrim""#), "{attr}");
+ assert!(spreads.contains(r#"<GraphicBounds Left="0" Top="0" Right="612" Bottom="792"/>"#), "the trim box");
+
+ let back = crate::cmd::interchange::import(&bytes, None).unwrap();
+ let bi = back.spreads.iter().flat_map(|sp| sp.items.iter()).find(|i| i.graphic().is_some()).unwrap();
+ let bg = bi.graphic().unwrap();
+ let ba = &back.assets[&bg.asset];
+ assert_eq!((ba.page, ba.pdf_crop), (1, designcraft_doc::PdfCrop::Trim));
+ let (want, got) = (d.assets[&g.asset].shown_box().unwrap(), ba.shown_box().expect("the trim box found on the page"));
+ assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} vs {want:?}");
+ let bb = bi.bounds();
+ assert!([bb.x0 - bounds.x0, bb.y0 - bounds.y0, bb.x1 - bounds.x1, bb.y1 - bounds.y1].iter().all(|v| v.abs() < 1e-3), "{bb:?} vs {bounds:?}");
+ assert!((bg.size.0 - g.size.0).abs() < 1e-3 && (bg.size.1 - g.size.1).abs() < 1e-3);
+ let (a, b) = ((bi.xf * bg.xf).as_coeffs(), (item.xf * g.xf).as_coeffs());
+ assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3), "{a:?} vs {b:?}");
+
+ // A page the PDF doesn't have imports, and the PDF export leaves it out with a warning.
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ let mut body = String::new();
+ std::io::Read::read_to_string(&mut f, &mut body).unwrap();
+ out.start_file(f.name(), zip::write::SimpleFileOptions::default()).unwrap();
+ std::io::Write::write_all(&mut out, body.replace(r#"PageNumber="2""#, r#"PageNumber="4294967295""#).as_bytes()).unwrap();
+ }
+ let hostile = designcraft_idml::import_idml(&out.finish().unwrap().into_inner()).unwrap();
+ assert_eq!(hostile.assets.values().map(|a| a.page).collect::<Vec<_>>(), [u32::MAX - 1]);
+ t.edit(|doc, _| {
+ *doc = hostile;
+ Ok(())
+ })
+ .unwrap();
+ let r = t.execute("file.exportPdf", &json!({})).unwrap();
+ assert!(r["warnings"].to_string().contains("has no page 4294967295"), "{r}");
+}
+
+/// An IDML placed PDF cropped to its media box, without `GraphicBounds`: the graphic takes the
+/// media box (the page with its 9 pt bleed).
+#[test]
+fn idml_placed_pdf_cropped_to_its_media_box_gets_media_box_bounds() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "trim", "width": 630, "x": 0, "y": 0})).unwrap();
+ let bytes = designcraft_idml::export_idml(&t.doc().unwrap().doc);
+
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let mut edited = false;
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ let mut body = Vec::new();
+ std::io::Read::read_to_end(&mut f, &mut body).unwrap();
+ if f.name().starts_with("Spreads/") {
+ let text = String::from_utf8(body).unwrap().replace(r#"PDFCrop="CropTrim""#, r#"PDFCrop="CropMedia""#);
+ let start = text.find("<GraphicBounds ").unwrap();
+ let end = start + text[start..].find("/>").unwrap() + 2;
+ body = format!("{}{}", &text[..start], &text[end..]).into_bytes();
+ edited = true;
+ }
+ out.start_file(f.name(), zip::write::SimpleFileOptions::default()).unwrap();
+ std::io::Write::write_all(&mut out, &body).unwrap();
+ }
+ assert!(edited);
+ let back = crate::cmd::interchange::import(&out.finish().unwrap().into_inner(), None).unwrap();
+ let g = back.spreads.iter().flat_map(|sp| sp.items.iter()).find_map(|i| i.graphic().cloned()).unwrap();
+ let a = &back.assets[&g.asset];
+ assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::Media);
+ assert!((g.size.0 - 630.0).abs() < 1e-3 && (g.size.1 - 810.0).abs() < 1e-3, "{:?}", g.size);
+ let b = a.shown_box().unwrap_or([0.0, 0.0, 1.0, 1.0]);
+ assert!(b.iter().zip([0.0, 0.0, 1.0, 1.0]).all(|(x, y)| (x - y).abs() < 1e-6), "{b:?}");
+}
+
+/// A Bounding Box crop needs the page rendered to find its box. IDML import leaves that until
+/// the graphic is drawn or exported (its `GraphicBounds` give its size), so opening a document
+/// doesn't render every placed PDF; drawing and PDF export find the same box placing it did.
+#[test]
+fn idml_bounding_box_crop_is_measured_when_drawn_not_on_import() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("frame.create", &json!({"rect": [100, 200, 300, 260], "content": "unassigned"})).unwrap();
+ s.execute("object.fill", &json!({"swatch": "[Black]"})).unwrap();
+ let b64 = s.execute("file.exportPdf", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "contentVisible", "width": 200, "x": 20, "y": 30})).unwrap();
+ let placed = t.doc().unwrap().doc.assets.values().next().unwrap().shown_box().expect("placing measures the box");
+ assert!(placed[0] > 0.1 && placed[2] < 0.6, "the drawn rectangle, not the page: {placed:?}");
+
+ let bytes = designcraft_idml::export_idml(&t.doc().unwrap().doc);
+ let back = crate::cmd::interchange::import(&bytes, None).unwrap();
+ let a = back.assets.values().next().unwrap();
+ assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::ContentVisible);
+ assert!(a.content_box_pending(), "import didn't render the page: {:?}", a.pdf_box);
+ let close = |b: [f64; 4]| b.iter().zip(placed).all(|(x, y)| (x - y).abs() < 1e-9);
+ let drawn = designcraft_render::shown_box(a).expect("drawing measures the box");
+ assert!(close(drawn), "{drawn:?} vs {placed:?}");
+ let boxed = crate::cmd::interchange::with_pdf_boxes(&back);
+ let exported = boxed.assets.values().next().unwrap().shown_box().expect("PDF export gets the box");
+ assert!(close(exported), "{exported:?} vs {placed:?}");
+}
++
+ #[test]
+ fn type_para_sets_a_drop_cap_that_survives_idml() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("style.character.create", &json!({"name": "Initial", "chars": {"fontStyle": "Bold"}})).unwrap();
+ let text = "Once upon a time there was a paragraph long enough to run beside its drop cap for a few lines and then some more.";
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 400], "content": "text", "text": text})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();
+ s.execute("type.para", &json!({"attrs": {"dropCapLines": 3, "dropCapChars": 1, "dropCapStyle": "Initial", "dropCapAlignLeft": false}})).unwrap();
+ let d = s.doc().unwrap().doc.clone();
+ let cs = designcraft_compose::compose_story(&d, designcraft_doc::StoryId(sid), &Default::default());
+ let lines = &cs.frames[0].lines;
+ let dc = &lines[0].glyphs[0];
+ assert_eq!(dc.byte, 0);
+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "on line 3's baseline");
+ assert!(lines[0].drop_cap.is_some_and(|b| b.end == 1));
+ let p = &d.story(designcraft_doc::StoryId(sid)).unwrap().paras[0].para;
+ assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_style.as_deref()), (Some(3), Some(1), Some("Initial")));
+ let back = designcraft_idml::import_idml(&designcraft_idml::export_idml(&d)).unwrap();
+ let p = &back.stories.values().find(|st| st.text.starts_with("Once")).unwrap().paras[0].para;
+ assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_align_left), (Some(3), Some(1), Some(false)));
+ // The drop cap's character style goes through IDML as a leading Dropcap nested style.
+ assert_eq!(p.drop_cap_style.as_deref(), Some("Initial"));
+ assert_eq!(p.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Initial")]));
+ }
+
+ #[test]
+ fn table_of_contents_definition_round_trips_through_idml_and_updates() {
+ let mut s = Session::new();
+ s.execute("file.newSample", &json!({})).unwrap();
+ let page = s.doc().unwrap().doc.page_count() + 1;
+ s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();
+ let basic = designcraft_doc::story::BASIC_PARAGRAPH;
+ s.execute(
+ "toc.generate",
+ &json!({"page": page, "title": "Inside", "titleStyle": basic, "entries": [
+ {"style": "Cover Title", "level": 1, "pageNumber": "before", "separator": " ^ "},
+ {"style": "Headline", "level": 2, "entryStyle": basic, "pageNumber": "none"},
+ ]}),
+ )
+ .unwrap();
+ let toc_text = |s: &Session| {
+ let d = &s.doc().unwrap().doc;
+ d.story(d.toc.as_ref().unwrap().story).unwrap().text.clone()
+ };
+ let before = s.doc().unwrap().doc.toc.clone().unwrap();
+ let text = toc_text(&s);
+ let b64 = s.execute("file.exportIdml", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ s.execute("file.openIdml", &json!({"base64": b64, "name": "toc.idml"})).unwrap();
+ let after = s.doc().unwrap().doc.toc.clone().expect("the TOC definition is imported");
+ assert_eq!((&after.title, &after.title_style, &after.entries), (&before.title, &before.title_style, &before.entries));
+ assert_eq!(toc_text(&s), text);
+ s.execute("toc.update", &json!({})).unwrap();
+ assert_eq!(toc_text(&s), text);
+ }
diff --cc crates/epub/src/lib.rs
index 7ae14c715,32e327aa3..16084535d
--- a/crates/epub/src/lib.rs
+++ b/crates/epub/src/lib.rs
@@@ -758,6 -1508,312 +1508,312 @@@ mod tests
assert!(z.by_name("OEBPS/nav.xhtml").is_ok());
}
+ /// #766: anchored graphics are exported where they are anchored (inline in the text, an
+ /// above-line object as a block of its own), and their images go into the package.
+ #[test]
+ fn anchored_objects_are_exported_in_place() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 200.0), lid, "AB\nCD", ParaFormat::default()).unwrap();
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
+ Arc::new(Asset {
- page: 0,
+ id: aid,
+ name: "dot.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(vec![7]),
+ pixels: Some((1, 1)),
++ ..Default::default()
+ }),
+ );
+ let graphic = |d: &mut Document, alt: &str| {
+ let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)));
+ item.alt_text = alt.into();
+ item.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (1.0, 1.0),
+ xf: Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ item
+ };
+ let inline = designcraft_doc::AnchoredObject::new(graphic(&mut d, "inline"), designcraft_doc::AnchorPosition::Inline { y_offset: 0.0 });
+ let above = designcraft_doc::AnchoredObject::new(
+ graphic(&mut d, "above"),
+ designcraft_doc::AnchorPosition::AboveLine { align: designcraft_doc::anchored::AnchorAlign::Center, space_before: 0.0, space_after: 0.0 },
+ );
+ let st = d.story_mut(sid).unwrap();
+ st.insert_object(1, inline);
+ // Byte offsets: "A" (1), the mark (3), "B\nC" (3): the second object goes between C and D.
+ st.insert_object(7, above);
+ let bytes = export_epub(&d, &EpubOptions::default()).unwrap();
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
+ let mut html = String::new();
+ z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut html).unwrap();
+ let img = |alt: &str| format!("<img src=\"images/dot-{}.png\" alt=\"{alt}\"/>", aid.0);
+ assert!(html.contains(&format!("A{}B</p>", img("inline"))), "{html}");
+ assert!(html.contains(&format!("C<span class=\"anchored\" style=\"display:block;text-align:center\">{}</span>D", img("above"))), "{html}");
+ assert!(z.by_name(&format!("OEBPS/images/dot-{}.png", aid.0)).is_ok(), "the image is in the package");
+ let page = export_html(&d, &HtmlOptions::default());
+ assert!(page.contains("alt=\"inline\"") && page.contains("alt=\"above\""), "{page}");
+ // story_html on its own still leaves objects out.
+ assert!(!story_html(&d, sid).contains("<img"));
+ }
+
+ fn st_typed(d: &mut Document, sid: StoryId) {
+ if let Some(st) = d.story_mut(sid) {
+ st.paras[8].style = "Typed".into();
+ }
+ }
+
+ /// #767: consecutive `li` paragraphs share one list (`ol` for a numbered style), and
+ /// consecutive `pre` paragraphs of one style one block with their lines on separate lines.
+ #[test]
+ fn lists_and_preformatted_blocks_are_grouped() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ for (name, tag, list) in [
+ ("Bullet", "li", Some(designcraft_doc::ListType::Bullets)),
+ ("Number", "li", Some(designcraft_doc::ListType::Numbers)),
+ ("Typed", "li", None),
+ ("Code", "pre", None),
+ ] {
+ let para = designcraft_doc::ParaAttrs { list_type: list, ..Default::default() };
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: None,
+ next_style: None,
+ para,
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new() });
+ }
+ let text = "Intro\nfirst\nsecond\none\ntwo\nx = 1\ny = 2\nEnd\n• typed";
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap();
+ let st = d.story_mut(sid).unwrap();
+ for (i, style) in ["Bullet", "Bullet", "Number", "Number", "Code", "Code"].into_iter().enumerate() {
+ st.paras[i + 1].style = style.into();
+ }
+ let html = story_html(&d, sid);
+ let li = |c: &str, t: &str| format!("<li class=\"{c}\">{t}</li>");
+ assert!(
+ html.contains(&format!(
+ "<ul>\n{}\n{}\n</ul>\n<ol>\n{}\n{}\n</ol>\n",
+ li("bullet", "first"),
+ li("bullet", "second"),
+ li("number", "one"),
+ li("number", "two")
+ )),
+ "{html}"
+ );
+ assert!(html.contains("<pre class=\"code\">x = 1\ny = 2</pre>\n<p class=\"basic-paragraph\">End</p>"), "{html}");
+ assert_eq!(html.matches("<pre").count(), 1, "{html}");
+ // A style without a list type of its own (typed bullets) gets no second marker.
+ st_typed(&mut d, sid);
+ let html = story_html(&d, sid);
+ assert!(html.contains("<ul style=\"list-style:none\">\n<li class=\"typed\">• typed</li>\n</ul>\n"), "{html}");
+ }
+
+ /// #769, #770: the navigation lists the h1–h3 headings (nested by level) and links to them,
+ /// with its title in the book's language; without headings, each story's first paragraph.
+ #[test]
+ fn navigation_follows_the_headings() {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ for (name, tag) in [("Chapter", "h1"), ("Section", "h2")] {
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: name.into(),
+ based_on: None,
+ next_style: None,
+ para: Default::default(),
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert(format!("p:{name}"), designcraft_doc::ExportTag { tag: tag.into(), class: String::new() });
+ }
+ let text = "One\nBody\nOne point one\nMore\nTwo\nText";
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 300.0), lid, text, ParaFormat::default()).unwrap();
+ let st = d.story_mut(sid).unwrap();
+ for (i, style) in [(0, "Chapter"), (2, "Section"), (4, "Chapter")] {
+ st.paras[i].style = style.into();
+ }
+ // A story that starts with body text adds nothing to the table of contents.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 400.0, 300.0, 500.0), lid, "Text after the figure.", ParaFormat::default()).unwrap();
+ let read = |d: &Document, opts: &EpubOptions, path: &str| {
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap();
+ let mut s = String::new();
+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();
+ s
+ };
+ let nl = EpubOptions { language: "nl".into(), ..Default::default() };
+ let nav = read(&d, &nl, "OEBPS/nav.xhtml");
+ let link = |f: &str, t: &str, l: &str| format!("<a href=\"{f}#{t}\">{l}</a>");
+ // Each h1 starts a chapter file (#768).
+ let want = format!(
+ "<h1>Inhoud</h1><ol><li>{}<ol><li>{}</li></ol></li><li>{}</li></ol>",
+ link("content.xhtml", "s0-p0", "One"),
+ link("content.xhtml", "s0-p2", "One point one"),
+ link("content2.xhtml", "s0-p4", "Two")
+ );
+ assert!(nav.contains(&want), "{nav}");
+ assert!(!nav.contains("Text after the figure"), "{nav}");
+ let content = read(&d, &nl, "OEBPS/content.xhtml");
+ assert!(content.contains("<h1 id=\"s0-p0\" class=\"chapter\">One</h1>") && content.contains("<h2 id=\"s0-p2\""), "{content}");
+ let custom = EpubOptions { toc_title: Some("In dit boek".into()), ..Default::default() };
+ assert!(read(&d, &custom, "OEBPS/nav.xhtml").contains("<h1>In dit boek</h1>"));
+ // Without headings: one entry per story, its first paragraph.
+ let mut plain = Document::new(&NewDocument::default());
+ let lid = plain.default_layer();
+ plain.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Opening\nrest", ParaFormat::default()).unwrap();
+ let nav = read(&plain, &EpubOptions::default(), "OEBPS/nav.xhtml");
+ assert!(nav.contains(&format!("<h1>Contents</h1><ol><li>{}</li></ol>", link("content.xhtml", "s0", "Opening"))), "{nav}");
+ // A heading shallower than the one before it but deeper than its parent stays under the
+ // parent: h1 A, h3 B, h2 C nest B and C under A.
+ let e = |t: &str, l: u8| (t.to_string(), t.to_string(), l);
+ let l = |t: &str| link("content.xhtml", t, t);
+ assert_eq!(
+ nav_list(&[e("A", 1), e("B", 3), e("C", 2), e("D", 1)], &BTreeMap::new()),
+ format!("<li>{}<ol><li>{}</li><li>{}</li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))
+ );
+ assert_eq!(
+ nav_list(&[e("A", 1), e("B", 2), e("C", 3), e("D", 1)], &BTreeMap::new()),
+ format!("<li>{}<ol><li>{}<ol><li>{}</li></ol></li></ol></li><li>{}</li>", l("A"), l("B"), l("C"), l("D"))
+ );
+ }
+
+ /// #768: the book is split into one file per chapter, before each h1, with well-formed
+ /// sections; the spine and manifest list the files in order.
+ #[test]
+ fn chapters_are_split_at_h1() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ let lid = d.default_layer();
+ d.styles_mut().paragraph.push(designcraft_doc::ParagraphStyle {
+ name: "Chapter".into(),
+ based_on: None,
+ next_style: None,
+ para: Default::default(),
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ d.styles_mut().export_tags.insert("p:Chapter".into(), designcraft_doc::ExportTag { tag: "h1".into(), class: String::new() });
+ // A title page without a heading, then a story that opens with a chapter and has a
+ // second one in the middle.
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Title page", ParaFormat::default()).unwrap();
+ let (_, sid) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 200.0, 300.0, 400.0), lid, "One\nFirst text\nTwo\nSecond text", ParaFormat::default())
+ .unwrap();
+ let st = d.story_mut(sid).unwrap();
+ st.paras[0].style = "Chapter".into();
+ st.paras[2].style = "Chapter".into();
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap();
+ let mut read = |path: &str| {
+ let mut s = String::new();
+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();
+ s
+ };
+ let (c1, c2, c3) = (read("OEBPS/content.xhtml"), read("OEBPS/content2.xhtml"), read("OEBPS/content3.xhtml"));
+ assert!(c1.contains("Title page") && !c1.contains("One"), "{c1}");
+ assert!(c2.contains("<section id=\"s1\">\n<h1 id=\"s1-p0\"") && c2.contains("First text") && !c2.contains("Two"), "{c2}");
+ assert!(c3.contains("<section>\n<h1 id=\"s1-p2\""), "{c3}");
+ for c in [&c1, &c2, &c3] {
+ assert_eq!(c.matches("<section").count(), c.matches("</section>").count(), "{c}");
+ assert!(!c.contains(CHAPTER_MARK));
+ }
+ let opf = read("OEBPS/content.opf");
+ assert!(opf.contains("<itemref idref=\"content\"/>\n<itemref idref=\"content2\"/>\n<itemref idref=\"content3\"/>\n</spine>"), "{opf}");
+ assert!(opf.contains("<item id=\"content3\" href=\"content3.xhtml\""), "{opf}");
+ let nav = read("OEBPS/nav.xhtml");
+ assert!(nav.contains("href=\"content2.xhtml#s1-p0\"") && nav.contains("href=\"content3.xhtml#s1-p2\""), "{nav}");
+ assert!(z.by_name("OEBPS/content4.xhtml").is_err());
+ // HTML stays one page, without the marks.
+ let html = export_html(&d, &HtmlOptions::default());
+ assert!(!html.contains(CHAPTER_MARK) && html.contains("Second text"));
+ }
+
+ /// Note links stay working across chapter files: a link whose target ended up in another
+ /// file (endnotes end the book) names that file; one in its own file stays as it is.
+ #[test]
+ fn note_links_point_at_the_chapter_file_of_their_target() {
+ let files: BTreeMap<String, String> =
+ [("enref-1", "content.xhtml"), ("fn-1", "content.xhtml"), ("fnref-1", "content.xhtml"), ("en-1", "content2.xhtml")]
+ .into_iter()
+ .map(|(id, f)| (id.to_string(), f.to_string()))
+ .collect();
+ let first = "<p>First<a id=\"enref-1\" href=\"#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>";
+ assert_eq!(
+ link_across_chapters(first, "content.xhtml", &files),
+ "<p>First<a id=\"enref-1\" href=\"content2.xhtml#en-1\">1</a><a id=\"fnref-1\" href=\"#fn-1\">*</a></p><aside id=\"fn-1\"><a href=\"#fnref-1\">*</a></aside><a href=\"#gone\">x</a>"
+ );
+ let last = "<li id=\"en-1\"><a href=\"#enref-1\">1</a> End note</li>";
+ assert_eq!(link_across_chapters(last, "content2.xhtml", &files), "<li id=\"en-1\"><a href=\"content.xhtml#enref-1\">1</a> End note</li>");
+ }
+
+ #[test]
+ fn split_chapters_keeps_sections_well_formed() {
+ let m = CHAPTER_MARK;
+ assert_eq!(split_chapters("<section id=\"s0\">\n<p>a</p>\n</section>\n"), vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n"]);
+ assert_eq!(
+ split_chapters(&format!("<section id=\"s0\">\n{m}<h1>A</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<h1>A</h1>\n</section>\n"]
+ );
+ assert_eq!(
+ split_chapters(&format!("<section id=\"s0\">\n<p>a</p>\n{m}<h1>B</h1>\n</section>\n")),
+ vec!["<section id=\"s0\">\n<p>a</p>\n</section>\n", "<section>\n<h1>B</h1>\n</section>\n"]
+ );
+ assert_eq!(split_chapters(""), vec![String::new()]);
+ }
+
+ #[test]
+ fn iso8601_timestamps() {
+ for (t, want) in [
+ (0, "1970-01-01T00:00:00Z"),
+ (951_782_400, "2000-02-29T00:00:00Z"),
+ (1_791_891_000, "2026-10-13T11:30:00Z"),
+ (-86_400, "1969-12-31T00:00:00Z"),
+ ] {
+ assert_eq!(iso8601(t), want);
+ }
+ }
+
+ /// #771, #773: dcterms:modified is a real time, the default identifier is a stable urn:uuid
+ /// that differs between documents with the same title, and a JPEG cover keeps its type.
+ #[test]
+ fn package_metadata_and_cover_image() {
+ let opf = |d: &Document, opts: &EpubOptions| {
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(d, opts).unwrap())).unwrap();
+ let mut s = String::new();
+ z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut s).unwrap();
+ let names: Vec<String> = z.file_names().map(str::to_string).collect();
+ (s, names)
+ };
+ let id_of = |opf: &str| opf.split("<dc:identifier id=\"bookid\">").nth(1).and_then(|r| r.split('<').next()).unwrap_or_default().to_string();
+ let mut a = Document::new(&NewDocument::default());
+ a.title = "Same".into();
+ a.created = 1_700_000_000;
+ let mut b = a.clone();
+ b.created = 1_700_000_001;
+ let (oa, _) = opf(&a, &EpubOptions::default());
+ let (oa2, _) = opf(&a, &EpubOptions::default());
+ let (ob, _) = opf(&b, &EpubOptions::default());
+ assert!(id_of(&oa).starts_with("urn:uuid:") && id_of(&oa).len() == 45, "{}", id_of(&oa));
+ assert_eq!(id_of(&oa), id_of(&oa2), "stable from export to export");
+ assert_ne!(id_of(&oa), id_of(&ob), "not shared by two books with the same title");
+ // Modified: the given time, else the document's save (or creation) time.
+ assert!(oa.contains("<meta property=\"dcterms:modified\">2023-11-14T22:13:20Z</meta>"), "{oa}");
+ let at = EpubOptions { modified: Some(1_791_891_000), ..Default::default() };
+ assert!(opf(&a, &at).0.contains("2026-10-13T11:30:00Z"));
+ // A JPEG cover is packaged as such.
+ let jpeg = EpubOptions { cover: Some(vec![0xFF, 0xD8, 0xFF, 0xE0, 1, 2]), ..Default::default() };
+ let (o, names) = opf(&a, &jpeg);
+ assert!(o.contains("href=\"images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\""), "{o}");
+ assert!(names.contains(&"OEBPS/images/cover.jpg".to_string()), "{names:?}");
+ }
+
#[test]
fn styles_whose_names_slug_alike_keep_their_own_classes() {
let mut d = Document::new(&NewDocument::default());
@@@ -815,6 -1871,106 +1871,113 @@@
assert_eq!(base64(b"M"), "TQ==");
}
+ /// #774: an image without alt text is decorative (`alt=""`) and reported, and package names
+ /// come from the original file names.
+ #[test]
+ fn images_get_readable_names_and_no_file_name_alt() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let place = |d: &mut Document, name: &str, mime: &str, alt: &str, y: f64| {
+ let aid = AssetId(d.alloc());
+ d.assets.insert(
+ aid,
- Arc::new(Asset { page: 0, id: aid, name: name.into(), mime: mime.into(), link: None, data: Arc::new(vec![1]), pixels: Some((1, 1)) }),
++ Arc::new(Asset {
++ id: aid,
++ name: name.into(),
++ mime: mime.into(),
++ data: Arc::new(vec![1]),
++ pixels: Some((1, 1)),
++ ..Default::default()
++ }),
+ );
+ let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(36.0, y, 72.0, y + 36.0)));
+ item.alt_text = alt.into();
+ item.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (1.0, 1.0),
+ xf: Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ aid.0
+ };
+ let a = place(&mut d, "/tmp/Anim Frame (1).GIF", "image/gif", "", 36.0);
+ let b = place(&mut d, "photo.jpg", "image/jpeg", "A heron", 120.0);
+ let c = place(&mut d, "???.png", "image/png", "Mark", 200.0);
+ assert_eq!(images_without_alt(&d), vec!["/tmp/Anim Frame (1).GIF".to_string()]);
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &EpubOptions::default()).unwrap())).unwrap();
+ let mut x = String::new();
+ z.by_name("OEBPS/content.xhtml").unwrap().read_to_string(&mut x).unwrap();
+ assert!(x.contains(&format!("<img src=\"images/anim-frame-1-{a}.gif\" alt=\"\"/>")), "{x}");
+ assert!(x.contains(&format!("<img src=\"images/photo-{b}.jpg\" alt=\"A heron\"/>")), "{x}");
+ assert!(x.contains(&format!("<img src=\"images/{c}.png\" alt=\"Mark\"/>")), "{x}");
+ assert!(z.by_name(&format!("OEBPS/images/anim-frame-1-{a}.gif")).is_ok());
+ }
+
+ /// #775: the generic fallback follows the font, and embedded fonts are packaged and declared.
+ #[test]
+ fn generic_fallbacks_and_embedded_fonts() {
+ let none = BTreeMap::new();
+ for (family, want) in [
+ ("Source Serif 4", "serif"),
+ ("Source Sans 3", "sans-serif"),
+ ("Microsoft Sans Serif", "sans-serif"),
+ ("JetBrains Mono", "monospace"),
+ ("Courier New", "monospace"),
+ ("Franklin Gothic", "sans-serif"),
+ ("Garamond", "serif"),
+ ] {
+ assert_eq!(generic_family(family, &none), want, "{family}");
+ }
+ let known: BTreeMap<String, String> =
+ [("Montserrat".to_string(), "sans-serif".to_string()), ("Odd".to_string(), "nonsense".to_string())].into();
+ assert_eq!(generic_family("Montserrat", &known), "sans-serif");
+ assert_eq!(generic_family("Odd", &known), "serif", "only CSS generic families are used");
+ assert_eq!(css_weight_style("Semibold Italic"), (600, "italic"));
+ assert_eq!(css_weight_style("Bold"), (700, "normal"));
+ assert_eq!(css_weight_style("Extra Bold"), (800, "normal"));
+ assert_eq!(css_weight_style("Regular"), (400, "normal"));
+ assert_eq!(css_weight_style("Light"), (300, "normal"));
+ assert_eq!(css_weight_style("Thin Oblique"), (100, "italic"));
+ assert_eq!(css_weight_style("Black"), (900, "normal"));
+
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Hello", ParaFormat::default()).unwrap();
+ if let Some(basic) = d.styles_mut().paragraph.iter_mut().find(|s| s.name == story::BASIC_PARAGRAPH) {
+ basic.chars.font_family = Some("Montserrat".into());
+ basic.chars.font_style = Some("Bold Italic".into());
+ }
+ assert_eq!(stylesheet_fonts(&d), vec![("Montserrat".to_string(), "Bold Italic".to_string())]);
+ let opts = EpubOptions {
+ generic_families: known,
+ fonts: vec![EmbeddedFont { family: "Montserrat".into(), style: "Bold Italic".into(), data: b"OTTO font".to_vec() }],
+ ..Default::default()
+ };
+ let mut z = zip::ZipArchive::new(std::io::Cursor::new(export_epub(&d, &opts).unwrap())).unwrap();
+ let mut read = |path: &str| {
+ let mut s = String::new();
+ z.by_name(path).unwrap().read_to_string(&mut s).unwrap();
+ s
+ };
+ let css = read("OEBPS/style.css");
+ assert!(
+ css.starts_with(
+ "@font-face { font-family: \"Montserrat\"; src: url(\"fonts/0-montserrat-bold-italic.otf\"); font-weight: 700; font-style: italic; }"
+ ),
+ "{css}"
+ );
+ assert!(css.contains("font-family: \"Montserrat\", sans-serif;"), "{css}");
+ let opf = read("OEBPS/content.opf");
+ assert!(opf.contains("<item id=\"font0\" href=\"fonts/0-montserrat-bold-italic.otf\" media-type=\"font/otf\"/>"), "{opf}");
+ assert_eq!(read("OEBPS/fonts/0-montserrat-bold-italic.otf"), "OTTO font");
+ // HTML takes the generic families too, and embeds nothing.
+ let html = export_html(&d, &HtmlOptions { generic_families: opts.generic_families.clone(), ..Default::default() });
+ assert!(html.contains("\"Montserrat\", sans-serif;") && !html.contains("@font-face"), "{html}");
+ }
+
#[test]
fn metadata_is_serialized_for_its_output_context() {
let mut d = Document::new(&NewDocument::default());
diff --cc crates/fonts/src/fontdb.rs
index 279379ca6,94721b38e..60ec3d6f6
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@@ -712,14 -844,54 +844,62 @@@ fn make_face(bytes: FontBytes, source:
})
}
+/// `family` without what layout apps add to a family name, if it has any: InDesign's `$ID/`
+/// prefix (`$ID/Arial` → `Arial`) and the font-format suffix appended when a family is installed
+/// in several formats (`Minion Pro (OTF)` → `Minion Pro`).
+fn plain_family(family: &str) -> Option<&str> {
+ let unprefixed = family.trim_start().strip_prefix("$ID/").map(str::trim).filter(|f| !f.is_empty());
+ without_format_suffix(unprefixed.unwrap_or(family)).or(unprefixed)
+}
+
+ /// A font's height above the baseline (font units) if it is plausible: above 0 and at most 4 em.
+ pub(crate) fn plausible(v: Option<f64>, upem: f64) -> Option<f64> {
+ v.filter(|v| *v > 0.0 && *v <= 4.0 * upem)
+ }
+
+ /// The top of the first of `chars` the font has a non-empty outline for, in font units: the
+ /// highest point of its unhinted outline at `location`, if [`plausible`]. For flat-topped letters
+ /// that is the cap height (`H`) or x-height (`x`).
+ pub(crate) fn measured_top(f: &skrifa::FontRef<'_>, location: LocationRef<'_>, chars: &[char], upem: f64) -> Option<f64> {
+ struct Top(f32);
+ impl OutlinePen for Top {
+ fn move_to(&mut self, _x: f32, y: f32) {
+ self.0 = self.0.max(y);
+ }
+ fn line_to(&mut self, _x: f32, y: f32) {
+ self.0 = self.0.max(y);
+ }
+ fn quad_to(&mut self, _cx: f32, _cy: f32, _x: f32, y: f32) {
+ self.0 = self.0.max(y);
+ }
+ fn curve_to(&mut self, _cx0: f32, _cy0: f32, _cx1: f32, _cy1: f32, _x: f32, y: f32) {
+ self.0 = self.0.max(y);
+ }
+ fn close(&mut self) {}
+ }
+ let cmap = f.charmap();
+ let glyphs = f.outline_glyphs();
+ chars.iter().find_map(|&c| {
+ let g = glyphs.get(cmap.map(c)?)?;
+ let mut pen = Top(f32::NEG_INFINITY);
+ g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen).ok()?;
+ plausible(Some(f64::from(pen.0)), upem)
+ })
+ }
+
+ /// The OS/2 typographic ascender in font units at `location`, if the font has an OS/2 table and
+ /// the value is [`plausible`].
+ fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64) -> Option<f64> {
+ use skrifa::raw::TableProvider;
+ let mut v = f.os2().ok()?.s_typo_ascender() as f64;
+ if !location.coords().is_empty()
+ && let Ok(mvar) = f.mvar()
+ {
+ v += mvar.metric_delta(skrifa::raw::tables::mvar::tags::HASC, location.coords()).map_or(0.0, |d| d.to_f64());
+ }
+ plausible(Some(v), upem)
+ }
+
/// `family` without the font-format suffix layout apps append when a family is installed in
/// several formats (`Minion Pro (OTF)` → `Minion Pro`), if it has one.
fn without_format_suffix(family: &str) -> Option<&str> {
@@@ -1235,9 -1460,54 +1468,54 @@@ impl ScopedFonts<'_>
/// Style names available for `family` (Regular first, then by weight).
pub fn styles(&self, family: &str) -> Vec<String> {
- let v = self.exact_styles(family);
+ self.style_traits(family).into_iter().map(|t| t.2).collect()
+ }
+
+ /// Weight and italic of a style of `family`: from the font when it is known, else from the
+ /// style's name.
+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {
+ let base = base_style(style);
+ self.style_traits(family)
+ .into_iter()
+ .find(|t| t.2.eq_ignore_ascii_case(base))
+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))
+ }
+
+ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked
+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the
+ /// family has no such style.
+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {
+ let (weight, cur_italic) = self.traits_of(family, current);
+ let want_italic = italic.unwrap_or(cur_italic);
+ let want_weight = match bold {
+ Some(true) => 700.0,
+ Some(false) => 400.0,
+ None => weight,
+ };
+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.
+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];
+ let widths = |s: &str| {
+ let n = norm(s);
+ WIDTHS.iter().filter(|w| n.contains(*w)).count()
+ };
+ let cur_widths = widths(current);
+ self.style_traits(family)
+ .into_iter()
+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))
+ .min_by(|a, b| {
+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());
+ let (ka, kb) = (key(a), key(b));
+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))
+ })
+ .map(|t| t.2)
+ }
+
+ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),
+ /// Regular first, then by weight.
+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {
+ let v = self.exact_style_traits(family);
- match without_format_suffix(family) {
+ match plain_family(family) {
- Some(base) if v.is_empty() => self.exact_styles(base),
+ Some(base) if v.is_empty() => self.exact_style_traits(base),
_ => v,
}
}
@@@ -1286,14 -1568,66 +1577,66 @@@
None
}
+ /// `family`'s kind (format, class, PANOSE) and when its file was added, read from its Regular
+ /// face (else its first), for the font menus' filters, which look at every family. A face
+ /// already loaded is asked; an installed family that isn't loaded is read from its file, which
+ /// is then let go rather than kept loaded. None for an unknown family or an unreadable file.
+ pub fn family_kind(&self, family: &str) -> Option<(crate::kind::FaceKind, Option<std::time::SystemTime>)> {
+ let styles = self.styles(family);
+ let style = styles.iter().find(|s| *s == "Regular").or(styles.first())?.clone();
+ if self.own().iter().chain(self.db.read_faces().iter()).any(|f| f.family.eq_ignore_ascii_case(family)) {
+ let f = self.find(family, &style)?;
+ return Some((f.kind(), f.added()));
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let path = {
+ let cat = self.db.read_catalog();
+ let of_family = |c: &&CatalogEntry| c.family.eq_ignore_ascii_case(family);
+ let entry = cat.iter().filter(of_family).find(|c| norm(&c.style) == norm(&style)).or_else(|| cat.iter().find(of_family));
+ entry.map(|c| c.path.clone())?
+ };
+ if std::fs::metadata(&path).ok()?.len() > MAX_DOCUMENT_FONT_BYTES {
+ return None;
+ }
+ let data = Arc::new(std::fs::read(&path).ok()?);
+ let found = enumerate_faces(&data);
+ let pick = found
+ .iter()
+ .find(|(_, f, st, _)| f.eq_ignore_ascii_case(family) && norm(st) == norm(&style))
+ .or_else(|| found.iter().find(|(_, f, _, _)| f.eq_ignore_ascii_case(family)))?
+ .clone();
+ let (index, fam, st, coords) = pick;
+ let face = make_face(FontBytes::Owned(data.clone()), FontSource::Installed(path), index, fam, st, coords)?;
+ Some((face.kind(), face.added()))
+ }
+ #[cfg(target_arch = "wasm32")]
+ None
+ }
+
/// Is `family` available (the document's, loaded, or installed on the system), as named or
- /// without a format suffix (see [`ScopedFonts::face`])?
+ /// without an `$ID/` prefix or a format suffix (see [`ScopedFonts::face`])?
pub fn has_family(&self, family: &str) -> bool {
- self.has_exact_family(family) || without_format_suffix(family).is_some_and(|base| self.has_exact_family(base))
+ self.has_exact_family(family) || plain_family(family).is_some_and(|base| self.has_exact_family(base))
}
+ /// The family and style of the face whose PostScript name is `name`, ignoring case (the
+ /// document's, loaded, or installed on the system, not loading it). SVGs exported from
+ /// Illustrator name fonts this way (`font-family="'MyriadPro-Regular'"`).
+ pub fn postscript_face(&self, name: &str) -> Option<(String, String)> {
+ let named = |ps: Option<&str>| ps.is_some_and(|ps| ps.eq_ignore_ascii_case(name));
+ if let Some(f) = self.own().iter().chain(self.db.read_faces().iter()).find(|f| named(f.postscript_name())) {
+ return Some((f.family.clone(), f.style.clone()));
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(c) = self.db.read_catalog().iter().find(|c| named(c.postscript.as_deref())) {
+ return Some((c.family.clone(), c.style.clone()));
+ }
+ None
+ }
+
fn has_exact_family(&self, family: &str) -> bool {
- if self.own().iter().any(|f| f.family.eq_ignore_ascii_case(family)) || self.db.is_loaded(family) {
+ if self.own().iter().any(|f| f.family.eq_ignore_ascii_case(family) || has_wws_family(f, family)) || self.db.is_loaded(family) {
return true;
}
#[cfg(not(target_arch = "wasm32"))]
diff --cc crates/format/src/lib.rs
index 3bbe8b344,86393f803..29eb554df
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@@ -205,6 -309,60 +309,60 @@@ mod tests
use designcraft_doc::geom::Rect;
use designcraft_doc::{Asset, ParaFormat, SpreadRef};
+ fn png_asset(d: &mut Document, data: &[u8]) -> AssetId {
+ let aid = AssetId(d.alloc());
+ let a = Asset {
- page: 0,
+ id: aid,
+ name: "x.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(data.to_vec()),
+ pixels: Some((1, 1)),
++ ..Default::default()
+ };
+ d.assets.insert(aid, Arc::new(a));
+ aid
+ }
+
+ fn place(d: &mut Document, asset: AssetId, crop: f64) -> designcraft_doc::ItemId {
+ use designcraft_doc::geom::{Affine, shapes};
+ use designcraft_doc::{Content, Graphic, Item, ItemId, Shape};
+ let id = ItemId(d.alloc());
+ let mut it = Item::new(id, d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)));
+ it.content = Content::Graphic(Graphic {
+ asset,
+ size: (1.0, 1.0),
+ xf: Affine::translate((crop, crop)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [crop; 4],
+ });
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ id
+ }
+
+ fn asset_entries(bytes: &[u8]) -> usize {
+ let z = zip::ZipArchive::new(Cursor::new(bytes)).unwrap();
+ z.file_names().filter(|n| n.starts_with("assets/")).count()
+ }
+
+ /// Zip `d` the way files were saved with one asset per placement (nothing merged or pruned).
+ fn save_uncompacted(d: &Document) -> Vec<u8> {
+ let mut buf = Cursor::new(Vec::new());
+ let mut z = zip::ZipWriter::new(&mut buf);
+ let opts = zip::write::SimpleFileOptions::default();
+ z.start_file("mimetype", opts).unwrap();
+ z.write_all(MIME.as_bytes()).unwrap();
+ z.start_file("document.json", opts).unwrap();
+ z.write_all(&serde_json::to_vec(d).unwrap()).unwrap();
+ for (id, a) in &d.assets {
+ z.start_file(format!("assets/{}.png", id.0), opts).unwrap();
+ z.write_all(&a.data).unwrap();
+ }
+ z.finish().unwrap();
+ buf.into_inner()
+ }
+
#[test]
fn roundtrip_with_assets() {
let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
diff --cc crates/idml/src/import.rs
index 3535ef024,9fd519efb..38d89948c
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -132,6 -263,9 +263,9 @@@ struct Importer<'r>
page_index: HashMap<String, usize>,
item_ids: HashMap<String, ItemId>,
assets: BTreeMap<AssetId, Arc<Asset>>,
- /// Assets read from a link path at a page, so later placements of that path and page reuse
- /// them unread.
- linked_assets: HashMap<(String, u32), AssetId>,
++ /// Assets read from a link path at a page and crop, so later placements of that path, page
++ /// and crop reuse them unread.
++ linked_assets: HashMap<(String, u32, designcraft_doc::PdfCrop), AssetId>,
ctx: ItemCtx,
sections: Vec<Section>,
footnote_options: designcraft_doc::FootnoteOptions,
@@@ -2197,13 -2545,45 +2537,39 @@@ impl<'r> Importer<'r>
let size = ((r - l).abs(), (b - t).abs());
let link = g.find("Link");
let uri = link.and_then(|k| k.get("LinkResourceURI")).map(uri_to_path);
+ let graphic = |asset, size| {
+ Content::Graphic(designcraft_doc::Graphic {
+ asset,
+ size,
+ xf: gxf * Affine::translate((l, t)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ })
+ };
let mut data = g.prop_el("Contents").map(|c| base64_decode(&c.text_content())).unwrap_or_default();
- // PDF Import Options: `PDFAttribute/@PageNumber` is 1-based; `Asset.page` is 0-based. A
- // missing or malformed value means page 1, and an out-of-range page later fails to render
- // rather than panicking.
- let page = g
- .find("PDFAttribute")
- .or_else(|| g.prop_el("PDFAttribute"))
- .and_then(|a| a.get("PageNumber"))
- .and_then(|v| v.trim().parse::<u64>().ok())
- .and_then(|n| u32::try_from(n.saturating_sub(1)).ok())
- .unwrap_or(0);
++ let page = pdf_page_in(g);
++ // Where the box sits on the page needs the PDF parsed: the engine finds it after import.
++ let pdf_crop = pdf_attribute(g).and_then(|a| a.get("PDFCrop")).map_or(designcraft_doc::PdfCrop::Crop, names::pdf_crop_in);
+ let mut read_from = None;
if data.is_empty()
&& let Some(p) = &uri
- && let Some(d) = (self.read_link)(p)
{
- data = d;
- // Every placement of a linked file at one page shares one asset; read the file once.
- let key = (p.clone(), page);
++ // Every placement of a linked file with one page and crop shares one asset; read the
++ // file once.
++ let key = (p.clone(), page, pdf_crop);
+ if let Some(id) = self.linked_assets.get(&key) {
+ let size = self.assets.get(id).and_then(|a| svg_viewbox_size(&a.data)).unwrap_or(size);
+ return graphic(*id, size);
+ }
+ if let Some(d) = (self.read_link)(p) {
+ data = d;
+ read_from = Some(key);
+ }
}
+ // InDesign draws a viewBox-only SVG at one unit to the point: its GraphicBounds are the
+ // art's bounds, which can overhang the viewBox, so they must not size the viewBox.
+ let size = svg_viewbox_size(&data).unwrap_or(size);
let (mime, px) = sniff_image(&data);
let mime = mime.map(str::to_string).unwrap_or_else(|| match link.and_then(|k| k.get("LinkResourceFormat")).unwrap_or("") {
f if f.contains("JPEG") => "image/jpeg".into(),
@@@ -2218,21 -2598,14 +2584,16 @@@
});
let name =
uri.as_deref().and_then(|p| p.rsplit(['/', '\\']).next()).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| "image".into());
- let id = AssetId(self.alloc());
+ let fresh = AssetId(self.alloc());
let link_path = uri.filter(|p| p.contains('/') || p.contains('\\'));
- let page = pdf_page_in(g);
- // Where the box sits on the page needs the PDF parsed: the engine finds it after import.
- let pdf_crop = g.find("PDFAttribute").and_then(|a| a.get("PDFCrop")).map_or(designcraft_doc::PdfCrop::Crop, names::pdf_crop_in);
- self.assets
- .insert(id, Arc::new(Asset { page, id, name, mime, link: link_path, data: Arc::new(data), pixels, pdf_crop, ..Default::default() }));
- Content::Graphic(designcraft_doc::Graphic {
- asset: id,
- size,
- xf: gxf * Affine::translate((l, t)),
- auto_fit: Default::default(),
- fit_align: 4,
- crop: [0.0; 4],
- })
- let id =
- designcraft_doc::insert_asset(&mut self.assets, Asset { page, id: fresh, name, mime, link: link_path, data: Arc::new(data), pixels });
++ let id = designcraft_doc::insert_asset(
++ &mut self.assets,
++ Asset { page, id: fresh, name, mime, link: link_path, data: Arc::new(data), pixels, pdf_crop, ..Default::default() },
++ );
+ if let Some(key) = read_from {
+ self.linked_assets.insert(key, id);
+ }
+ graphic(id, size)
}
fn link_threads(&mut self) {
@@@ -2535,11 -2989,6 +2977,21 @@@ fn path_of(pg: &El) -> PathData
PathData::new(subs)
}
- /// The page a placed PDF shows (0-based), from its `PDFAttribute` (`PageNumber` is 1-based).
++/// A placed PDF's `PDFAttribute` (Image Import Options), as a child or a property.
++fn pdf_attribute(g: &El) -> Option<&El> {
++ g.find("PDFAttribute").or_else(|| g.prop_el("PDFAttribute"))
++}
++
++/// The page a placed PDF shows (0-based), from `PDFAttribute/@PageNumber` (1-based). A missing or
++/// malformed value means page 1; a page the PDF lacks draws nothing and is left out of PDF export.
+fn pdf_page_in(g: &El) -> u32 {
- g.find("PDFAttribute").and_then(|a| a.get("PageNumber")).and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |n| n.saturating_sub(1))
++ pdf_attribute(g)
++ .and_then(|a| a.get("PageNumber"))
++ .and_then(|v| v.trim().parse::<u64>().ok())
++ .and_then(|n| u32::try_from(n.saturating_sub(1)).ok())
++ .unwrap_or(0)
+}
+
/// IDML link URI → file system path (`file:/a%20b` → `/a b`, `file:///C:/x` → `C:/x`).
pub(crate) fn uri_to_path(uri: &str) -> String {
let rest = uri.strip_prefix("file://").or_else(|| uri.strip_prefix("file:")).unwrap_or(uri);
diff --cc crates/idml/src/tests.rs
index ce98f6e8c,042a0c8d9..fb61a7637
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -1400,40 -1568,1033 +1568,1071 @@@ fn list_numbering_format_expression_and
check(&import_idml(&export_idml(&d)).unwrap());
}
+ fn fixture_with_styles(styles: &str) -> Vec<u8> {
+ zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", STORY),
+ ])
+ }
+
+ /// Paragraph styles `Body` (based on the root) and `Loose` (no BasedOn), both with `attrs`.
+ fn keep_styles(attrs: &str) -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12"/>
+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {attrs}>
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>
+ </ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" {attrs}/>
+ </RootParagraphStyleGroup>
+ </idPkg:Styles>"#
+ )
+ }
+
+ /// Keep Lines Together whose mode no style sets is InDesign's default: at start/end of paragraph.
+ /// An explicit mode still wins.
+ #[test]
+ fn keep_lines_mode_defaults_to_start_and_end() {
+ let keep = r#"KeepLinesTogether="true" KeepFirstLines="2" KeepLastLines="2""#;
+ for (attrs, all) in [(keep.to_string(), false), (format!(r#"{keep} KeepAllLinesTogether="true""#), true)] {
+ let d = import_idml_with(&fixture_with_styles(&keep_styles(&attrs)), &|_| None).unwrap();
+ for name in ["Body", "Loose"] {
+ let (pp, _) = d.styles.resolve_para_style(name);
+ assert_eq!((pp.keep_lines_together, pp.keep_all_lines, pp.keep_first, pp.keep_last), (true, all, 2, 2), "{name}: {attrs}");
+ }
+ }
+ }
+
+ type Resolved = (designcraft_doc::ParaProps, designcraft_doc::CharProps);
+
+ /// (IDML attribute, InDesign's default as IDML writes it, another value, the resolved field,
+ /// its value for InDesign's default, its value for the other value).
+ type AttrRow = (&'static str, &'static str, &'static str, fn(&Resolved) -> String, String, String);
+
+ macro_rules! attr_rows {
+ ($($attr:literal: $default:literal => $dv:expr, $other:literal => $ov:expr, |$r:ident| $field:expr;)*) => {
+ vec![$(($attr, $default, $other, (|$r: &Resolved| format!("{:?}", $field)) as fn(&Resolved) -> String, format!("{:?}", $dv), format!("{:?}", $ov)),)*]
+ };
+ }
+
+ /// InDesign's defaults for a new document's [No Paragraph Style], for every paragraph and
+ /// character attribute the importer reads (except the font family: see below).
+ fn indesign_text_defaults() -> Vec<AttrRow> {
+ use designcraft_doc::{Align, Capitalization, Composer, Digits, GridAlign, Leading, ListType, Position, StartParagraph, TextDirection};
+ attr_rows! {
+ "Justification": "LeftAlign" => Align::Left, "CenterAlign" => Align::Center, |r| r.0.align;
+ "ParagraphDirection": "LeftToRightDirection" => TextDirection::LeftToRight, "RightToLeftDirection" => TextDirection::RightToLeft, |r| r.0.direction;
+ "LeftIndent": "0" => 0.0, "6" => 6.0, |r| r.0.left_indent;
+ "RightIndent": "0" => 0.0, "6" => 6.0, |r| r.0.right_indent;
+ "FirstLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.first_line_indent;
+ "LastLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.last_line_indent;
+ "SpaceBefore": "0" => 0.0, "6" => 6.0, |r| r.0.space_before;
+ "SpaceAfter": "0" => 0.0, "6" => 6.0, |r| r.0.space_after;
+ "DropCapLines": "0" => 0, "3" => 3, |r| r.0.drop_cap_lines;
+ "DropCapCharacters": "0" => 0, "1" => 1, |r| r.0.drop_cap_chars;
+ "DropcapDetail": "1" => (true, false), "2" => (false, true), |r| (r.0.drop_cap_align_left, r.0.drop_cap_scale_descenders);
+ "GridAlignment": "None" => GridAlign::None, "AlignToBaseline" => GridAlign::AllLines, |r| r.0.grid_align;
+ "Composer": "HL Composer" => Composer::Paragraph, "HL Single" => Composer::SingleLine, |r| r.0.composer;
+ "Hyphenation": "true" => true, "false" => false, |r| r.0.hyphenate;
+ "HyphenateWordsLongerThan": "5" => 5, "7" => 7, |r| r.0.hyph_min_word;
+ "HyphenateAfterFirst": "2" => 2, "3" => 3, |r| r.0.hyph_after_first;
+ "HyphenateBeforeLast": "2" => 2, "3" => 3, |r| r.0.hyph_before_last;
+ "HyphenateLadderLimit": "3" => 3, "0" => 0, |r| r.0.hyph_limit;
+ "HyphenationZone": "36" => 36.0, "18" => 18.0, |r| r.0.hyph_zone;
+ "HyphenateCapitalizedWords": "true" => true, "false" => false, |r| r.0.hyph_capitalized;
+ "HyphenateLastWord": "true" => true, "false" => false, |r| r.0.hyph_last_word;
+ "HyphenateAcrossColumns": "true" => true, "false" => false, |r| r.0.hyph_across_column;
+ "HyphenWeight": "5" => 0.5, "9" => 0.9, |r| r.0.hyph_weight;
+ "MinimumWordSpacing": "80" => 0.8, "70" => 0.7, |r| r.0.word_space_min;
+ "DesiredWordSpacing": "100" => 1.0, "90" => 0.9, |r| r.0.word_space_desired;
+ "MaximumWordSpacing": "133" => 1.33, "150" => 1.5, |r| r.0.word_space_max;
+ "MinimumLetterSpacing": "0" => 0.0, "-5" => -0.05, |r| r.0.letter_space_min;
+ "DesiredLetterSpacing": "0" => 0.0, "1" => 0.01, |r| r.0.letter_space_desired;
+ "MaximumLetterSpacing": "0" => 0.0, "5" => 0.05, |r| r.0.letter_space_max;
+ "MinimumGlyphScaling": "100" => 1.0, "97" => 0.97, |r| r.0.glyph_scale_min;
+ "DesiredGlyphScaling": "100" => 1.0, "101" => 1.01, |r| r.0.glyph_scale_desired;
+ "MaximumGlyphScaling": "100" => 1.0, "103" => 1.03, |r| r.0.glyph_scale_max;
+ "AutoLeading": "120" => 1.2, "100" => 1.0, |r| r.0.auto_leading;
+ "SingleWordJustification": "FullyJustified" => Align::FullyJustified, "LeftAlign" => Align::Left, |r| r.0.single_word_justify;
+ "KeepWithNext": "0" => 0, "1" => 1, |r| r.0.keep_with_next;
+ "KeepLinesTogether": "false" => false, "true" => true, |r| r.0.keep_lines_together;
+ "KeepAllLinesTogether": "false" => false, "true" => true, |r| r.0.keep_all_lines;
+ "KeepFirstLines": "2" => 2, "3" => 3, |r| r.0.keep_first;
+ "KeepLastLines": "2" => 2, "3" => 3, |r| r.0.keep_last;
+ "StartParagraph": "Anywhere" => StartParagraph::Anywhere, "NextColumn" => StartParagraph::NextColumn, |r| r.0.start_paragraph;
+ "BulletsAndNumberingListType": "NoList" => ListType::None, "BulletList" => ListType::Bullets, |r| r.0.list_type;
+ "BalanceRaggedLines": "NoBalancing" => false, "FullyBalanced" => true, |r| r.0.balance_ragged;
+ "Kashidas": "DefaultKashidas" => true, "KashidasOff" => false, |r| r.0.kashidas;
+ "RuleAbove": "false" => false, "true" => true, |r| r.0.rule_above.on;
+ "RuleAboveColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_above.color;
+ "RuleAboveTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_above.tint;
+ "RuleBelow": "false" => false, "true" => true, |r| r.0.rule_below.on;
+ "RuleBelowColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_below.color;
+ "RuleBelowTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.tint;
+ "ParagraphShadingOn": "false" => false, "true" => true, |r| r.0.shading_on;
+ "ParagraphShadingColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.shading_color;
+ "ParagraphShadingTint": "20" => 0.2f32, "50" => 0.5f32, |r| r.0.shading_tint;
+ "ParagraphBorderOn": "false" => false, "true" => true, |r| r.0.border_on;
+ "ParagraphBorderColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.border_color;
+ "ParagraphBorderTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.border_tint;
+ "FontStyle": "Regular" => "Regular", "Bold" => "Bold", |r| r.1.font_style;
+ "PointSize": "12" => 12.0, "9" => 9.0, |r| r.1.size;
+ "Leading": "Auto" => Leading::Auto, "14" => Leading::Points(14.0), |r| r.1.leading;
+ "KerningMethod": "$ID/Metrics" => designcraft_doc::Kerning::Metrics, "$ID/Optical" => designcraft_doc::Kerning::Optical, |r| r.1.kerning;
+ "Tracking": "0" => 0.0, "20" => 20.0, |r| r.1.tracking;
+ "HorizontalScale": "100" => 1.0, "90" => 0.9, |r| r.1.h_scale;
+ "VerticalScale": "100" => 1.0, "90" => 0.9, |r| r.1.v_scale;
+ "BaselineShift": "0" => 0.0, "2" => 2.0, |r| r.1.baseline_shift;
+ "Skew": "0" => 0.0, "10" => 10.0, |r| r.1.skew;
+ "FillColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.1.fill;
+ "FillTint": "-1" => 1.0, "50" => 0.5, |r| r.1.fill_tint;
+ "StrokeColor": "Swatch/None" => "[None]", "Color/Black" => "[Black]", |r| r.1.stroke;
+ "StrokeTint": "-1" => 1.0, "50" => 0.5, |r| r.1.stroke_tint;
+ "StrokeWeight": "1" => 1.0, "2" => 2.0, |r| r.1.stroke_weight;
+ "Capitalization": "Normal" => Capitalization::Normal, "AllCaps" => Capitalization::AllCaps, |r| r.1.capitalization;
+ "Position": "Normal" => Position::Normal, "Superscript" => Position::Superscript, |r| r.1.position;
+ "Underline": "false" => false, "true" => true, |r| r.1.underline;
+ "StrikeThru": "false" => false, "true" => true, |r| r.1.strikethrough;
+ "UnderlineTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.underline_tint;
+ "StrikeThruTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.strikethrough_tint;
+ "Ligatures": "true" => true, "false" => false, |r| r.1.ligatures;
+ "NoBreak": "false" => false, "true" => true, |r| r.1.no_break;
+ "OTFContextualAlternate": "true" => true, "false" => false, |r| designcraft_doc::otf::is_on(&r.1.otf_features, "calt");
+ "DigitsType": "DefaultDigits" => Digits::Default, "ArabicDigits" => Digits::Arabic, |r| r.1.digits;
+ "AppliedLanguage": "$ID/English: USA" => "English: USA", "$ID/German: 2006 Reform" => "German: 2006 Reform", |r| r.1.language;
+ }
+ }
+
+ /// [No paragraph style] with `root` attributes and `Body`, based on it, with `body` attributes.
+ fn text_styles(root: &str, body: &str) -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <RootParagraphStyleGroup Self="rp">
+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" {root}/>
+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {body}>
+ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>
+ </idPkg:Styles>"#
+ )
+ }
+
+ fn resolve_body(root: &str, body: &str) -> Resolved {
+ let d = import_idml_with(&fixture_with_styles(&text_styles(root, body)), &|_| None).unwrap();
+ d.styles.resolve_para_style("Body")
+ }
+
+ /// Text attributes an IDML file leaves unset are InDesign's defaults; written ones win, and a
+ /// file that writes every default (as InDesign's own exports do) imports the same.
+ #[test]
+ fn absent_text_attributes_take_indesign_defaults() {
+ let rows = indesign_text_defaults();
+ let all = |pick: fn(&AttrRow) -> &str| rows.iter().map(|r| format!(r#"{}="{}""#, r.0, pick(r))).collect::<Vec<_>>().join(" ");
+ let (defaults, others) = (all(|r| r.1), all(|r| r.2));
+ let omitted = resolve_body("", "");
+ let written = resolve_body(&defaults, "");
+ for (attr, _, _, field, want, _) in &rows {
+ assert_eq!(field(&omitted), *want, "{attr} omitted");
+ assert_eq!(field(&written), *want, "{attr} written as InDesign's default");
+ }
+ assert_eq!(omitted, written);
+ for (root, body) in [(others.as_str(), ""), ("", others.as_str())] {
+ let r = resolve_body(root, body);
+ for (attr, _, _, field, _, want) in &rows {
+ assert_eq!(field(&r), *want, "{attr} written on the {}", if root.is_empty() { "style" } else { "root" });
+ }
+ }
+ // Product difference: InDesign's default face isn't available, so unset fonts are DesignCraft's.
+ assert_eq!(omitted.1.font_family, designcraft_doc::CharProps::default().font_family);
+ }
+
+ /// A tint of -1 is the colour's own tint (100 %): written on a style, it replaces its parent's.
+ /// Tints are never negative or above 100 %.
+ #[test]
+ fn minus_one_tint_is_the_colours_own() {
+ let tints = |v: &str| {
+ ["UnderlineTint", "StrikeThruTint", "FillTint", "StrokeTint", "ParagraphShadingTint", "ParagraphBorderTint", "RuleAboveTint", "RuleBelowTint"]
+ .map(|k| format!(r#"{k}="{v}""#))
+ .join(" ")
+ + r#" RuleAbove="true" RuleBelow="true""#
+ };
+ for (body, want) in [("-1", 1.0), ("150", 1.0)] {
+ let r = resolve_body(&tints("50"), &tints(body));
+ let got = [
+ r.1.underline_tint,
+ r.1.strikethrough_tint,
+ r.1.fill_tint,
+ r.1.stroke_tint,
+ r.0.shading_tint,
+ r.0.border_tint,
+ r.0.rule_above.tint,
+ r.0.rule_below.tint,
+ ];
+ assert_eq!(got, [want; 8], "{body}");
+ }
+ // Footnote rules, table fills and strokes, cell fills.
+ let prefs = PREFS.replace("</idPkg:Preferences>", r#"<FootnoteOption RuleTint="-1"/></idPkg:Preferences>"#);
+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartRowFillTint="-1" EndRowFillTint="-1" TopBorderStrokeTint="-1">
+ <Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0" FillColor="Color/Black" FillTint="-1" TopEdgeStrokeTint="-1"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>
+ </idPkg:Story>"#;
+ let d = import_idml_with(
+ &zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", &prefs),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", story),
+ ]),
+ &|_| None,
+ )
+ .unwrap();
+ assert_eq!(d.footnote_options.rule.tint, 1.0);
+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ let alt = t.options.alt_rows.as_ref().unwrap();
+ assert_eq!((alt.first_tint, alt.next_tint, t.options.border.tint), (1.0, 1.0, 1.0));
+ let c = t.cell(0, 0).unwrap();
+ assert_eq!((c.fill_tint, c.strokes[0].tint), (1.0, 1.0));
+ }
+
+ /// Rules in Text Color take the colour of the paragraph's text; they round-trip as Text Color.
+ #[test]
+ fn text_color_rules_round_trip() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let rule = designcraft_doc::Rule { on: true, ..Default::default() };
+ assert_eq!(rule.color, designcraft_doc::TEXT_COLOR);
+ let para = designcraft_doc::ParaAttrs {
+ rule_above: Some(rule.clone()),
+ rule_below: Some(designcraft_doc::Rule { color: "[Black]".into(), ..rule }),
+ kashidas: Some(false),
+ ..Default::default()
+ };
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Ruled", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().paras[0].para = para.clone();
+ let bytes = export_idml(&d);
+ let story = zip_text(&bytes, "Stories/");
+ assert!(story.contains(r#"<RuleAboveColor type="string">Text Color</RuleAboveColor>"#), "{story}");
+ assert!(story.contains(r#"Kashidas="KashidasOff""#), "{story}");
+ let back = import_idml(&bytes).unwrap();
+ let p = &back.stories.values().find(|s| s.text == "Ruled").unwrap().paras[0];
+ assert_eq!((p.para.rule_above.as_ref(), p.para.rule_below.as_ref()), (para.rule_above.as_ref(), para.rule_below.as_ref()));
+ assert_eq!(p.para.kashidas, Some(false));
+ }
+
+ /// `[Basic Paragraph]` is InDesign's `$ID/NormalParagraphStyle`, both ways.
+ #[test]
+ fn basic_paragraph_is_normal_paragraph_style() {
+ let d = import_idml_with(&fixture(), &|_| None).unwrap();
+ let basic = d.styles.para(st::BASIC_PARAGRAPH).unwrap();
+ assert_eq!(basic.based_on.as_deref(), Some(designcraft_doc::NO_PARA_STYLE));
+ assert_eq!(d.styles.para("Text/Body").unwrap().based_on.as_deref(), Some(st::BASIC_PARAGRAPH));
+ let s = d.stories.values().find(|s| s.text.starts_with("Hello")).unwrap();
+ assert_eq!(s.paras[1].style, st::BASIC_PARAGRAPH);
+ assert!(d.styles.paragraph.iter().all(|p| !p.name.contains("NormalParagraphStyle")));
+ let bytes = export_idml(&d);
+ let styles = zip_text(&bytes, "Resources/Styles.xml");
+ assert!(styles.contains(r#"Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle""#), "{styles}");
+ assert!(zip_text(&bytes, "Stories/").contains(r#"AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle""#));
+ let back = import_idml(&bytes).unwrap();
+ assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1);
+ }
+
+ /// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults
+ /// for a new document.
+ #[test]
+ fn absent_item_and_document_attributes_take_indesign_defaults() {
+ use designcraft_doc::{Cap, FirstBaseline, Join, StrokeAlign, VerticalJustification};
+ use designcraft_geom::corners::CornerShape;
+ let path = |x: f64| {
+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]
+ .iter()
+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
+ .collect();
+ format!(
+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#
+ )
+ };
+ let designmap = format!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">
+ <NumberingList Self="NumberingList/Steps" Name="Steps"/>
+ <RootTableStyleGroup Self="rts"><TableStyle Self="TableStyle/Banded" Name="Banded" StartRowFillCount="1"/></RootTableStyleGroup>
+ <Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartColumnFillCount="2"><Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>
+ <Spread Self="sp1"><Page Self="p1"/>
+ <Rectangle Self="plain">{}</Rectangle>
+ <Rectangle Self="round" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner">{}</Rectangle>
+ <Rectangle Self="legacy" CornerOption="RoundedCorner">{}</Rectangle>
+ <Rectangle Self="sized" TopLeftCornerOption="RoundedCorner" TopLeftCornerRadius="5">{}</Rectangle>
+ <TextFrame Self="tf" ParentStory="s1">{}</TextFrame>
+ </Spread>
+ </Document>"#,
+ path(0.0),
+ path(100.0),
+ path(200.0),
+ path(300.0),
+ path(400.0)
+ );
+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();
+ // Document Setup, margins and columns, grids, Advanced Type, transparency, black.
+ let s = &d.settings;
+ assert_eq!((s.page_width, s.page_height, s.facing_pages, s.intent), (612.0, 792.0, true, designcraft_doc::Intent::Print));
+ assert_eq!((s.bleed, s.slug), ([0.0; 4], [0.0; 4]));
+ let page = &d.spreads[0].pages[0];
+ assert_eq!((page.margins.top, page.margins.bottom, page.margins.inside, page.margins.outside), (36.0, 36.0, 36.0, 36.0));
+ assert_eq!((page.columns.count, page.columns.gutter), (1, 12.0));
+ assert_eq!((s.baseline_grid.start, s.baseline_grid.increment, s.baseline_grid.view_threshold), (36.0, 12.0, 0.75));
+ assert_eq!((s.grid.horizontal, s.grid.vertical, s.grid.subdivisions, s.grid.in_back), (72.0, 72.0, 8, true));
+ let a = &s.advanced_type;
+ assert_eq!((a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position), (58.3, 33.3, 58.3, 33.3));
+ assert_eq!((s.blend_space, s.overprint_black, s.keyboard_increment), (designcraft_doc::BlendSpace::Cmyk, true, 1.0));
+ // Fill, stroke, transparency, wrap and corners of a frame with no attributes.
+ let item = |n: usize| d.spreads[0].items[n].clone();
+ let plain = item(0);
+ assert!(plain.fill.is_none() && plain.stroke.is_none());
+ let st = &plain.stroke;
+ assert_eq!((st.weight, st.miter_limit, st.cap, st.join, st.align), (1.0, 4.0, Cap::Butt, Join::Miter, StrokeAlign::Center));
+ assert_eq!((plain.opacity, plain.blend, plain.wrap.mode), (1.0, designcraft_color::BlendMode::Normal, designcraft_doc::WrapMode::None));
+ assert!(plain.corners.is_none());
+ // A corner shape without a size: 12 pt.
+ for n in [1, 2] {
+ assert_eq!(item(n).corners.corners.map(|c| (c.shape, c.size)), [(CornerShape::Rounded, 12.0); 4], "item {n}");
+ }
+ assert_eq!(item(3).corners.corners[0].size, 5.0);
+ // Text Frame Options.
+ let tf = item(4);
+ let o = &tf.text_frame().unwrap().options;
+ assert_eq!((o.columns, o.gutter, o.inset, o.balance_columns, o.ignore_wrap), (1, 12.0, [0.0; 4], false, false));
+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Top, FirstBaseline::Ascent, 0.0));
+ assert_eq!((o.auto_size, o.auto_size_ref), (designcraft_doc::AutoSize::Off, 4), "auto-size from the centre");
+ // Numbered lists don't continue across stories.
+ assert_eq!(d.settings.lists, vec![designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: false }]);
+ // Table and cell options.
+ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();
+ assert_eq!((t.options.space_before, t.options.space_after, t.options.repeat_header), (4.0, -4.0, true));
+ assert_eq!((t.options.border.weight, t.options.border.color.as_str()), (1.0, "[Black]"));
+ assert_eq!((t.rows[0].mode, t.rows[0].height), (designcraft_doc::RowHeightMode::AtLeast, 3.0));
+ // Alternating fills: the first rows or columns Black 20 %, the next None.
+ let fills = |a: &designcraft_doc::AltFills| (a.first_color.clone(), a.first_tint, a.next_color.clone(), a.next_tint, a.next);
+ let want = ("[Black]".to_string(), 0.2f32, "[None]".to_string(), 1.0f32, 1);
+ assert_eq!(fills(t.options.alt_rows.as_ref().unwrap()), want);
+ let cols = t.options.alt_cols.as_ref().unwrap();
+ assert_eq!((fills(cols), cols.first), (want.clone(), 2));
+ let banded = d.styles.table.iter().find(|s| s.name == "Banded").unwrap();
+ let mut bt = designcraft_doc::Table::new(0, 1, 1, 0, 0, 100.0);
+ d.styles.resolve_table_style(&banded.name).apply_to(&mut bt, &d.styles.cell);
+ assert_eq!(fills(bt.options.alt_rows.as_ref().unwrap()), want);
+ let c = t.cell(0, 0).unwrap();
+ assert_eq!((c.insets, c.vj, c.fill.as_str()), ([4.0; 4], VerticalJustification::Top, "[None]"));
+ for e in &c.strokes {
+ assert_eq!((e.weight, e.color.as_str(), e.tint, &e.kind), (1.0, "[Black]", 1.0, &designcraft_doc::StrokeType::Solid));
+ }
+ }
+
+ /// IDML has no attribute for a drop cap's character style: it is the nested style list's leading
+ /// "through 1 Dropcap" entry, read into the drop cap style and written back from it.
+ #[test]
+ fn drop_caps_import_and_round_trip() {
+ // A style with a drop cap and its character style; a paragraph overriding both locally.
+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">
+ <Properties><AllNestedStyles type="list"><ListItem type="record">
+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>
+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>
+ </ParagraphStyle>
+ </RootParagraphStyleGroup>"#;
+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);
+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2">
+ <Properties><AllNestedStyles type="list"><ListItem type="record">
+ <AppliedCharacterStyle type="object">CharacterStyle/$ID/[No character style]</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>
+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>
+ </ParagraphStyleRange>
+ </Story>
+ </idPkg:Story>"#;
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", story),
+ ]);
+ let check = |d: &Document| {
+ let st = d.styles.para("Opener").unwrap();
+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));
+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));
+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]), "one entry, not duplicated");
+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];
+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));
+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));
+ };
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ check(&d);
+ let bytes = export_idml(&d);
+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"), "not an IDML attribute");
+ check(&import_idml(&bytes).unwrap());
+ // A drop cap style set without nested styles is written as one; Align Left Edge and Scale for
+ // Descenders as DropcapDetail.
+ let mut d = d;
+ if let Some(s) = d.styles_mut().para_mut("Opener") {
+ s.para.nested_styles = None;
+ s.para.drop_cap_align_left = Some(false);
+ s.para.drop_cap_scale_descenders = Some(true);
+ }
+ let bytes = export_idml(&d);
+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));
+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));
+ let back = import_idml(&bytes).unwrap();
+ let st = back.styles.para("Opener").unwrap();
+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), Some("Strong")));
+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));
+ assert_eq!(st.para.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Strong")]));
+ }
+
+ /// IDML styles and stories with an `Opener` style whose drop cap style is `Strong`, plus `styles`
+ /// (more paragraph styles) and `paras` (the story's paragraph ranges). `WORDS` in them stands for
+ /// a nested style list of `Strong` through 1 word.
+ fn drop_cap_fixture(styles: &str, paras: &str) -> Vec<u8> {
+ let nested = |style: &str, delim: &str| {
+ format!(
+ r#"<AllNestedStyles type="list"><ListItem type="record"><AppliedCharacterStyle type="object">CharacterStyle/{style}</AppliedCharacterStyle><Delimiter type="enumeration">{delim}</Delimiter><Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles>"#
+ )
+ };
+ let words = nested("Strong", "AnyWord");
+ let opener = format!(
+ r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3"><Properties>{}</Properties></ParagraphStyle>
+ {}
+ </RootParagraphStyleGroup>"#,
+ nested("Strong", "Dropcap"),
+ styles.replace("WORDS", &words)
+ );
+ let styles = STYLES.replace("</RootParagraphStyleGroup>", &opener);
+ let story = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Story Self="s1">{}</Story>
+ </idPkg:Story>"#,
+ paras.replace("WORDS", &words)
+ );
+ zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ])
+ }
+
+ /// A nested style list replaces the inherited one, drop cap style entry included: a style or
+ /// paragraph with a list of its own and no Dropcap entry has no drop cap style.
+ #[test]
+ fn own_nested_styles_clear_an_inherited_drop_cap_style() {
+ let styles = r#"<ParagraphStyle Self="ParagraphStyle/Child" Name="Child"><Properties><BasedOn type="object">ParagraphStyle/Opener</BasedOn>WORDS</Properties></ParagraphStyle>
+ <ParagraphStyle Self="ParagraphStyle/Plain" Name="Plain"><Properties>WORDS</Properties></ParagraphStyle>"#;
+ let paras = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener"><Properties>WORDS</Properties>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Cleared</Content><Br/></CharacterStyleRange>
+ </ParagraphStyleRange>
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Inherited</Content></CharacterStyleRange>
+ </ParagraphStyleRange>"#;
+ let d = import_idml_with(&drop_cap_fixture(styles, paras), &|_| None).unwrap();
+ let cap = |name: &str| d.styles.para(name).unwrap().para.drop_cap_style.clone();
+ assert_eq!(cap("Opener").as_deref(), Some("Strong"));
+ assert_eq!(cap("Child").as_deref(), Some(st::NO_CHAR_STYLE), "its own list replaces Opener's");
+ assert_eq!(cap("Plain"), None, "nothing to clear");
+ let story = d.stories.values().find(|s| s.text.starts_with("Cleared")).unwrap();
+ assert_eq!(story.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));
+ assert_eq!(story.paras[1].para.drop_cap_style, None);
+ assert_eq!(d.styles.resolve_para(&story.paras[1]).0.drop_cap_style, "Strong");
+ }
+
+ /// Paragraphs in table cells and footnotes are cleared like story paragraphs.
+ #[test]
+ fn own_nested_styles_clear_an_inherited_drop_cap_style_in_cells_and_notes() {
+ let opener = |text: &str| {
+ format!(
+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener"><Properties>WORDS</Properties><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>"#
+ )
+ };
+ let paras = format!(
+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">
+ <Content>Body</Content><Footnote>{}</Footnote>
+ <Table HeaderRowCount="0" FooterRowCount="0"><Row Name="0" MinimumHeight="24"/><Column Name="0" SingleColumnWidth="60"/><Cell Name="0:0">{}</Cell></Table>
+ </CharacterStyleRange></ParagraphStyleRange>"#,
+ opener("Note"),
+ opener("Cell")
+ );
+ let d = import_idml_with(&drop_cap_fixture("", &paras), &|_| None).unwrap();
+ let story = d.stories.values().find(|s| !s.notes.is_empty()).expect("story with a footnote");
+ let note = &story.notes[0].text;
+ assert_eq!(note.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE), "{:?}", note.text);
+ let cell = &story.tables.values().next().expect("a table").cell(0, 0).unwrap().text;
+ assert_eq!(cell.paras[0].para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE), "{:?}", cell.text);
+ }
+
+ /// A paragraph that clears its style's drop cap style without nested styles of its own round-trips:
+ /// it is written with the style's list, the Dropcap entry set to [None].
+ #[test]
+ fn a_cleared_drop_cap_style_round_trips() {
+ let paras = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>
+ </ParagraphStyleRange>"#;
+ let mut d = import_idml_with(&drop_cap_fixture("", paras), &|_| None).unwrap();
+ let sid = *d.stories.keys().next().unwrap();
+ let clear = |d: &mut Document| d.story_mut(sid).unwrap().paras[0].para.drop_cap_style = Some(st::NO_CHAR_STYLE.into());
+ let resolved = |d: &Document| {
+ let st = d.stories.values().find(|s| s.text.starts_with("Once")).unwrap();
+ d.styles.resolve_para(&st.paras[0]).0
+ };
+ clear(&mut d);
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let pp = resolved(&back);
+ assert_eq!(pp.drop_cap_style, st::NO_CHAR_STYLE);
+ assert_eq!(pp.nested_styles, vec![designcraft_doc::NestedStyle::drop_cap(st::NO_CHAR_STYLE)]);
+ // The style's drop cap style without nested styles: the paragraph is written with an empty
+ // list, which clears it on import.
+ if let Some(s) = d.styles_mut().para_mut("Opener") {
+ s.para.nested_styles = None;
+ }
+ assert_eq!(resolved(&d).drop_cap_style, st::NO_CHAR_STYLE);
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.styles.para("Opener").unwrap().para.drop_cap_style.as_deref(), Some("Strong"));
+ let pp = resolved(&back);
+ assert_eq!(pp.drop_cap_style, st::NO_CHAR_STYLE);
+ assert!(pp.nested_styles.iter().all(|ns| ns.style != "Strong"), "{:?}", pp.nested_styles);
+ }
+
+ /// Frames take the corners and Text Frame Options they don't write from their object style chain,
+ /// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a
+ /// corner shape without a radius takes the chain's radius.
+ #[test]
+ fn frames_inherit_object_style_corners_and_text_frame_options() {
+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};
+ use designcraft_geom::corners::CornerShape as C;
+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.
+ let path = |x: f64| {
+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]
+ .iter()
+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))
+ .collect();
+ format!(
+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#
+ )
+ };
+ let corners = |opt: &str, r: &str| {
+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")
+ };
+ let inset = |v: f64| {
+ format!(
+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,
+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)
+ )
+ };
+ let designmap = format!(
+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">
+ <RootObjectStyleGroup Self="ro">
+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>
+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">
+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>
+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>
+ </ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">
+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>
+ </ObjectStyle>
+ </RootObjectStyleGroup>
+ <Story Self="s1"/>
+ <Spread Self="sp1"><Page Self="p1"/>
+ <TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>
+ <Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>
+ <Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>
+ <Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>
+ </Spread>
+ </Document>"#,
+ none = corners("None", "12"),
+ inset = inset(3.0),
+ p0 = path(0.0),
+ p1 = path(100.0),
+ p2 = path(200.0),
+ p3 = path(300.0),
+ );
+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();
+ let item = |n: usize| d.spreads[0].items[n].clone();
+ // Path order: top-left, bottom-left, bottom-right, top-right.
+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));
+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);
+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);
+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));
+ assert_eq!(item(2).corners.corners[3].size, 11.34);
+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);
+ let tf = item(0);
+ let o = &tf.text_frame().unwrap().options;
+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));
+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));
+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));
+ }
+ #[test]
+ fn type_on_a_path_keeps_its_start_and_end_brackets() {
+ use designcraft_geom::{Anchor, PathData, Point, SubPath};
+ for end in [Some(250.0), None] {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = designcraft_doc::ItemId(d.alloc());
+ let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(100.0, 300.0)), Anchor::corner(Point::new(500.0, 300.0))], false));
+ let mut it = designcraft_doc::Item::new(id, lid, Shape::GraphicLine, line);
+ let sid = designcraft_doc::StoryId(d.alloc());
+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };
+ tf.options.path = Some(designcraft_doc::PathType { start: 30.0, end, ..Default::default() });
+ it.content = designcraft_doc::Content::Text(tf);
+ let mut story = designcraft_doc::Story::with_text(sid, "Along", Default::default());
+ story.frames = vec![id];
+ d.stories.insert(sid, std::sync::Arc::new(story));
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let pt = back.spreads[0].items[0].text_frame().unwrap().options.path.clone().unwrap();
+ assert!((pt.start - 30.0).abs() < 1e-6, "{pt:?}");
+ assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");
+ }
+ }
+
+ #[test]
+ fn a_strokes_gradient_vector_round_trips() {
+ let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());
+ let id = designcraft_doc::ItemId(d.alloc());
+ let mut it = designcraft_doc::Item::new(
+ id,
+ d.default_layer(),
+ designcraft_doc::Shape::Path,
+ designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(10.0, 10.0, 110.0, 60.0)),
+ );
+ it.stroke.gradient_vector = Some([10.0, 35.0, 110.0, 35.0]);
+ d.insert_item(designcraft_doc::SpreadRef::Doc(0), it, None).unwrap();
+ let back = crate::import_idml(&crate::export_idml(&d)).unwrap();
+ let v = back.spreads[0].items[0].stroke.gradient_vector.unwrap();
+ assert!(v.iter().zip([10.0, 35.0, 110.0, 35.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{v:?}");
+ }
+
+ #[test]
+ fn frame_preference_import_caps_column_count_without_composition() {
+ for (raw, expected) in [("4000000000", 216), ("1e300", 216), ("-100", 1), ("0", 1), ("NaN", 1), ("inf", 1), ("-inf", 1)] {
+ for attribute in [true, false] {
+ let preference = if attribute {
+ format!(r#"<TextFramePreference TextColumnCount="{raw}"/>"#)
+ } else {
+ format!(
+ r#"<TextFramePreference><Properties><TextColumnCount type="number">{raw}</TextColumnCount></Properties></TextFramePreference>"#
+ )
+ };
+ let document = format!(
+ r#"<Document><Story Self="s"/><Spread Self="spread"><Page Self="page"/><TextFrame Self="frame" ParentStory="s">{preference}</TextFrame></Spread></Document>"#
+ );
+ let d = import_idml_with(&zip_files(&[("designmap.xml", &document)]), &|_| None).unwrap();
+ let frame = d.spreads[0].items[0].text_frame().unwrap();
+ // Inspect imported data only: never compose an unbounded input value.
+ assert_eq!(frame.options.columns, expected, "{raw}, attribute={attribute}");
+ }
+ }
+ }
+
+ #[test]
+ fn frame_preference_property_color_resolves_for_frames_and_object_styles() {
+ let document = r#"<Document>
+ <Color Self="Color/Near" Model="Process" Space="RGB" ColorValue="255 0 0" Name="Near" Visible="true"/>
+ <Color Self="Color/Far" Model="Process" Space="RGB" ColorValue="0 0 255" Name="Far" Visible="true"/>
+ <RootObjectStyleGroup Self="root">
+ <ObjectStyle Self="ObjectStyle/Base" Name="Base" EnableTextFrameGeneralOptions="true"><TextFramePreference ColumnRuleStrokeColor="Color/Far"/></ObjectStyle>
+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" EnableTextFrameGeneralOptions="true"><Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></ObjectStyle>
+ </RootObjectStyleGroup>
+ <Story Self="s"/><Spread Self="spread"><Page Self="page"/>
+ <TextFrame Self="local" ParentStory="s" AppliedObjectStyle="ObjectStyle/Base"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ <TextFrame Self="inherited" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"/>
+ <TextFrame Self="attribute" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference ColumnRuleStrokeColor="Color/Far"><Properties><ColumnRuleStrokeColor type="object">Color/Near</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ <TextFrame Self="invalid" ParentStory="s" AppliedObjectStyle="ObjectStyle/Child"><TextFramePreference><Properties><ColumnRuleStrokeColor type="object">missing</ColumnRuleStrokeColor></Properties></TextFramePreference></TextFrame>
+ </Spread></Document>"#;
+ let d = import_idml_with(&zip_files(&[("designmap.xml", document)]), &|_| None).unwrap();
+ let colors: Vec<_> = d.spreads[0].items.iter().map(|it| it.text_frame().unwrap().options.column_rule_color.as_str()).collect();
+ assert_eq!(colors, vec!["Near", "Near", "Far", designcraft_color::swatch::NONE]);
+ assert_eq!(d.styles.object_style("Child").unwrap().text_frame.as_ref().unwrap().column_rule_color, "Near");
+ }
+
+ /// A two-page spread with ruler guides on its pages (and one on the parent), in `origin` ruler
+ /// coordinates.
+ fn guides_package(origin: &str) -> Vec<u8> {
+ let prefs = PREFS.replace("</idPkg:Preferences>", &format!(r#"<ViewPreference RulerOrigin="{origin}"/></idPkg:Preferences>"#));
+ let spread = SPREAD.replace(
+ r#"<Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>"#,
+ r#"<Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350">
+ <Guide Self="g1" Orientation="Vertical" Location="40" FitToPage="true" ItemLayer="L1" Locked="true"/>
+ <Guide Self="g2" Orientation="Horizontal" Location="100" FitToPage="false"/>
+ </Page>"#,
+ );
+ let master = MASTER.replace(
+ r#"<Page Self="mp1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>"#,
+ r#"<Page Self="mp1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"><Guide Self="mg" Orientation="Vertical" Location="84"/></Page>"#,
+ );
+ zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", &prefs),
+ ("MasterSpreads/MasterSpread_m1.xml", &master),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", STORY),
+ ])
+ }
+
+ /// Ruler guides come in from IDML (they were dropped): on their page, measured from the ruler
+ /// origin, with Fit to Page, Locked and their layer; parent pages' too. They go out again.
+ #[test]
+ fn ruler_guides_import_and_round_trip() {
+ use designcraft_doc::Orientation::{Horizontal, Vertical};
+ let guides = |d: &Document| {
+ let p = &d.spreads[0].pages[1];
+ p.guides.iter().map(|g| (g.orientation, g.position, g.spread, g.locked, g.layer.is_some())).collect::<Vec<_>>()
+ };
+ // The second page starts at x 500 in our spread coordinates.
+ let d = import_idml(&guides_package("PageOrigin")).unwrap();
+ assert_eq!(guides(&d), [(Vertical, 540.0, false, true, true), (Horizontal, 100.0, true, false, false)]);
+ let d = import_idml(&guides_package("SpineOrigin")).unwrap();
+ assert_eq!(guides(&d)[0].1, 540.0, "the spine is the second page's left edge");
+ let d = import_idml(&guides_package("SpreadOrigin")).unwrap();
+ assert_eq!(guides(&d)[0].1, 40.0);
+ assert_eq!(d.parents[0].pages[0].guides.len(), 1, "a parent page's guide");
+ assert_eq!(d.parents[0].pages[0].guides[0].position, 84.0);
+ // Round trip: written under each page, read back where they were.
+ let d = import_idml(&guides_package("PageOrigin")).unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(guides(&back), guides(&d));
+ assert_eq!(back.parents[0].pages[0].guides.len(), 1);
+ }
+
+ /// A package entry nothing in `designmap.xml` refers to is never decompressed: a damaged one
+ /// (its checksum no longer matches) does not stop the import.
+ #[test]
+ fn unreferenced_entries_are_not_read() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for (n, c) in [
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", STORY),
+ ] {
+ w.start_file(n, SimpleFileOptions::default()).unwrap();
+ w.write_all(c.as_bytes()).unwrap();
+ }
+ w.start_file("junk/irrelevant.bin", stored).unwrap();
+ w.write_all(b"<<payload-of-an-unused-entry>>").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ let at = bytes.windows(9).position(|w| w == b"<<payload").unwrap();
+ bytes[at] = b'X';
+ let d = import_idml(&bytes).unwrap();
+ assert_eq!(d.spreads.len(), 1);
+ }
+
+ /// A part that expands past the 512 MiB limit while claiming to hold one byte is refused once the
+ /// limit is reached, with an error that says so, instead of being read whole into memory.
+ #[test]
+ fn oversized_part_is_refused() {
+ use zip::write::SimpleFileOptions;
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Story src="Stories/Story_big.xml"/>
+ </Document>"#;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ w.start_file("mimetype", SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ w.start_file("designmap.xml", SimpleFileOptions::default()).unwrap();
+ w.write_all(designmap.as_bytes()).unwrap();
+ w.start_file("Stories/Story_big.xml", SimpleFileOptions::default()).unwrap();
+ let chunk = vec![b' '; 1 << 20];
+ for _ in 0..512 {
+ w.write_all(&chunk).unwrap();
+ }
+ w.write_all(b" ").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ assert!(bytes.len() < 8 << 20, "{}", bytes.len());
+ // Claim one byte in the local header and the central directory record (no ZIP64 fields or
+ // data descriptors here), so only the bytes actually decompressed can show the part is too big.
+ let mut patched = 0;
+ for i in 0..bytes.len().saturating_sub(46) {
+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {
+ b"PK\x03\x04" => (22, 26, 30),
+ b"PK\x01\x02" => (24, 28, 46),
+ _ => continue,
+ };
+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;
+ if bytes.get(i + name_at..i + name_at + len) == Some(b"Stories/Story_big.xml".as_slice()) {
+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&1u32.to_le_bytes());
+ patched += 1;
+ }
+ }
+ assert_eq!(patched, 2);
+ let Err(err) = import_idml(&bytes) else { panic!("an oversized part imported") };
+ assert!(err.to_string().contains("limit"), "{err}");
+ }
+
+ /// A package with more entries than any document needs is refused before any is read.
+ #[test]
+ fn too_many_entries_are_refused() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for i in 0..100_000 {
+ w.start_file(format!("junk/{i}"), stored).unwrap();
+ }
+ let Err(err) = import_idml(&w.finish().unwrap().into_inner()) else { panic!("a package with 100 001 entries imported") };
+ assert!(err.to_string().contains("entries"), "{err}");
+ }
+
+ /// InDesign writes `LeadingModel="LeadingModelAkiBelow"` on [No paragraph style] of every
+ /// document, but only its Japanese composers use the leading model: with the Paragraph Composer,
+ /// a 24 pt paragraph after a 32 pt one sits a Roman 28.8 pt below it (Montilla Design's Flex Layout
+ /// file: frames fitted to that came out overset).
+ #[test]
+ fn the_default_cjk_leading_model_applies_only_with_a_japanese_composer() {
+ let styles = |composer: &str| {
+ STYLES.replace(
+ r#"Name="$ID/[No paragraph style]" PointSize="12">"#,
+ &format!(r#"Name="$ID/[No paragraph style]" PointSize="12" LeadingModel="LeadingModelAkiBelow" Composer="{composer}">"#),
+ )
+ };
+ let model = |composer: &str| {
+ let s = styles(composer);
+ let pkg = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &s),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", STORY),
+ ]);
+ let d = import_idml(&pkg).unwrap();
+ d.styles.para(designcraft_doc::NO_PARA_STYLE).unwrap().chars.leading_model
+ };
+ assert_eq!(model("HL Composer"), None, "the Paragraph Composer leads baseline to baseline");
+ assert_eq!(model("HL Single"), None);
+ assert_eq!(model("$ID/HL Composer J"), Some(designcraft_doc::cjk::LeadingModel::AkiBelow));
+ assert_eq!(model("$ID/HL Single J"), Some(designcraft_doc::cjk::LeadingModel::AkiBelow));
+ }
+
+ mod liquid_page_rules {
+ use super::*;
+ use designcraft_doc::LiquidRule as R;
+ use std::sync::Arc;
+
+ // Literal XML expectations, independent of names.rs and serde spellings.
+ const CASES: [(&str, R); 6] = [
+ ("Scale", R::Scale),
+ ("Off", R::Off),
+ ("Recenter", R::ReCenter),
+ ("GuideBased", R::GuideBased),
+ ("ObjectBased", R::ObjectBased),
+ ("UseMaster", R::ControlledByParent),
+ ];
+
+ fn fixture(rule: Option<&str>, parent_rule: Option<&str>) -> Vec<u8> {
+ let attribute = |value: Option<&str>| value.map(|v| format!(r#" LayoutRule="{v}""#)).unwrap_or_default();
+ let (rule, parent_rule) = (attribute(rule), attribute(parent_rule));
+ let map = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Preferences src="Resources/Preferences.xml"/>
+ <idPkg:MasterSpread src="MasterSpreads/A.xml"/>
+ <idPkg:MasterSpread src="MasterSpreads/B.xml"/>
+ <idPkg:Spread src="Spreads/S.xml"/>
+ </Document>"#;
+ let parent = format!(
+ r#"<idPkg:MasterSpread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <MasterSpread Self="ma" NamePrefix="A" BaseName="Base" PageCount="2">
+ <Page Self="a1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>
+ <Page Self="a2"{parent_rule} GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>
+ </MasterSpread>
+ </idPkg:MasterSpread>"#
+ );
+ // Based-on belongs to the whole derived master: both pages apply the same master.
+ let derived = format!(
+ r#"<idPkg:MasterSpread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <MasterSpread Self="mb" NamePrefix="B" BaseName="Derived" PageCount="2">
+ <Page Self="b1"{rule} AppliedMaster="ma" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>
+ <Page Self="b2" AppliedMaster="ma" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>
+ </MasterSpread>
+ </idPkg:MasterSpread>"#
+ );
+ let spread = format!(
+ r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s" PageCount="2">
+ <Page Self="p1" AppliedMaster="ma" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350">
+ <MarginPreference ColumnCount="3" ColumnGutter="12" Top="10" Bottom="20" Left="30" Right="40"/>
+ </Page>
+ <Page Self="p2"{rule} AppliedMaster="ma" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>
+ </Spread>
+ </idPkg:Spread>"#
+ );
+ zip_files(&[
+ ("designmap.xml", map),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/A.xml", &parent),
+ ("MasterSpreads/B.xml", &derived),
+ ("Spreads/S.xml", &spread),
+ ])
+ }
+
+ #[test]
+ fn import_literal_xml() {
+ let baseline = import_idml(&fixture(None, None)).unwrap();
+ assert_eq!((baseline.spreads.len(), baseline.parents.len()), (1, 2));
+ assert!(baseline.spreads.iter().chain(&baseline.parents).all(|sp| sp.pages.len() == 2));
+ assert!(baseline.spreads.iter().chain(&baseline.parents).flat_map(|sp| &sp.pages).all(|pg| pg.liquid == R::Off));
+ let cases = CASES.into_iter().map(|(literal, rule)| (Some(literal), rule)).chain([
+ (None, R::Off),
+ (Some("ReCenter"), R::Off),
+ (Some("controlledByParent"), R::Off),
+ (Some("PreserveExisting"), R::Off),
+ ]);
+ for (literal, rule) in cases {
+ let actual = import_idml(&fixture(literal, Some("Recenter"))).unwrap();
+ assert_eq!(actual.spreads[0].pages[1].liquid, rule, "ordinary Page: {literal:?}");
+ assert_eq!(actual.parents[1].pages[0].liquid, rule, "master Page: {literal:?}");
+ // Same XML without rule attributes supplies the complete allowed-delta oracle.
+ let mut expected = baseline.clone();
+ Arc::make_mut(&mut expected.spreads[0]).pages[1].liquid = rule;
+ Arc::make_mut(&mut expected.parents[1]).pages[0].liquid = rule;
+ Arc::make_mut(&mut expected.parents[0]).pages[1].liquid = R::ReCenter;
+ // Import assigns a fresh creation timestamp; all other document fields are compared.
+ expected.created = actual.created;
+ assert_eq!(actual, expected, "{literal:?}: only the three explicit rule fields may change apart from the import timestamp");
+ assert_eq!(actual.spreads[0].pages[0].liquid, R::Off, "omitted does not infer inheritance");
+ assert_eq!(actual.spreads[0].pages[0].parent, Some(actual.parents[0].id));
+ assert_eq!(actual.parents[1].parent.as_ref().unwrap().based_on, Some(actual.parents[0].id));
+ assert!(actual.parents.iter().flat_map(|sp| &sp.pages).all(|pg| pg.parent.is_none()));
+ if rule == R::ControlledByParent {
+ // The right document page resolves to A's right page, not B's controlled page.
+ assert_eq!(actual.parent_page_for(1), Some((0, 1)));
+ assert_eq!(actual.parents[0].pages[1].liquid, R::ReCenter);
+ }
+ }
+ }
+
+ #[test]
+ fn export_and_round_trip() {
+ use std::io::Read;
+
+ let baseline = import_idml(&fixture(None, None)).unwrap();
+ for (literal, rule) in CASES {
+ // Set native enums directly; the literal importer under test does not build this input.
+ let mut source = baseline.clone();
+ let pages = &mut Arc::make_mut(&mut source.spreads[0]).pages;
+ pages[0].parent = None;
+ pages[0].liquid = R::ControlledByParent;
+ pages[1].liquid = rule;
+ Arc::make_mut(&mut source.parents[0]).pages[1].liquid = R::ReCenter;
+ Arc::make_mut(&mut source.parents[1]).pages[0].liquid = rule;
+ source.check().unwrap();
+ let bytes = export_idml(&source);
+ let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
+ for (directory, tag, spread, rules) in [
+ ("Spreads", "Spread", &source.spreads[0], ["UseMaster", literal]),
+ ("MasterSpreads", "MasterSpread", &source.parents[0], ["Off", "Recenter"]),
+ ("MasterSpreads", "MasterSpread", &source.parents[1], [literal, "Off"]),
+ ] {
+ let path = format!("{directory}/{tag}_u{:x}.xml", spread.id.0);
+ let mut part = Vec::new();
+ archive.by_name(&path).unwrap().read_to_end(&mut part).unwrap();
+ let root = xml::parse(&part).unwrap();
+ let body = root.find(tag).unwrap();
+ let pages: Vec<_> = body.find_all("Page").collect();
+ assert_eq!(pages.len(), spread.pages.len(), "{path}");
+ for (page, expected) in spread.pages.iter().zip(rules) {
+ let id = format!("u{:x}", page.id.0);
+ let matches: Vec<_> = pages.iter().filter(|p| p.get("Self") == Some(id.as_str())).collect();
+ assert_eq!(matches.len(), 1, "{path}: {id}");
+ assert_eq!(matches[0].get("LayoutRule"), Some(expected), "{path}: {id}");
+ }
+ }
+ let actual = import_idml(&bytes).unwrap();
+ assert_eq!((actual.spreads.len(), actual.parents.len()), (1, 2));
+ assert_eq!(actual.spreads[0].pages[0].parent, None);
+ assert_eq!(actual.spreads[0].pages[1].parent, Some(actual.parents[0].id));
+ assert_eq!(actual.parent_page_for(1), Some((0, 1)));
+ assert!(actual.parents.iter().flat_map(|sp| &sp.pages).all(|pg| pg.parent.is_none()));
+ for (index, prefix, name, based_on) in [(0, "A", "Base", None), (1, "B", "Derived", Some(actual.parents[0].id))] {
+ let info = actual.parents[index].parent.as_ref().unwrap();
+ assert_eq!((&info.prefix[..], &info.name[..], info.based_on), (prefix, name, based_on));
+ }
+ for (got, want) in actual.spreads.iter().chain(&actual.parents).zip(source.spreads.iter().chain(&source.parents)) {
+ assert_eq!(got.pages.len(), want.pages.len());
+ for (got, want) in got.pages.iter().zip(&want.pages) {
+ // IDs are allocated afresh; parent associations were checked explicitly above.
+ let mut normalized = got.clone();
+ normalized.id = want.id;
+ normalized.parent = want.parent;
+ assert_eq!(&normalized, want, "{literal}: all other Page fields, including the stored rule");
+ }
+ }
+ }
+ }
+ }
++
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}
diff --cc crates/idml/src/tests/assets.rs
index 000000000,6817208cd..b72a1f9e3
mode 000000,100644..100644
--- a/crates/idml/src/tests/assets.rs
+++ b/crates/idml/src/tests/assets.rs
@@@ -1,0 -1,193 +1,221 @@@
+ //! Placed files: every placement of one file shares an asset.
+
+ use std::cell::Cell;
+
-use designcraft_doc::{AssetId, Content};
++use designcraft_doc::{AssetId, Content, PdfCrop};
+
+ use super::*;
+
+ const PHOTO: &str = "file:/photos/wedding%20day/couple.jpg";
+
+ /// A graphic frame at `x` showing `image` (an `<Image>` element) with `crop` on every side.
+ fn frame(n: usize, x: f64, crop: f64, image: &str) -> String {
+ format!(
+ r#"<Rectangle Self="r{n}" ItemLayer="L1" ItemTransform="1 0 0 1 {x} 0" ContentType="GraphicType">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 30"/><PathPointType Anchor="40 30"/><PathPointType Anchor="40 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <FrameFittingOption TopCrop="{crop}" LeftCrop="{crop}" BottomCrop="{crop}" RightCrop="{crop}"/>
+ {image}
+ </Rectangle>"#
+ )
+ }
+
+ fn image(n: usize, uri: &str, contents: Option<&[u8]>) -> String {
+ let contents = contents.map(|c| format!("<Contents><![CDATA[{}]]></Contents>", base64_encode(c))).unwrap_or_default();
+ format!(
+ r#"<Image Self="im{n}" ItemTransform="1 0 0 1 {n} 0">
+ <Properties>{contents}<GraphicBounds Left="0" Top="0" Right="40" Bottom="30"/></Properties>
+ <Link Self="lk{n}" LinkResourceURI="{uri}" LinkResourceFormat="$ID/JPEG" StoredState="Normal"/>
+ </Image>"#
+ )
+ }
+
-/// A graphic frame showing `pdf` (a `<PDF>` element) with the page `PageNumber` (1-based).
-fn pdf_frame(n: usize, x: f64, page: u32) -> String {
++/// A graphic frame showing `insert.pdf` (a `<PDF>` element) at page `PageNumber` (1-based),
++/// cropped to `crop` (`PDFCrop`).
++fn pdf_frame(n: usize, x: f64, page: u32, crop: &str) -> String {
+ format!(
+ r#"<Rectangle Self="r{n}" ItemLayer="L1" ItemTransform="1 0 0 1 {x} 0" ContentType="GraphicType">
+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>
+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 30"/><PathPointType Anchor="40 30"/><PathPointType Anchor="40 0"/>
+ </PathPointArray></GeometryPathType></PathGeometry></Properties>
+ <PDF Self="im{n}" ItemTransform="1 0 0 1 {n} 0">
+ <Properties><GraphicBounds Left="0" Top="0" Right="40" Bottom="30"/></Properties>
+ <Link Self="lk{n}" LinkResourceURI="file:/art/insert.pdf" LinkResourceFormat="$ID/PDF" StoredState="Normal"/>
- <PDFAttribute PageNumber="{page}" PDFCrop="CropMedia" TransparentBackground="true"/>
++ <PDFAttribute PageNumber="{page}" PDFCrop="{crop}" TransparentBackground="true"/>
+ </PDF>
+ </Rectangle>"#
+ )
+ }
+
+ fn package(frames: &[String]) -> Vec<u8> {
+ let spread = format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+ <idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">
+ <Spread Self="sp1" PageCount="1" ItemTransform="1 0 0 1 0 0">
+ <Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 0"/>
+ {}
+ </Spread>
+ </idPkg:Spread>"#,
+ frames.join("\n")
+ );
+ zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", STYLES),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", &spread),
+ ("Stories/Story_s1.xml", STORY),
+ ])
+ }
+
+ /// (asset, crop, transform) of each graphic, left to right.
+ fn placements(d: &Document) -> Vec<(AssetId, [f64; 4], designcraft_geom::Affine)> {
+ let mut out: Vec<(f64, AssetId, [f64; 4], designcraft_geom::Affine)> = d.spreads[0]
+ .items
+ .iter()
+ .filter_map(|i| match &i.content {
+ Content::Graphic(g) => Some((i.xf.translation().x, g.asset, g.crop, g.xf)),
+ _ => None,
+ })
+ .collect();
+ out.sort_by(|a, b| a.0.total_cmp(&b.0));
+ out.into_iter().map(|(_, a, c, x)| (a, c, x)).collect()
+ }
+
+ #[test]
+ fn one_file_placed_several_times_imports_as_one_asset() {
+ let bytes = vec![42u8; 300];
+ let reads = Cell::new(0);
+ let reader = |p: &str| {
+ reads.set(reads.get() + 1);
+ p.ends_with("couple.jpg").then(|| bytes.clone())
+ };
+ // Three placements linking the file, and one embedding the same bytes under another path:
+ // that one keeps its own asset and path.
+ let frames = vec![
+ frame(1, 0.0, 1.0, &image(1, PHOTO, None)),
+ frame(2, 100.0, 2.0, &image(2, PHOTO, None)),
+ frame(3, 200.0, 3.0, &image(3, PHOTO, None)),
+ frame(4, 300.0, 4.0, &image(4, "file:/elsewhere/copy.jpg", Some(&bytes))),
+ ];
+ let d = import_idml_with(&package(&frames), &reader).unwrap();
+ assert_eq!(reads.get(), 1, "the linked file is read once");
+ assert_eq!(d.assets.len(), 2);
+ let p = placements(&d);
+ assert_eq!(p.iter().map(|(_, c, _)| c[0]).collect::<Vec<_>>(), vec![1.0, 2.0, 3.0, 4.0]);
+ let link = |id| d.assets.get(id).and_then(|a| a.link.as_deref());
+ let links: Vec<_> = p.iter().map(|(id, _, _)| link(id)).collect();
+ assert_eq!(links[..3], [Some("/photos/wedding day/couple.jpg"); 3]);
+ assert_eq!(links[3], Some("/elsewhere/copy.jpg"));
+ assert!(p[..3].iter().all(|(id, _, _)| *id == p[0].0));
+
+ // Exported linked or embedded, the round trip keeps the two assets and each placement's crop
+ // and transform.
+ for embed_images in [false, true] {
+ let out = export_idml_with(&d, &ExportOptions { embed_images });
+ let back = import_idml_with(&out, &reader).unwrap();
+ assert_eq!(back.assets.len(), 2, "embed_images: {embed_images}");
+ let q = placements(&back);
+ assert_eq!(q.len(), 4);
+ for ((_, c0, x0), (_, c1, x1)) in p.iter().zip(&q) {
+ assert_eq!(c0, c1);
+ assert!(x0.as_coeffs().iter().zip(x1.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{x0:?} {x1:?}");
+ }
+ }
+ }
+
+ /// An `<SVG>` placement linking `uri`, whose GraphicBounds are `bounds` (left top right bottom).
+ fn svg(n: usize, uri: &str, bounds: [f64; 4]) -> String {
+ let [l, t, r, b] = bounds;
+ format!(
+ r#"<SVG Self="sv{n}" ItemTransform="1 0 0 1 0 0">
+ <Properties><GraphicBounds Left="{l}" Top="{t}" Right="{r}" Bottom="{b}"/></Properties>
+ <Link Self="lk{n}" LinkResourceURI="{uri}" LinkResourceFormat="$ID/SVG" StoredState="Normal"/>
+ </SVG>"#
+ )
+ }
+
+ #[test]
+ fn placed_svg_with_only_a_viewbox_keeps_its_viewbox_size() {
+ const OVERHANG: &str =
+ r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100"><line x1="-10" y1="50" x2="0" y2="50" stroke="#000"/></svg>"##;
+ const SIZED: &str =
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" viewBox="0 0 200 100"><rect width="200" height="100"/></svg>"#;
+ let reader = |p: &str| match p {
+ "/art/overhang.svg" => Some(OVERHANG.as_bytes().to_vec()),
+ "/art/sized.svg" => Some(SIZED.as_bytes().to_vec()),
+ _ => None,
+ };
+ // GraphicBounds are the art's bounds: 211 wide for the overhanging one, placed twice (the second
+ // reuses the first's asset); a sized SVG is still stretched onto its bounds.
+ let frames = vec![
+ frame(1, 0.0, 0.0, &svg(1, "file:/art/overhang.svg", [-11.0, 0.0, 200.0, 100.0])),
+ frame(2, 100.0, 0.0, &svg(2, "file:/art/overhang.svg", [-11.0, 0.0, 200.0, 100.0])),
+ frame(3, 200.0, 0.0, &svg(3, "file:/art/sized.svg", [-10.0, 0.0, 200.0, 100.0])),
+ ];
+ let d = import_idml_with(&package(&frames), &reader).unwrap();
+ let mut gs: Vec<_> = d.spreads[0]
+ .items
+ .iter()
+ .filter_map(|i| match &i.content {
+ Content::Graphic(g) => Some((i.xf.translation().x, g.size, g.xf.translation().x)),
+ _ => None,
+ })
+ .collect();
+ gs.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let got: Vec<_> = gs.into_iter().map(|(_, size, x)| (size, x)).collect();
+ assert_eq!(got, vec![((200.0, 100.0), -11.0), ((200.0, 100.0), -11.0), ((210.0, 100.0), -10.0)]);
+ }
+
+ /// `PDFAttribute/@PageNumber` (1-based) is read into `Asset.page` (0-based), and the same file at
+ /// different pages stays apart (#905).
+ #[test]
+ fn a_pdf_placement_reads_its_page_number() {
+ let bytes = b"%PDF-1.7\n% fixture".to_vec();
+ let reader = |p: &str| p.ends_with("insert.pdf").then(|| bytes.clone());
- let frames = vec![pdf_frame(1, 0.0, 2), pdf_frame(2, 100.0, 1), pdf_frame(3, 200.0, 2)];
++ let frames = vec![pdf_frame(1, 0.0, 2, "CropMedia"), pdf_frame(2, 100.0, 1, "CropMedia"), pdf_frame(3, 200.0, 2, "CropMedia")];
+ let d = import_idml_with(&package(&frames), &reader).unwrap();
+ let p = placements(&d);
+ let page = |id| d.assets.get(&id).map(|a| a.page);
+ assert_eq!(page(p[0].0), Some(1), "PageNumber=\"2\" is the second page, stored 0-based");
+ assert_eq!(page(p[1].0), Some(0), "PageNumber=\"1\" is the first page");
+ assert_eq!(p[0].0, p[2].0, "the same file at the same page shares one asset");
+ assert_ne!(p[0].0, p[1].0, "the same file at another page is another asset");
+
- // Exported (linked or embedded), the page survives the round trip.
++ // Exported (linked or embedded), every placement writes its page and crop, page 1 included,
++ // and both survive the round trip.
+ for embed_images in [false, true] {
+ let out = export_idml_with(&d, &ExportOptions { embed_images });
++ let spreads = super::zip_text(&out, "Spreads/");
++ assert_eq!(spreads.matches(r#"PDFCrop="CropMedia""#).count(), 3, "{spreads}");
++ assert!(spreads.contains(r#"PageNumber="1""#) && spreads.contains(r#"PageNumber="2""#), "{spreads}");
+ let back = import_idml_with(&out, &reader).unwrap();
- let pages: Vec<_> = placements(&back).iter().map(|(id, _, _)| back.assets.get(id).map(|a| a.page)).collect();
- assert_eq!(pages, vec![Some(1), Some(0), Some(1)], "embed_images: {embed_images}");
++ let shown: Vec<_> = placements(&back).iter().map(|(id, _, _)| back.assets.get(id).map(|a| (a.page, a.pdf_crop))).collect();
++ let (first, second) = (Some((0, PdfCrop::Media)), Some((1, PdfCrop::Media)));
++ assert_eq!(shown, vec![second, first, second], "embed_images: {embed_images}");
+ }
+ }
++
++/// 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);
++}
diff --cc crates/pdf/src/export.rs
index 95a0a6569,b76af6ec5..15c55cc54
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@@ -1173,10 -1204,10 +1204,11 @@@ impl Exporter<'_>
/// A placed PDF as krilla embeds it. krilla refuses a PDF newer than the file it writes (the
/// export fails at the end with `VersionMismatch(Pdf17)`), and PDF/X-4 is PDF 1.6 while
/// VectorCraft and most tools write 1.7. PDF 1.7 changed nothing in how a page draws, so a 1.7
- /// file goes in as 1.6 (its header relabelled, as `qpdf --force-version=1.6` does). A newer
+ /// file goes in as 1.6 (its header and catalog `/Version` relabelled, as
+ /// `qpdf --force-version=1.6` does). A newer
/// file is left out and the export fails naming it ([`Exporter::check_placed_versions`]).
- fn placed_pdf(&mut self, asset: &designcraft_doc::Asset) -> Option<krilla::pdf::PdfDocument> {
+ /// Returns the document with its page count.
+ fn placed_pdf(&mut self, asset: &designcraft_doc::Asset) -> Option<(krilla::pdf::PdfDocument, usize)> {
use hayro_syntax::PdfVersion as V;
let Ok(pdf) = krilla::pdf::Pdf::new(asset.data.clone()) else {
self.warn(format!("{}: can't read the placed PDF", asset.name));
diff --cc crates/pptx/src/tests.rs
index 000000000,98e78384e..06566abdb
mode 000000,100644..100644
--- a/crates/pptx/src/tests.rs
+++ b/crates/pptx/src/tests.rs
@@@ -1,0 -1,289 +1,289 @@@
+ //! Package structure and object mapping tests.
+
+ use std::io::Read;
+ use std::sync::Arc;
+
+ use designcraft_compose::Cache;
+ use designcraft_doc::build::NewDocument;
+ use designcraft_doc::{
+ Asset, AssetId, Content, Document, Fill, Graphic, Item, ItemId, ParaFormat, Shape, SpreadRef, Stroke, StrokeType, TextFrameOptions,
+ };
+ use designcraft_geom::{Affine, Rect, shapes};
+
+ use crate::{LineBreaks, PptxError, PptxOptions, export_pptx};
+
+ fn unzip(bytes: &[u8]) -> zip::ZipArchive<std::io::Cursor<Vec<u8>>> {
+ zip::ZipArchive::new(std::io::Cursor::new(bytes.to_vec())).unwrap()
+ }
+
+ fn part(z: &mut zip::ZipArchive<std::io::Cursor<Vec<u8>>>, name: &str) -> String {
+ let mut s = String::new();
+ z.by_name(name).unwrap_or_else(|_| panic!("missing {name}")).read_to_string(&mut s).unwrap();
+ s
+ }
+
+ fn export(d: &Document, opts: &PptxOptions) -> zip::ZipArchive<std::io::Cursor<Vec<u8>>> {
+ unzip(&export_pptx(d, &Cache::new(), opts).unwrap().bytes)
+ }
+
+ fn rect_item(d: &mut Document, r: Rect, shape: Shape) -> ItemId {
+ let id = ItemId(d.alloc());
+ let path = if shape == Shape::Oval { shapes::ellipse(r) } else { shapes::rectangle(r) };
+ let mut it = Item::new(id, d.default_layer(), shape, path);
+ it.fill = Fill::swatch("[Black]");
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ id
+ }
+
+ fn edit(d: &mut Document, id: ItemId, f: impl FnOnce(&mut Item)) {
+ let it = d.spreads.iter_mut().flat_map(|sp| Arc::make_mut(sp).items.iter_mut()).find(|it| it.id == id).unwrap();
+ f(Arc::make_mut(it));
+ }
+
+ /// The text of each shape on a slide (runs joined).
+ fn shape_texts(slide: &str) -> Vec<String> {
+ slide
+ .split("<p:sp>")
+ .skip(1)
+ .map(|sp| sp.split("<a:t>").skip(1).filter_map(|t| t.split("</a:t>").next()).collect::<String>())
+ .filter(|t| !t.is_empty())
+ .collect()
+ }
+
+ /// Every XML part parses.
+ fn well_formed(z: &mut zip::ZipArchive<std::io::Cursor<Vec<u8>>>) {
+ let names: Vec<String> = z.file_names().map(str::to_string).collect();
+ for n in names.iter().filter(|n| n.ends_with(".xml") || n.ends_with(".rels")) {
+ let x = part(z, n);
+ let mut r = quick_xml::Reader::from_str(&x);
+ loop {
+ match r.read_event() {
+ Ok(quick_xml::events::Event::Eof) => break,
+ Ok(_) => {}
+ Err(e) => panic!("{n}: {e}"),
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn package_has_the_parts_powerpoint_needs() {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Hello & <world>", ParaFormat::default()).unwrap();
+ let r = export_pptx(&d, &Cache::new(), &PptxOptions::default()).unwrap();
+ assert_eq!(r.slides, 2);
+ let mut z = unzip(&r.bytes);
+ for p in [
+ "[Content_Types].xml",
+ "_rels/.rels",
+ "ppt/presentation.xml",
+ "ppt/_rels/presentation.xml.rels",
+ "ppt/slideMasters/slideMaster1.xml",
+ "ppt/slideLayouts/slideLayout1.xml",
+ "ppt/theme/theme1.xml",
+ "ppt/slides/slide1.xml",
+ "ppt/slides/slide2.xml",
+ "ppt/slides/_rels/slide2.xml.rels",
+ "docProps/core.xml",
+ ] {
+ assert!(z.by_name(p).is_ok(), "{p}");
+ }
+ well_formed(&mut z);
+ let pres = part(&mut z, "ppt/presentation.xml");
+ let (w, h) = (d.settings.page_width, d.settings.page_height);
+ assert!(pres.contains(&format!("<p:sldSz cx=\"{}\" cy=\"{}\"/>", (w * 12_700.0).round() as i64, (h * 12_700.0).round() as i64)), "{pres}");
+ let s1 = part(&mut z, "ppt/slides/slide1.xml");
+ assert_eq!(shape_texts(&s1), ["Hello &amp; &lt;world&gt;"]);
+ }
+
+ #[test]
+ fn shapes_keep_geometry_fill_stroke_and_effects() {
+ let mut d = Document::new(&NewDocument::default());
+ let a = rect_item(&mut d, Rect::new(72.0, 72.0, 172.0, 122.0), Shape::Rectangle);
+ let b = rect_item(&mut d, Rect::new(200.0, 72.0, 300.0, 122.0), Shape::Oval);
+ let c = rect_item(&mut d, Rect::new(72.0, 200.0, 172.0, 300.0), Shape::Rectangle);
+ edit(&mut d, a, |it| {
+ it.stroke = Stroke { swatch: "[Black]".into(), weight: 2.0, kind: StrokeType::Dashed { pattern: vec![4.0, 2.0] }, ..Stroke::default() };
+ it.opacity = 0.5;
+ });
+ edit(&mut d, b, |it| it.effects.drop_shadow.on = true);
+ edit(&mut d, c, |it| {
+ let ctr = it.bounds().center();
+ it.xf = Affine::rotate_about(30f64.to_radians(), ctr);
+ });
+ let mut z = export(&d, &PptxOptions::default());
+ let s = part(&mut z, "ppt/slides/slide1.xml");
+ // 72 pt from the page corner, 100 × 50 pt.
+ assert!(s.contains("<a:off x=\"914400\" y=\"914400\"/><a:ext cx=\"1270000\" cy=\"635000\"/></a:xfrm><a:prstGeom prst=\"rect\">"), "{s}");
+ assert!(s.contains("<a:prstGeom prst=\"ellipse\">"));
+ assert!(s.contains("<a:custDash><a:ds d=\"200000\" sp=\"100000\"/></a:custDash>"), "{s}");
+ assert!(s.contains("<a:alpha val=\"50000\"/>"));
+ assert!(s.contains("<a:outerShdw"));
+ assert!(s.contains("rot=\"1800000\""), "{s}");
+ }
+
+ #[test]
+ fn composed_lines_become_line_breaks_with_the_story_text() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let text = "Every page begins as an empty field of possibility. The grid arrives first: margins that frame the reading area, columns that set the rhythm.";
+ let (fid, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, text, ParaFormat::default()).unwrap();
+ let cache = Cache::new();
+ let lines = cache.get(&d, sid, None).frame(fid).map_or(0, |f| f.lines.len());
+ assert!(lines > 3, "the frame breaks the text into lines");
+ let r = export_pptx(&d, &cache, &PptxOptions::default()).unwrap();
+ let mut z = unzip(&r.bytes);
+ let s = part(&mut z, "ppt/slides/slide1.xml");
+ assert_eq!(s.matches("<a:br>").count(), lines - 1, "{s}");
+ // The text survives intact (line-end spaces kept, the composer's hyphens shown).
+ let joined = shape_texts(&s).concat();
+ assert_eq!(joined.replace('-', ""), text);
+ assert!(s.contains("<a:spcPct"), "leading as percentage line spacing");
+ assert!(s.contains("typeface=\"Source Serif 4\""));
+ }
+
+ #[test]
+ fn reflow_writes_one_box_with_native_columns() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 500.0, 300.0), lid, "One\nTwo", ParaFormat::default()).unwrap();
+ edit(&mut d, fid, |it| {
+ if let Content::Text(t) = &mut it.content {
+ t.options = TextFrameOptions { columns: 2, gutter: 12.0, ..t.options.clone() };
+ }
+ });
+ let mut z = export(&d, &PptxOptions { line_breaks: LineBreaks::Reflow, ..Default::default() });
+ let s = part(&mut z, "ppt/slides/slide1.xml");
+ assert!(s.contains("numCol=\"2\" spcCol=\"152400\""), "{s}");
+ assert!(!s.contains("<a:br>"));
+ assert_eq!(s.matches("<a:p>").count(), 2);
+ }
+
+ #[test]
+ fn threaded_story_splits_at_its_frames() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
+ let (f1, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 160.0, 110.0), lid, text, ParaFormat::default()).unwrap();
+ let f2 = rect_item(&mut d, Rect::new(300.0, 72.0, 388.0, 400.0), Shape::Rectangle);
+ edit(&mut d, f2, |it| {
+ it.fill = Fill::none();
+ it.content = Content::Text(designcraft_doc::TextFrame { story: sid, options: TextFrameOptions::default() });
+ });
+ if let Some(st) = d.stories.get_mut(&sid) {
+ Arc::make_mut(st).frames = vec![f1, f2];
+ }
+ let mut z = export(&d, &PptxOptions::default());
+ let s = part(&mut z, "ppt/slides/slide1.xml");
+ // Two text shapes, the story starting in the first and ending in the second.
+ let texts: Vec<String> = shape_texts(&s).iter().map(|t| t.replace('-', "")).collect();
+ assert_eq!(texts.len(), 2, "{s}");
+ assert!(texts[0].starts_with("alpha") && !texts[0].contains("omega"), "{texts:?}");
+ assert!(texts[1].trim_end().ends_with("omega"), "{texts:?}");
+ assert_eq!(texts.concat().trim_end(), text);
+ }
+
+ fn png(w: u32, h: u32) -> Vec<u8> {
+ let img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 30, 30, 255]));
+ let mut out = std::io::Cursor::new(Vec::new());
+ img.write_to(&mut out, image::ImageFormat::Png).unwrap();
+ out.into_inner()
+ }
+
+ #[test]
+ fn pictures_are_cropped_to_their_frames() {
+ let mut d = Document::new(&NewDocument::default());
+ let asset = AssetId(d.alloc());
+ d.assets.insert(
+ asset,
+ Arc::new(Asset {
+ id: asset,
+ name: "red.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: Arc::new(png(200, 100)),
+ pixels: Some((200, 100)),
- page: 0,
++ ..Default::default()
+ }),
+ );
+ let id = rect_item(&mut d, Rect::new(100.0, 100.0, 200.0, 200.0), Shape::Rectangle);
+ edit(&mut d, id, |it| {
+ it.fill = Fill::none();
+ // 200 × 100 image at 1:1, its left quarter cut off by the frame.
+ it.content = Content::Graphic(Graphic {
+ asset,
+ size: (200.0, 100.0),
+ xf: Affine::translate((50.0, 100.0)),
+ auto_fit: designcraft_doc::Fitting::None,
+ fit_align: 0,
+ crop: [0.0; 4],
+ });
+ });
+ let mut z = export(&d, &PptxOptions::default());
+ assert!(z.by_name("ppt/media/image1.png").is_ok());
+ let s = part(&mut z, "ppt/slides/slide1.xml");
+ assert!(s.contains("<a:srcRect l=\"25000\" t=\"0\" r=\"25000\" b=\"0\"/>"), "{s}");
+ let rels = part(&mut z, "ppt/slides/_rels/slide1.xml.rels");
+ assert!(rels.contains("../media/image1.png"));
+ }
+
+ #[test]
+ fn bad_pages_and_hostile_geometry_are_errors_not_crashes() {
+ let mut d = Document::new(&NewDocument::default());
+ let r = export_pptx(&d, &Cache::new(), &PptxOptions { pages: Some(vec![5]), ..Default::default() });
+ assert!(matches!(r, Err(PptxError::BadPage(6))));
+ assert!(matches!(export_pptx(&d, &Cache::new(), &PptxOptions { pages: Some(vec![]), ..Default::default() }), Err(PptxError::NoPages)));
+ let a = rect_item(&mut d, Rect::new(10.0, 10.0, 10.0, 10.0), Shape::Rectangle);
+ let b = rect_item(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0), Shape::Rectangle);
+ edit(&mut d, a, |it| it.xf = Affine::new([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]));
+ edit(&mut d, b, |it| it.xf = Affine::new([f64::NAN, 0.0, 0.0, 1e300, f64::INFINITY, 0.0]));
+ let lid = d.default_layer();
+ let (t, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(10.0, 10.0, 60.0, 60.0), lid, "x", ParaFormat::default()).unwrap();
+ edit(&mut d, t, |it| it.xf = Affine::new([1.0, 0.0, 3.0, 1.0, 0.0, 0.0]));
+ let mut z = export(&d, &PptxOptions::default());
+ well_formed(&mut z);
+ }
+
+ #[test]
+ fn fonts_embed_as_embedded_opentype() {
+ let face = designcraft_fonts::FontDb::global().face("Source Serif 4", "Regular");
+ let eot = crate::fonts::eot(&face).unwrap();
+ let le32 = |at: usize| u32::from_le_bytes([eot[at], eot[at + 1], eot[at + 2], eot[at + 3]]);
+ assert_eq!(le32(0) as usize, eot.len());
+ assert_eq!(le32(4) as usize, face.data().len());
+ assert_eq!(le32(8), 0x0002_0001);
+ assert_eq!(u16::from_le_bytes([eot[34], eot[35]]), 0x504C, "magic");
+ assert!(eot.ends_with(face.data()));
+
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "Embedded", ParaFormat::default()).unwrap();
+ let mut z = export(&d, &PptxOptions { embed_fonts: true, ..Default::default() });
+ let pres = part(&mut z, "ppt/presentation.xml");
+ assert!(
+ pres.contains("embedTrueTypeFonts=\"1\"") && pres.contains("<p:embeddedFont><p:font typeface=\"Source Serif 4\"/><p:regular r:id="),
+ "{pres}"
+ );
+ assert!(z.by_name("ppt/fonts/font1.fntdata").is_ok());
+ let ct = part(&mut z, "[Content_Types].xml");
+ assert!(ct.contains("application/x-fontdata"));
+ }
+
+ #[test]
+ fn fonts_whose_licence_forbids_outline_embedding_are_not_embedded() {
+ use designcraft_fonts::testing::{font_with, with_fs_type};
+ let db = designcraft_fonts::FontDb::with_font_dirs(vec![]);
+ // Restricted (0x0002, 0x0003 with reserved bit 0) and Bitmap embedding only (bit 9, with any
+ // other bits) refuse; Installable, Preview & Print and Editable embed.
+ for (fs_type, embeds) in [(0x0000, true), (0x0004, true), (0x0008, true), (0x0002, false), (0x0003, false), (0x0200, false), (0x0208, false)] {
+ let family = format!("PPTX Licence {fs_type:04x}");
+ assert_eq!(db.add_font(with_fs_type(font_with(&family, &['l']).unwrap(), fs_type).unwrap()), 1);
+ let r = crate::fonts::eot(&db.face(&family, "Regular"));
+ if embeds {
+ assert!(r.is_ok(), "fsType {fs_type:#06x}");
+ } else {
+ assert!(matches!(r, Err(crate::fonts::NoEmbed::Restricted)), "fsType {fs_type:#06x}");
+ }
+ }
+ }
diff --cc crates/render/tests/placed_pdf.rs
index 000000000,d7487086a..0b713af84
mode 000000,100644..100644
--- a/crates/render/tests/placed_pdf.rs
+++ b/crates/render/tests/placed_pdf.rs
@@@ -1,0 -1,249 +1,255 @@@
+ //! Placed PDFs are drawn through pdfcraft's patched hayro crates. Calculator functions whose `idiv`
+ //! divides by zero or overflows, stitching functions nested a hundred thousand deep, and mesh
+ //! shadings with points far off the page, ten thousand overlapping triangles or forty thousand
+ //! patches do not panic, overflow the stack or take more than a minute, and the rest of the page is
+ //! drawn. A page with a `/UserUnit` is sized in points, and so are its boxes. The function and mesh
+ //! cases follow pdfcraft's tests in `crates/render/src/raster.rs`.
+
+ use std::sync::Arc;
+ use std::sync::mpsc::{self, RecvTimeoutError};
+ use std::time::Duration;
+
+ use designcraft_compose::Cache;
+ use designcraft_doc::build::NewDocument;
-use designcraft_doc::{Asset, AssetId, Content, Document, Graphic, Item, ItemId, Shape, SpreadRef};
++use designcraft_doc::{Asset, AssetId, Content, Document, Graphic, Item, ItemId, PdfCrop, Shape, SpreadRef};
+ use designcraft_geom::{Affine, Rect, shapes};
-use designcraft_render::{Rendered, Renderer, pdf_page_box, pdf_page_size};
++use designcraft_render::{Rendered, Renderer, pdf_crop_box, pdf_page_size};
+ use hayro::hayro_interpret::Function;
+ use hayro::hayro_syntax::Pdf;
+ use hayro::hayro_syntax::object::{Object, ObjectIdentifier};
+
+ const WHITE: [u8; 4] = [255, 255, 255, 255];
+ const RED: [u8; 4] = [255, 0, 0, 255];
+ const BLUE: [u8; 4] = [0, 0, 255, 255];
+
+ /// An exponential function of one input with one output.
+ const LEAF: &str = "<</FunctionType 2/Domain[0 1]/C0[0]/C1[1]/N 1>>";
+
+ /// Mesh entries common to the shadings below: RGB colors, 8-bit coordinates and components.
+ const MESH: &str = "/ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8";
+
+ /// One triangle of a free-form triangle mesh: three vertices of a flag, x, y and a color.
+ const TRIANGLE: [u8; 18] = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255];
+
+ /// A stream object with the `dict` entries, its `/Length` and `data`.
+ fn stream(dict: &str, data: &[u8]) -> Vec<u8> {
+ let mut s = format!("<<{dict} /Length {}>>\nstream\n", data.len()).into_bytes();
+ s.extend_from_slice(data);
+ s.extend_from_slice(b"\nendstream");
+ s
+ }
+
+ /// A one-page PDF whose page dictionary holds the `page` entries (boxes, resources) and whose page
+ /// draws `content`. The `objects` are numbered from 5.
+ fn pdf(page: &str, content: &str, objects: &[Vec<u8>]) -> Vec<u8> {
+ let mut bodies = vec![
+ b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
+ b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
+ format!("<</Type/Page/Parent 2 0 R{page}/Contents 4 0 R>>").into_bytes(),
+ stream("", content.as_bytes()),
+ ];
+ bodies.extend_from_slice(objects);
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, body) in bodies.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", bodies.len() + 1).as_bytes());
+ for offset in offsets {
+ out.extend_from_slice(format!("{offset:010} 00000 n\r\n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<</Size {}/Root 1 0 R>>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes());
+ out
+ }
+
+ /// The page of a document `size` points square with `pdf` placed to fill it, rendered by
+ /// `Renderer::render_page` at one pixel per point. Fails when the render panics or takes more
+ /// than a minute.
+ fn placed(size: f64, pdf: Vec<u8>) -> Rendered {
+ let (tx, rx) = mpsc::channel();
+ std::thread::spawn(move || {
+ let mut d = Document::new(&NewDocument { width: size, height: size, facing_pages: false, ..Default::default() });
+ let id = AssetId(d.alloc());
- let asset =
- d.add_asset(Asset { id, name: "art.pdf".into(), mime: "application/pdf".into(), link: None, data: Arc::new(pdf), pixels: None, page: 0 });
++ let asset = d.add_asset(Asset { id, name: "art.pdf".into(), mime: "application/pdf".into(), data: Arc::new(pdf), ..Default::default() });
+ let id = ItemId(d.alloc());
+ let mut item = Item::new(id, d.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, size, size)));
+ item.content =
+ Content::Graphic(Graphic { asset, size: (size, size), xf: Affine::IDENTITY, auto_fit: Default::default(), fit_align: 4, crop: [0.0; 4] });
+ d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ let mut renderer = Renderer::new();
+ renderer.threads = 0;
+ let _ = tx.send(renderer.render_page(&d, &Cache::new(), 0, 1.0, false, &Default::default()));
+ });
+ match rx.recv_timeout(Duration::from_secs(60)) {
+ Ok(page) => page.expect("the page renders"),
+ Err(RecvTimeoutError::Timeout) => panic!("the placed PDF did not render within a minute"),
+ Err(RecvTimeoutError::Disconnected) => panic!("the render of the placed PDF panicked"),
+ }
+ }
+
+ /// A 40-point page that paints an axial shading through the first of `functions` (objects 6
+ /// onwards), then a blue square over the whole page.
+ fn shaded(functions: &[Vec<u8>]) -> Vec<u8> {
+ let mut objects = vec![b"<</ShadingType 2/ColorSpace/DeviceRGB/Coords[0 0 40 0]/Function 6 0 R>>".to_vec()];
+ objects.extend_from_slice(functions);
+ pdf("/MediaBox[0 0 40 40]/Resources<</Shading<</S 5 0 R>>>>", "/S sh 0 0 1 rg 0 0 40 40 re f", &objects)
+ }
+
+ /// A calculator (Type 4) function of one input that runs `program`.
+ fn calculator(program: &str) -> Vec<u8> {
+ stream("/FunctionType 4/Domain[0 1]/Range[0 1 0 1 0 1]", program.as_bytes())
+ }
+
+ /// The function that is object 5 of a PDF holding `objects`.
+ fn function(objects: &[&str]) -> Option<Function> {
+ let objects: Vec<Vec<u8>> = objects.iter().map(|o| o.as_bytes().to_vec()).collect();
+ let parsed = Pdf::new(pdf("/MediaBox[0 0 20 20]", "", &objects)).unwrap();
+ let object = parsed.xref().get::<Object<'_>>(ObjectIdentifier::new(5, 0)).unwrap();
+ Function::new(&object)
+ }
+
+ #[test]
+ fn placed_pdf_function_dividing_by_zero_leaves_the_page_drawn() {
+ assert_eq!(placed(40.0, shaded(&[calculator("{ pop 1 0 idiv }")])).pixel(20, 20), BLUE);
+ }
+
+ #[test]
+ fn placed_pdf_function_dividing_the_smallest_integer_by_minus_one_leaves_the_page_drawn() {
+ assert_eq!(placed(40.0, shaded(&[calculator("{ pop -2147483648 -1 idiv }")])).pixel(20, 20), BLUE);
+ }
+
+ /// A chain of 100,000 functions: each stitching function names the next by reference, and the last
+ /// is an exponential function.
+ #[test]
+ fn placed_pdf_chain_of_stitching_functions_leaves_the_page_drawn() {
+ let mut functions: Vec<Vec<u8>> =
+ (7..100_006).map(|next| format!("<</FunctionType 3/Domain[0 1]/Functions[{next} 0 R]/Bounds[]/Encode[0 1]>>").into_bytes()).collect();
+ functions.push(b"<</FunctionType 2/Domain[0 1]/C0[0 0 0]/C1[1 1 1]/N 1>>".to_vec());
+ assert_eq!(placed(40.0, shaded(&functions)).pixel(20, 20), BLUE);
+ }
+
+ /// Stitching functions that each name the next through `N 0 R`: 64 evaluate, 65 are refused.
+ #[test]
+ fn function_limits_depth_guard_refuses_a_chain_of_references() {
+ for functions in [64, 65] {
+ let objects: Vec<String> = (5..5 + functions)
+ .map(|number| {
+ if number < 4 + functions {
+ format!("<</FunctionType 3/Domain[0 1]/Functions[{} 0 R]/Bounds[]/Encode[0 1]>>", number + 1)
+ } else {
+ LEAF.to_owned()
+ }
+ })
+ .collect();
+ let objects: Vec<&str> = objects.iter().map(String::as_str).collect();
+ let chain = function(&objects);
+ if functions == 64 {
+ assert_eq!(chain.unwrap().eval([0.5].into_iter().collect()).unwrap().as_slice(), &[0.5]);
+ } else {
+ assert!(chain.is_none(), "65 functions are one past the function-depth guard");
+ }
+ }
+ }
+
+ /// Stitching functions with a cycle, no children or a missing child are refused; one child named
+ /// twice still evaluates.
+ #[test]
+ fn function_limits_stitching_cycles_are_refused_and_shared_children_work() {
+ for objects in [
+ &["<</FunctionType 3/Domain[0 1]/Functions[5 0 R]/Bounds[]/Encode[0 1]>>"][..],
+ &[
+ "<</FunctionType 3/Domain[0 1]/Functions[6 0 R]/Bounds[]/Encode[0 1]>>",
+ "<</FunctionType 3/Domain[0 1]/Functions[5 0 R]/Bounds[]/Encode[0 1]>>",
+ ],
+ &["<</FunctionType 3/Domain[0 1]/Functions[]/Bounds[]/Encode[]>>"],
+ &["<</FunctionType 3/Domain[0 1]/Functions[99 0 R]/Bounds[]/Encode[0 1]>>"],
+ &["<</FunctionType 3/Domain[0 1]/Functions[6 0 R 99 0 R]/Bounds[0.5]/Encode[0 1 0 1]>>", LEAF],
+ ] {
+ assert!(function(objects).is_none(), "accepted invalid children: {objects:?}");
+ }
+ let shared = function(&["<</FunctionType 3/Domain[0 1]/Functions[6 0 R 6 0 R]/Bounds[0.5]/Encode[0 1 0 1]>>", LEAF]).unwrap();
+ let output = shared.eval([0.75].into_iter().collect()).unwrap();
+ assert!((output[0] - 0.5).abs() < 0.001);
+ }
+
+ /// Ten thousand triangles that each cover half of the placed page, which is drawn 1000 pixels
+ /// square.
+ #[test]
+ fn many_overlapping_mesh_triangles_finish() {
+ let shading = stream(&format!("/ShadingType 4 {MESH} /BitsPerFlag 8 /Decode [0 125 0 125 0 1 0 1 0 1]"), &TRIANGLE.repeat(10_000));
+ let page = placed(125.0, pdf("/MediaBox[0 0 125 125]/Resources<</Shading<</Sh0 5 0 R>>>>", "/Sh0 sh", &[shading]));
+ let p = page.pixel(12, 112);
+ assert!(p != WHITE && p[3] == 255, "the triangles are drawn: {p:?}");
+ }
+
+ /// One Coons patch: its flag, twelve points around a square of 8-bit coordinates, four colors.
+ fn coons() -> Vec<u8> {
+ let mut patch = vec![0u8];
+ for p in [(0, 0), (0, 85), (0, 170), (0, 255), (85, 255), (170, 255), (255, 255), (255, 170), (255, 85), (255, 0), (170, 0), (85, 0)] {
+ patch.extend_from_slice(&[p.0, p.1]);
+ }
+ patch.extend_from_slice(&[255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 0]);
+ patch
+ }
+
+ /// A 40-point page that paints `shading` (object 5), then a red square at its bottom left.
+ fn meshed(shading: Vec<u8>) -> Vec<u8> {
+ pdf("/MediaBox[0 0 40 40]/Resources<</Shading<</Sh0 5 0 R>>>>", "/Sh0 sh 1 0 0 rg 0 0 4 4 re f", &[shading])
+ }
+
+ /// Meshes whose points lie far off the page are sampled only where the page shows them.
+ #[test]
+ fn mesh_shadings_far_off_the_page_render() {
+ let far = "/Decode [-40000 40000 -40000 40000 0 1 0 1 0 1]";
+ for (what, shading) in [
+ ("a Coons patch", stream(&format!("/ShadingType 6 {MESH} /BitsPerFlag 8 {far}"), &coons())),
+ ("a triangle mesh", stream(&format!("/ShadingType 4 {MESH} /BitsPerFlag 8 {far}"), &TRIANGLE)),
+ ] {
+ assert_eq!(placed(40.0, meshed(shading)).pixel(1, 38), RED, "{what} far off the page: the rest of the page draws");
+ }
+ for (what, decode) in [("on the page", "[0 40 0 40 0 1 0 1 0 1]"), ("covering the page", "[-40000 40000 -40000 40000 0 1 0 1 0 1]")] {
+ let page = placed(40.0, meshed(stream(&format!("/ShadingType 6 {MESH} /BitsPerFlag 8 /Decode {decode}"), &coons())));
+ let center = page.pixel(20, 20);
+ assert!(center != WHITE && center[3] == 255, "a patch {what} is shaded: {center:?}");
+ }
+ // A patch filling a 4 × 4 pt rectangle as a pattern is still shaded.
+ let shading = stream(&format!("/ShadingType 6 {MESH} /BitsPerFlag 8 /Decode [10 14 10 14 0 1 0 1 0 1]"), &coons());
+ let page = placed(
+ 40.0,
+ pdf("/MediaBox[0 0 40 40]/Resources<</Pattern<</P0<</PatternType 2/Shading 5 0 R>>>>>>", "/Pattern cs /P0 scn 10 10 4 4 re f", &[shading]),
+ );
+ let middle = page.pixel(12, 28);
+ assert!(middle != WHITE && middle[3] == 255, "a small patch is shaded: {middle:?}");
+ }
+
+ /// Forty thousand Coons patches beside the page, and a lattice with no vertices per row.
+ #[test]
+ fn mesh_shadings_with_many_patches_or_no_rows_finish() {
+ for shading in [
+ stream(&format!("/ShadingType 6 {MESH} /BitsPerFlag 8 /Decode [100 140 100 140 0 1 0 1 0 1]"), &coons().repeat(40_000)),
+ stream(&format!("/ShadingType 5 {MESH} /VerticesPerRow 0 /Decode [0 40 0 40 0 1 0 1 0 1]"), &[0; 64]),
+ ] {
+ assert_eq!(placed(40.0, meshed(shading)).pixel(1, 38), RED, "the rest of the page draws");
+ }
+ }
+
+ /// A page with `/UserUnit 2` is twice its media box in points, and Image Import Options › Crop
+ /// to measures the trim box in points as well.
+ #[test]
+ fn a_page_with_a_user_unit_and_its_boxes_are_sized_in_points() {
+ let page = pdf("/MediaBox[0 0 100 50]/TrimBox[10 10 90 40]/UserUnit 2", "", &[]);
+ assert_eq!(pdf_page_size(&page, 0), Some((200.0, 100.0)));
- assert_eq!(pdf_page_box(&page, 0, "trim"), Some((20.0, 20.0, 160.0, 60.0)));
- assert_eq!(pdf_page_box(&page, 0, "media"), Some((0.0, 0.0, 200.0, 100.0)));
++ let near = |crop: PdfCrop, frac: [f64; 4], size: (f64, f64)| {
++ let (f, s) = pdf_crop_box(&page, 0, crop).unwrap();
++ assert!(
++ f.iter().zip(frac).all(|(a, b)| (a - b).abs() < 1e-6) && (s.0 - size.0).abs() < 1e-6 && (s.1 - size.1).abs() < 1e-6,
++ "{crop:?}: {f:?} {s:?}"
++ );
++ };
++ near(PdfCrop::Trim, [0.1, 0.2, 0.9, 0.8], (160.0, 60.0));
++ near(PdfCrop::Media, [0.0, 0.0, 1.0, 1.0], (200.0, 100.0));
+ }
diff --cc crates/tools/src/tests.rs
index 6c75b0da6,aacfb8d3f..ba49ff4bb
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@@ -705,3 -748,569 +748,569 @@@ fn pen_click_snaps_to_a_guide()
let x = p["anchors"][0]["p"][0].as_f64().unwrap();
assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");
}
+
+ /// A text frame with overset text (selected), an empty frame and a threaded pair x → y, on page 1.
+ struct ThreadDoc {
+ d: Document,
+ l: CanvasLayout,
+ s: Selection,
+ c: Cache,
+ /// The selected text frame.
+ a: ItemId,
+ /// An empty (unassigned) frame.
+ e: ItemId,
+ x: ItemId,
+ y: ItemId,
+ }
+
+ fn thread_doc() -> ThreadDoc {
+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });
+ let lid = d.default_layer();
+ let (a, _) = d
+ .add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 250.0, 160.0), lid, &"Words flow on. ".repeat(40), ParaFormat::default())
+ .unwrap();
+ let e = ItemId(d.alloc());
+ d.insert_item(SpreadRef::Doc(0), Item::new(e, lid, Shape::Rectangle, shapes::rectangle(Rect::new(100.0, 400.0, 250.0, 500.0))), None).unwrap();
+ let (x, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 100.0, 450.0, 160.0), lid, "x", ParaFormat::default()).unwrap();
+ let (y, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 400.0, 450.0, 500.0), lid, "", ParaFormat::default()).unwrap();
+ d.thread(x, y).unwrap();
+ let l = CanvasLayout::new(&d, false);
+ ThreadDoc { s: Selection::items(vec![a]), c: Cache::new(), l, d, a, e, x, y }
+ }
+
+ impl ThreadDoc {
+ fn cx(&self) -> ToolContext<'_> {
+ ctx(&self.d, &self.s, &self.c, &self.l)
+ }
+ /// Canvas point of a spread-0 point.
+ fn at(&self, x: f64, y: f64) -> Point {
+ self.l.to_canvas(SpreadRef::Doc(0), Point::new(x, y))
+ }
+ fn port(&self, id: ItemId, out: bool) -> Point {
+ thread::port_center(&self.d, &self.l, id, out, 1.0).unwrap()
+ }
+ }
+
+ fn click(t: &mut Box<dyn Tool>, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
+ let mut v = t.pointer(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods));
+ v.extend(t.pointer(cx, &PointerEvent::new(PointerKind::Up, p.x, p.y).with_mods(mods)));
+ v
+ }
+
+ fn thread_exec(p: serde_json::Value) -> Vec<Action> {
+ vec![Action::Exec("text.thread".into(), p)]
+ }
+
+ #[test]
+ fn out_port_loads_text_and_a_click_threads_an_empty_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ let port = td.port(td.a, true);
+ // The out port sits on the right edge, 12 px above the bottom-right corner.
+ assert!((port - td.at(250.0, 148.0)).hypot() < 1e-9, "{port:?}");
+ // A press just off the port's centre still loads (any zoom: tolerance is in pixels).
+ assert!(click(&mut t, &cx, port + designcraft_geom::Vec2::new(3.0, -3.0), Mods::default()).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ let over_e = td.at(175.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::ThreadLink);
+ // A frame something already threads into can't join; neither can the loaded frame itself.
+ assert_eq!(t.cursor(&cx, td.at(375.0, 450.0), Mods::default()), Cursor::NotAllowed);
+ assert_eq!(t.cursor(&cx, td.at(175.0, 130.0), Mods::default()), Cursor::LoadedText);
+ assert_eq!(click(&mut t, &cx, over_e, Mods::default()), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ // Unloaded again: the cursor and clicks are back to normal.
+ assert_eq!(t.cursor(&cx, over_e, Mods::default()), Cursor::Arrow);
+ }
+
+ #[test]
+ fn ports_hit_at_any_zoom() {
+ let td = thread_doc();
+ let mut cx = td.cx();
+ cx.zoom = 4.0;
+ let port = thread::port_center(&td.d, &td.l, td.a, false, 4.0).unwrap();
+ assert!((port - td.at(100.0, 100.0 + 14.5 / 4.0)).hypot() < 1e-9);
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(1.5, 1.5)), Some((td.a, false)));
+ assert_eq!(thread::port_at(&cx, port + designcraft_geom::Vec2::new(4.0, 0.0)), None, "8 screen px away at 4×");
+ }
+
+ #[test]
+ fn loaded_click_on_empty_page_makes_a_column_frame() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let a = click(&mut t, &cx, td.at(200.0, 600.0), Mods::default());
+ assert_eq!(a, thread_exec(serde_json::json!({"from": td.a.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}})));
+ }
+
+ #[test]
+ fn loaded_drag_makes_a_frame_of_that_size_and_shift_autoflows() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let (p0, p1) = (td.at(320.0, 560.0), td.at(470.0, 700.0));
+ let shift = Mods { shift: true, ..Default::default() };
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y).with_mods(shift)).is_empty());
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y).with_mods(shift)).is_empty());
+ assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::from_points(p0, p1))]);
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y).with_mods(shift));
+ assert_eq!(
+ a,
+ thread_exec(
+ serde_json::json!({"from": td.a.0, "rect": [320.0, 560.0, 470.0, 700.0], "spread": {"kind": "doc", "index": 0}, "autoflow": true})
+ )
+ );
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow, "autoflow unloads");
+ }
+
+ #[test]
+ fn loaded_drag_snaps_like_frame_drawing() {
+ let td = thread_doc();
+ let cx = ToolContext { snap: SnapView::FACTORY, ..td.cx() };
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ // Press and release a point or two inside the column's edges: both sides snap to them.
+ let (p0, p1) = (td.at(col.x0 + 1.5, 560.0), td.at(col.x1 - 2.0, 650.0));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p0.x, p0.y));
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, p1.x, p1.y));
+ let Some(Overlay::Marquee(m)) = t.overlays(&cx).first().cloned() else { panic!("no marquee") };
+ assert!((m.x0 - td.at(col.x0, 0.0).x).abs() < 1e-9 && (m.x1 - td.at(col.x1, 0.0).x).abs() < 1e-9, "{m:?}");
+ let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p1.x, p1.y));
+ let [Action::Exec(id, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!(id, "text.thread");
+ let r: Vec<f64> = p["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert_eq!((r[0], r[2]), (col.x0, col.x1), "{p}");
+ }
+
+ #[test]
+ fn alt_click_stays_loaded() {
+ let mut td = thread_doc();
+ let original = td.d.clone();
+ let mut t = create("selection");
+ let alt = Mods { alt: true, ..Default::default() };
+ let col = td.d.spreads[0].pages[0].column_rects()[0];
+ let empty = td.at(200.0, 600.0);
+ let new_frame_from =
+ |f: ItemId| thread_exec(serde_json::json!({"from": f.0, "rect": [col.x0, 600.0, col.x1, col.y1], "spread": {"kind": "doc", "index": 0}}));
+ {
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.a.0, "to": td.e.0})));
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::LoadedText);
+ // The thread failed (the document is unchanged): still loaded from a.
+ assert_eq!(click(&mut t, &cx, empty, alt), new_frame_from(td.a));
+ }
+ // That click's command ran: the next click threads after the frame it added.
+ let (n, _) =
+ td.d.add_text_frame(SpreadRef::Doc(0), Rect::new(col.x0, 600.0, col.x1, col.y1), td.d.default_layer(), "", ParaFormat::default()).unwrap();
+ td.d.thread(td.a, n).unwrap();
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": n.0, "to": td.e.0})));
+ }
+ // Undone: back on a, not on a's old neighbour or the frame the undo removed.
+ td.d = original;
+ {
+ let cx = td.cx();
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.a));
+ }
+ // From x, which threads into y: when threading e in between fails, x stays loaded, not y.
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), alt), thread_exec(serde_json::json!({"from": td.x.0, "to": td.e.0})));
+ assert_eq!(click(&mut t, &cx, empty, Mods::default()), new_frame_from(td.x));
+ }
+
+ #[test]
+ fn escape_unloads_and_keeps_the_selection() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, true), Mods::default());
+ assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // An ordinary click on empty space deselects again.
+ let p = td.at(500.0, 700.0);
+ assert_eq!(
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)),
+ vec![Action::Exec("selection.set".into(), serde_json::json!({"ids": []}))]
+ );
+ }
+
+ #[test]
+ fn loaded_click_on_the_linked_frame_unthreads() {
+ // x is selected; its out port links to y.
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.x, true), Mods::default());
+ let over_y = td.at(375.0, 450.0);
+ assert_eq!(t.cursor(&cx, over_y, Mods::default()), Cursor::Unthread);
+ assert_eq!(
+ click(&mut t, &cx, over_y, Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))]
+ );
+ // From y's in port, x is the frame before.
+ let td = ThreadDoc { s: Selection::items(vec![td.y]), ..td };
+ let cx = td.cx();
+ click(&mut t, &cx, td.port(td.y, false), Mods::default());
+ assert_eq!(
+ click(&mut t, &cx, td.at(375.0, 130.0), Mods::default()),
+ vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.y.0, "side": "before"}))]
+ );
+ }
+
+ #[test]
+ fn in_port_threads_in_front() {
+ let td = thread_doc();
+ let cx = td.cx();
+ let mut t = create("selection");
+ click(&mut t, &cx, td.port(td.a, false), Mods::default());
+ assert_eq!(click(&mut t, &cx, td.at(175.0, 450.0), Mods::default()), thread_exec(serde_json::json!({"from": td.e.0, "to": td.a.0})));
+ }
+
+ #[test]
+ fn double_click_on_a_port_breaks_its_link() {
+ let td = thread_doc();
+ let td = ThreadDoc { s: Selection::items(vec![td.x]), ..td };
+ let cx = td.cx();
+ // A double click sent as such (control channel), and the canvas's second press.
+ let second = |p: Point| [PointerEvent::new(PointerKind::DoubleClick, p.x, p.y), PointerEvent::new(PointerKind::Down, p.x, p.y).with_clicks(2)];
+ let p = td.port(td.x, true);
+ for ev in second(p) {
+ let mut t = create("selection");
+ click(&mut t, &cx, p, Mods::default());
+ let a = t.pointer(&cx, &ev);
+ assert_eq!(a, vec![Action::Exec("text.unthread".into(), serde_json::json!({"frame": td.x.0, "side": "after"}))], "{ev:?}");
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, p.x, p.y)).is_empty());
+ assert_eq!(t.cursor(&cx, td.at(500.0, 700.0), Mods::default()), Cursor::Arrow);
+ // The in port of the first frame has no link: nothing to break.
+ let q = td.port(td.x, false);
+ for ev in second(q) {
+ assert!(t.pointer(&cx, &ev).is_empty(), "{ev:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn clicks_in_a_row_edit_and_select_text() {
+ 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, 300.0, 200.0), lid, "Two words", ParaFormat::default()).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let (x, y) = (150.0 + off.x, 110.0 + off.y);
+ let press = |n: u8| PointerEvent::new(PointerKind::Down, x, y).with_clicks(n);
+ // Selection tool: the second press of a double click edits the text there.
+ let mut t = create("selection");
+ let a = t.pointer(&cx, &press(1));
+ assert!(matches!(&a[0], Action::Exec(id, _) if id == "selection.set"), "{a:?}");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
+ let a = t.pointer(&cx, &press(2));
+ assert_eq!(a.first(), Some(&Action::SwitchTool("type".into())));
+ assert!(matches!(&a[1], Action::Exec(id, p) if id == "text.placeCaret" && p["frame"] == fid.0), "{a:?}");
+ // Type tool: word, line, paragraph, then the story.
+ let mut t = create("type");
+ let unit = |a: Vec<Action>| match a.as_slice() {
+ [Action::Exec(id, p)] if id == "text.selectAt" => p["unit"].as_str().map(str::to_string),
+ [Action::Exec(id, _)] if id == "text.placeCaret" => None,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(unit(t.pointer(&cx, &press(1))), None);
+ for (n, want) in [(2, "word"), (3, "line"), (4, "paragraph"), (5, "story"), (9, "story")] {
+ assert_eq!(unit(t.pointer(&cx, &press(n))).as_deref(), Some(want), "{n} clicks");
+ }
+ // A double click sent as such (control channel) selects a word too.
+ assert_eq!(unit(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x, y))).as_deref(), Some("word"));
+ // Moving a little while pressed keeps the unit selected.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());
+ }
+
+ #[test]
+ fn pen_continues_an_open_path_from_either_end_point() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let anchors = vec![
+ designcraft_geom::Anchor::corner(Point::new(100.0, 100.0)),
+ designcraft_geom::Anchor {
+ p: Point::new(200.0, 100.0),
+ h_in: Point::new(170.0, 80.0),
+ h_out: Point::new(230.0, 120.0),
+ kind: designcraft_geom::AnchorKind::Smooth,
+ },
+ ];
+ let mut it = Item::new(id, lid, Shape::Path, designcraft_geom::PathData::single(designcraft_geom::SubPath::new(anchors, false)));
+ it.stroke = Stroke::default();
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| (x + off.x, y + off.y);
+ let ev = |k: PointerKind, (x, y): (f64, f64)| PointerEvent::new(k, x, y);
+ let mut t = create("pen");
+ // The cursor says the end point continues the path; elsewhere it's the plain pen.
+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::PenContinue);
+ assert_eq!(t.cursor(&cx, Point::new(at(150.0, 300.0).0, at(150.0, 300.0).1), Mods::default()), Cursor::Pen);
+ // Clicking the last anchor adds nothing yet; the next click appends to that path.
+ assert!(t.pointer(&cx, &ev(PointerKind::Down, at(200.0, 100.0))).is_empty());
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(200.0, 100.0))).is_empty(), "a click on the end point changes nothing");
+ t.pointer(&cx, &ev(PointerKind::Down, at(300.0, 200.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(300.0, 200.0)));
+ let [Action::Exec(cmd, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!((cmd.as_str(), p["id"].as_u64(), p["subpath"].as_u64()), ("path.appendAnchor", Some(id.0), Some(0)));
+ assert_eq!((p["anchor"]["p"][0].as_f64(), p["anchor"]["p"][1].as_f64()), (Some(300.0), Some(200.0)));
+ // Clicking the first anchor of the other end closes it.
+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));
+ assert_eq!(a, vec![Action::Exec("path.close".into(), serde_json::json!({"id": id.0, "subpath": 0}))]);
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, at(100.0, 100.0))).is_empty());
+ // From the first anchor, the path is reversed first; a drag there sets its direction lines.
+ let mut t = create("pen");
+ let a = t.pointer(&cx, &ev(PointerKind::Down, at(100.0, 100.0)));
+ assert_eq!(a, vec![Action::Exec("path.reverse".into(), serde_json::json!({"ids": [id.0], "subpath": 0}))]);
+ t.pointer(&cx, &ev(PointerKind::Drag, at(80.0, 140.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, at(80.0, 140.0)));
+ assert_eq!(
+ a,
+ vec![Action::Exec(
+ "path.setAnchor".into(),
+ serde_json::json!({"id": id.0, "subpath": 0, "anchor": "last", "in": [120.0, 60.0], "out": [80.0, 140.0]})
+ )]
+ );
+ // Closed paths and locked paths aren't continued.
+ let mut d2 = d.clone();
+ d2.item_mut(id).unwrap().locked = true;
+ let cx = ctx(&d2, &s, &c, &l);
+ let t = create("pen");
+ assert_eq!(t.cursor(&cx, Point::new(at(200.0, 100.0).0, at(200.0, 100.0).1), Mods::default()), Cursor::Pen);
+ }
+
+ #[test]
+ fn the_selection_tool_drags_a_path_type_bracket_along_its_path() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let line = designcraft_geom::PathData::single(designcraft_geom::SubPath::new(
+ vec![designcraft_geom::Anchor::corner(Point::new(100.0, 300.0)), designcraft_geom::Anchor::corner(Point::new(500.0, 300.0))],
+ false,
+ ));
+ let mut it = Item::new(id, lid, Shape::GraphicLine, line);
+ let sid = designcraft_doc::StoryId(d.alloc());
+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };
+ tf.options.path = Some(designcraft_doc::PathType { start: 40.0, end: Some(300.0), ..Default::default() });
+ it.content = designcraft_doc::Content::Text(tf);
+ let mut st = designcraft_doc::Story::with_text(sid, "On the line", Default::default());
+ st.frames = vec![id];
+ d.stories.insert(sid, Arc::new(st));
+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let at = |x: f64, y: f64| Point::new(x + off.x, y + off.y);
+ let ev = |k: PointerKind, p: Point| PointerEvent::new(k, p.x, p.y);
+ // Not selected: no brackets.
+ let none = Selection::default();
+ assert!(create("selection").overlays(&ctx(&d, &none, &c, &l)).is_empty());
+ let s = Selection { items: vec![id], ..Default::default() };
+ let cx = ctx(&d, &s, &c, &l);
+ let mut t = create("selection");
+ // Both brackets drawn across the path at 140 and 400 (a line and a tick each).
+ let o = t.overlays(&cx);
+ let xs: Vec<f64> = o.iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { (a.x == b.x).then_some(a.x - off.x) } else { None }).collect();
+ assert_eq!(xs, [140.0, 400.0], "{o:?}");
+ assert_eq!(t.cursor(&cx, at(140.0, 300.0), Mods::default()), Cursor::PathBracket);
+ assert_ne!(t.cursor(&cx, at(250.0, 300.0), Mods::default()), Cursor::PathBracket);
+ // Drag the start bracket: its distance along the path follows the pointer, off the path too.
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, at(140.0, 301.0))), vec![Action::Begin("Move Bracket".into())]);
+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(220.0, 330.0)));
+ let [Action::Preview(cmd, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert_eq!((cmd.as_str(), p["id"].as_u64()), ("type.pathOptions", Some(id.0)));
+ assert!((p["start"].as_f64().unwrap() - 120.0).abs() < 1e-6, "{p}");
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, at(220.0, 330.0))), vec![Action::Commit]);
+ // The end bracket.
+ t.pointer(&cx, &ev(PointerKind::Down, at(400.0, 300.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Drag, at(450.0, 290.0)));
+ let [Action::Preview(_, p)] = a.as_slice() else { panic!("{a:?}") };
+ assert!((p["end"].as_f64().unwrap() - 350.0).abs() < 1e-6, "{p}");
+ }
+
+ #[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)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ 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,
++ ..Default::default()
+ }),
+ );
+ 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}))]);
+ // 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 eyedropper_ignores_inactive_states_of_a_multi_state_object() {
+ use designcraft_doc::{Asset, AssetId, Content, Graphic};
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ d.assets.insert(
+ AssetId(1),
+ std::sync::Arc::new(Asset {
+ id: AssetId(1),
+ name: "photo.png".into(),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(vec![]),
+ pixels: Some((100, 100)),
- page: 0,
++ ..Default::default()
+ }),
+ );
+ let area = Rect::new(100.0, 100.0, 200.0, 200.0);
+ let raster = {
+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ it.content = Content::Graphic(Graphic {
+ asset: AssetId(1),
+ size: (100.0, 100.0),
+ xf: designcraft_geom::Affine::translate((0.0, 0.0)),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ it
+ };
+ let mut vector = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ vector.fill.swatch = "[Black]".into();
+ let target = add_rect(&mut d, Rect::new(400.0, 100.0, 450.0, 150.0));
+ let s = Selection { items: vec![target], ..Default::default() };
+ let sample = Action::Exec("color.sample".into(), serde_json::json!({"at": [120.0, 130.0], "spread": {"kind": "doc", "index": 0}}));
+ // Children [vector, raster] with the raster on top: it samples only while it is the active state.
+ for (active, samples) in [(1, true), (0, false)] {
+ let mut group = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(area));
+ group.content = Content::Group { items: vec![std::sync::Arc::new(vector.clone()), std::sync::Arc::new(raster.clone())] };
+ group.states = vec!["a".into(), "b".into()];
+ group.active_state = active;
+ let mut d2 = d.clone();
+ d2.insert_item(SpreadRef::Doc(0), group, None).unwrap();
+ let (c, l) = (Cache::new(), CanvasLayout::new(&d2, false));
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let cx = ctx(&d2, &s, &c, &l);
+ let a = create("eyedropper").pointer(&cx, &PointerEvent::new(PointerKind::Down, 120.0 + off.x, 130.0 + off.y));
+ assert_eq!(a.contains(&sample), samples, "active state {active}: {a:?}");
+ }
+ }
+
+ #[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);
+ }
diff --cc crates/ui-egui/src/dialogs.rs
index d18f05a20,7d02776a2..4005f2895
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -1181,120 -1565,324 +1565,326 @@@ pub fn show(app: &mut DesignApp, ctx: &
// forms remain reachable at large UI scales, without shrinking their text.
let footer_height = ui.spacing().interact_size.y.max(ui.text_style_height(&egui::TextStyle::Button) + 2.0 * ui.spacing().button_padding.y);
let body_height = (available.y - ui.min_size().y - footer_height - 12.0 - 2.0 * ui.spacing().item_spacing.y).max(1.0);
- egui::ScrollArea::both().id_salt(("dialog_body", &d.id)).min_scrolled_width(1.0).min_scrolled_height(1.0).max_width(width).max_height(body_height).show(ui, |ui| {
- match d.id.as_str() {
- "newDocument" => {
- ui.horizontal(|ui| {
- ui.with_layout(if crate::i18n::is_rtl(&app.ui.language) { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Preset"));
- let cur = d.s("preset");
- egui::ComboBox::from_id_salt("preset").selected_text(&cur).width(180.0).show_ui(ui, |ui| {
- for p in designcraft_doc::build::PRESETS {
- if ui.selectable_label(cur == p.name, p.name).clicked() {
- d.fields.insert("preset".into(), json!(p.name));
- d.fields.insert("width".into(), json!(format_measure(p.width, p.units)));
- d.fields.insert("height".into(), json!(format_measure(p.height, p.units)));
- d.fields.insert("facingPages".into(), json!(p.intent == designcraft_doc::Intent::Print));
- }
+ egui::ScrollArea::both()
+ .id_salt(("dialog_body", &d.id))
+ .min_scrolled_width(1.0)
+ .min_scrolled_height(1.0)
+ .max_width(width)
+ .max_height(body_height)
+ .show(ui, |ui| match d.id.as_str() {
+ "newDocument" => {
+ ui.horizontal(|ui| {
+ ui.with_layout(
+ if crate::i18n::is_rtl(&app.ui.language) {
+ egui::Layout::right_to_left(egui::Align::Center)
+ } else {
+ egui::Layout::left_to_right(egui::Align::Center)
+ },
+ |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Preset"));
+ let cur = d.s("preset");
+ egui::ComboBox::from_id_salt("preset").selected_text(&cur).width(180.0).show_ui(ui, |ui| {
+ for p in designcraft_doc::build::PRESETS {
+ if ui.selectable_label(cur == p.name, p.name).clicked() {
+ d.fields.insert("preset".into(), json!(p.name));
+ d.fields.insert("width".into(), json!(format_measure(p.width, p.units)));
+ d.fields.insert("height".into(), json!(format_measure(p.height, p.units)));
+ d.fields.insert("facingPages".into(), json!(p.intent == designcraft_doc::Intent::Print));
+ }
+ }
+ });
+ },
+ );
+ });
+ if crate::i18n::is_rtl(&app.ui.language) {
+ // egui Grid currently supports LTR only. Use explicit RTL rows;
+ // the numeric editors retain LTR alignment and logical values.
+ for (first, key, second, other, toggle) in [
+ ("Width", "width", "Height", "height", false),
+ ("Pages", "pages", "Facing Pages", "facingPages", true),
+ ("Columns", "columns", "Gutter", "gutter", false),
+ ("Top", "marginTop", "Bottom", "marginBottom", false),
+ ("Inside", "marginInside", "Outside", "marginOutside", false),
+ ("Bleed", "bleed", "Primary Text Frame", "primaryTextFrame", true),
+ ] {
+ ui.horizontal(|ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, first));
+ text_field(ui, &mut d, key, 80.0);
+ if toggle {
+ check(ui, &mut d, other, crate::i18n::tr(&app.ui.language, second));
+ } else {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, second));
+ text_field(ui, &mut d, other, 80.0);
+ }
+ });
+ });
}
+ } else {
+ egui::Grid::new("nd").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
+ text_field(ui, &mut d, "width", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
+ text_field(ui, &mut d, "height", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Pages"));
+ text_field(ui, &mut d, "pages", 80.0);
+ ui.label("");
+ check(ui, &mut d, "facingPages", crate::i18n::tr(&app.ui.language, "Facing Pages"));
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Columns"));
+ text_field(ui, &mut d, "columns", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Gutter"));
+ text_field(ui, &mut d, "gutter", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Top"));
+ text_field(ui, &mut d, "marginTop", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bottom"));
+ text_field(ui, &mut d, "marginBottom", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Inside"));
+ text_field(ui, &mut d, "marginInside", 80.0);
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Outside"));
+ text_field(ui, &mut d, "marginOutside", 80.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bleed"));
+ text_field(ui, &mut d, "bleed", 80.0);
+ ui.label("");
+ check(ui, &mut d, "primaryTextFrame", crate::i18n::tr(&app.ui.language, "Primary Text Frame"));
+ ui.end_row();
+ });
+ }
+ }
+ "frameSize" => {
+ egui::Grid::new("fs").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
+ text_field(ui, &mut d, "width", 90.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
+ text_field(ui, &mut d, "height", 90.0);
+ ui.end_row();
});
+ }
+ "findChange" => {
+ ui.horizontal(|ui| {
+ for (label, grep) in [("Text", false), ("GREP", true)] {
+ if ui
+ .selectable_label(
+ !d.b("objectMode") && d.b("grep") == grep,
+ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label)),
+ )
+ .clicked()
+ {
+ if d.set_field("objectMode", json!(false)) {
+ app.session.reset_find_scope();
+ }
+ d.fields.insert("grep".into(), json!(grep));
+ }
+ }
+ if ui.selectable_label(d.b("objectMode"), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Object"))).clicked()
+ && d.set_field("objectMode", json!(true))
+ {
+ app.session.reset_find_scope();
+ }
});
- });
- if crate::i18n::is_rtl(&app.ui.language) {
- // egui Grid currently supports LTR only. Use explicit RTL rows;
- // the numeric editors retain LTR alignment and logical values.
- for (first, key, second, other, toggle) in [
- ("Width", "width", "Height", "height", false),
- ("Pages", "pages", "Facing Pages", "facingPages", true),
- ("Columns", "columns", "Gutter", "gutter", false),
- ("Top", "marginTop", "Bottom", "marginBottom", false),
- ("Inside", "marginInside", "Outside", "marginOutside", false),
- ("Bleed", "bleed", "Primary Text Frame", "primaryTextFrame", true),
- ] {
+ if d.b("objectMode") {
+ // Find/Change › Object: objects by fill and kind; change their fill or opacity.
+ let swatches: Vec<String> = app
+ .session
+ .active()
+ .map(|st| st.doc.swatches.iter().filter(|w| !w.hidden).map(|w| w.name.clone()).collect())
+ .unwrap_or_default();
+ egui::Grid::new("fco").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (key, label, any) in [("objFill", "Find fill:", "(any)"), ("objChangeFill", "Change fill to:", "(unchanged)")] {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
+ let cur = d.s(key);
+ egui::ComboBox::from_id_salt(key)
+ .selected_text(if cur.is_empty() { any } else { cur.as_str() })
+ .width(180.0)
+ .show_ui(ui, |ui| {
+ if ui
+ .selectable_label(cur.is_empty(), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, any)))
+ .clicked()
+ {
+ d.fields.insert(key.into(), json!(""));
+ }
+ for w in &swatches {
+ if ui.selectable_label(*w == cur, w).clicked() {
+ d.fields.insert(key.into(), json!(w));
+ }
+ }
+ });
+ ui.end_row();
+ }
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Kind:"));
+ let cur = d.s("objKind");
+ egui::ComboBox::from_id_salt("objKind").selected_text(if cur.is_empty() { "(any)" } else { cur.as_str() }).show_ui(
+ ui,
+ |ui| {
+ for v in ["", "text", "graphic", "shape", "line", "group"] {
+ if ui
+ .selectable_label(
+ cur == v,
+ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if v.is_empty() { "(any)" } else { v })),
+ )
+ .clicked()
+ {
+ d.fields.insert("objKind".into(), json!(v));
+ }
+ }
+ },
+ );
+ ui.end_row();
+ });
+ let mut crit = json!({});
+ if !d.s("objFill").is_empty() {
+ crit["fill"] = json!(d.s("objFill"));
+ }
+ if !d.s("objKind").is_empty() {
+ crit["kind"] = json!(d.s("objKind"));
+ }
ui.horizontal(|ui| {
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, first));
- text_field(ui, &mut d, key, 80.0);
- if toggle {
- check(ui, &mut d, other, crate::i18n::tr(&app.ui.language, second));
- } else {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, second));
- text_field(ui, &mut d, other, 80.0);
- }
- });
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find All"))).clicked() {
+ let n = app.run("find.objects", crit.clone()).ok().and_then(|r| r["ids"].as_array().map(Vec::len)).unwrap_or(0);
+ d.fields.insert("status".into(), json!(format!("{n} found")));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked()
+ && !d.s("objChangeFill").is_empty()
+ {
+ let mut p = crit.clone();
+ p["change"] = json!({"fill": d.s("objChangeFill")});
+ let n = app.run("find.changeObjects", p).ok().and_then(|r| r["changed"].as_u64()).unwrap_or(0);
+ d.fields.insert("status".into(), json!(format!("{n} changed")));
+ }
+ });
+ ui.label(d.s("status"));
+ } else {
+ egui::Grid::new("fc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Find what:"));
+ text_field(ui, &mut d, "find", 260.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Change to:"));
+ text_field(ui, &mut d, "change", 260.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Search:"));
+ let cur = d.s("scope");
+ egui::ComboBox::from_id_salt("fcscope")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &cur)))
+ .show_ui(ui, |ui| {
+ for v in ["document", "story", "selection"] {
+ if ui.selectable_label(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, v))).clicked()
+ && d.set_field("scope", json!(v))
+ {
+ app.session.reset_find_scope();
+ }
+ }
+ });
+ ui.end_row();
+ });
+ ui.horizontal(|ui| {
+ check(ui, &mut d, "caseSensitive", crate::i18n::tr(&app.ui.language, "Case sensitive"));
+ check(ui, &mut d, "wholeWord", crate::i18n::tr(&app.ui.language, "Whole word"));
});
+ ui.horizontal(|ui| {
+ let params0 = find_change_params(&d);
+ let params = || params0.clone();
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Find Next"))).clicked() {
+ let r = app.run("find.next", params());
+ let msg = match r {
+ Ok(Value::Null) => "No matches".to_string(),
+ Ok(_) => "Found".to_string(),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Change All"))).clicked() {
+ let msg = match app.run("find.change", params()) {
+ Ok(v) => format!("{} replacement(s) made", v["count"]),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Count"))).clicked() {
+ let msg = match app.run("find.find", params()) {
+ Ok(v) => format!("{} match(es)", v.as_array().map(|a| a.len()).unwrap_or(0)),
+ Err(e) => e,
+ };
+ d.fields.insert("status".into(), json!(msg));
+ }
+ });
+ if let Some(st) = d.fields.get("status").and_then(Value::as_str) {
+ ui.label(egui::RichText::new(st).color(crate::theme::Tokens::get(ui.ctx()).text_dim));
+ }
}
- } else {
- egui::Grid::new("nd").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
- text_field(ui, &mut d, "width", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
- text_field(ui, &mut d, "height", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Pages"));
- text_field(ui, &mut d, "pages", 80.0);
- ui.label("");
- check(ui, &mut d, "facingPages", crate::i18n::tr(&app.ui.language, "Facing Pages"));
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Columns"));
- text_field(ui, &mut d, "columns", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Gutter"));
- text_field(ui, &mut d, "gutter", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Top"));
- text_field(ui, &mut d, "marginTop", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bottom"));
- text_field(ui, &mut d, "marginBottom", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Inside"));
- text_field(ui, &mut d, "marginInside", 80.0);
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Outside"));
- text_field(ui, &mut d, "marginOutside", 80.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Bleed"));
- text_field(ui, &mut d, "bleed", 80.0);
- ui.label("");
- check(ui, &mut d, "primaryTextFrame", crate::i18n::tr(&app.ui.language, "Primary Text Frame"));
- ui.end_row();
- });
}
- }
- "frameSize" => {
- egui::Grid::new("fs").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Width"));
- text_field(ui, &mut d, "width", 90.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));
- text_field(ui, &mut d, "height", 90.0);
- ui.end_row();
- });
- }
- "findChange" => {
- ui.horizontal(|ui| {
- for (label, grep) in [("Text", false), ("GREP", true)] {
- if ui.selectable_label(!d.b("objectMode") && d.b("grep") == grep, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {
- d.fields.insert("grep".into(), json!(grep));
- d.fields.insert("objectMode".into(), json!(false));
- }
+ "paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),
+ "deleteParagraphStyle" => delete_paragraph_style(app, ui, &mut d),
+ "characterStyleOptions" => character_style_options(app, ui, &mut d),
+ "deleteCharacterStyle" => delete_character_style(app, ui, &mut d),
+ "footnoteOptions" => footnote_options(app, ui, &mut d),
+ "paragraphRules" => {
+ let current = d.fields.get("current").cloned().unwrap_or_default();
+ paragraph_rules(app, ui, &mut d, "", &current);
+ }
+ "insertXref" => insert_xref(app, ui, &mut d),
+ "findFont" => find_font(app, ui, &mut d),
+ "colorPicker" => color_picker(ui, &mut d),
+ "preferences" => preferences(app, ui, &mut d, body_height),
+ "print" => print_dialog(app, ui, &mut d),
+ "pdfImport" => {
+ ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0));
+ ui.horizontal(|ui| {
+ crate::rtl::label(
+ ui,
+ crate::i18n::tr(&app.ui.language, "Page (1–{count}):").replace("{count}", &d.n("pages").unwrap_or(1.0).to_string()),
+ );
+ text_field(ui, &mut d, "page", 60.0);
+ });
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Crop to:"));
+ let cur = d.s("crop");
+ let label = |v: &str| match v {
++ "contentVisible" => crate::i18n::tr(&app.ui.language, "Bounding Box (Visible Layers Only)"),
++ "contentAll" => crate::i18n::tr(&app.ui.language, "Bounding Box (All Layers)"),
+ "trim" => crate::i18n::tr(&app.ui.language, "Trim"),
+ "bleed" => crate::i18n::tr(&app.ui.language, "Bleed"),
+ "art" => crate::i18n::tr(&app.ui.language, "Art"),
+ "media" => crate::i18n::tr(&app.ui.language, "Media"),
+ _ => crate::i18n::tr(&app.ui.language, "Crop"),
+ };
+ egui::ComboBox::from_id_salt("pdf_crop").selected_text(crate::rtl::widget(ui, label(&cur))).show_ui(ui, |ui| {
- for v in ["crop", "trim", "bleed", "art", "media"] {
++ for v in designcraft_doc::PdfCrop::ALL.map(designcraft_doc::PdfCrop::name) {
+ if ui.selectable_label(label(&cur) == label(v), label(v)).clicked() {
+ d.fields.insert("crop".into(), json!(v));
+ }
+ }
+ });
+ });
+ }
+ "layerOptions" => {
+ let mut layers = d.fields.get("layers").and_then(Value::as_array).cloned().unwrap_or_default();
+ if layers.is_empty() {
+ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "This PDF has no layers."));
}
- if ui.selectable_label(d.b("objectMode"),crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Object"))).clicked() {
- d.fields.insert("objectMode".into(), json!(true));
+ for l in &mut layers {
+ let mut on = l["visible"].as_bool().unwrap_or(true);
+ if ui.checkbox(&mut on, l["name"].as_str().unwrap_or("")).changed() {
+ l["visible"] = json!(on);
+ }
}
- });
- if d.b("objectMode") {
- // Find/Change › Object: objects by fill and kind; change their fill or opacity.
- let swatches: Vec<String> = app.session.active().map(|st| st.doc.swatches.iter().filter(|w| !w.hidden).map(|w| w.name.clone()).collect()).unwrap_or_default();
- egui::Grid::new("fco").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- for (key, label, any) in [("objFill", "Find fill:", "(any)"), ("objChangeFill", "Change fill to:", "(unchanged)")] {
+ d.fields.insert("layers".into(), json!(layers));
+ }
+ "colorSettings" => {
+ let profiles = d.fields.get("profiles").and_then(Value::as_array).cloned().unwrap_or_default();
+ egui::Grid::new("color_settings").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (key, label, kind) in [("rgb", "RGB:", "rgb"), ("cmyk", "CMYK:", "cmyk")] {
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, label));
let cur = d.s(key);
- egui::ComboBox::from_id_salt(key).selected_text(if cur.is_empty() { any } else { cur.as_str() }).width(180.0).show_ui(ui, |ui| {
- if ui.selectable_label(cur.is_empty(), crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, any))).clicked() {
- d.fields.insert(key.into(), json!(""));
- }
- for w in &swatches {
- if ui.selectable_label(*w == cur, w).clicked() {
- d.fields.insert(key.into(), json!(w));
+ egui::ComboBox::from_id_salt(("ws", key)).selected_text(&cur).width(260.0).show_ui(ui, |ui| {
+ for pr in profiles.iter().filter(|p| p["kind"] == kind) {
+ let name = pr["name"].as_str().unwrap_or("");
+ if ui.selectable_label(name == cur, name).clicked() {
+ d.fields.insert(key.into(), json!(name));
}
}
});
diff --cc crates/ui-egui/src/panels/properties.rs
index 49cb920f2,52ce7e688..ca341edd0
--- a/crates/ui-egui/src/panels/properties.rs
+++ b/crates/ui-egui/src/panels/properties.rs
@@@ -2141,6 -2482,107 +2482,107 @@@ mod tests
text_attrs(app).unwrap()["chars"]["language"].clone()
}
+ fn linked_graphics(paths: &[Option<&str>]) -> (DesignApp, Vec<designcraft_doc::ItemId>, Vec<designcraft_doc::AssetId>) {
+ use designcraft_doc::{Asset, AssetId, Content, Graphic, ItemId};
+ use std::sync::Arc;
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"title": "Linked graphics"})).unwrap();
+ let mut items = Vec::new();
+ let mut assets = Vec::new();
+ for (index, path) in paths.iter().enumerate() {
+ let x = 72 + index * 100;
+ let id = ItemId(app.run("frame.create", json!({"rect": [x, 72, x + 72, 144]})).unwrap()["id"].as_u64().unwrap());
+ let doc = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc);
+ let aid = AssetId(doc.alloc());
+ doc.assets.insert(
+ aid,
+ Arc::new(Asset {
+ id: aid,
+ name: "photo.svg".into(),
+ mime: "image/svg+xml".into(),
+ link: path.map(str::to_owned),
+ data: Arc::new(
+ br##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#4488cc"/></svg>"##
+ .to_vec(),
+ ),
+ pixels: Some((32, 32)),
- page: 0,
++ ..Default::default()
+ }),
+ );
+ doc.item_mut(id).unwrap().content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (72.0, 72.0),
+ xf: designcraft_geom::Affine::IDENTITY,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ items.push(id);
+ assets.push(aid);
+ }
+ (app, items, assets)
+ }
+
+ fn links_harness(app: DesignApp, width: f32) -> Harness<'static, DesignApp> {
+ let mut ready = false;
+ let mut h = Harness::builder().with_size(vec2(width, 600.0)).build_ui_state(
+ move |ui, app: &mut DesignApp| {
+ if !ready {
+ crate::theme::install_fonts(ui.ctx(), "");
+ crate::theme::apply(ui.ctx(), &Tokens::for_brightness(Default::default()));
+ ready = true;
+ return;
+ }
+ links_panel(app, ui);
+ },
+ app,
+ );
+ h.input_mut().max_texture_side = Some(8192);
+ h.run_steps(3);
+ h
+ }
+
+ #[test]
+ fn links_panel_distinguishes_same_named_sources_and_keeps_link_actions() {
+ let first = "/project/assets/studio-a/photo.svg";
+ let second = "/project/assets/studio-b/photo.svg";
+ let (app, items, assets) = linked_graphics(&[Some(first), Some(second), None]);
+ let mut h = links_harness(app, 320.0);
+ assert_eq!(h.get_all_by_label("photo.svg").count(), 3);
+ assert!(h.query_by_label(first).is_some(), "the first source path is visible in the row");
+ h.get_by_label(second).click();
+ h.run_steps(3);
+ h.get_by_label("Go To").click();
+ h.run_steps(3);
+ assert_eq!(h.state().session.active().unwrap().selection.items, vec![items[1]]);
+ h.get_by_label("Embed").click();
+ h.run_steps(3);
+ assert!(h.state().session.active().unwrap().doc.assets[&assets[1]].link.is_none());
+ assert_eq!(h.state().session.active().unwrap().doc.assets[&assets[0]].link.as_deref(), Some(first));
+ assert!(h.query_by_label(second).is_none(), "an embedded graphic no longer shows a source path");
+ assert_eq!(h.get_all_by_label("Embedded").count(), 2);
+ assert_eq!(h.get_all_by_label("photo.svg").count(), 3);
+ h.get_by_label(first).click();
+ h.run_steps(3);
+ h.get_by_label("Go To").click();
+ h.run_steps(3);
+ assert_eq!(h.state().session.active().unwrap().selection.items, vec![items[0]]);
+ }
+
+ #[test]
+ fn links_panel_keeps_long_source_paths_inside_a_narrow_panel() {
+ let path = "/project/assets/studio-a/very-long-folder-name/another-long-folder-name/photo.svg";
+ let (app, _, _) = linked_graphics(&[Some(path)]);
+ let mut h = links_harness(app, 240.0);
+ let source = h.get_by_label(path).rect();
+ assert!(source.width() < 150.0, "the source is truncated to its column: {source:?}");
+ assert!(source.right() <= 240.0, "the source stays inside the narrow panel: {source:?}");
+ assert!(h.get_by_label("Page · PPI").rect().right() <= 240.0);
+ h.get_by_label(path).click();
+ h.run_steps(3);
+ assert!(h.output().shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(text) if text.galley.job.text == path && !text.galley.elided && text.visual_bounding_rect().right() <= 240.0)), "the selected path is painted in full and wraps inside the panel");
+ }
+
#[test]
fn properties_character_section_sets_the_language() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());