DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge upstream main a184db6f8 with our 15 PRs (batch-0) into next
aiongg18ae8e476109
diff --cc Cargo.lockindex 1b64ea98c,c9bbd7130..2fd71fa3a--- a/Cargo.lock+++ b/Cargo.lock@@@ -808,22 -796,15 +808,31 @@@ dependencies ="libm",]+[[package]]+name = "craft-atomic"+version = "0.1.0"+source = "git+https://github.com/storytold/craft-libs?rev=e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e#e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e"+dependencies = [+ "rustix 1.1.5",+]++[[package]]+name = "craft-cms"+version = "0.1.0"+source = "git+https://github.com/storytold/craft-libs?rev=e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e#e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e"+dependencies = [+ "rayon",+]++ [[package]]+ name = "craft-pdf"+ version = "0.1.0"+ source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"+ dependencies = [+ "krilla",+ "thiserror 2.0.21",+ ]+[[package]]name = "craft-print"version = "0.1.0"diff --cc Cargo.tomlindex be914a1b3,6d765135b..7327ea70c--- a/Cargo.toml+++ b/Cargo.toml@@@ -11,6 -11,9 +11,8 @@@ rust-version = "1.95repository = "https://github.com/storytold/designcraft"[workspace.dependencies]+ # Shared writer; the immutable revision must be published before this consumer.+ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.1.0", default-features = false }-craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }# internaldesigncraft-geom = { path = "crates/geom" }designcraft-color = { path = "crates/color" }@@@ -109,15 -100,10 +111,16 @@@ lto = "thincodegen-units = 16debug = 0-# Opt-in cancelable macOS termination on the pinned winit 0.30 line.+# Windows 11: winit 0.30.13 resizes a window wrongly while it is dragged across monitors with+# different display scales (rust-windowing/winit#4041, #4600). It flips between the two scales,+# grows by the scale ratio (3600×2250 → 9048×5757 between 250 % and 100 %) and outgrows the GPU+# surface. Pinned to the one commit of rust-windowing/winit#4694, the 0.30.x backport of the fix+# winit master has had since 488c036a (#4341): during a live drag it applies the rect Windows+# suggests (+21/−34 lines in src/platform_impl/windows/event_loop.rs on top of v0.30.13). Remove+# once eframe depends on a winit release with the fix.[patch.crates-io]+winit = { git = "https://github.com/rust-windowing/winit", rev = "39c4009c41e5977d779cf8a365792c8153ca77c5" }+ krilla = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.8.2" }-winit = { git = "https://github.com/skylartaylor/winit.git", rev = "3d51077fd1a966f84df9ef287839dc84fd5b4ca7" }# The hayro crates from pdfcraft's vendor/ directory, with the patches its README lists.hayro = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }hayro-interpret = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0ffaa5e5e6658bccdf8655a3ba689c9" }diff --cc README.mdindex f48fb94e7,e2d5105dc..11e032fa6--- a/README.md+++ b/README.md@@@ -87,8 -87,9 +87,10 @@@ by its own renderer. Try it yourself wiLine breaks are identical on screen and in PDF.- **Fast.** Multithreaded SIMD rendering (vello_cpu), copy-on-write documents with O(1) undosnapshots, and cached composition.-- **Open.** A documented native format, IDML import and export, editable PowerPoint export, and PNG, PDF (PDF/X-4, PDF/A-2b)- and EPUB export.+- **Open.** A documented native format, IDML import and export, INDD import (through- [indd-utils](https://github.com/storytold/indd-utils)), and PNG, PDF (PDF/X-4, PDF/A-2b) and EPUB export.++ [indd-utils](https://github.com/storytold/indd-utils)), editable PowerPoint export, and PNG, PDF++ (PDF/X-4, PDF/A-2b) and EPUB export.+No subscription, no licence server, no telemetry.- **Agent-native.** Every menu item, tool gesture, panel control and dialog can be driven over aJSON control channel and an **MCP server**, so Claude and other agents can lay out and editdiff --cc ROADMAP.mdindex a84578bb7,984973a07..f26825ebf--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -1,8 -1,225 +1,226 @@@# DesignCraft roadmap**Stage: pre-alpha** · next: alpha, ~5–7 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%)+ - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage.+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026+ - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.++ - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.+ - CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Full InDesign CJK composition parity, frame-grid layout and detailed ruby remain unfinished. Warichu sets the selected run in smaller lines inside the line after the line is broken.++ 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.++ ## Status (2026-10-01)++ **Working today**+ - Document model: facing/non-facing spreads, parent pages with page-number markers, sections, layers, frames (text / graphic / unassigned), threaded stories, paragraph/character/object styles with based-on, swatches (process/spot/tints/gradients), corner options, text wrap, drop shadow, opacity/blend.+ - Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together, widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.+ - FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.+ - Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.+ - UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.+ - Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.+ - Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.+ - PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.+ - IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`). Placed PDFs keep their page (`PDFAttribute`), font names with the `$ID/` prefix resolve, and the IDML in a package links the images in its Links folder without embedding them.+ - Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.+ - Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.+ - EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).+ - Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.+ - Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.+ - Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named.+ - Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.+ - Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands.+ - Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus.+ - Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands.+ - Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands.+ - Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands.+ - Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`.+ - Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts.+ - Damage-region repaint: after an edit the canvas re-renders only the frames whose composed text (or the items that) changed and patches its texture — pixel-identical to a full render; typing in a frame repaints in under a millisecond instead of a full-viewport render (22 ms measured on the sample).+ - Crash recovery: unsaved documents are written to the recovery folder every 30 s and reopened (unsaved, remembering their files) after a crash; File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.+ - Graphics backend chosen before the window exists (DirectX 12 on Windows, Vulkan on Linux, Metal on macOS, OpenGL as the fallback; `WGPU_BACKEND` overrides) with a start-up fallback: a backend whose start never showed a frame is skipped at the next start and the status bar says so (`gpu.json`). Found on an AMD hybrid-graphics laptop whose Vulkan driver faulted at the first present.+ - Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).+ - Color panel (fill/stroke proxy, CMYK/RGB/Lab sliders with channel ramps, tint slider for swatches, spectrum ramp, Add to Swatches) and Color Picker (double-click the proxy); mixed colours are unnamed (not listed in Swatches until added); `object.color`, `swatch.addToSwatches`, `swatch.addUnnamed`.+ - Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).+ - Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.+ - Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).+ - File ▸ Export Text (`file.exportText`): a story as Text Only or RTF (fonts, styles, alignment, indents, tables as tab-separated rows); Export EPUB now asks for a path in the UI.+ - Tagged PDF (`file.exportPdf {tagged}`, on by default from the UI): structure tree with stories as paragraphs in reading order, figures carrying their alt text, parent-page items and printer's marks as artifacts.+ - Global Light (`object.globalLight`, `globalLight` on drop/inner shadows; Use Global Light in the Effects panel) and Generate Static Caption (`object.caption`: template over name, path, alt text, label, effective ppi, dimensions, format; any side, offset, style).+ - Control panel scale X/Y, rotation and shear fields (`transform.info`, absolute `transform.set {scaleX, scaleY, rotation, shear}` about the reference point) and Preferences › Transformations are Totals for nested objects and placed graphics.+ - Variable fonts: each named instance is a style (Font menu, shaping with feature variations, metrics, outlines) and embeds at its axis settings in PDF; free axis sliders still to come.+ - Object ▸ Select (first/next above, next/last below, container, content, previous/next in group), full Object ▸ Convert Shape (`object.convertShape`), Table ▸ Split Cell Horizontally/Vertically.+ - Attributes panel (`object.attributes`: Overprint Fill/Stroke/Gap, Nonprinting), with Overprint Gap in Overprint Preview and IDML.+ - Page Numbering View (Preferences: section or absolute): page labels everywhere follow it; Go to Page takes section names, numbers or `+n`.+ - Preferences › Advanced Type (document `advancedType`: superscript/subscript size and position; IDML TextPreference); subscripts now drop 33.3% like InDesign.+ - Preferences › Composition › Highlight: keep violations, H&J violations (three shades), custom tracking/kerning, substituted fonts.+ - File ▸ Export HTML (`file.exportHtml`): one self-contained page in reading order, styles as CSS, images inline, alt text from Object Export Options (also in EPUB).+ - File ▸ Export PowerPoint (`file.exportPptx`, CLI `--export x.pptx`): every page becomes a slide of editable objects: shapes (preset or custom geometry, solid and gradient fills, dashed/compound strokes with arrowheads, shadows, glow, feather, opacity), pictures cropped like their frames (SVG kept as SVG), native tables (merged cells, fills, per-edge borders) and text boxes. By default the text keeps DesignCraft's line breaks, justified spacing and leading; threaded stories split at their frames and lines pushed aside by a wrap get boxes of their own. `lineBreaks: reflow` writes one box per frame in native columns instead. TrueType fonts are embedded where their licences allow, and objects without a PowerPoint equivalent are rasterised. Checked against PowerPoint for Mac and LibreOffice.+ - Swatches panel colour groups (`swatch.newColorGroup`, `moveToGroup`, `ungroupColorGroup`, `renameColorGroup`; folders and a row context menu; IDML ColorGroup).+ - Object ▸ Generate QR Code (`object.qrCode`: web link, text, SMS, email, business card; vector modules as a compound path, into a frame or re-encoded in place).+ - Conditional text (`condition.new/options/delete/apply/list`, Conditional Text panel): hidden conditions drop their text from layout and exports, indicators underline on screen, IDML Condition/AppliedConditions.+ - Endnotes (`endnote.insert/edit/delete/list/options`, Type ▸ Insert Endnote): references number through the document, the endnote frame on a new last page lists them under a heading; IDML keeps the listed text only.+ - Editorial notes (`note.new/edit/delete/convertToText/list`, Notes panel): anchored in text, flagged on screen, never printed or exported.+ - File ▸ Print Booklet (`file.printBooklet`): saddle-stitch or 2-up consecutive printer spreads as PDF, padded with blanks, with a gap between pages.+ - Edit ▸ Transparency Blend Space (`edit.transparencyBlendSpace`; RGB for web/mobile documents; IDML TransparencyPreference) — exported PDFs give pages with transparency a DeviceCMYK or DeviceRGB page group, so viewers and RIPs blend in that space. On screen, spreads with transparency in a CMYK blend space are shown through the working CMYK profile (their colours keep to its gamut, as when composited in CMYK).+ - High Contrast interface theme (fifth Interface Color Theme: black chrome, white text, yellow selection).+ - Place Excel workbooks (.xlsx): the first worksheet's used range becomes a table (shared/inline strings, numbers, booleans).+ - Object Library (`library.new/open/add/place/remove/list/json/close`, Library panel): `.dclib` files of snippets that keep stories, styles, swatches and images.+ - Ink Manager (`ink.list`, `ink.options`; Swatches panel menu): All Spots to Process, per-ink conversion and ink aliases in PDF output; IDML ConvertToProcess/AliasInkName.+ - Appearance of Black complete: Printing/Exporting rich black for RGB output (PNG), Overprint [Black] Swatch at 100% (document, IDML OverprintBlack).+ - Hyperlinks and Bookmarks panels (Window ▸ Interactive): new from the selection, edit (`hyperlink.edit`), go to source (`hyperlink.goToSource`), rename bookmarks (`bookmark.rename`), go to page, delete.+ - Nested line styles (`nestedLineStyles` paragraph attribute, Paragraph Style Options › Drop Caps and Nested Styles, IDML AllNestedLineStyles): the first lines restyle until the line breaks settle.+ - User dictionary hyphenation exceptions (`hyphenation.addException/removeException/list`, Edit ▸ Spelling ▸ User Dictionary): `ex~am~ple` breaks only at `~`, a plain word never hyphenates.+ - Frame Fitting Options (`object.fittingOptions`, Object ▸ Fitting ▸ Frame Fitting Options…): Auto-Fit refits on resize, fitting, Align From reference point, crop amounts; IDML FrameFittingOption.+ - Paragraph borders (per-side weights, colour, tint, offsets) and shading offsets, drawn per column part of split paragraphs (also when overset); Paragraph panel controls; IDML ParagraphBorder*/ParagraphShading*Offset.+ - Font menu: search, favourites (stars, Show Favorites Only; `favoriteFonts` preference) and each family previewed in its own face. Western (and other-script) families come first, then Japanese, Simplified Chinese, Traditional Chinese and Korean ones, each group alphabetical and set off by a separator; the group comes from the font's own data (`meta` languages, family names in a CJK language, OS/2 code pages, else what it covers), read once (installed fonts by the font scan, without loading them). CJK families show their native names, the English name on hover; Preferences › Type › Show Font Names in English (`showFontNamesInEnglish`) shows English names throughout. Search matches either name; documents store the English name. Every family list (Character panel, Control bar, Properties, style dialogs, Find Font, Glyphs) follows this order.+ - Application preferences (engine `Prefs`) now persist across launches (desktop: prefs.json beside ui.json).+ - View ▸ Fit Selection in Window (⌥⌘=) and Find/Change ▸ Object (`find.objects`, `find.changeObjects`: by fill, stroke, weight, opacity, kind, layer, label).+ - Custom workspaces (`window.newWorkspace/deleteWorkspace/resetWorkspace`; workspace switcher shows the current one): bars and panel arrangement saved by name.+ - Word/RTF Import Options (File ▸ Place with Import Options…, `place.styles`, `file.place {styleMap, styleConflicts}`): map imported styles onto the document's, use existing / redefine / auto-rename on conflicts, or remove formatting.+ - Custom anchored objects (`anchored.insert/options {position: custom}`): placed relative to the anchor, frame, column, page margins or page edge with reference points and offsets, no space in the text, keep within column; IDML Anchored position.+ - Variable font axes: Character panel sliders; any axis values (`fontStyle: "Bold {wght:650}"`) make that instance for layout, screen and PDF.+ - Image Import Options › Crop to for placed PDFs (`file.place {pdfCrop: crop|art|trim|bleed|media|contentVisible|contentAll}`, Place PDF dialog): the graphic spans that page box, the document stores the choice, and IDML keeps it as `PDFCrop`.+ - Stroke styles: striped (thick-thin… and custom bands), wavy and straight-hash strokes now draw on screen and in PDF; named custom stripe/dash/dot styles (`strokeStyle.new/delete/list`, Stroke panel Type list; IDML Striped/Dashed/DottedStrokeStyle).+ - Object ▸ Primary Text Frame (`object.primaryTextFrame`): any text frame's story can become (or stop being) the primary story Smart Text Reflow follows.+ - Column rules (Text Frame Options › Column Rules, `object.textFrameOptions {columnRule, columnRuleWeight, columnRuleColor, columnRuleTint, columnRuleOffset, columnRuleTopInset, columnRuleBottomInset}`, reported by `document.inspect`): a bar centred in each gutter of a multi-column frame, inside the insets and between the columns of right-to-left and vertical frames too, broken around paragraphs that span columns, with weight, colour, tint, horizontal offset and top/bottom insets; on screen, in PDF (tagged as an artifact) and in IDML (`ColumnRule…` attributes of `TextFramePreference`, also in object styles). The dialog shows the frame's options and changes only the fields edited. Rule stroke types and overprint aren't there yet.+ - Place a page of an IDML or DesignCraft document (`file.place {layoutPage}`): its objects, stories, styles and swatches as one group (INDD files are not readable).+ - Articles panel (`article.new/add/remove/options/delete/list`): reading order and content of EPUB and HTML exports.+ - Object ▸ Clipping Path (`object.clippingPath {type: alpha|edges, threshold, tolerance}`): traces the placed image and makes the outline the frame.+ - Gridify: arrow keys while dragging a frame or shape tool add columns/rows (`frame.grid`), one undo step.+ - Gap tool (U, `gap.move`): drag the space between objects (or an object and the page edge) and both sides resize.+ - XML basics (`xml.newTag/deleteTag/tag/mapStyle/structure`, `file.exportXml`, `file.importXml`; Tags panel with structure; View ▸ Show Tagged Frames): tagged frames export in reading order, mapped paragraph styles become elements, imported elements flow into frames with matching tags. Inline text tagging (`xml.tagText`, an `xmlTag` character attribute, exported as nested elements) and tag markers (View ▸ Structure ▸ Show Tag Markers) too. DTDs (`xml.loadDtd`, `xml.validate`, `xml.deleteDtd`; Tags panel): loading one adds its elements as tags and names the root; validation checks content models (sequences, choices, `?*+`, mixed content, EMPTY/ANY, parameter entities) and required attributes, and lists each problem with its element path.+ - Adjust Layout / Layout Adjustment (`adjustLayout` on Document Setup and Margins and Columns): objects follow each page's margin box to its new size and position.+ - Content Collector and Placer tools (B; `conveyor.collect/place/list/clear`): copies of objects (with stories, styles, images) ride a conveyor between pages and documents; Alt-click keeps them on it.+ - Linked stories (Edit ▸ Place and Link, `story.placeAndLink/links/updateLink/unlink`): child stories copy a parent, show out of date in the Links panel and update.+ - Edit ▸ Menus (`window.hideMenuItem`): hide menu items; menus with hidden items end in Show All Menu Items.+ - View ▸ Separations Preview (`view.separations`): one process plate as ink density, or areas over an ink limit in red (a GCR preview of the rendered view; spot plates and the flattener preview aren't there).+ - Separations Preview plates now come from each object's own colour (CMYK as authored; RGB and images through the colour settings, images via a cached 17³ table), so pure black shows only on the black plate.+ - Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Spanish is hyphenated with Javier Bezos's Liang patterns (`hyph-es.tex` 5.0, MIT) through the `hypher` crate; hyphenation for other languages isn't bundled yet.+ - Books (`book.new/open/add/remove/list/styleSource/paginate/syncStyles/exportPdf`, Book panel): `.dcbook` files, continuous page numbering, style sync from a style source, one merged PDF.+ - Track Changes (`changes.track/list/acceptAll/rejectAll`, Type ▸ Track Changes): typing is marked added (highlighted on screen), deletions are kept but hidden from layout and exports until accepted or rejected. Per-change accept/reject and authors aren't there yet.+ - Track Changes: per-change Accept / Reject (`changes.accept`, `changes.reject`) and a Track Changes panel listing every change.+ - Move table rows and columns (`table.moveRow`, `table.moveColumn`, Table panel buttons; with whole rows or columns selected, drag them with the Type tool — `table.dropCells`).+ - Distribute Rows Evenly (`table.distributeRows`, Table menu and panel): selected rows receive equal fixed heights preserving their composed total height, with undo/redo. Row-spanning merges and rows outside the composed frames are rejected; shrinking tall cells can overset their text.+ - Object States (`states.create/show/rename/release/list`, Object States panel): multi-state objects show one state on screen and in PDF.+ - Buttons (`button.set/clear/list`, Buttons and Forms panel): go to page / next / previous / first / last / URL as PDF link annotations. Form fields too (`form.set/clear/list`: text fields, check boxes, combo and list boxes, signature fields; required, multiline, defaults) exported as AcroForm widgets through an incremental update (not in PDF/X).+ - Power Zoom (Hand tool: press and hold still for half a second, or Alt-press): zoom out to the spread, aim the red view rectangle, release to zoom back in there.+ - Graphic cells (`table.placeGraphic`, `table.textCell`, Table › Convert Cell Type, Table panel): images in table cells, fitted or filled, clipped to the cell on screen and in PDF.+ - Live Distribute (Space while dragging a selection handle; `transform.resize {distribute}`): objects keep their size and spread with the bounds.+ - Liquid Layout (`liquid.pageRule/object`, `guide.liquid`, `layout.createAlternate`, Liquid Layout panel): scale / re-center / guide-based / object-based page rules applied on page resize and Document Setup; dashed liquid guides; alternate layouts as resized page copies in a named section. Text in an alternate layout stays linked to the original stories (Links panel shows them out of date; `story.updateLink`).+ - Split Window / New Window (`window.split`, `window.newWindow`, Window ▸ Arrange): two side-by-side views of the document with their own zoom, scroll and render cache. New Window puts the second view in its own OS window (an egui viewport; a floating window on the web).+ - Transparency flattener (`file.exportPdf {flatten: high|medium|low|ppi}`, Edit ▸ Transparency Flattener Presets): each object involving transparency becomes an opaque image of its area over what's beneath it, so everything else stays vector (spreads with transparent parent items are rasterised whole).+ - Video and sound (place .mp4/.mov/.webm/.mp3/.wav…, `media.options/get`, Media panel): media frames show a poster or placeholder on screen, in print and in PDF, and export as HTML5 `<video>`/`<audio>` in EPUB. Interactive PDF export (`file.exportPdf {media: true}`, File ▸ Export PDF (Interactive)) embeds each file and plays it in a Screen annotation through a rendition action (controls, loop, play on page load). No in-app playback.+ - Right-to-left text (World-Ready basics): right-to-left runs are shaped right to left, lines are reordered by the Unicode Bidirectional Algorithm (matched against the reference implementation), Paragraph Direction (`type.para {direction}`, Paragraph panel, IDML ParagraphDirection, EPUB `dir`). Digits (`digits`: Default, Arabic, Hindi, Farsi, Native by language; Character panel for right-to-left text; IDML DigitsType) draw 0–9 in another script. Kashidas (`kashidas` paragraph attribute, on by default): justified Arabic lines stretch at one join per word (after seen/sad when possible, never inside lam–alef) with a drawn tatweel before word spaces widen. Carets follow the drawing: the caret before a right-to-left glyph sits at its right edge, arrow keys move as drawn (by words in the line's direction), clicks find the nearest drawn caret position and selections highlight the selected glyphs. Binding: Right to Left (Document Setup, `layout.documentSetup {binding}`, IDML PageBinding) makes page 1 a left page and lays spreads out right to left.+ - Interface language (Edit ▸ Interface Language, `app.language`): German, French, Spanish, Italian, Japanese, Simplified Chinese and Arabic menu titles, common menu items and panel names (our own translations). Common dialog, panel and tooltip labels are also localized, with English fallback for untranslated strings. Arabic translations cover every key in the shared interface translation table, including menu commands and utility labels. German and Japanese cover the whole interface: every key of every catalog. The Type menu's Story Direction, Horizontal/Vertical, Tate-Chu-Yoko, Ruby… and Kenten are translated too. Arabic labels use Unicode bidi run ordering and contextual shaping; welcome and new-document form layouts follow RTL direction independently of document binding. CJK and Arabic glyphs come from [craft-fonts](https://github.com/storytold/craft-fonts) when built with `CRAFT_FONTS_DIR` (all releases): BIZ UDPGothic and Noto Sans CJK SC for the UI (Chinese forms first in the Chinese interface), Noto Sans Arabic, and Mincho for Japanese documents (the web build embeds BIZ UDPGothic only); otherwise from system fonts. Ukrainian covers all 1,430 existing catalog keys, including publishing dialogs and built-in names, with persisted selection, grammatical count captions, English fallback and bundled Cyrillic UI glyph coverage.+ - Page transitions (`page.transition/transitions`, Page Transitions panel): twelve transition types with speed and direction per spread, written into exported PDFs as `/Trans` entries through an incremental update.+ - PDF/X-4 export (`file.exportPdf {standard: "x4"}`): an output intent with our own Generic CMYK ICC profile (lut16 tables generated from the parametric press model), GTS_PDFXVersion in Info and XMP, `pdf:Trapped` in XMP as in Info, RGB images without a profile tagged sRGB, no image interpolation (none in PDF/A either), and built-in PDF/X-4 checks reported as warnings. qpdf finds no errors in the result.+ - EPS place: placed at its (high-resolution) bounding box and shown, printed and exported through its TIFF preview, or a placeholder when it has none. PostScript itself isn't interpreted.+ - Preferences: Dictionary (user dictionary; `spelling.setWords/words`), Spelling (Dynamic Spelling: red squiggles on the canvas, also Edit ▸ Spelling), Autocorrect (word list, applied as you type), Notes, Track Changes, Story Editor Display and File Handling (recovery interval) sections.+ - Colour management exposed: Edit ▸ Color Settings (`color.settings`: RGB/CMYK working spaces, intent, black-point compensation; `color.loadProfile` for ICC files; `color.convert` through the working spaces, with gamut checks) and View ▸ Proof Setup / Proof Colors (press, sRGB, legacy Mac RGB, colour-blindness simulations, simulate paper) on the canvas.+ - Keyboard: Tab / Shift+Tab hide and show all panels / all but Tools (`window.hidePanels`, `window.hidePanelsExceptTools`); Cmd+F6 / Cmd+Shift+F6 cycle documents; panel fields are reached with Tab and Escape returns to the layout.+ - Smart guides and snapping (View ▸ Snap to Guides / Snap to Document Grid / Smart Guides, `view.snapPreferences` and Preferences ▸ Guides & Pasteboard): moving, drawing, resizing, rotating and pen/anchor drags snap in order to the document and baseline grids, ruler guides, margins and columns, other objects' edges and centres (parent-page items too, by visible stroked bounds), equal spacing, matching dimensions and matching rotation, with guides, gap marks and measurements drawn on the canvas. Shift and Cmd constrain the gesture.+ - View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.+ - Vertical type (Vertical Type Tool, Type ▸ Story Direction `type.storyDirection`, IDML StoryOrientation): the direction belongs to the story, so every frame of a thread is vertical or horizontal together and a frame threaded onto a story takes its direction (`object.textFrameOptions {vertical}` sets the frames' stories); lines run top to bottom and follow each other right to left; the arrow keys follow them (Down and Up along the line, Left and Right to the next and previous line, keeping the position along it); CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text); Korean breaks at spaces, word by word (Hangul in any language, hanja in Korean text), or between syllables when the paragraph asks for it (`type.para {koreanCharBreaks}`, Paragraph Style Options ▸ Justification; not written to IDML). Upright text is shaped top to bottom: punctuation and brackets take their vertical forms (OpenType `vert`; `vkrn` and `vpal` through OpenType features), glyphs advance by their vertical metrics (`vmtx`) and hang from their vertical origins (`VORG`) on the centre of the ideographic em box (`BASE`, else OS/2), which the first line's ascent follows; turned text keeps its horizontal forms. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML RubyString; group ruby spread 1-2-1 or centred) and kenten emphasis dots (`type.kenten`, IDML KentenKind) are set over their text — to its right in vertical frames — without changing line breaks. Warichu and ruby options (per-character ruby, positions, overhang) aren't there yet.+ - Math expressions (Type ▸ Insert Math Expression…, `math.insert`, `math.svg`): a LaTeX subset (fractions, scripts, roots, big operators with limits, Greek, relations and operators with math spacing, `\left…\right`, `\text`) typeset by our own engine into SVG, placed inline at the cursor or as a frame; the LaTeX is kept as alt text and can be edited.+ - Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; in exported PDFs such graphics go out as 300 ppi images of their visible layers.+ - Effects: Inner Glow (edge or centre), Bevel and Emboss (inner bevel lit from the light angle), Satin (`object.innerGlow`, `object.bevel`, `object.satin`); PDF export now keeps soft effects: objects with shadows, glows, feathers, bevels or satin go out as 300 ppi transparent images of their appearance (threaded text frames excepted).+ - Directional Feather (`object.directionalFeather {widths: [top, left, bottom, right]}`): each side fades over its own width.+ - View ▸ Flattener Preview (`view.flattenerPreview`): objects involving transparency highlighted in red; knockout groups export as images (PDF output has no knockout groups).+ - Live captions (`object.caption {live: true}`, Object ▸ Captions ▸ Generate Live Caption): the caption text is re-filled from the source object's metadata after every edit (same undo step).+ - Style Export Tagging (`style.exportTag`, Paragraph Style Options ▸ Export Tagging): paragraph and character styles choose their HTML element and class in EPUB/HTML.+ - Tagged Text: export (`file.exportText {format: "tagged"}`) and place (detected by its header; ASCII, UTF-8 or UTF-16) with paragraph and character styles, font, typeface and size, and `<0x…>` characters.+ - Tagged PDF: one structure element per paragraph (H1–H6 and BlockQuote from Export Tagging, else P) in reading order, frame fills, strokes, rules and tables as artifacts, figures with alt text.+ - EPUB: cover image from the first page (`file.exportEpub {cover}`), and Fixed Layout export (`file.exportFixedEpub`, File ▸ Export EPUB (Fixed Layout)…): pre-paginated pages as 144 ppi images with their text kept for search and read-aloud.+ - Interactive PDF options (`file.exportPdf {fullScreen, bookmarksPanel, pageLayout, view, advanceSeconds}`, File ▸ Export PDF (Interactive)…): page mode, layout, opening view and page timing in the catalog and pages.+ - Object Export Options (`object.exportOptions`): tagged-PDF artifact, EPUB/HTML rasterize (the object as an image), alignment and page break before, alt text.+ - Scripts panel (Window ▸ Utilities ▸ Scripts, `script.run`): saved command scripts (with `$N.path` references to earlier results) run as one undo step; edit, add, load and delete them in the panel. Scripts use DesignCraft's command language, not ExtendScript.+ - Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).+ - Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.+ - Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.+ - View › Overprint Preview (⌥⇧⌘Y): overprinting fills, strokes and 100% [Black] text mix with what's beneath on screen.+ - Type on a Path (⇧T tool, `type.onPath`): a story along any line, curve or shape on screen and in PDF; Type on a Path Options (start, flip, baseline/ascender/descender/centre) and Delete Type from Path. Round-trips through IDML as TextPath; on-path caret drawing is still to come.+ - Preferences › Appearance of Black: 100% K on screen accurately (dark grey) or as rich black (`window.richBlack`); the printing/export side is still to come.+ - Spreads of up to 10 pages: Add to Previous Spread and Allow Spread to Shuffle (Pages panel; `layout.pages.toSpread`, `layout.spreadShuffle`); inserted pages go around kept spreads.+ - Page tool (⇧P) and `layout.pageSize`: pages of their own size (or a preset); the spine stays put and objects keep their place on their page.+ - File › Print (⌘P): printer, copies, page range, spreads, marks, bleed; printed as PDF through the system spooler (`file.print`, `file.printers`, `dryRun` for agents). Shortcuts now act like choosing the menu item (dialogs open), and UI commands win shortcut ties (⌘N opens New Document).+ - Nested styles (through/up to N sentences, words, characters, letters, digits, tabs, breaks, spaces or given characters) and GREP styles (regex → character style), edited in Paragraph Style Options and composed under local formatting; `ui.dialog.open` for agents. Nested line styles are still to come; nested and GREP styles round-trip through IDML.+ - Table and cell styles (round-trip through IDML): cell styles (fill, insets, vertical justification, strokes, paragraph style) and table styles (region cell styles, border, alternating rows, spacing); apply from the Table panel, edits re-apply to every user; `style.cell.*`, `style.table.*`.+ - Style groups: paragraph and character styles shown in group folders, Move to Group (new, existing, none); `style.group` renames every use (styles, stories, table cells, footnotes, object styles).+ - Scrubby zoom: drag the Zoom tool left or right to zoom continuously around the press point.+ - Guides belong to the active layer: hidden with it (or with its Show Guides off) and locked with it.+ - Pencil tool (N): freehand strokes simplified to smooth paths (Alt closes); Smooth and Erase tools re-fit or remove the stretch you drag along (`path.smooth`, `path.erase`).+ - Edit › Keyboard Shortcuts: every command, click and press the new keys, conflicts shown, per-command and global reset; `window.setShortcut`.+ - Primary Text Frame (New Document) and Smart Text Reflow: pages are added while the primary story oversets and empty ones at the end removed, in the same undo step (Preferences › Type).+ - Glyphs panel: every character of any font (rendered by our renderer), search by character or U+code, click to insert, recently used.+ - UI scaling (Preferences › Interface, 50–200%; `window.uiScale`); the window title steps aside when the bar is crowded.+ - Underline / Strikethrough Options: weight, offset, colour and tint (Character panel; screen, PDF and IDML).+ - Relink to Folder and Relink File Extension (`links.relinkFolder`; missing links found by name).+ - File › Package (⌥⇧⌘P): the document relinked to a Links folder, the placed files, the font files that draw its text in a Document Fonts folder (the fonts it names and any fallback fonts that draw characters those lack; except fonts whose licence restricts it, OS/2 `fsType`), an IDML copy, an optional PDF and a report (fonts, fallback fonts, links, preflight, instructions); Copy Links To (`links.copyTo`).+ - Document fonts: opening a `.designcraft` or `.idml` file loads the fonts in the `Document Fonts` folder beside it (as Package writes it), ahead of installed fonts with the same name, so a packaged document opens with its fonts on another machine. Damaged, oversized (over 256 MB per file, 512 MB in all) and surplus (over 200) font files are skipped and listed in `file.open`'s `warnings`; `font.list` gives each font's `source`. Document fonts belong to their document, as in InDesign: other open documents don't see them (each document with a same-named font draws with its own), and closing the document (or reverting it, or a book chapter's export ending) makes them unavailable. Their files stay in memory until DesignCraft quits, so reopening a document doesn't read or load them again; on the web there is no folder to read.+ - Load Swatches / Save Swatches for Exchange (.ase: CMYK, RGB, Lab, Gray; spot or process) from the Swatches panel menu; `swatch.load` / `swatch.save`.+ - Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); `object.pathfinder`.+ - Make / Release Compound Path (⌘8; nested paths become holes), Create Outlines (⇧⌘O; one path per text colour), Scissors tool (C) with `path.split`.+ - Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character).+ - Floating panels: tear a panel off the dock (its float button, or drag its header away) into a movable, resizable window; Dock puts it back; positions persist; `window.floatPanel` / `window.dockPanel`.+ - Place SVG (vector in PDF export via krilla-svg, resvg on screen, text in the bundled fonts), Photoshop (.psd/.psb composite in its colour mode — Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK, Lab, 8/16-bit — with merged transparency; extra alpha and spot channels don't change the image), BMP, and Illustrator files saved with PDF compatibility (.ai). New `designcraft-images` crate (L2) for sniffing, sizes and decoding. EPS is still missing.+ - View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough).+ - OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.+ - Add Anchor Point (=), Delete Anchor Point (-) and Convert Direction Point (⇧C) tools (click toggles smooth/corner, drag pulls out handles), with `path.addAnchor`, `path.deleteAnchor`, `path.convertAnchor`.+ - Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel sets type, angle, reverse and edits stops on a ramp (drag, add, drag off to remove, location, colour). Edited gradients are unnamed swatches; `object.gradient`; the vector round-trips through IDML.+ - Document Setup (⌥⌘P): intent, number of pages, start page # (an even start begins with a left page), facing pages, size presets and orientation, bleed and slug per edge; `layout.documentSetup {}` reports the setup.+ - Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots.+ - Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands.+ - Parent item overrides: Cmd+Shift-click a parent item on a page (or Override All Parent Page Items, ⌥⇧⌘L) makes an editable local copy that hides the parent's; Remove All Local Overrides and Detach All Objects from Parent in the Pages panel menu.+ - Place PDF: placed PDF pages are sized by their crop box, drawn on screen through hayro (with mip levels) and embedded in exported PDFs as vector form XObjects (krilla), `<PDF>` in IDML.+ - Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation.+ - Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page.+ - Soft effects: blurred drop shadow, inner shadow, outer glow, basic feather.+ - ~200 commands, all reachable through the JSON control channel; headless CLI rendering to PNG.+ - MCP server (`designcraft-cli mcp [--connect PORT]`, docs/mcp.md): headless engine or the running app; commands, batch, document/story inspection, page renders as images, window screenshots, pointer/keyboard/dialog input.+ - Web build (`apps/designcraft-web`, trunk): the same UI on WebGPU with a WebGL2 fallback; open/place via the browser file picker or drag-and-drop, save/export as downloads.++ **Next (in order):** books · New Window / split view · Ink Manager and Separations Preview · XML structure, tags and export · buttons and forms · PDF/X-4 output intent (needs krilla support) · EPS place.++ ## How far from full parity (estimate, 2026-10-04)++ **Breadth: ~99% weighted** (P0 core 99%, P1 100%, P2 97%) over the 275 features of the InDesign catalogue, scored+ row by row in [docs/parity.md](docs/parity.md) (`cargo xtask parity` recomputes it). Many features scored done still+ lack some of InDesign's options or dialog details, so **overall parity including depth is about 83%**.++ **Remaining work: about 170 wall-clock hours of a single Claude Opus 5.5 agent** (±30%), or roughly 60–85 hours with+ four agents in parallel on separate crates:++ | Work | Estimate |+ |---|---|+ | Open P0 (2: PDF/X-4 validation against a certified checker, PostScript interpretation for EPS) | 8 h |+ | Open P1 (none partial) | 0 h |+ | Open P2 (3 partial: localization breadth, INDD pages (not readable clean-room), in-app media playback) | 14 h |+ | Depth and pixel fidelity of every dialog, panel and menu against InDesign 2026 | 90 h |+ | Performance (incremental composition, GPU raster) and interchange hardening (IDML/PDF corpus) | 55 h |++ Basis: since the first estimate this effort landed about 45 arcs (from parent overrides, Preferences, Stroke panel,+ gradients and Pathfinder to table/cell styles, nested/GREP styles and Print) in roughly 14 hours on a heavily loaded+ machine — about 1–2 hours per catalogue row.++ ## Agents: CLI and MCP++ Every command is reachable from `designcraft-cli` (`run`, `script` with `$N.path` result references, `app` for the+ running window, `describe`, `commands`), from MCP (`designcraft-cli mcp`, tools including `execute` and `batch` with the+ same references), and from the app's JSON control channel. See [docs/agents.md](docs/agents.md).++ ## 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 2026DesignCraft aims at full Adobe InDesign parity, and to be better: faster, open (documented JSONformat + IDML), scriptable by agents (MCP), and available on the web.@@@ -98,7 -315,7 +316,8 @@@ Interface strings translated, of 1,724| Korean | ko | none | 0% || Vietnamese | vi | none | 0% |+Also shipped: Czech (99%), Italian (85%), Ukrainian (83%), Polish (99%).+ Also shipped: Italian (85%), Ukrainian (83%), Georgian (100%).## Upcoming@@@ -126,85 -343,66 +345,141 @@@ list) · [roadmap.md](docs/roadmap.md)## Progress log-- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.-Newest first.+- **2026-10-14** · Threading keeps generated and linked stories, text that refers to a story, local IDs and locked frames intact; a colour chosen at a caret waits for the typing, Swap Fill and Stroke on text keeps each run's colours, control-channel input never reads or writes the system clipboard, and IDML frame preferences given as properties import with bounded column counts (#84). No readiness percentage change.+- **2026-10-14** · The Liquid Layout panel follows InDesign's: Liquid Page Rule with the page number, Content › Auto-Fit, and Object Constraints › Resize with Page and Pin for the selected object on an object-based page; Create Alternate Layout moved to the Layout menu. No readiness percentage change.+- **2026-10-14** · On an object-based page the Page tool shows a selected object's liquid pins and resize locks as InDesign does: a click pins a side to the page edge or locks the width or height, with InDesign's tooltips. No readiness percentage change.+- **2026-10-14** · With the Page tool, the Control panel shows the page as InDesign's does: W/H from a reference point, page-size preset (US Business Card added), orientation, Liquid Page Rule and Show Parent Page Overlay, which draws the parent page's size over a resized page. No readiness percentage change.+- **2026-10-14** · The Page tool works as InDesign's: a click selects a page and shows its handles and liquid page rule; dragging a handle previews the rule and springs back, Alt-drag resizes the page from the opposite edge, Shift keeps proportions, with a W/H readout. No readiness percentage change.+- **2026-10-14** · With the Page tool, a guide dragged from a ruler is a liquid guide (dashed), as in InDesign; guide-based pages stretch the objects it crosses. No readiness percentage change.+- **2026-10-14** · The Pages panel menu follows InDesign's order: Insert Pages…, Move Pages…, Duplicate Spread (and at End of Document), Delete Page (and Delete Spread for a spread of several pages), New Parent…, Apply Parent to Pages, Override All Parent Page Items, Parent Pages, Create Alternate Layout…, Numbering & Section Options…, Allow Selected Spread to Shuffle. No readiness percentage change.+- **2026-10-14** · Pages panel: Alt-drag copies a page that is a spread of its own (one undo step; `layout.pages.duplicateSpread` takes `to`), a page dropped on Create new page is duplicated at the end, Edit page size offers the presets and Custom Page Size…; duplicated pages keep their own size, rule and guides; thumbnails of pages of their own size stay in their rows. No readiness percentage change.+- **2026-10-13** · IDML: an anchored object takes each anchor setting it leaves unset from its object style, the styles that one is based on, then `[None]`; other item attributes read through the same chain. A left-aligned anchored object's X offset reads in the layout's direction. A rotated group's bounds follow its children's outlines instead of the box of their rotated boxes. No readiness percentage change.+- **2026-10-13** · Control-channel clicks and drags validate positive counts and the complete pending-event budget before queuing input (#732). Oversized requests leave pending gestures intact, preventing unbounded click-count allocation. No readiness percentage change.+- **2026-10-13** · Switching between document and parent pages refreshes the canvas immediately, preventing black parent pages and stale document objects when the zoom stays the same. Ordinary edits retain partial repainting. No readiness percentage change.+- **2026-10-13** · Placed PDFs are drawn through pdfcraft's patched hayro crates: calculator functions whose `idiv` divides by zero or overflows, chains of stitching functions a hundred thousand deep, and mesh shadings with points far off the page, ten thousand overlapping triangles or forty thousand patches no longer panic, overflow the stack, run for over a minute or use more than 2 GiB of memory. A page with a `/UserUnit`, and its trim, bleed and art boxes, are sized in points. No readiness percentage change.+- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.+- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.+- **2026-10-13** · Commands refuse parameter keys their params description doesn't name (#776): the control channel, MCP (`-32602`, every `batch` step checked before the first runs) and `designcraft-cli --cmd` answer with an “unknown parameter” error naming the nearest or the accepted keys instead of running with defaults; journals still replay. Descriptions of the table, anchored-object, data-merge and placing commands now name every key they read. No readiness percentage change.+- **2026-10-13** · File ▸ Open Recent lists the documents last opened or saved (newest first, no duplicates; Save a Copy and exports don't count), with Clear Recent Files; the start screen shows the last eight, below the community card, as cards with a picture of the first page: saving puts one in the file (`preview.png`), so the start screen reads it without opening the document. A file that is gone is dimmed and says so when chosen, and stays listed. Preferences ▸ File Handling sets how many are kept (default 20, 0–100). `file.openRecent {index}`, `file.recentFiles`, `file.clearRecent` (#706). No readiness percentage change.+- **2026-10-13** · Dropping an `.ase` file on the window loads its swatches, as Load Swatches does (the drop failed with "Can't Place the File"). No readiness percentage change.+- **2026-10-13** · Text takes gradient swatches: a gradient fill or stroke on characters spans the text frame's box (on a path: the path's), on screen and in PDF. No readiness percentage change.+- **2026-10-13** · Gradient swatches work on strokes: drawn across the path's box on screen and in PDF (they drew nothing), set with `object.gradient {target: stroke}` and in the Gradient panel when the Stroke box is in front; the stroke's gradient vector moves with the shape and round-trips through IDML. No readiness percentage change.+- **2026-10-13** · The Gradient panel follows InDesign's layout (thumbnail, Type, Location, Angle, Reverse, ramp with midpoint diamonds) and takes swatches dragged from the Swatches panel: dropped on a stop they colour it, elsewhere they add a stop. Stops keep their CMYK through panel edits; `object.gradient` stops accept a `swatch`. No readiness percentage change.+- **2026-10-13** · New Swatch works as InDesign's: a gradient made in the Gradient panel becomes "New Gradient Swatch" (still applied), an unnamed colour a listed swatch, a named swatch a "copy" (`swatch.new`); `swatch.create {gradient}` makes a gradient swatch from colour swatches. No readiness percentage change.+- **2026-10-13** · Radial gradients stretch with the object's box, as InDesign draws them: by default an ellipse reaching the frame's sides (it was a circle reaching only the longer side), and a Gradient Swatch tool drag keeps the box's proportions; on screen and in PDF. No readiness percentage change.+- **2026-10-13** · Inner Glow takes a blend mode (Screen by default) and a Technique (Softer or Precise); Basic Feather takes Choke and Corners (Sharp, Rounded, Diffused), in the Effects dialog and `object.effects`. Inner glow and bevel blend modes now mix with the object below them instead of an empty layer. Noise isn't drawn. No readiness percentage change.+- **2026-10-13** · Text Frame Options is laid out as InDesign's: General (Columns: Fixed Number or Fixed Width with Number, Width and Gutter; Balance Columns; Inset Spacing with the link button; Vertical Justification; Ignore Text Wrap), Baseline Options (First Baseline Offset and Min) and Column Rules. `object.textFrameOptions` takes `columnWidth` and `firstBaselineMin`. No readiness percentage change.+- **2026-10-13** · The Window menu follows InDesign's order (Arrange, Workspace, then the panels alphabetically with Color, Editorial, Object & Layout, Styles… submenus), and Window › Workspace lists the workspaces as InDesign does, now with Essentials Classic: the Control panel and an icon column of named panel groups. No readiness percentage change.+- **2026-10-13** · `.indd` and `.indt` documents open through File › Open, drop, the web inbox, `file.open`, `file.openBytes`, `file.openIdml` and the CLI: [storytold/indd-utils](https://github.com/storytold/indd-utils) converts them to IDML in memory and the IDML importer reads the result, on desktop and web. Converter warnings come first in the open result; an unreadable file is an open error (#21, #114). No readiness percentage change until a real-file corpus measures it.+- **2026-10-13** · macOS: a command chosen with the mouse in the menu bar runs at once. It used to wait for the next mouse move or key press over the window, so File › Open, Place and Save As seemed to take 10–20 seconds to open their dialogs. No readiness percentage change.+- **2026-10-13** · An explicit recovery folder (`file.recovery.save` with `dir`) never overwrites or deletes another running app's checkpoints. Document uids start at 1 in every process, so two apps saving recovery to one chosen folder replaced or removed each other's `<uid>.designcraft`. A run replaces or removes only the entries it wrote or recovered there, refuses an occupied uid, and refuses a folder whose run lock another app holds. No readiness percentage change.+- **2026-10-13** · PDF export leaves out form fields, buttons and video or sound that don't print: inside a hidden group, on a hidden or non-printing layer, or marked non-printing. Page content and interactive elements follow one inclusion rule. No readiness percentage change.+- **2026-10-13** · IDML export keeps parent item overrides: each page lists its overridden parent items and the local copy keeps its link to the parent item, so a reopened IDML file shows only the local copy (#725). No readiness percentage change.+- **2026-10-13** · Reflowable EPUB and HTML export include tables (header and footer rows, merged cells), footnotes (a linked note after the paragraph that refers to it) and endnotes (a linked section at the end of the book). No readiness percentage change.+- **2026-10-13** · Word import: table cells read text by the same rules as body text, so deleted text, moved-away text and field codes stay out (#721). Word's Normal comes in as its own paragraph style "Normal" over the document defaults, so text formatted only by Normal keeps its look; it conflicts only with a document's own Normal, and the style map can send it to [Basic Paragraph] (#722). No readiness percentage change.+- **2026-10-13** · Text recomposes when the document baseline grid changes, when a layer holding a text-wrap object is shown or hidden, or when a section's start number, numbering style, prefix or marker changes; the composition cache keyed only on the section count and item identities and kept the old layout. No readiness percentage change.+- **2026-10-13** · Path edits (`path.setAnchor`, `path.moveAnchors`, `path.appendAnchor`, `path.reverse`, `path.close`, anchor add/delete/convert, Erase, Smooth and Scissors) refuse a path that is locked, sits in a locked group or on a locked layer (#735). Properties links to the Stroke, Character, Paragraph, Effects, Text Wrap and Info panels open them in a customized panel layout too (#736). No readiness percentage change.+- **2026-10-13** · The Story Editor stays with the document its story belongs to: it hides while another document is active and closes with its document, so its edits never reach another document's story with the same id (#729). Undo restores the selection from before the command and Redo the one after it (#716). No readiness percentage change.+- **2026-10-13** · Saving never reports success without a file: a document that can't be written is an error from Save, Save As, Save a Copy, Package, snippet export and the web serializer, leaving the existing file, the unsaved state and the recovery checkpoint as they were. Placed files over 4 GiB are written with zip64 sizes. A web Save whose browser download can't start reports the error and keeps the document unsaved (#741, #708). No readiness percentage change.+- **2026-10-13** · Colour management runs on craft-libs' `craft-cms`. The default CMYK working space is its Coated FOGRA39 profile (Generic CMYK and Device CMYK stay selectable); CMYK swatches show relative colorimetric with the settings' black point compensation, and PDF/X-4 output intents embed the working CMYK profile (FOGRA39 by default). Profile names the built-in stands in for resolve to it; other unknown names are an error, and saved settings naming one start with the default. No readiness percentage change.+- **2026-10-13** · Command scripts look up only a well-formed `$N.path` / `$last.path` reference; other strings starting with `$`, such as a GREP replacement of `$1` and a nonbreaking space, stay as written, and `$$` writes a literal `$` (#749). No readiness percentage change.+- **2026-10-13** · Dialogs and the About window move when you drag their title row, so the page behind them can be seen. A dragged dialog may go partly off-screen, but its title row stays reachable; each dialog opens centred, and again after the window is resized. No readiness percentage change.+- **2026-10-12** · Placed Excel tables and Excel data-merge records keep numeric precision, including small values, and preserve numeric-looking cached formula strings as text. No readiness percentage change.+- **2026-10-13** · Links rows show their source paths; selecting a link shows its full path wrapped inside the panel, so same-named files from different folders can be distinguished. No readiness percentage change.+- **2026-10-13** · HTML and reflowable EPUB order grouped stories and graphics by their transformed spread position, including nested groups and rotated frames. Explicit Article order is unchanged. No readiness percentage change.+- **2026-10-13** · A selected placed graphic shows its own brown bounding box with handles: dragging one resizes the graphic inside its frame (Shift keeps proportions, Alt from the centre) and leaves the frame as it is; `transform.set` takes the graphic's new spread `bounds`. Builds on #415 and #550. No readiness percentage change.+- **2026-10-13** · Create Outlines makes one compound path per line (and per text colour within a line), grouped, as InDesign does: Ungroup then leaves each line on its own to be spaced and made into one compound path again. A single line in one colour stays a single compound path. No readiness percentage change.+- **2026-10-13** · Ungroup only takes groups apart: a frame with pasted-in content stays whole (and selected), is named by its shape in the Layers and Properties panels, and offers Convert Shape rather than Ungroup. Non-groups stay selected. No readiness percentage change.+- **2026-10-13** · Copy with a placed graphic selected (Direct Selection) copies just the graphic, uncropped, where it sits on the page and without the frame's stroke, so Paste Into puts the whole image in place; Cut and Delete then remove only the graphic and leave its frame empty. Nested selections copy in their spread coordinates. No readiness percentage change.+- **2026-10-13** · Object effects (Basic Feather, Inner Glow, shadows, glows, bevel, satin, directional and gradient feathers) apply to frames with pasted-in content, on screen and in image exports: the frame, its clipped content and its stroke are one object to the effect. PDF export still has no soft effects for any object. No readiness percentage change.+- **2026-10-13** · Backspace between two consecutive tables, pasting a table next to a table anchor, and pasting several paragraphs right before one keep every table on its own anchor paragraph. Previously a table was dropped or left without its anchor, and the saved file failed to reopen. No readiness percentage change.+- **2026-10-12** · The engine's atomic writer, used by saves and exports (documents, snippets, books, libraries, swatches, XML, interchange, MCP, desktop and CLI writes), delegates to craft-libs/craft-atomic. Failed writes retain the original; new files follow the umask and replaced files keep their permissions. Recovery checkpoints and package output keep their own no-follow writers. No readiness percentage change.+- **2026-10-13** · New Document has Preview (off by default, kept for the session): a document with the window's settings shows in the workspace and follows them once typing pauses. Create keeps it with a clean undo history and refuses invalid fields; Close removes it and shows the previous document again. The preview takes no Untitled number and writes no recovery data; one edited by a menu or script stays open as a document. No readiness percentage change.+- **2026-10-13** · Object styles carry effects (drop shadow, feather, inner and outer shadows and glows, bevel, satin, gradient and directional feather). New styles from a selection keep its effects, `style.object.edit` changes a style's effects and every item that follows them, `style.object.clearOverrides` returns items to their style, and new frames take their default style's effects. IDML carries only the drop shadow and feather, for ObjectStyles (with their effects category and BasedOn chain) as for items (#653). No readiness percentage change.+- **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change.+- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.+- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.+- **2026-10-12** · Linked text files (#597): placed Word, RTF and text files can stay linked; the Links panel shows them OK / Modified / Missing, and Update imports the file again into the same frames with the saved style map (the Links panel asks before replacing edits made in the layout). No readiness percentage change.+- **2026-10-12** · Text in oval, polygon and other non-rectangular text frames follows the frame's outline: each line is set in the part of its band inside the shape, one inset away from the outline, in every column and in vertical frames; text wrap still applies on top (#646). No readiness percentage change.+- **2026-10-12** · Colour entry: the Color Picker's hex, R/G/B and C/M/Y/K fields and the Color panel's number fields keep typed text until it is complete; panel and picker values are applied on a fixed scale (`{model, …}` colours in 0..1), so M 1 is 1 %. Picking keeps a CMYK colour CMYK; dialogs leave the page behind them undimmed; colours that round to the same swatch name share one swatch (#323). No readiness percentage change.+- **2026-10-12** · Placed photos show in their own colours: embedded ICC profiles (Adobe RGB, ProPhoto, P3, grey) are converted to sRGB on screen, and CMYK JPEGs (including YCCK), CMYK TIFFs and CMYK PSDs go through their embedded CMYK profile or the working CMYK space with the colour settings' intent and black-point compensation, instead of the profile-free formula. Unreadable profiles are ignored. No readiness percentage change.+- **2026-10-12** · Placed Word documents keep their bullets and numbering (#626): `numbering.xml` levels become bullet or numbered paragraphs with Word's number formats, label text, start numbers, restarts and list indents, also when a paragraph style carries the list. No readiness percentage change.+- **2026-10-12** · Text strokes can sit behind the fill: the stroke lies wholly outside the letters at its full weight on screen, in PNG and in PDF, set from the Properties panel or Character Style Options. IDML `StrokeAlignment` on text imports and exports as this setting, so imported text with outside-aligned strokes keeps its letter shapes (#619). No readiness percentage change.+- **2026-10-12** · Type tool: Option/Alt+Left/Right kerns the pair at the caret (manual kerning) or tracks a selection by the Kerning/Tracking increment (Preferences › Units & Increments, 20/1000 em), five times with Cmd/Ctrl; moving by words is Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere, and Option/Alt+Shift+Left/Right still selects by words (#621). No readiness percentage change.+- **2026-10-12** · Autoflow on Place threads one frame per page column (right to left in a right-to-left story), so text no longer runs across the gutter; pages Smart Text Reflow adds get a primary frame with the page's columns (#625). No readiness percentage change.+- **2026-10-12** · Vector art copied in Illustrator, VectorCraft, Figma or Inkscape pastes as editable paths, as InDesign pastes Illustrator art: the SVG those apps put on the clipboard becomes paths with their fills, strokes (weight, caps, joins, dashes) and opacity, groups stay groups and text comes in as outlines, centred in the view (`edit.pasteSvg`, `ui.paste`). Edit › Paste reads the system clipboard when nothing was copied in DesignCraft. No readiness percentage change.+- **2026-10-12** · Pages panel: double-clicking a parent shows that parent and selects only its row; parent rows show rendered thumbnails. Commands name parents by id, full name, or a prefix only one parent has; an unknown or ambiguous name is an error instead of clearing the page's parent (#624). No readiness percentage change.+- **2026-10-12** · With the Type tool, dragging a table's column or row border resizes it (the double-arrow cursor shows over a border): later columns and rows move along, Shift keeps the table size, and Shift on the right or bottom edge scales every column or row. A dragged row becomes At Least; one undo step per drag, Esc cancels; works in rotated frames and turned spreads. Scripts use `table.resizeBorder`. No readiness percentage change.+- **2026-10-12** · The Tools panel's Fill/Stroke keys work: D (default fill and stroke), X (fill or stroke in front), Shift+X (swap per object, tints included) and / (Apply None), as `color.*` commands; swap and default are one undo step (`object.swapFillStroke`, `object.defaultFillStroke`); the Color panel follows the proxy's fill/stroke choice. No readiness percentage change.+- **2026-10-12** · With a placed graphic selected (Direct Selection), the Transform values act on the graphic inside its frame, as in InDesign: a tilted frame's image can be straightened to 0°. No readiness percentage change.+- **2026-10-11** · Font menu laid out like InDesign's: filters (classification, favourites,+ recently added), families opening to their styles, the selected text as the sample in three+ sizes, Recently Used fonts, Show Similar Fonts and each font's format.+- **2026-10-12** · The Effects panel shows the level its settings apply to ("Group: Color Dodge 100%") and, as in InDesign, Isolate Blending and Knockout Group for a selected group. No readiness percentage change.+- **2026-10-12** · Edit › Step and Repeat has its InDesign dialog: Repeat (Count, or Rows and Columns with Create as a grid), Offset (Vertical, Horizontal, in ruler units) and Preview, which shows the copies while the dialog is open; Cancel takes them away and OK makes them as one undo step. No readiness percentage change.+- **2026-10-12** · Load Styles: the Paragraph Styles and Character Styles panels load styles from another DesignCraft document or an IDML file, with the styles, swatches and lists they name; a dialog picks the styles and what happens to one the document defines differently (`style.load`). No readiness percentage change.+- **2026-10-12** · On screen, blend modes blend with the objects below and not with the paper, as in InDesign and in PDF export: a Color Dodge or Screen object over blank paper shows as it is. No readiness percentage change.+ - **2026-10-15** · Define Lists… is listed under Type › Bulleted & Numbered Lists in command search and Edit › Menus, matching the menu, and the parity doc no longer lists a Type › Paragraph Rules… menu item that does not exist. No readiness percentage change.+ - **2026-10-15** · Pressing Enter in the Layers panel's rename field without typing leaves an unnamed object unnamed, so it keeps following its automatic label instead of taking it as a fixed name. No readiness percentage change.+ - **2026-10-15** · Apply Gradient (.) with the Stroke box in front puts a new default gradient on the stroke in one undo step and leaves the fill's swatch and tint as they were. No readiness percentage change.+ - **2026-10-15** · In a facing-pages document, two odd-numbered pages in a row after a section restart (page 2 starting at 1) each get their own spread and stay right pages, instead of sharing a spread with an odd page on the left. No readiness percentage change.+ - **2026-10-15** · Character formatting set at a caret on a blank line (an empty paragraph) applies to the line's paragraph mark and to the text typed there, also after the caret has left the line and come back; typed text used to take the previous paragraph's format. No readiness percentage change.+ - **2026-10-15** · Very wide effects stay sharp at high zoom: a wide Basic Feather draws the object itself at full resolution, with only the soft mask at a reduced one, and wide inner shadows, inner glows, satin and bevels are clipped to the shape at full resolution, so they no longer blur the object or bleed past its edge. No readiness percentage change.+ - **2026-10-15** · The Typography panel controls every OpenType feature a character format carries: Other Features lists Proportional Metrics, Horizontal Kana, Localized Forms, Mark Positioning, Justification Alternates and Roman Italics. Lining, Oldstyle, Tabular or Proportional chosen alone also sets the other figure axis, so IDML export keeps the figure style instead of writing Default. Standard Ligatures follows and sets Character › Ligatures. No readiness percentage change.+ - **2026-10-15** · Join Path and Convert Point leave a path on a locked layer or inside a locked group unchanged, as the other path edits do. No readiness percentage change.+ - **2026-10-15** · A kerning value chosen in the Character panel or Properties at a caret kerns the pair at the caret (the character before it takes the value, in one undo step), and the field shows that pair's kerning; at the start of a story or paragraph it is kept for the next typing, and a selection is kerned as before (`type.kernPair`). No readiness percentage change.+ - **2026-10-15** · Japanese, Chinese and Korean input methods type into stories with the Type tool: the marked text shows in place, underlined (the clause being converted twice), with the candidate window at the caret, and the commit is one undo step. Keys, shortcuts, the clipboard and Undo wait while the input method composes; a click, a tool switch or another command keeps the marked text as typed. Not yet checked by hand with a system input method. No readiness percentage change.+ - **2026-10-15** · IDML placed PDFs keep their page and Crop to box (`PDFAttribute` `PageNumber` and `PDFCrop`, written for every placed PDF); two crops of one PDF page stay two assets; a page the PDF lacks is left out of PDF export with a warning instead of failing it; `$ID/` font names resolve; the IDML in a package links the images in its Links folder without embedding them. No readiness percentage change.+ - **2026-10-15** · The CJK leading model and character alignment take effect only in paragraphs set with a Japanese composer (`HL Composer J`, `HL Single J`), which IDML import and export keep: Western and Arabic paragraphs set baseline to baseline on the Roman baseline, a paragraph switched to a Japanese composer gets the file's Aki Below spacing, and under Aki Below a line's leading is the space below it. No readiness percentage change.+ - **2026-10-15** · Document pages follow their parent page's margins and columns unless margins were set on the page itself (`Page::local_margins`): applying a different parent gives a page that parent's margins, a page that changes side after an insert takes the other parent page's, and a page given margins equal to its parent's keeps them when the parent changes. IDML import and older files mark pages whose margins differ from their parent as their own. No readiness percentage change.+ - **2026-10-15** · Start-up picks the GPU that drives the display (or the kind `WGPU_POWER_PREF` or the adapter `WGPU_ADAPTER_NAME` names), and when a start-up fails or hangs it restarts on the next adapter, then the next backend, then a software renderer, keeping recovered documents; start-up errors are logged to standard error and the log file (#273, #334). No readiness percentage change.+ - **2026-10-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 loadthe text cursor, then click a frame to thread it, click empty space for a column-wide frame ordrag one (it snaps like frame drawing); Shift-click autoflows, Alt-click stays loaded on the@@@ -212,19 -410,24 +487,35 @@@`text.thread`, `text.unthread`, `text.removeFromThread` with undo; locked frames and layersrefuse threads. The alpha gate now waits only on the Primary Text Frame page fixes (#165). Noreadiness percentage change.+- **2026-10-12** · Properties › Transform shows rotation, shear and X/Y scale, and Rotate 90° and Flip Horizontal/Vertical buttons, as InDesign's does. No readiness percentage change.+- **2026-10-12** · Underlines and strikethroughs are drawn as one bar per stretch of text on screen, as in PDF export: a bar per letter left faint seams between the letters. No readiness percentage change.+- **2026-10-12** · The section marker character shows its section's marker text on document pages (nothing when the section has none) instead of the word "Section", which stays on parent pages; editing the marker recomposes (#556). No readiness percentage change.+- **2026-10-12** · IDML import keeps a font family name exactly as written, trailing spaces included, and font lookup falls back to the name without surrounding spaces; `FontStyle="Nothing"` leaves the style to the paragraph (#558). No readiness percentage change.+- **2026-10-12** · Clipping paths saved with images in IDML (Detect Edges, Alpha Channel, Photoshop Path, User-Modified Path, inverted or not) clip the image on screen and in PDF and survive IDML export; `object.clippingPathOptions` reports, inverts or removes one (#450). No readiness percentage change.+- **2026-10-12** · Anchored objects with text wrap push text aside: other stories' text under them and the lines of their own story after the anchor's line (#557). No readiness percentage change.+- **2026-10-12** · Hyphenation Zone applies to the Single-line Composer only, as in InDesign. With the default Paragraph Composer, ragged text hyphenates where InDesign does (aper-natem), giving the same line breaks. No readiness percentage change.+- **2026-10-12** · Text frame auto-size: Height Only, Width Only, Height and Width (also keeping proportions) frames grow and shrink to fit their text after edits, around their reference point, with minimum sizes and No Line Breaks, in the same undo step (#180). No readiness percentage change.+- **2026-10-12** · Text Frame Options › Balance Columns (`object.textFrameOptions {balanceColumns}`, IDML `VerticalBalanceColumns`) evens out the columns of the frame a story ends in, from its last column break on; frames the text runs on from fill normally (#609). No readiness percentage change.+- **2026-10-13** · Layout ▸ Table of Contents opens a real dialog: title and title style, Include Paragraph Styles and Other Styles lists with Add and Remove, and per style its entry style, page number position (after, before, none), separator and level. Replace Existing regenerates the current table of contents in place; otherwise OK makes a new frame on the page in view. IDML export writes the definition as a TOC style that import reads back, so Update works after a round trip. No readiness percentage change.+ - **2026-10-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** · Windows: dragging the window across monitors with different display scales keeps its size instead of growing until it crashes (winit pinned to its 0.30.x backport of the fix). The GPU surface may be as large as the adapter's largest texture (16384 px on DirectX 12, Vulkan and Metal hardware) instead of 8192, and a wgpu error is logged instead of closing the app. No readiness percentage change.- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.@@@ -232,48 -439,31 +527,52 @@@- **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-11** · Document chapter numbering (#341): style, automatic, start at, same as previous+ document in the book; Update Numbering resolves it in book order.+- **2026-10-11** · Advanced workspace's object Control panel compacted into aligned two-row+ groups (#255): spinners, fill/stroke chips, proportion links, corners, Auto-Fit, alignment.+- **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** · 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-12** · Double-clicking a frame handle fits the frame to its content as in InDesign (a corner fits both sides, an edge only its own). Object › Fitting › Fit Frame to Content now fits text frames to their text too, growing them for overset text. 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 (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-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-11** · Properties › Appearance's Fill and Stroke menus gain InDesign's Tint field and, for a text frame, Apply To: Frame / Text. 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** · 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:** Type › Justification… (Cmd+Alt+Shift+J, also in the Paragraph panel menu) sets word and letter spacing, glyph scaling and the composer on the selected paragraphs, sharing the Paragraph Style Options section (#531). 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-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-11** · Japanese captions now cover print ranges, imported style handling and table+ row/column movement, including row-height distribution. Existing translation and RTL helpers+ handle the display; command IDs, stored option values and user-defined style names are unchanged.+- **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-11** · Live corners: the yellow widget on a selected rectangle frame shows corner+ diamonds; dragging one rounds the corners, Alt-click steps the corner shape (#186).+- **2026-10-11** · Optical kerning (#181): pairs are spaced from their outlines (ink gap per band,+ pulled towards the font's stem gap, bounded) instead of silently using the font's kern pairs.+- **2026-10-11** · New Document laid out like InDesign's (#325): Recent, Saved, Print, Web and+ Mobile preset tabs beside the preset's details; saved document presets live in the engine+ (`file.savePreset`, `file.deletePreset`, `file.new {preset}`); `file.new` takes intent, units,+ start page and per-edge bleed and slug.+- **2026-10-11** · macOS: fonts that font services and managers activate (Adobe Fonts,+ RightFont) are listed, read from the files CoreText has available (#261, #327).+- **2026-10-11:** Document pages take their parent page's margins and columns (left or right parent page by side) and follow its changes unless they have their own; parent ruler guides draw and snap on the pages based on it. IDML import marks a page margin preference that differs from its parent as the page's own. No readiness percentage change.+- **2026-10-11** · Document Setup laid out like InDesign's: Page Size, Margins (new: every+ page's, `layout.documentSetup {margins}`), Bleed and Slug with links, Adjust Layout.+- **2026-10-11** · IDML reads and writes a spread's view rotation (Rotate Spread) as the+ rotation part of the spread transform (#484).+- **2026-10-11** · The document grid is drawn (View ▸ Grids & Guides ▸ Show/Hide Document Grid,+ ⌘'), on the lines Snap to Document Grid uses, behind or in front of page items (#530).+- **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-11 (DC-1):** Hold Cmd+Space for the Zoom cursor and click/scrubby zoom, with Alt-click to zoom out. Releasing restores the selected tool; text editing and existing tool drags retain their input. Space remains Hand, and navigation changes neither the document nor undo history. 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, CLIsmoke-tested under QEMU).diff --cc apps/designcraft-cli/src/main.rsindex 7c99fbe7d,c4373ffb6..f40bd524e--- a/apps/designcraft-cli/src/main.rs+++ b/apps/designcraft-cli/src/main.rs@@@ -1,9 -1,9 +1,9 @@@//! Headless DesignCraft.//!//! ```text- //! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub|.html|.rtf|.txt] [--all-pages DIR]-//! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub|.pptx] [--pdf-options JSON] [--all-pages DIR]-//! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub] [--all-pages DIR]++//! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub|.pptx|.html|.rtf|.txt] [--all-pages DIR]//! # --page, --scale and --pdf-options apply to the exports that follow them+//! # .rtf and .txt hold the story being edited or of the selected frame//! designcraft-cli commands [FILTER] # list commands (JSON), optionally only ids/labels/menus containing FILTER//! designcraft-cli describe ID # one command: label, menu, shortcut, parameters//! designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]@@@ -66,7 -68,7 +68,7 @@@ with `designcraft-cli describe COMMAND`Options:--in FILE / --sample open a document (.designcraft or .idml) or the sample first--save OUT save as .designcraft after the script succeeds-- --export OUT export after the script succeeds (.pdf, .idml, .epub, .png, .jpg); repeatable++ --export OUT export after the script succeeds (.pdf, .idml, .epub, .pptx, .png, .jpg); repeatable--keep-going run every step, recording failures as {"error": ...} resultsPrints {"completed": n, "results": [...]}, plus failedIndex / failedCommand / error and a@@@ -220,36 -245,6 +245,39 @@@ fn option_after_last_export(args: &[Strunused}+/// What `--export OUT` writes. The extension of `OUT` picks it, in any case.+enum Export {+ /// A page as PNG or JPEG.+ Image,+ Pdf,+ /// The document itself.+ Document,++ /// Editable PowerPoint slides.++ Pptx,+ /// What this command writes to a `path`.+ Command(&'static str),+}++impl Export {+ /// A name with another extension is an error: it used to get a PNG of the page. One with no+ /// extension still does (`--export /dev/stdout`).+ fn of(out: &str) -> Result<Self, String> {+ let ext = std::path::Path::new(out).extension().and_then(|e| e.to_str()).map(str::to_lowercase);+ Ok(match ext.as_deref() {+ None | Some("png" | "jpg" | "jpeg") => Export::Image,+ Some("pdf") => Export::Pdf,+ Some("designcraft") => Export::Document,+ Some("idml") => Export::Command("file.exportIdml"),+ Some("epub") => Export::Command("file.exportEpub"),++ Some("pptx") => Export::Pptx,+ Some("html" | "htm") => Export::Command("file.exportHtml"),+ // The story being edited or of the selected frame.+ Some("rtf" | "txt") => Export::Command("file.exportText"),- Some(_) => return Err(format!("--export {out}: unknown file type (.png, .jpg, .pdf, .designcraft, .idml, .epub, .html, .rtf, .txt)")),++ Some(_) => return Err(format!("--export {out}: unknown file type (.png, .jpg, .pdf, .designcraft, .idml, .epub, .pptx, .html, .rtf, .txt)")),+ })+ }+}+fn run(args: &[String]) -> Result<(), String> {if let Some(opt) = option_after_last_export(args) {return Err(format!(@@@ -302,33 -289,27 +330,41 @@@"--page" => page = val()?.parse().map_err(|_| "bad --page")?,"--scale" => scale = val()?.parse().map_err(|_| "bad --scale")?,"--pdf-options" => {- pdf_opts = serde_json::from_str(&val()?).map_err(|e| format!("--pdf-options: {e}"))?;+ // The export adds its path to them.- if !pdf_opts.is_object() {- return Err("--pdf-options: expected a JSON object".into());- }+ pdf_opts = match serde_json::from_str(&val()?).map_err(|e| format!("--pdf-options: {e}"))? {+ Value::Null => json!({}),+ o @ Value::Object(_) => o,+ _ => return Err("--pdf-options: expected a JSON object".to_string()),+ };}"--export" => {let out = val()?;- if out.ends_with(".epub") {- let r = s.execute("file.exportEpub", &json!({"path": out})).map_err(|e| e.to_string())?;- eprintln!("wrote {out} ({} bytes)", r["bytes"]);- } else if out.ends_with(".pdf") {- let mut p = pdf_opts.clone();- p["path"] = json!(out);- let r = s.execute("file.exportPdf", &p).map_err(|e| e.to_string())?;- eprintln!("wrote {out} ({} pages, {} bytes)", r["pages"], r["bytes"]);- for w in r["warnings"].as_array().into_iter().flatten() {- eprintln!("warning: {}", w.as_str().unwrap_or_default());+ match Export::of(&out)? {+ Export::Image => export(&mut s, &out, page, scale)?,+ Export::Pdf => {+ let mut p = pdf_opts.clone();+ p["path"] = json!(out);+ let r = s.execute("file.exportPdf", &p).map_err(|e| e.to_string())?;+ eprintln!("wrote {out} ({} pages, {} bytes)", r["pages"], r["bytes"]);+ for w in r["warnings"].as_array().into_iter().flatten() {+ eprintln!("warning: {}", w.as_str().unwrap_or_default());+ }+ }+ Export::Document => {+ s.execute("file.saveAs", &json!({"path": out})).map_err(|e| e.to_string())?;+ eprintln!("saved {out}");+ }++ Export::Pptx => {++ let r = s.execute("file.exportPptx", &json!({"path": out})).map_err(|e| e.to_string())?;++ eprintln!("wrote {out} ({} slides, {} bytes)", r["slides"], r["bytes"]);++ for w in r["warnings"].as_array().into_iter().flatten() {++ eprintln!("warning: {}", w.as_str().unwrap_or_default());++ }++ }+ Export::Command(cmd) => {+ let r = s.execute(cmd, &json!({"path": out})).map_err(|e| e.to_string())?;+ eprintln!("wrote {out} ({} bytes)", r["bytes"]);}- } else {- export(&mut s, &out, page, scale)?;}}"--all-pages" => {@@@ -459,16 -453,21 +495,17 @@@ fn script(args: &[String]) -> Result<()if let Some(out) = &save {exec(b, "file.saveAs", json!({"path": out}))?;}- for out in &export {- let lower = out.to_lowercase();+ for (kind, out) in &export {let p = json!({"path": out});- if lower.ends_with(".pdf") {- exec(b, "file.exportPdf", p)?;- } else if lower.ends_with(".idml") {- exec(b, "file.exportIdml", p)?;- } else if lower.ends_with(".epub") {- exec(b, "file.exportEpub", p)?;- } else if lower.ends_with(".pptx") {- exec(b, "file.exportPptx", p)?;- } else {+ match kind {// PNG / JPEG of the first page.- b.call("app.export", p)?;- }+ Export::Image => b.call("app.export", p)?,+ Export::Pdf => exec(b, "file.exportPdf", p)?,+ // A copy: the document in the app stays the file it is (`--save` is Save As).+ Export::Document => exec(b, "file.saveACopy", p)?,++ Export::Pptx => exec(b, "file.exportPptx", p)?,+ Export::Command(cmd) => exec(b, cmd, p)?,+ };}}outln!("{}", serde_json::to_string_pretty(&report.to_json()).unwrap_or_default());diff --cc apps/designcraft/src/main.rsindex 5d29bb9a4,c379d5aaf..287a2866c--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@@ -89,9 -68,6 +90,8 @@@ impl eframe::App for Appif self.app.take_ime_discard() {discard_marked_text();}+ #[cfg(target_os = "macos")]+ mac_window::sync_movable(ui.ctx(), &mut self.movable);- self.startup.leave();}fn on_exit(&mut self) {// A normal exit before the third frame is not a crash.diff --cc contributors/people.tomlindex a8958ec92,4a7e55103..5092f7b39--- a/contributors/people.toml+++ b/contributors/people.toml@@@ -49,7 -43,7 +51,12 @@@ sync_github_name = tru[people.webdevtodayjason]display_name = "Jason Brashear"+[people.switch87]+real_name = "Gert Pellin"+display_name = "Gert Pellin"+sync_github_name = false+++ [people.Nmarello]+ real_name = "Nick Marello"+ display_name = "Nick Marello"+ sync_github_name = falsediff --cc crates/compose/src/lib.rsindex adad658f5,90844842a..d5fa047f5--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -1364,7 -975,14 +1374,12 @@@ fn compose_with_db(doc: &Document, storpi = j;continue 'paras;}+ // An empty last paragraph (the story ends with a return) isn't overset text, as in+ // InDesign: nothing of it is left to show.+ if prange.is_empty() && prange.start >= story.text.len() {+ break 'paras;+ }out.overset_at = Some(glyphs.get(g0).map(|g| g.byte).unwrap_or(prange.start));- // The part of the paragraph that fits keeps its shading and border.- para_box_decos(&mut out, pi, &pp);break 'paras;}let f = &frames[cur.fi];@@@ -1562,23 -1066,11 +1577,23 @@@// Footnotes referenced on this line need room at the bottom of the column too// (a line at the top of a column is set anyway).let line_notes = if notes.active() { notes.refs_in(line_glyphs) } else { Vec::new() };- let col_w = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)].width();+ let col_w = notes.area(&cols[cur.fi], cur.col).map_or(0.0, |r| r.width());let reserve = notes.reserve(doc, cur.fi, cur.col, &line_notes, col_w, f, opts);let reserve = if cur.last_baseline.is_none() { notes.reserve(doc, cur.fi, cur.col, &[], col_w, f, opts) } else { reserve };- // As in InDesign, a line is set when its baseline fits: its descenders may hang below the frame.- let fits = baseline <= col.y1 - reserve + 0.01 && !capped;+ // A horizontal text frame's bottom inset limits the last baseline, not+ // the font's descender box. Descenders remain in the line metrics and may+ // hang below that edge. Paths, vertical text, inline objects and text above+ // reserved footnotes keep the full extent to prevent collisions.+ let fit_descent = if f.opts.path.is_some()+ || f.vertical+ || reserve > 0.0+ || line_glyphs.iter().any(|g| sub_objects.get(&g.byte).is_some_and(|o| !o.custom))+ {+ desc+ } else {+ 0.0+ };+ let fits = baseline + fit_descent <= col.y1 - reserve + 0.01 && !capped;if !fits {if cur.can_next_sub() {g0 = s;diff --cc crates/compose/src/tests.rsindex ac6377f8d,affa3f86e..d6344f521--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -146,75 -146,6 +146,94 @@@ fn wrap_pushes_text_aside()assert!(below.x0 < 1.0);}+/// A small frame holding one character (a tombstone at the end of an article: a 7.6 pt symbol in+/// a 10.5 pt box), in a paragraph whose style is 14 pt, with a text-wrap object on the spread at+/// `wrap`.+fn tombstone(frame: Rect, wrap: Rect) -> (Document, StoryId) {+ let (mut d, sid, _) = doc_with("X", frame, ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ st.paras[0].chars = designcraft_doc::CharAttrs { size: Some(14.0), ..Default::default() };+ st.format_chars(0..1, |f| f.over.size = Some(7.6));+ let lid = d.default_layer();+ let mut it = designcraft_doc::Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(wrap));+ it.wrap.mode = WrapMode::BoundingBox;+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ (d, sid)+}++/// A text-wrap object elsewhere on the spread doesn't affect a frame it doesn't overlap: the small+/// frame's one character is set (it was overset: every frame took every wrap object on the+/// spread, and then no gap narrower than 1.5 em of the paragraph's size was used).+#[test]+fn small_single_character_frame_sets_beside_unrelated_text_wrap() {+ let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 310.5), Rect::new(0.0, 0.0, 120.0, 60.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "the tombstone is set");+ assert_eq!(cs.line_count(), 1);+}++/// A narrow frame that a text-wrap object overlaps further down sets the lines the object doesn't+/// reach: the minimum gap width only applies to gaps a wrap object cuts.+#[test]+fn narrow_frame_sets_lines_no_wrap_object_reaches() {+ let (d, sid) = tombstone(Rect::new(300.0, 300.0, 310.5, 340.0), Rect::new(290.0, 330.0, 330.0, 360.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "the first line is above the wrap object");+ assert_eq!(cs.line_count(), 1);+ let (top, baseline) = (cs.frames[0].columns[0].y0, cs.frames[0].lines[0].baseline);+ assert!(baseline - top < 20.0, "on the first line: {baseline} (text area from {top})");+}++/// A wrap object that cuts a narrow frame leaves the sliver beside it (under 1.5 em) empty: no+/// line is set beside the object, and the text continues below it.+#[test]+fn a_wrap_object_cutting_a_narrow_frame_leaves_its_sliver_empty() {+ let text = ["of"; 400].join(" ");+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 60.0, 400.0), ParaAttrs::default());+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.size = Some(6.0));+ // An 8 pt sliver at 6 pt: narrower than 1.5 em (9 pt), wide enough for a word.+ add_wrap_objects(&mut d, &[(Rect::new(0.0, 50.0, 52.0, 120.0), [0.0; 4], WrapMode::BoundingBox)]);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = &cs.frames[0].lines;+ assert!(lines.iter().all(|l| l.baseline <= 50.0 + 1e-6 || l.baseline - l.ascent >= 120.0 - 1e-6), "a line beside the object");+ assert!(lines.iter().any(|l| l.baseline - l.ascent >= 120.0 - 1e-6), "no text below the object");+}++/// A wrap object beside the second column of a two-column frame leaves the first column, narrower+/// than 1.5 em, set in full.+#[test]+fn a_wrap_object_beside_column_two_leaves_a_narrow_column_one_set() {+ let (mut d, sid, fid) = doc_with(&["X"; 12].join(" "), Rect::new(0.0, 0.0, 46.0, 100.0), ParaAttrs::default());+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.columns = 2;+ o.gutter = 12.0;+ // 17 pt columns at 14 pt: narrower than 1.5 em (21 pt).+ d.story_mut(sid).unwrap().format_chars(0..23, |f| f.over.size = Some(14.0));+ add_wrap_objects(&mut d, &[(Rect::new(35.0, 0.0, 60.0, 100.0), [0.0; 4], WrapMode::BoundingBox)]);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let first = all_lines(&cs).iter().filter(|l| l.column == 0).count();+ assert!(first >= 4, "{first} lines in column 1");+}+++/// In a frame of narrow columns, a wrap object beside column 2 leaves column 1 alone: only a gap++/// the object cuts in its own column is held to the minimum width (it was dropped, as the object++/// overlapped the line's band, and the text went past column 1).++#[test]++fn wrap_object_beside_one_narrow_column_leaves_the_other_alone() {++ // Two 18 pt columns (12 pt gutter): narrower than 1.5 em of the 14 pt paragraph.++ let (mut d, sid) = tombstone(Rect::new(300.0, 300.0, 348.0, 340.0), Rect::new(336.0, 300.0, 380.0, 340.0));++ let fid = d.spreads[0].items.iter().find(|i| i.text_frame().is_some_and(|t| t.story == sid)).unwrap().id;++ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;++ let cs = compose_story(&d, sid, &ComposeOptions::default());++ let f = &cs.frames[0];++ assert_eq!(f.columns.len(), 2);++ assert!(f.columns[0].width() < 21.0, "column 1 is narrower than 1.5 em: {}", f.columns[0].width());++ assert!(!cs.is_overset());++ let l = &f.lines[0];++ assert_eq!(l.column, 0, "set in column 1");++ assert!(l.baseline - f.columns[0].y0 < 20.0, "on its first line: {}", l.baseline);++}++/// Insert rectangles with wrap, given as (bounds, [top, left, bottom, right] offsets, mode).fn add_wrap_objects(d: &mut Document, objects: &[(Rect, [f64; 4], WrapMode)]) {let lid = d.default_layer();diff --cc crates/doc/src/lib.rsindex f981fdeb5,517383945..0a2e6578a--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@@ -354,9 -324,7 +356,9 @@@ pub struct DocSettingspub bleed_color: [u8; 3],pub slug_color: [u8; 3],pub keyboard_increment: f64,+ /// Kerning/Tracking increment (Alt+Left/Right in text), in 1/1000 em.+ pub kerning_increment: f64,- /// Named lists (Type › Bulleted and Numbered Lists › Define Lists).+ /// Named lists (Type › Bulleted & Numbered Lists › Define Lists).#[serde(default, skip_serializing_if = "Vec::is_empty")]pub lists: Vec<NumberedList>,/// The story in the primary text frames (Smart Text Reflow adds and removes pages for it).diff --cc crates/doc/src/slice.rsindex e0a6dd383,85f48f48a..a613dad03--- a/crates/doc/src/slice.rs+++ b/crates/doc/src/slice.rs@@@ -92,10 -89,10 +92,10 @@@ impl Story*p = crate::story::ParaFormat { table: None, ..pf.clone() };}}- // Payloads of notes, cross-references and index markers, in order.+ // Marker payloads in text order, keeping newly allocated destination note ids.let first = |m: char| self.text[..pos].matches(m).count();let (nf, nx, ni, na) = (first(FOOTNOTE_REF), first(XREF_MARK), first(INDEX_MARK), first(ANCHOR_MARK));- let no = first(crate::anchored::OBJECT_MARK);+ let (no, ne, nn) = (first(crate::anchored::OBJECT_MARK), first(ENDNOTE_REF), first(NOTE_MARK));for (k, o) in src.objects.iter().enumerate() {if let Some(slot) = self.objects.get_mut(no + k) {*slot = o.clone();@@@ -107,14 -104,17 +107,16 @@@*slot = Arc::new(crate::notes::Footnote { id, text: n.text.clone() });}}- // Limit payload copies to inserted markers so excess source entries cannot overwrite+ // Notes keep the ids made for their new markers, so a pasted copy never shares an id.- for (k, n) in src.endnotes.iter().enumerate() {++ // Payload copies stop at the inserted markers so excess source entries cannot overwrite+ // notes already following the insertion point.- let ne = first(ENDNOTE_REF);+ for (k, n) in src.endnotes.iter().take(src.text.matches(ENDNOTE_REF).count()).enumerate() {if let Some(slot) = self.endnotes.get_mut(ne + k) {let id = slot.id;*slot = Arc::new(crate::notes::Footnote { id, text: n.text.clone() });}}- for (k, n) in src.editorial.iter().enumerate() {- let nn = first(NOTE_MARK);+ for (k, n) in src.editorial.iter().take(src.text.matches(NOTE_MARK).count()).enumerate() {if let Some(slot) = self.editorial.get_mut(nn + k) {let id = slot.id;*slot = Arc::new(crate::endnotes::EditorialNote { id, ..(**n).clone() });diff --cc crates/doc/src/tests.rsindex 65fa12ee5,6ead2dfb8..723de21b1--- a/crates/doc/src/tests.rs+++ b/crates/doc/src/tests.rs@@@ -279,18 -262,29 +279,41 @@@ fn page_names_follow_sections()assert_eq!(d.page_name(5), "4");}+ /// A section restarting at 1 on page 2 leaves two odd (right) pages in a row; each gets its own+ /// spread instead of sharing one with the odd page on the left.+ #[test]+ fn consecutive_right_pages_get_separate_spreads() {+ let mut d = Document::new(&NewDocument { pages: 4, ..Default::default() });+ d.sections.push(Section {+ start: 1,+ start_number: Some(1),+ style: NumberStyle::Arabic,+ prefix: String::new(),+ marker: String::new(),+ include_prefix: false,+ });+ d.repaginate();+ let sides: Vec<Vec<PageSide>> = d.spreads.iter().map(|s| s.pages.iter().map(|p| p.side).collect()).collect();+ assert_eq!(sides, vec![vec![PageSide::Right], vec![PageSide::Right], vec![PageSide::Left, PageSide::Right]]);+ let flat: Vec<PageSide> = sides.into_iter().flatten().collect();+ for (i, side) in flat.iter().enumerate() {+ assert_eq!(*side == PageSide::Right, d.page_number(i) % 2 == 1, "page {i}");+ }+ d.check().unwrap();+ }++#[test]+fn hostile_section_start_numbers_saturate() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ let first = d.sections.iter_mut().find(|s| s.start == 0).unwrap();+ first.start_number = Some(u32::MAX);+ let continuing = Section { start: 2, start_number: None, ..first.clone() };+ d.sections.push(continuing);+ assert_eq!(d.page_number(1), u32::MAX);+ assert_eq!(d.page_number(2), u32::MAX);+ assert_eq!(d.page_name(2), u32::MAX.to_string());+}+#[test]fn document_serde_roundtrip() {let mut d = doc();diff --cc crates/engine/src/atomic.rsindex ba7d091ce,96eb2f1f5..ca8604d4f--- a/crates/engine/src/atomic.rs+++ b/crates/engine/src/atomic.rs@@@ -14,34 -33,135 +14,29 @@@ use std::path::Path/// Atomically replace (or create) `path` with `bytes`. See the module docs.pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {- write_atomic_with(path, |f| f.write_all(bytes))+ craft_atomic::atomic_write(path, bytes)}- /// [`write_atomic`] for a command's `path` parameter. craft-atomic's errors name the path.- pub(crate) fn write_file(path: &str, bytes: &[u8]) -> crate::Result<()> {- write_atomic(Path::new(path), bytes).map_err(|e| crate::EngineError::Other(e.to_string()))- }-/// Atomically replace (or create) `path` with what `fill` writes into the temporary file. When/// `fill`, the flush or the rename fails, the temporary file is removed, `path` is untouched and-/// the error is returned.+/// the error is returned. A panic in `fill` is returned as an error too, so the temporary file is+/// removed then as well.pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {- let target = resolve_links(path)?;- target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?;- let dir = match target.parent() {- Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),- _ => PathBuf::from("."),- };- let existing = std::fs::metadata(&target).ok();- if existing.is_some() {- check_writable(&target)?;- }- let mut tmp = create_temp(&dir, existing.as_ref())?;- if let Some(existing) = existing {- // Restore the exact mode before any document bytes are written, and flush it along with- // the content. The caller's umask may have restricted the initial temporary-file mode.- keep_permissions(tmp.as_file(), &existing)?;- }- fill(tmp.as_file_mut())?;- tmp.as_file().sync_all()?;- // Closing the file before renaming also allows replacement on Windows. TempPath removes the- // staging file on every error; NamedTempFile does the same if the writer unwinds.- let tmp = tmp.into_temp_path();- retry_rename(RENAME_TRIES, || std::fs::rename(&tmp, &target))?;- // The new bytes are in place. A failed folder flush can't be undone and must not report the- // save as failed.- let _ = sync_dir(&dir);- Ok(())+ craft_atomic::atomic_write_with(path, |file| {+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fill(file)))+ .unwrap_or_else(|_| Err(io::Error::other("the file writer stopped unexpectedly")))+ })}-/// Create a fresh temporary file beside the target (the same folder, so the rename stays on one-/// volume). A short randomized name supports long destination names and skips existing entries.-fn create_temp(dir: &Path, existing: Option<&std::fs::Metadata>) -> io::Result<tempfile::NamedTempFile> {- let mut builder = tempfile::Builder::new();- builder.prefix(".designcraft-save-").suffix(".tmp");+#[cfg(test)]+mod tests {#[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;-- // Private replacements are private from creation. New files retain fs::write's normal- // 0666 mode restricted by the caller's umask.- let mode = existing.map_or(0o666, |metadata| metadata.permissions().mode());- builder.permissions(std::fs::Permissions::from_mode(mode));- }- #[cfg(not(unix))]- let _ = existing;- builder.tempfile_in(dir)-}--/// The file a chain of symbolic links ends at (`path` itself when it is not a link). A dangling-/// link resolves to the missing file it names, which is then created.-fn resolve_links(path: &Path) -> io::Result<PathBuf> {- let mut p = path.to_path_buf();- for _ in 0..MAX_LINKS {- match std::fs::symlink_metadata(&p) {- Ok(m) if m.file_type().is_symlink() => {- let to = std::fs::read_link(&p)?;- p = match p.parent() {- Some(dir) if to.is_relative() => dir.join(to),- _ => to,- };- }- _ => return Ok(p),- }- }- Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: too many levels of symbolic links", path.display())))-}--/// A rename replaces a file the user can't write (Unix only needs the folder to be writable);-/// refuse, as writing it in place would. Opening for writing without truncating changes nothing.-#[cfg(unix)]-fn check_writable(target: &Path) -> io::Result<()> {- OpenOptions::new().write(true).open(target).map(drop)-}--/// Windows refuses to rename over a read-only file by itself.-#[cfg(not(unix))]-fn check_writable(_: &Path) -> io::Result<()> {- Ok(())-}--/// The replacement keeps the replaced file's mode (Unix; Windows files keep only a read-only flag,-/// and a read-only file can't be replaced).-#[cfg(unix)]-fn keep_permissions(tmp: &File, replaced: &std::fs::Metadata) -> io::Result<()> {- tmp.set_permissions(replaced.permissions())-}--#[cfg(not(unix))]-fn keep_permissions(_: &File, _: &std::fs::Metadata) -> io::Result<()> {- Ok(())-}+ use std::fs::OpenOptions;+ use std::io::Write as _;+ use std::path::PathBuf;-/// Run `rename` up to `tries` times, pausing with a doubling delay while it fails with-/// `PermissionDenied` (a scanner holding the file on Windows). Other errors return at once.-fn retry_rename(tries: u32, mut rename: impl FnMut() -> io::Result<()>) -> io::Result<()> {- let mut delay = RENAME_FIRST_DELAY_MS;- let mut left = tries.max(1);- loop {- left = left.saturating_sub(1);- match rename() {- Err(e) if e.kind() == io::ErrorKind::PermissionDenied && left > 0 => {- std::thread::sleep(std::time::Duration::from_millis(delay));- delay = delay.saturating_mul(2).min(RENAME_MAX_DELAY_MS);- }- r => return r,- }- }-}--/// Flush a folder's entries (Unix). Rust's portable file API cannot open a directory on Windows;-/// this does not establish power-loss durability for its directory entries.-#[cfg(unix)]-fn sync_dir(dir: &Path) -> io::Result<()> {- File::open(dir)?.sync_all()-}--#[cfg(not(unix))]-fn sync_dir(_: &Path) -> io::Result<()> {- Ok(())-}+ use craft_atomic::{RenameRetry, retry_rename};-#[cfg(test)]-mod tests {use super::*;fn dir(name: &str) -> PathBuf {diff --cc crates/engine/src/cmd/file.rsindex 054f1fde1,5b9ef9c85..377c46a5e--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -13,55 -13,23 +13,55 @@@ use crate::{DocState, EngineError, Resupub fn specs() -> Vec<CommandSpec> {vec![cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?, primaryTextFrame?: bool}",always, file_new),cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();+ presets.extend(+ s.prefs+ .document_presets+ .iter()+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),+ );+ Ok(Value::Array(presets))+ }),+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,+ "{name, …the settings as file.new} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",+ always, save_preset),+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();+ let before = s.prefs.document_presets.len();+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if s.prefs.document_presets.len() == before {+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));+ }+ ok()+ }),cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped (and, for .idml, package parts missing)}",+ "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}",always, file_open),- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", always, file_open_bytes),- cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),- cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),- cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {- let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?.to_string();+ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes),+ cmd!(noundo "file.openRecent", "Open Recent File", [], None,+ "{index} — reopen entry `index` of File › Open Recent (as file.open); a file that is gone is an error and stays listed",+ has_recent, file_open_recent),+ cmd!(query "file.recentFiles", "Recent Files", [], None, "{} → [{path, name, exists}] File › Open Recent, most recent first", always, |s, _| {+ Ok(Value::Array(s.prefs.recent_files.iter().map(|p| recent_entry(p)).collect()))+ }),+ cmd!(noundo "file.clearRecent", "Clear Recent Files", ["File", "Open Recent"], None, "{} — empty File › Open Recent", has_recent, |s, _| {+ s.prefs.recent_files.clear();+ ok()+ }),+ cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| {+ let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?;+ let path = with_document_extension(path);let mut copy = (*s.doc()?.doc).clone();super::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path));- let bytes = to_bytes(©);+ let bytes = to_bytes_with_preview(©, &s.cache)?;#[cfg(not(target_arch = "wasm32"))]- crate::atomic::write_file(&path, &bytes)?;+ crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?;Ok(json!({"path": path, "bytes": bytes.len()}))}),cmd!(noundo "file.revert", "Revert", ["File"], None, "{} — back to the last saved version (not undoable)", can_revert, file_revert),@@@ -392,91 -158,34 +393,107 @@@ fn file_sample(s: &mut Session, _p: &VaOk(json!({"index": i}))}+fn has_recent(s: &Session) -> std::result::Result<(), String> {+ if s.prefs.recent_files.is_empty() { Err("no recent files".into()) } else { Ok(()) }+}++/// A recent file's first-page picture as straight RGBA, for the start screen.+pub struct RecentPreview {+ pub width: u32,+ pub height: u32,+ pub rgba: Vec<u8>,+}++/// The picture a `.designcraft` file saved of its first page; None when the file is gone, isn't+/// ours, or was saved before files had one (it gets one when saved again).+pub fn recent_preview(path: &str) -> Option<RecentPreview> {+ #[cfg(not(target_arch = "wasm32"))]+ {- let file = std::fs::File::open(path).ok()?;- let png = designcraft_format::read_preview(std::io::BufReader::new(file))?;++ let bytes = crate::io::read(path).ok()?;++ let png = designcraft_format::read_preview(std::io::Cursor::new(bytes))?;+ let img = designcraft_images::decode_rgba(&png)?;+ let (width, height) = img.dimensions();+ Some(RecentPreview { width, height, rgba: img.into_raw() })+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = path;+ None+ }+}++/// One File › Open Recent row: the path, its file name and whether it is still there.+fn recent_entry(path: &str) -> Value {+ let name = std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string());+ #[cfg(not(target_arch = "wasm32"))]- let exists = std::path::Path::new(path).is_file();++ let exists = crate::io::is_file(path);+ #[cfg(target_arch = "wasm32")]+ let exists = false;+ json!({"path": path, "name": name, "exists": exists})+}++fn file_open_recent(s: &mut Session, p: &Value) -> Result<Value> {+ let index =+ p.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("file.openRecent", "missing `index`"))?;+ let path = s+ .prefs+ .recent_files+ .get(index)+ .cloned()+ .ok_or_else(|| bad("file.openRecent", format!("no recent file {index} (the list has {})", s.prefs.recent_files.len())))?;+ #[cfg(not(target_arch = "wasm32"))]- if !std::path::Path::new(&path).is_file() {++ if !crate::io::is_file(&path) {+ return Err(EngineError::Other(format!("{path} can't be found: it was moved, renamed or deleted, or its disk isn't connected")));+ }+ file_open(s, &json!({"path": path}))+}++ /// An InDesign file that DesignCraft can't open yet, with how to bring it over. Decoding one as a+ /// DesignCraft document only reported "not a DesignCraft document: expected value at line 1+ /// column 1" (#21).+ fn foreign_document(name: &str) -> Option<&'static str> {+ let ext = std::path::Path::new(name).extension().and_then(|e| e.to_str())?.to_ascii_lowercase();+ match ext.as_str() {+ "indd" | "indt" => Some(+ "InDesign documents (.indd) and templates (.indt) can't be opened yet. In InDesign, choose File ▸ Export… ▸ InDesign Markup (IDML) and open the .idml in DesignCraft.",+ ),+ _ => None,+ }+ }++/// `file.open`: the document opens and moves to the front of File › Open Recent.fn file_open(s: &mut Session, p: &Value) -> Result<Value> {+ let r = open_path(s, p)?;+ if let Some(path) = str_param(p, "path") {+ s.prefs.note_recent_file(path);+ }+ Ok(r)+}++fn open_path(s: &mut Session, p: &Value) -> Result<Value> {let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;+ if let Some(hint) = foreign_document(path) {+ return Err(EngineError::Other(format!("{path}: {hint}")));+ }#[cfg(not(target_arch = "wasm32"))]{- let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;- if path.to_ascii_lowercase().ends_with(".idml") {++ let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;+ // The content decides first: a file's extension may be missing or wrong. The extension+ // then routes files whose content isn't recognised to the reader that explains why.+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();+ let native = designcraft_format::is_designcraft(&bytes) || bytes.trim_ascii_start().starts_with(b"{");+ if designcraft_idml::is_idml(&bytes) || (!native && (super::interchange::is_indd(path, &bytes) || ext == "idml")) {return super::interchange::open_idml(s, p);}- let bytes = crate::io::read_file(path).map_err(EngineError::Other)?;- let mut d = from_bytes(&bytes)?;+ if !native && ext != designcraft_format::EXTENSION {+ return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file")));+ }+ let (mut d, mut warnings) = load_bytes(&bytes)?;super::interchange::resolve_packaged_links(&mut d, std::path::Path::new(path).parent());super::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));- let (fonts, faces, warnings) = load_document_fonts(&mut d, path);+ let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path);+ warnings.extend(font_warnings);+ warnings.extend(super::style::grep_style_warnings(&d));let mut st = DocState::new(d, Some(path.to_string()));st.fonts = fonts;let i = s.add_document(st);@@@ -527,13 -239,17 +547,18 @@@ fn document_fonts_folder(dir: &std::pat}fn file_open_bytes(s: &mut Session, p: &Value) -> Result<Value> {+ if let Some(name) = str_param(p, "name")+ && let Some(hint) = foreign_document(name)+ {+ return Err(EngineError::Other(format!("{name}: {hint}")));+ }let b = base64_decode(str_param(p, "base64").unwrap_or(""));- // IDML packages are recognised by their stored `mimetype` first entry.- if designcraft_idml::is_idml(&b) {+ // IDML packages are recognised by their stored `mimetype` first entry, INDD files by their+ // signature (or their name).+ if designcraft_idml::is_idml(&b) || super::interchange::is_indd(str_param(p, "name").unwrap_or_default(), &b) {return super::interchange::open_idml(s, p);}- let mut d = from_bytes(&b)?;+ let (mut d, warnings) = load_bytes(&b)?;super::datamerge::resolve_sources_on_open(&mut d, None);if let Some(n) = str_param(p, "name") {d.title = n.to_string();@@@ -544,20 -260,20 +569,22 @@@fn file_save(s: &mut Session, p: &Value) -> Result<Value> {let st = s.doc_mut()?;+ // Saving to the document's own file keeps its name, even one opened without the extension.let path = str_param(p, "path")- .map(str::to_string)+ .map(with_document_extension).or_else(|| st.path.clone()).ok_or_else(|| bad("file.save", "missing `path` (document has never been saved)"))?;+ // Before anything about the document changes: a refused save leaves it as it was.+ crate::file_access::check_write(&path).map_err(EngineError::Other)?;// Prepare paths for the destination without changing the live document until persistence succeeds.let mut saved = (*st.doc).clone();super::datamerge::refresh_relative_paths(&mut saved, std::path::Path::new(&path));let paths_changed = saved.data_merge != st.doc.data_merge;let saved = if paths_changed { Arc::new(saved) } else { st.doc.clone() };- let bytes = to_bytes(&saved);+ let bytes = to_bytes_with_preview(&saved, &s.cache)?;#[cfg(not(target_arch = "wasm32"))]- crate::atomic::write_file(&path, &bytes)?;+ crate::io::write_file(&path, &bytes).map_err(EngineError::Other)?;+ let st = s.doc_mut()?;if paths_changed {st.doc = saved;st.bump_revision();diff --cc crates/engine/src/cmd/find.rsindex 465dd6d0c,83d137248..1ec04b81e--- a/crates/engine/src/cmd/find.rs+++ b/crates/engine/src/cmd/find.rs@@@ -1,8 -1,11 +1,12 @@@//! Edit → Find/Change: plain text and GREP (regular expressions) with InDesign's metacharacters,//! optional formatting in the change, scoped to the document, a story or the selection.+ use std::ops::Range;+ use std::sync::{Arc, Weak};++use designcraft_compose::grep::{Grep, GrepOptions, translate_replacement};- use designcraft_doc::{StoryId, TextSel, story};+ use designcraft_doc::story::floor_char_boundary;+ use designcraft_doc::{Document, Selection, StoryId, TextSel};use serde_json::{Value, json};use super::{CommandSpec, bad, bool_or, cmd, has_doc, str_param};@@@ -26,9 -30,10 +31,10 @@@ pub fn specs() -> Vec<CommandSpec>"Change All (Object)",[],None,- "{…find.objects criteria, change: {fill?, stroke?, strokeWeight?, opacity?}} → {changed}",+ "{…the criteria of find.objects, change: {fill?, stroke?, strokeWeight?, opacity?}} → {changed}",has_doc,|s, p| {+ s.reset_find_scope();let ids = find_objects(&s.doc()?.doc, p);let ch = p.get("change").cloned().unwrap_or(Value::Null);if !ch.is_object() {@@@ -97,46 -119,202 +103,195 @@@ fn build(p: &Value) -> Result<Grep>if f.is_empty() {return Err(bad("find", "empty search"));}- let grep = bool_or(p, "grep", false);- let mut pat = if grep { metachars(f, true) } else { regex::escape(&metachars(f, false)) };- if bool_or(p, "wholeWord", false) {- pat = format!(r"\b(?:{pat})\b");- }- regex::RegexBuilder::new(&pat)- .case_insensitive(!bool_or(p, "caseSensitive", false))- .multi_line(true)- .build()- .map_err(|e| bad("find", format!("bad GREP: {e}")))+ let opts = GrepOptions { case_insensitive: !bool_or(p, "caseSensitive", false), multi_line: true, whole_word: bool_or(p, "wholeWord", false) };+ let re = if bool_or(p, "grep", false) { Grep::new(f, opts) } else { Grep::literal(&metachars(f), opts) };+ re.map_err(|e| bad("find", e))}- fn scope(s: &Session, p: &Value) -> Result<Vec<(StoryId, std::ops::Range<usize>)>> {+ #[derive(Clone, Debug, PartialEq, Eq)]+ enum Domain {+ Document,+ Story,+ Selection,+ Explicit(StoryId),+ }++ impl Domain {+ fn from_params(p: &Value) -> Self {+ if let Some(id) = p.get("story").and_then(Value::as_u64) {+ return Self::Explicit(StoryId(id));+ }+ match str_param(p, "scope").unwrap_or("document") {+ "story" => Self::Story,+ "selection" => Self::Selection,+ _ => Self::Document,+ }+ }+ }++ /// Whether two requests use the same search domain, including explicit-story precedence.+ pub fn same_find_domain(a: &Value, b: &Value) -> bool {+ Domain::from_params(a) == Domain::from_params(b)+ }++ #[derive(Clone, Debug, PartialEq, Eq)]+ struct Matcher {+ find: String,+ grep: bool,+ case_sensitive: bool,+ whole_word: bool,+ }++ impl Matcher {+ fn from_params(p: &Value) -> Self {+ Self {+ find: str_param(p, "find").unwrap_or("").to_string(),+ grep: bool_or(p, "grep", false),+ case_sensitive: bool_or(p, "caseSensitive", false),+ whole_word: bool_or(p, "wholeWord", false),+ }+ }+ }++ /// A search owns its original domain, not the selection used to paint the latest hit.+ /// Weak identity avoids retaining an old document merely for this transient cache.+ #[derive(Clone)]+ pub(crate) struct FindContext {+ document: Weak<Document>,+ uid: u64,+ revision: u64,+ selection: Selection,+ domain: Domain,+ matcher: Matcher,+ targets: Vec<(StoryId, Range<usize>)>,+ order: Vec<usize>,+ target: usize,+ offset: usize,+ last_match_end: Option<usize>,+ }++ impl FindContext {+ pub(crate) fn is_current(&self, st: &DocState) -> bool {+ self.uid == st.uid && Weak::ptr_eq(&self.document, &Arc::downgrade(&st.doc)) && self.revision == st.revision && self.selection == st.selection+ }++ fn acknowledge(&mut self, st: &DocState) {+ self.revision = st.revision;+ self.selection = st.selection.clone();+ }++ fn restart(&mut self, st: &DocState) -> Result<()> {+ self.target = 0;+ self.last_match_end = None;+ self.order = (0..self.targets.len()).collect();+ let caret = st.selection.text.filter(|t| t.cell.is_none() && st.selection.cells.is_none());+ if self.domain == Domain::Document+ && let Some(t) = st.selection.text+ && let Some(i) = self.targets.iter().position(|(sid, _)| *sid == t.story)+ {+ self.order.rotate_left(i);+ }+ let first = self.order.first().and_then(|i| self.targets.get(*i));+ self.offset = match first {+ Some((sid, r)) if self.domain != Domain::Selection => caret.filter(|t| t.story == *sid).map_or(r.start, |t| t.range().end.min(r.end)),+ Some((_, r)) => r.start,+ None => 0,+ };+ if let Some((sid, r)) = first {+ let text = target_text(&st.doc, *sid, r)?;+ if text.get(self.offset.saturating_sub(r.start)..).is_none() {+ return Err(bad("find", "invalid UTF-8 search cursor"));+ }+ }+ Ok(())+ }++ fn advance_target(&mut self) {+ self.target = self.target.saturating_add(1);+ self.last_match_end = None;+ self.offset = self.order.get(self.target).and_then(|i| self.targets.get(*i)).map_or(0, |(_, r)| r.start);+ }++ fn advance_empty(&mut self, text: &str, relative_end: usize, end: usize) {+ // Move one Unicode scalar, not one byte; an endpoint is returned at most once.+ if let Some(ch) = text.get(relative_end..).and_then(|rest| rest.chars().next()) {+ self.offset = end + ch.len_utf8();+ } else {+ self.advance_target();+ }+ }+ }++ fn target_text<'a>(d: &'a Document, sid: StoryId, r: &Range<usize>) -> Result<&'a str> {+ d.story(sid)+ .ok_or_else(|| bad("find", "no such story"))?+ .text+ .get(r.clone())+ .ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))+ }++ fn scope(s: &Session, p: &Value) -> Result<FindContext> {let st = s.doc()?;+ let domain = Domain::from_params(p);+ let matcher = Matcher::from_params(p);+ if let Some(previous) = s.find_context.as_ref().filter(|c| c.is_current(st) && c.domain == domain) {+ let mut context = previous.clone();+ if context.matcher != matcher {+ context.matcher = matcher;+ context.restart(st)?;+ }+ return Ok(context);+ }let d = &st.doc;- if let Some(sid) = p.get("story").and_then(Value::as_u64) {- let sid = StoryId(sid);- let len = d.story(sid).map(|x| x.len()).ok_or_else(|| bad("find", "no such story"))?;- return Ok(vec![(sid, 0..len)]);- }- match str_param(p, "scope").unwrap_or("document") {- "story" => {- let t = st.selection.text.ok_or_else(|| bad("find", "no story selected"))?;- Ok(vec![(t.story, 0..d.story(t.story).map(|x| x.len()).unwrap_or(0))])+ let targets = match domain {+ Domain::Explicit(sid) => {+ let len = d.story(sid).ok_or_else(|| bad("find", "no such story"))?.len();+ vec![(sid, 0..len)]}- "selection" => {+ Domain::Story | Domain::Selection => {+ if st.selection.cells.is_some() || st.selection.text.is_some_and(|t| t.cell.is_some()) {+ return Err(bad("find", "Story/Selection search in table cells or notes is not supported"));+ }let t = st.selection.text.ok_or_else(|| bad("find", "no text selected"))?;- Ok(vec![(t.story, t.range())])+ let story = d.story(t.story).ok_or_else(|| bad("find", "no such story"))?;+ let r = if domain == Domain::Selection { t.range() } else { 0..story.len() };+ target_text(d, t.story, &r)?;+ vec![(t.story, r)]}- _ => Ok(d.stories.values().map(|x| (x.id, 0..x.len())).collect()),- }+ Domain::Document => d.stories.values().map(|x| (x.id, 0..x.len())).collect(),+ };+ let mut context = FindContext {+ document: Arc::downgrade(d),+ uid: st.uid,+ revision: st.revision,+ selection: st.selection.clone(),+ domain,+ matcher,+ targets,+ order: Vec::new(),+ target: 0,+ offset: 0,+ last_match_end: None,+ };+ context.restart(st)?;+ Ok(context)}+/// Most matches `find.find` returns.+const MAX_MATCHES: usize = 10_000;+fn find(s: &mut Session, p: &Value) -> Result<Value> {let re = build(p)?;+ let context = scope(s, p)?;let st = s.doc()?;let mut out = Vec::new();- for (sid, r) in scope(s, p)? {- let Some(story) = st.doc.story(sid) else { continue };- let Some(text) = story.text.get(r.clone()) else { continue };+ for (sid, r) in &context.targets {+ let text = target_text(&st.doc, *sid, r)?;- for m in re.find_iter(text) {- out.push(json!({"story": sid.0, "start": r.start + m.start(), "end": r.start + m.end(), "text": m.as_str()}));- if out.len() >= 10_000 {- break;- }+ for m in re.find_all(text, MAX_MATCHES.saturating_sub(out.len())).map_err(|e| bad("find", e))? {+ out.push(json!({"story": sid.0, "start": r.start + m.start, "end": r.start + m.end, "text": text.get(m)}));}}+ s.find_context = Some(context);Ok(Value::Array(out))}@@@ -165,16 -343,21 +320,16 @@@ fn change(s: &mut Session, p: &Value) -for (sid, r) in targets {let Some(story) = d.story(sid) else { continue };// Collect matches first (positions refer to the original text), apply back to front.- let Some(text) = story.text.get(r.clone()) else { continue };- let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?.to_string();- let mut edits: Vec<(std::ops::Range<usize>, String)> = Vec::new();- for caps in re.captures_iter(&text) {- let Some(m) = caps.get(0) else { continue };- let mut out = String::new();- if grep {- caps.expand(&rep, &mut out);- } else {- out = rep.clone();- }- edits.push((r.start + m.start()..r.start + m.end(), out));- if first_only {- break;- }++ let text = story.text.get(r.clone()).ok_or_else(|| bad("find", "invalid selection bounds or UTF-8 boundary"))?;+ let edits: Vec<(std::ops::Range<usize>, String)> = if grep {+ re.replacements(text, &rep, first_only)+ } else {+ re.find_all(text, if first_only { 1 } else { usize::MAX }).map(|ms| ms.into_iter().map(|m| (m, rep.clone())).collect())}+ .map_err(|e| bad("find.change", e))?+ .into_iter()+ .map(|(m, out)| (r.start + m.start..r.start + m.end, out))+ .collect();let Some(st) = d.story_mut(sid) else { continue };for (range, new) in edits.iter().rev() {st.replace(range.clone(), new);@@@ -183,12 -366,19 +338,20 @@@}count += 1;}- if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid) {- let len = st.len();- t.anchor = t.anchor.min(len);- t.focus = t.focus.min(len);+ if let Some(t) = sel.text.as_mut().filter(|t| t.story == sid && t.cell.is_none()) {+ // Repair byte validity once against the final story, without remapping valid offsets.+ let range = t.range();+ let start = floor_char_boundary(&st.text, range.start);+ let mut end = range.end.min(st.len());+ if t.is_caret() {+ end = start;+ } else if !st.text.is_char_boundary(end) {+ let floor = floor_char_boundary(&st.text, end);+ end = st.text.get(floor..).and_then(|rest| rest.chars().next()).map_or(floor, |ch| floor + ch.len_utf8());+ }+ (t.anchor, t.focus) = if t.anchor <= t.focus { (start, end) } else { (end, start) };}+ // `first` is the first match of the whole search, not of each story.if first_only && count > 0 {break;}@@@ -199,29 -389,44 +362,44 @@@fn find_next(s: &mut Session, p: &Value) -> Result<Value> {let re = build(p)?;+ let mut context = scope(s, p)?;let st = s.doc()?;- let (start_story, start_pos) = st.selection.text.map(|t| (Some(t.story), t.range().end)).unwrap_or((None, 0));- let mut order: Vec<StoryId> = st.doc.stories.keys().copied().collect();- if let Some(ss) = start_story- && let Some(i) = order.iter().position(|x| *x == ss)- {- order.rotate_left(i);- }let mut hit = None;- for (k, sid) in order.iter().enumerate() {- let Some(story) = st.doc.story(*sid) else { continue };- let from = if k == 0 && start_story == Some(*sid) { start_pos.min(story.len()) } else { 0 };- if let Some(m) = re.find_at(&story.text, from).map_err(|e| bad("find.next", e))? {- hit = Some((*sid, m.start, m.end));+ while let Some((sid, r)) = context.order.get(context.target).and_then(|i| context.targets.get(*i)).cloned() {+ let text = target_text(&st.doc, sid, &r)?;+ let from = context.offset.checked_sub(r.start).ok_or_else(|| bad("find", "invalid search cursor"))?;+ if text.get(from..).is_none() {+ return Err(bad("find", "invalid UTF-8 search cursor"));+ }- if let Some(m) = re.find_at(text, from) {- let (a, b) = (r.start + m.start(), r.start + m.end());++ if let Some(m) = re.find_at(text, from).map_err(|e| bad("find.next", e))? {++ let (a, b) = (r.start + m.start, r.start + m.end);+ // Match find_iter/captures_iter: suppress an empty match adjacent to the+ // previous match's end, but keep adjacent nonempty matches.+ if m.is_empty() && context.last_match_end == Some(b) {- context.advance_empty(text, m.end(), b);++ context.advance_empty(text, m.end, b);+ continue;+ }+ hit = Some((sid, a, b));+ context.last_match_end = Some(b);+ if m.is_empty() {- context.advance_empty(text, m.end(), b);++ context.advance_empty(text, m.end, b);+ } else {+ context.offset = b;+ }break;}+ context.advance_target();}- let Some((sid, a, b)) = hit else { return Ok(Value::Null) };+ let Some((sid, a, b)) = hit else {+ s.find_context = Some(context);+ return Ok(Value::Null);+ };let frame = st.doc.story(sid).and_then(|x| x.frames.first().copied());let stm = s.doc_mut()?;- stm.selection = designcraft_doc::Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });- stm.revision += 1;- let _ = story::PAGE_NUMBER;+ stm.selection = Selection::text(TextSel { story: sid, anchor: a, focus: b, frame, cell: None });+ stm.bump_revision();+ context.acknowledge(stm);+ s.find_context = Some(context);Ok(json!({"story": sid.0, "start": a, "end": b}))}@@@ -254,41 -459,664 +432,700 @@@ mod testss.execute("find.next", &json!({"find": "or"})).unwrap();assert!(s.doc().unwrap().selection.text.is_some());}++ #[test]+ fn change_first_changes_one_match_in_the_whole_document() {+ for grep in [false, true] {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ for y in [36, 336] {+ s.execute("frame.create", &json!({"rect": [36, y, 300, y + 200], "content": "text", "text": "red and red"})).unwrap();+ }+ let r = s.execute("find.change", &json!({"find": "red", "change": "blue", "first": true, "grep": grep})).unwrap();+ assert_eq!(r["count"], 1);+ assert_eq!(s.execute("find.find", &json!({"find": "blue"})).unwrap().as_array().unwrap().len(), 1);+ assert_eq!(s.execute("find.find", &json!({"find": "red"})).unwrap().as_array().unwrap().len(), 3);+ }+ }++ fn scope_session(text: &str) -> (Session, designcraft_doc::StoryId) {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let frame = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100], "content": "text", "text": text})).unwrap();+ (s, designcraft_doc::StoryId(frame["story"].as_u64().unwrap()))+ }++ fn scope_select(s: &mut Session, sid: designcraft_doc::StoryId, a: usize, b: usize) {+ s.execute("text.select", &json!({"story": sid.0, "anchor": a, "focus": b})).unwrap();+ }++ fn scope_hit(s: &mut Session, p: &serde_json::Value, sid: designcraft_doc::StoryId, a: usize, b: usize) {+ assert_eq!(s.execute("find.next", p).unwrap(), json!({"story": sid.0, "start": a, "end": b}));+ let selected = s.doc().unwrap().selection.text.unwrap();+ assert_eq!((selected.story, selected.range(), selected.cell), (sid, a..b, None));+ }++ #[test]+ fn find_scope_first_change_stops_after_first_matching_story_and_repairs_selection() {+ for (texts, first, explicit, grep, expected, count) in [+ (vec!["red red", "red"], Some(true), false, false, vec!["blue red", "red"], 1),+ (vec!["keep", "red red", "red"], Some(true), false, false, vec!["keep", "blue red", "red"], 1),+ (vec!["keep", "other"], Some(true), false, false, vec!["keep", "other"], 0),+ (vec!["red red", "red"], Some(false), false, false, vec!["blue blue", "blue"], 3),+ (vec!["red red", "red"], None, false, false, vec!["blue blue", "blue"], 3),+ (vec!["red red", "red"], Some(true), true, false, vec!["blue red", "red"], 1),+ (vec!["red red", "red"], Some(false), true, false, vec!["blue blue", "red"], 2),+ (vec!["", "é🙂"], Some(true), false, true, vec!["X", "é🙂"], 1),+ (vec!["é", "🙂"], Some(false), false, true, vec!["XéX", "X🙂X"], 4),+ ] {+ let (mut s, sid) = scope_session(texts[0]);+ let mut sids = vec![sid];+ for text in texts.iter().skip(1) {+ let frame = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": text})).unwrap();+ sids.push(designcraft_doc::StoryId(frame["story"].as_u64().unwrap()));+ }+ assert_eq!(s.doc().unwrap().doc.stories.keys().copied().collect::<Vec<_>>(), sids);+ // Document Change keeps canonical target order even with a later story current.+ scope_select(&mut s, *sids.last().unwrap(), 0, 0);+ let before = s.doc().unwrap().doc.clone();+ let mut p = json!({+ "find": if grep { "(?:)" } else { "red" },+ "change": if grep { "X" } else { "blue" },+ "scope": "document", "grep": grep+ });+ if let Some(first) = first {+ p["first"] = json!(first);+ }+ if explicit {+ p["story"] = json!(sid.0);+ p["scope"] = json!("selection");+ }+ if first == Some(true) && !explicit && !grep && texts.last() == Some(&"red") {+ let last = *sids.last().unwrap();+ scope_hit(&mut s, &p, last, 0, 3);+ let first_hit = sids[if texts.len() == 2 { 0 } else { 1 }];+ assert_eq!(+ s.execute("find.find", &p).unwrap(),+ json!([+ {"story": first_hit.0, "start": 0, "end": 3, "text": "red"},+ {"story": first_hit.0, "start": 4, "end": 7, "text": "red"},+ {"story": last.0, "start": 0, "end": 3, "text": "red"}+ ]),+ "Count remains canonical after Next paints the later story"+ );+ }+ let selection = s.doc().unwrap().selection.clone();+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": count}));+ let st = s.doc().unwrap();+ assert_eq!(st.selection, selection);+ for (i, sid) in sids.iter().enumerate() {+ assert_eq!(st.doc.story(*sid).unwrap().text, expected[i]);+ if texts[i] == expected[i] {+ assert_eq!(st.doc.story(*sid), before.story(*sid), "untouched story {i} stays entirely unchanged");+ }+ }+ st.doc.check().unwrap();+ }++ // Identical replacement is still one counted match, not a reason to visit another story.+ let (mut s, sid) = scope_session("red red");+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "red"})).unwrap();+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());+ scope_select(&mut s, other_sid, 0, 3);+ let before = s.doc().unwrap().doc.clone();+ let selection = s.doc().unwrap().selection.clone();+ assert_eq!(+ s.execute("find.change", &json!({"find": "red", "change": "red", "scope": "document", "first": true})).unwrap(),+ json!({"count": 1})+ );+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red");+ assert_eq!(s.doc().unwrap().doc.story(other_sid), before.story(other_sid));+ assert_eq!(s.doc().unwrap().selection, selection);+ s.doc().unwrap().doc.check().unwrap();++ for reverse in [false, true] {+ let (mut s, sid) = scope_session("éX X");+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "X"})).unwrap();+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());+ scope_select(&mut s, sid, if reverse { 3 } else { 2 }, if reverse { 2 } else { 3 });+ let before = s.doc().unwrap().doc.clone();+ let mut selection = s.doc().unwrap().selection.clone();+ let t = selection.text.as_mut().unwrap();+ (t.anchor, t.focus) = if reverse { (6, 2) } else { (2, 6) };+ let p = json!({"find": "X", "change": "🙂", "scope": "document", "first": true});+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 3);+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));+ let st = s.doc().unwrap();+ assert_eq!(st.doc.story(sid).unwrap().text, "é🙂 X");+ assert_eq!(st.doc.story(other_sid), before.story(other_sid));+ assert_eq!(st.selection, selection, "first-match exit must follow final UTF-8 repair");+ st.doc.check().unwrap();+ assert_eq!(+ s.execute("find.find", &json!({"find": "🙂", "scope": "selection"})).unwrap(),+ json!([{"story": sid.0, "start": 2, "end": 6, "text": "🙂"}])+ );+ }+ }++ #[test]+ fn grep_in_the_documents_dialect() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Москва and Paris, 1\u{2013}2 days.\nok"})).unwrap();+ // `\u` uppercase, `\l` lowercase letter.+ let m = s.execute("find.find", &json!({"find": r"\u\l+", "grep": true, "caseSensitive": true})).unwrap();+ let words: Vec<&str> = m.as_array().unwrap().iter().map(|x| x["text"].as_str().unwrap()).collect();+ assert_eq!(words, ["Москва", "Paris"]);+ // `~=` en dash, `\h` space, `\r` paragraph end; the change uses groups, `~S` and `\r`.+ let r = s.execute("find.change", &json!({"find": r"(\d)~=(\d)\h(\l+)\.\r", "change": r"$1~=$2~S$3!\r", "grep": true})).unwrap();+ assert_eq!(r["count"], 1);+ let sid = s.execute("document.inspect", &json!({})).unwrap()["stories"][0]["id"].as_u64().unwrap();+ let text = s.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string();+ assert!(text.starts_with("Москва and Paris, 1\u{2013}2\u{A0}days!\nok"), "{text:?}");+ // A pattern that doesn't compile is an error, not a silent no-op.+ assert!(s.execute("find.find", &json!({"find": "[[:nope:]]", "grep": true})).is_err());+ assert!(s.execute("find.change", &json!({"find": "(", "change": "", "grep": true})).is_err());+ }+++ #[test]+ fn find_scope_exact_baseline_count_next_change() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let frame = s+ .execute(+ "frame.create",+ &json!({+ "rect": [36, 36, 300, 200], "content": "text", "text": "red red"+ }),+ )+ .unwrap();+ let sid = frame["story"].as_u64().unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();+ assert_eq!(+ s.execute("find.find", &json!({"find": "red", "scope": "selection"})).unwrap(),+ json!([{"story": sid, "start": 0, "end": 3, "text": "red"}])+ );+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "selection"})).unwrap(), json!({"story": sid, "start": 0, "end": 3}));+ assert_eq!(s.execute("find.change", &json!({"find": "red", "change": "blue", "scope": "selection"})).unwrap(), json!({"count": 1}));+ assert_eq!(s.execute("story.get", &json!({"story": sid})).unwrap()["text"], "blue red");+ }++ #[test]+ fn find_scope_change_growth_preserves_direction_and_full_scalar_hits() {+ for (text, find, change, changed, start, old_end, new_end) in [("a", "a", "é", "é", 0, 1, 2), ("éX", "X", "🙂", "é🙂", 2, 3, 6)] {+ for reverse in [false, true] {+ let (mut s, sid) = scope_session(text);+ // Real caret movement keeps the frame identity, unlike text.select.+ s.execute("text.move", &json!({"dir": "left", "extend": reverse})).unwrap();+ if !reverse {+ s.execute("text.move", &json!({"dir": "right", "extend": true})).unwrap();+ }+ let selected = s.doc().unwrap().selection.text.unwrap();+ assert_eq!((selected.anchor, selected.focus), if reverse { (old_end, start) } else { (start, old_end) });+ assert!(selected.frame.is_some());+ let mut expected = s.doc().unwrap().selection.clone();+ let t = expected.text.as_mut().unwrap();+ (t.anchor, t.focus) = if reverse { (new_end, start) } else { (start, new_end) };+ let p = json!({"find": find, "change": change, "scope": "selection"});+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": old_end, "text": find}]));+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));+ let st = s.doc().unwrap();+ assert_eq!(st.doc.story(sid).unwrap().text, changed);+ assert_eq!(st.selection, expected);+ let t = st.selection.text.unwrap();+ assert!(changed.is_char_boundary(t.anchor) && changed.is_char_boundary(t.focus));+ assert!(s.find_context.is_none());+ let p = json!({"find": change, "scope": "selection"});+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": start, "end": new_end, "text": change}]));+ scope_hit(&mut s, &p, sid, start, new_end);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ }+ }+ }++ #[test]+ fn find_scope_change_repairs_final_boundaries_without_remapping_valid_offsets() {+ for (text, (a, b), find, change, changed, (after_a, after_b), count) in [+ ("aX", (1, 1), "a", "é", "éX", (0, 0), 1), // A caret stays collapsed and floors.+ ("aX", (2, 2), "a", "é", "éX", (2, 2), 1), // A valid caret stays at its byte offset.+ ("abc", (1, 2), "abc", "🙂", "🙂", (0, 4), 1), // Both endpoints need repair.+ ("abc", (2, 1), "abc", "🙂", "🙂", (4, 0), 1),+ ("é🙂", (2, 6), "🙂", "X", "éX", (2, 3), 1), // Existing shortening behavior.+ ("é🙂", (6, 2), "🙂", "X", "éX", (3, 2), 1),+ ("red", (0, 3), "red", "blue", "blue", (0, 3), 1), // Do not extend a valid upper bound.+ ("aX", (1, 2), "a", "zz", "zzX", (1, 2), 1), // Do not track the original X.+ ("aaX", (1, 2), "a", "é", "ééX", (0, 2), 2), // Per-edit repair would wrongly yield 0..4.+ ("aaX", (2, 3), "a", "é", "ééX", (2, 4), 2),+ ("abc", (1, 3), "abc", "", "", (0, 0), 1),+ ("abc", (2, 3), "abc", "é", "é", (2, 2), 1), // EOF clamp may collapse a nonempty range.+ ] {+ let (mut s, sid) = scope_session(text);+ scope_select(&mut s, sid, a, b);+ let mut expected = s.doc().unwrap().selection.clone();+ let t = expected.text.as_mut().unwrap();+ (t.anchor, t.focus) = (after_a, after_b);+ assert_eq!(s.execute("find.change", &json!({"find": find, "change": change, "scope": "document"})).unwrap(), json!({"count": count}));+ let st = s.doc().unwrap();+ assert_eq!(st.doc.story(sid).unwrap().text, changed, "{text} {a}->{b}");+ assert_eq!(st.selection, expected, "{text} {a}->{b}");+ assert!(changed.is_char_boundary(after_a) && changed.is_char_boundary(after_b));+ if after_a == after_b {+ assert_eq!(+ s.execute("find.find", &json!({"find": "(?:)", "grep": true, "scope": "selection"})).unwrap(),+ json!([{"story": sid.0, "start": after_a, "end": after_a, "text": ""}])+ );+ }+ }+ }++ #[test]+ fn find_scope_change_other_story_and_no_hits_preserve_selection() {+ for explicit in [false, true] {+ let (mut s, sid) = scope_session("éX");+ let frame = s.doc().unwrap().selection.text.unwrap().frame.unwrap();+ let other = s.execute("frame.create", &json!({"rect": [120, 36, 200, 100], "content": "text", "text": "a"})).unwrap();+ let other_sid = designcraft_doc::StoryId(other["story"].as_u64().unwrap());+ scope_select(&mut s, sid, 3, 2);+ let before = s.doc().unwrap().selection.clone();+ let mut p = json!({"find": "a", "change": "🙂", "scope": "document"});+ if explicit {+ p["story"] = json!(other_sid.0);+ }+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");+ assert_eq!(s.doc().unwrap().selection, before);+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 0}));+ assert_eq!(s.doc().unwrap().selection, before);+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "🙂");++ s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap();+ let before = s.doc().unwrap().selection.clone();+ assert!(before.text.is_none());+ p["find"] = json!("🙂");+ p["change"] = json!("é");+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));+ assert_eq!(s.doc().unwrap().selection, before);+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "éX");+ assert_eq!(s.doc().unwrap().doc.story(other_sid).unwrap().text, "é");+ }+ }++ #[test]+ fn find_scope_mixed_grep_matches_count_next_and_change() {+ for (text, pattern, expected, changed) in [+ ("a", "a*", vec![(0, 1)], "X"),+ ("aa", "a|(?:)", vec![(0, 1), (1, 2)], "XX"),+ ("ab", "a*", vec![(0, 1), (2, 2)], "XbX"),+ ("éa", "é|(?:)", vec![(0, 2), (3, 3)], "XaX"),+ ] {+ let (mut s, sid) = scope_session(text);+ scope_select(&mut s, sid, 0, text.len());+ let p = json!({"find": pattern, "grep": true, "scope": "selection", "change": "X"});+ let counted = s.execute("find.find", &p).unwrap();+ let ranges: Vec<_> =+ counted.as_array().unwrap().iter().map(|m| (m["start"].as_u64().unwrap() as usize, m["end"].as_u64().unwrap() as usize)).collect();+ assert_eq!(ranges, expected, "{pattern} on {text}");+ for (a, b) in &expected {+ scope_hit(&mut s, &p, sid, *a, *b);+ }+ for _ in 0..2 {+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "{pattern} on {text}");+ }+ assert_eq!(s.execute("find.find", &p).unwrap(), counted);+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], expected.len());+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, changed);+ }+ }++ #[test]+ fn find_scope_capture_replacement_and_first_keep_original_domain() {+ let (mut s, sid) = scope_session("a1 a2 | a3");+ scope_select(&mut s, sid, 0, 5);+ let p = json!({"find": r"a(\d)", "grep": true, "scope": "selection", "change": "b$1", "first": true});+ scope_hit(&mut s, &p, sid, 0, 2);+ scope_hit(&mut s, &p, sid, 3, 5);+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "b1 a2 | a3");+ }++ #[test]+ fn find_scope_selection_retains_nonempty_hits_count_change_and_native_text() {+ for (a, b) in [(0, 7), (7, 0)] {+ let (mut s, sid) = scope_session("red red | red");+ scope_select(&mut s, sid, a, b);+ let p = json!({"find": "red", "change": "blue", "scope": "selection", "attrs": {"fontStyle": "Italic"}});+ let before = s.doc().unwrap().doc.clone();+ let selection = s.doc().unwrap().selection.clone();+ let revision = s.doc().unwrap().revision;+ let history = s.doc().unwrap().history.undo.len();+ let strong = std::sync::Arc::strong_count(&before);+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);+ assert_eq!(s.doc().unwrap().selection, selection);+ assert_eq!(s.doc().unwrap().revision, revision);+ assert_eq!(std::sync::Arc::strong_count(&before), strong, "search stores weak document identity");+ scope_hit(&mut s, &p, sid, 0, 3);+ scope_hit(&mut s, &p, sid, 4, 7);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ assert_eq!(s.doc().unwrap().history.undo.len(), history);+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 2);+ let changed = s.doc().unwrap().doc.story(sid).unwrap().clone();+ assert_eq!(changed.text, "blue blue | red");+ assert_eq!(changed.char_format_at(0).over.font_style.as_deref(), Some("Italic"));+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);+ assert!(s.find_context.is_none());+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ assert!(s.find_context.is_none());+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap(), &changed);+ let native = s.execute("file.serialize", &json!({})).unwrap();+ s.execute("file.openBytes", &json!({"name": "scope.designcraft", "base64": native["base64"]})).unwrap();+ assert_eq!(serde_json::to_value(s.doc().unwrap().doc.story(sid).unwrap()).unwrap(), serde_json::to_value(&changed).unwrap());+ assert!(s.find_context.is_none());+ }+ }++ #[test]+ fn find_scope_matcher_restart_replacement_continuation_and_external_reselection() {+ let (mut s, sid) = scope_session("red blue red | blue red");+ scope_select(&mut s, sid, 0, 12);+ let mut p = json!({"find": "red", "scope": "selection", "change": "one"});+ scope_hit(&mut s, &p, sid, 0, 3);+ p["change"] = json!("two");+ p["attrs"] = json!({"fontStyle": "Italic"});+ scope_hit(&mut s, &p, sid, 9, 12);+ p["find"] = json!("blue");+ scope_hit(&mut s, &p, sid, 4, 8);+ p["find"] = json!("red");+ scope_hit(&mut s, &p, sid, 0, 3);+ p["caseSensitive"] = json!(true);+ scope_hit(&mut s, &p, sid, 0, 3);+ p["grep"] = json!(true);+ scope_hit(&mut s, &p, sid, 0, 3); // GREP alone changes matcher identity.+ p["find"] = json!("r.d");+ scope_hit(&mut s, &p, sid, 0, 3);+ p["wholeWord"] = json!(true);+ scope_hit(&mut s, &p, sid, 0, 3);+ let hit = s.doc().unwrap().selection.text.unwrap();+ scope_select(&mut s, sid, hit.anchor, hit.focus);+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1, "same-range external reselection starts a new domain");+ scope_hit(&mut s, &p, sid, 0, 3);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ scope_select(&mut s, sid, 20, 23);+ p["find"] = json!("red");+ scope_hit(&mut s, &p, sid, 20, 23);+ }++ #[test]+ fn find_scope_word_reselection_at_same_hit_recaptures_bounds() {+ let (mut s, sid) = scope_session("red red | red");+ scope_select(&mut s, sid, 0, 7);+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);+ scope_hit(&mut s, &p, sid, 0, 3);+ let selected = s.doc().unwrap().selection.clone();+ let frame = selected.text.unwrap().frame.unwrap();+ let point = {+ let st = s.doc().unwrap();+ let cs = s.cache.get(&st.doc, sid, None);+ let (fi, x, baseline, ascent, _) = designcraft_compose::caret(&cs, 1).unwrap();+ let inner = designcraft_geom::Point::new(x, baseline - ascent * 0.5);+ assert_eq!(cs.frames[fi].frame, frame);+ assert_eq!(designcraft_compose::hit(&cs, fi, inner), Some(1), "real point lies inside the current hit");+ let loc = st.doc.find(frame).unwrap();+ st.doc.parent_xf(&loc) * st.doc.text_xf(st.doc.item(frame).unwrap()) * inner+ };+ let before = s.doc().unwrap().doc.clone();+ let revision = s.doc().unwrap().revision;+ let history = s.doc().unwrap().history.undo.len();+ s.execute("text.selectWord", &json!({"frame": frame.0, "point": [point.x, point.y]})).unwrap();+ assert!(!s.text_drag, "explicit word reselection does not start a text drag");+ assert_eq!(s.doc().unwrap().selection, selected, "same full selection, including frame");+ assert!(s.doc().unwrap().revision > revision, "a new revision");+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ assert_eq!(s.doc().unwrap().history.undo.len(), history);+ assert!(s.find_context.is_none());+ assert_eq!(s.execute("find.find", &p).unwrap(), json!([{"story": sid.0, "start": 0, "end": 3, "text": "red"}]));+ assert_eq!(s.execute("find.change", &p).unwrap(), json!({"count": 1}));+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ assert_eq!(s.doc().unwrap().history.undo.len(), history + 1);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ s.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "blue red | red");+ }++ #[test]+ fn find_scope_story_explicit_story_document_order_and_scope_changes() {+ let (mut s, a) = scope_session("black red");+ let other = s.execute("frame.create", &json!({"rect": [150, 36, 100, 100], "content": "text", "text": "red"})).unwrap();+ let b = designcraft_doc::StoryId(other["story"].as_u64().unwrap());+ scope_select(&mut s, a, 0, 9);+ let story = json!({"find": "red", "scope": "story"});+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "Story does not enter B or wrap to its prefix");+ scope_select(&mut s, b, 0, 0);+ let explicit = json!({"find": "black", "story": a.0, "scope": "selection"});+ scope_hit(&mut s, &explicit, a, 0, 5);+ let selection = s.doc().unwrap().selection.clone();+ assert!(s.execute("find.next", &json!({"find": "red", "story": u64::MAX})).is_err());+ assert_eq!(s.doc().unwrap().selection, selection);+ scope_select(&mut s, a, 0, 9);+ scope_hit(&mut s, &json!({"find": "red"}), b, 0, 3);+ let counted = s.execute("find.find", &json!({"find": "red"})).unwrap();+ assert_eq!(counted[0]["story"], a.0, "Count retains canonical story order");+ assert_eq!(counted[1]["story"], b.0);+ scope_select(&mut s, a, 0, 9);+ scope_hit(&mut s, &json!({"find": "red", "scope": "selection"}), a, 6, 9);+ assert_eq!(s.execute("find.next", &story).unwrap(), serde_json::Value::Null, "scope change uses the current caret");+ s.execute("selection.set", &json!({"ids": []})).unwrap();+ for command in ["find.find", "find.next", "find.change"] {+ assert!(s.execute(command, &json!({"find": "red", "change": "blue", "scope": "selection"})).is_err());+ }+ }++ #[test]+ fn find_scope_substring_context_utf8_zero_width_and_invalid_ranges() {+ let (mut s, sid) = scope_session("scat é🙂 red");+ scope_select(&mut s, sid, 1, 4);+ let p = json!({"find": "cat", "wholeWord": true, "scope": "selection"});+ scope_hit(&mut s, &p, sid, 1, 4);+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);+ scope_select(&mut s, sid, 1, 4);+ let p = json!({"find": "^c|^a", "grep": true, "scope": "selection"});+ scope_hit(&mut s, &p, sid, 1, 2);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null, "cursor does not redefine ^");+ scope_select(&mut s, sid, 5, 11);+ let empty = json!({"find": "(?:)", "grep": true, "scope": "selection"});+ for pos in [5, 7, 11] {+ scope_hit(&mut s, &empty, sid, pos, pos);+ }+ for _ in 0..2 {+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);+ }+ assert_eq!(s.execute("find.find", &empty).unwrap().as_array().unwrap().len(), 3);+ scope_select(&mut s, sid, 7, 7);+ scope_hit(&mut s, &empty, sid, 7, 7);+ assert_eq!(s.execute("find.next", &empty).unwrap(), serde_json::Value::Null);+ scope_select(&mut s, sid, 12, 15);+ let nonempty = json!({"find": "red", "change": "blue", "scope": "selection"});+ scope_hit(&mut s, &nonempty, sid, 12, 15);+ assert_eq!(s.execute("find.change", &nonempty).unwrap()["count"], 1);+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "scat é🙂 blue");+ for range in [6..7, 0..usize::MAX] {+ let st = s.doc_mut().unwrap();+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel {+ story: sid,+ anchor: range.start,+ focus: range.end,+ frame: None,+ cell: None,+ });+ st.bump_revision();+ for command in ["find.find", "find.next", "find.change"] {+ let before = s.doc().unwrap().doc.clone();+ let err = s.execute(command, &json!({"find": "x", "change": "y", "scope": "selection"})).unwrap_err();+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ }+ }+ }++ #[test]+ fn find_scope_invalid_query_keeps_continuation_and_cross_boundary_nonmatches() {+ let (mut s, sid) = scope_session("red red | red");+ scope_select(&mut s, sid, 0, 7);+ let p = json!({"find": "red", "scope": "selection"});+ scope_hit(&mut s, &p, sid, 0, 3);+ let selected = s.doc().unwrap().selection.clone();+ assert!(s.execute("find.next", &json!({"find": "[", "grep": true, "scope": "selection"})).is_err());+ assert_eq!(s.doc().unwrap().selection, selected);+ scope_hit(&mut s, &p, sid, 4, 7);+ assert_eq!(s.execute("find.find", &json!({"find": "red |", "scope": "selection"})).unwrap(), json!([]));+ }++ #[test]+ fn find_scope_document_switch_edit_and_reset() {+ let (mut s, sid) = scope_session("red red | red");+ scope_select(&mut s, sid, 0, 7);+ let p = json!({"find": "red", "scope": "selection"});+ scope_hit(&mut s, &p, sid, 0, 3);+ s.execute("file.new", &json!({})).unwrap();+ s.set_active(0);+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);+ scope_select(&mut s, sid, 0, 7);+ scope_hit(&mut s, &p, sid, 0, 3);+ s.execute("story.setText", &json!({"story": sid.0, "text": "red"})).unwrap();+ assert!(s.find_context.is_none());+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);+ s.reset_find_scope();+ assert!(s.find_context.is_none());+ }++ #[test]+ fn find_scope_real_preview_restores_before_resolving_bounds() {+ let (mut s, sid) = scope_session("");+ s.execute(+ "data.source.select",+ &json!({+ "bytes": crate::cmd::base64_encode(b"x\nred red | red\n"), "name": "scope.csv"+ }),+ )+ .unwrap();+ s.execute("data.placeholder.add", &json!({"field": "x", "story": sid.0, "at": 0})).unwrap();+ let template = s.doc().unwrap().doc.clone();+ assert_eq!(template.story(sid).unwrap().text, "<<x>>");+ s.execute("data.preview", &json!({"record": 1})).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ // Install a viewport selection in the real preview. text.select is journaled+ // and would itself restore the template before selecting.+ let st = s.doc_mut().unwrap();+ st.selection = designcraft_doc::Selection::text(designcraft_doc::TextSel { story: sid, anchor: 0, focus: 7, frame: None, cell: None });+ st.bump_revision();+ let p = json!({"find": "red", "change": "blue", "scope": "selection"});+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 2);+ let history = s.doc().unwrap().history.undo.len();+ let err = s.execute("find.change", &p).unwrap_err();+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "<<x>>");+ assert_eq!(s.doc().unwrap().history.undo.len(), history);+ assert!(s.doc().unwrap().preview_stash.is_none());+ assert!(s.find_context.is_none());+ // Valid fresh bounds are allowed after restoration; no cached preview range+ // survives. A document query can see the preview, but Next sees the template.+ s.execute("data.preview", &json!({"record": 1})).unwrap();+ let document = json!({"find": "red"});+ assert_eq!(s.execute("find.find", &document).unwrap().as_array().unwrap().len(), 3);+ assert_eq!(s.execute("find.next", &document).unwrap(), serde_json::Value::Null);+ assert!(std::sync::Arc::ptr_eq(&template, &s.doc().unwrap().doc));+ assert_eq!(s.execute("find.find", &document).unwrap(), json!([]));+ assert_eq!(s.doc().unwrap().history.undo.len(), history);+ }++ fn child_scope_session(note: bool, child: &str) -> (Session, designcraft_doc::StoryId, designcraft_doc::TextSel) {+ let (mut s, sid) = scope_session("red");+ scope_select(&mut s, sid, 3, 3);+ if note {+ s.execute("footnote.insert", &json!({"text": child})).unwrap();+ } else {+ s.execute("table.insert", &json!({"rows": 1, "cols": 1})).unwrap();+ s.execute("text.insert", &json!({"text": child, "raw": true})).unwrap();+ }+ let selected = s.doc().unwrap().selection.text.unwrap();+ (s, sid, selected)+ }++ #[test]+ fn find_scope_children_error_atomically_and_parent_requests_stay_top_level() {+ for note in [false, true] {+ for child in ["red", "red x", "é red red red red red"] {+ let (mut s, sid, mut selected) = child_scope_session(note, child);+ selected.anchor = 0;+ selected.focus = child.len();+ s.doc_mut().unwrap().selection = designcraft_doc::Selection::text(selected);+ let before = s.doc().unwrap().doc.clone();+ let selection = s.doc().unwrap().selection.clone();+ let history = s.doc().unwrap().history.undo.len();+ let revision = s.doc().unwrap().revision;+ let journal = s.journal.clone();+ for scope in ["story", "selection"] {+ for command in ["find.find", "find.next", "find.change"] {+ let err = s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err();+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{err}");+ assert!(err.to_string().contains("not supported"));+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc));+ assert_eq!(s.doc().unwrap().selection, selection);+ assert_eq!(s.doc().unwrap().history.undo.len(), history);+ assert_eq!(s.doc().unwrap().revision, revision);+ assert_eq!(s.journal, journal);+ }+ }+ for explicit in [false, true] {+ let mut p = json!({"find": "red", "change": "blue"});+ if explicit {+ p["story"] = json!(sid.0);+ p["scope"] = json!("selection");+ }+ s.doc_mut().unwrap().selection = selection.clone();+ assert_eq!(s.execute("find.find", &p).unwrap().as_array().unwrap().len(), 1);+ scope_hit(&mut s, &p, sid, 0, 3);+ s.doc_mut().unwrap().selection = selection.clone();+ assert_eq!(s.execute("find.change", &p).unwrap()["count"], 1);+ assert_eq!(s.doc().unwrap().doc.text_story(sid, selected.cell).unwrap().text, child);+ assert_eq!(s.doc().unwrap().selection, selection, "parent replacement does not clamp child offsets");+ p["find"] = json!("blue");+ p["change"] = json!("red");+ s.execute("find.change", &p).unwrap();+ }+ }+ }+ let (mut s, _, _) = child_scope_session(false, "red");+ s.execute("table.selectTable", &json!({})).unwrap();+ for scope in ["story", "selection"] {+ for command in ["find.find", "find.next", "find.change"] {+ assert!(+ s.execute(command, &json!({"find": "red", "change": "blue", "scope": scope})).unwrap_err().to_string().contains("not supported")+ );+ }+ }+ }++ #[test]+ fn find_scope_threaded_overset_story_uses_logical_offsets() {+ let text = format!("{}red", "word ".repeat(100));+ let (mut s, sid) = scope_session(&text);+ let a = s.doc().unwrap().doc.story(sid).unwrap().frames[0];+ let next = s.execute("frame.create", &json!({"rect": [150, 36, 20, 1], "content": "text"})).unwrap();+ let b = designcraft_doc::ItemId(next["id"].as_u64().unwrap());+ s.edit(|d, _| Ok(d.thread(a, b)?)).unwrap();+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().frames.len(), 2);+ scope_select(&mut s, sid, 0, 0);+ scope_hit(&mut s, &json!({"find": "red", "scope": "story"}), sid, 500, 503);+ assert_eq!(s.execute("find.next", &json!({"find": "red", "scope": "story"})).unwrap(), serde_json::Value::Null);+ }++ #[test]+ fn find_scope_zero_width_story_explicit_and_document_endpoints_terminate() {+ for scope in ["story", "explicit", "document"] {+ let (mut s, sid) = scope_session("é🙂");+ scope_select(&mut s, sid, 0, 0);+ let mut p = json!({"find": "(?:)", "grep": true, "scope": scope});+ if scope == "explicit" {+ p["story"] = json!(sid.0);+ }+ for pos in [0, 2, 6] {+ scope_hit(&mut s, &p, sid, pos, pos);+ }+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ assert_eq!(s.execute("find.next", &p).unwrap(), serde_json::Value::Null);+ }+ }++ #[cfg(not(target_arch = "wasm32"))]+ #[test]+ fn find_scope_revert_releases_context_with_same_document_uid() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("scope.designcraft");+ let (mut s, sid) = scope_session("red red | red");+ s.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();+ scope_select(&mut s, sid, 0, 7);+ let p = json!({"find": "red", "scope": "selection"});+ scope_hit(&mut s, &p, sid, 0, 3);+ let uid = s.doc().unwrap().uid;+ s.execute("story.setText", &json!({"story": sid.0, "text": "red red"})).unwrap();+ scope_select(&mut s, sid, 0, 7);+ scope_hit(&mut s, &p, sid, 0, 3);+ s.execute("file.revert", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().uid, uid);+ assert!(s.find_context.is_none());+ assert_eq!(s.doc().unwrap().doc.story(sid).unwrap().text, "red red | red");+ assert!(s.execute("find.find", &p).is_err(), "revert's empty selection cannot inherit a previous range");+ }}/// Objects matching Find/Change › Object criteria, in document order (nested ones included).diff --cc crates/engine/src/cmd/fonts.rsindex 9a7444ed0,f119dd087..55bf4231b--- a/crates/engine/src/cmd/fonts.rs+++ b/crates/engine/src/cmd/fonts.rs@@@ -313,99 -225,22 +313,117 @@@ mod testsassert_eq!((&l[0]["family"], &l[0]["missing"]), (&json!("Nope (OTF)"), &json!(true)), "{l}");assert!(kinds(&mut s).iter().any(|k| k == "missingFont"));}++ /// A style name that differs only in spacing (Montilla Design's file sets `Regular ` with a+ /// trailing space) is the face the text is drawn in, not a missing style.+ #[test]+ fn a_style_with_extra_spacing_is_not_missing() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 4})).unwrap();+ s.execute("type.char", &json!({"fontFamily": "Source Serif 4", "fontStyle": "Regular "})).unwrap();+ let l = s.execute("font.list", &json!({})).unwrap();+ let entry = l.as_array().unwrap().iter().find(|f| f["style"] == "Regular ").unwrap();+ assert_eq!((&entry["missing"], &entry["styleMissing"]), (&json!(false), &json!(false)), "{l}");+ s.execute("type.char", &json!({"fontFamily": "Source Serif 4", "fontStyle": "Nope"})).unwrap();+ let l = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(l[0]["styleMissing"], json!(true), "{l}");+ }}++#[cfg(test)]+mod composite_tests {+ use super::*;+ use designcraft_doc::{+ ParaFormat,+ cjk::{CompositeFont, CompositeFontEntry},+ };++ #[test]+ fn inventory_resolves_composites_in_nested_cell_notes() {+ use designcraft_doc::{StoryId, Table, build::NewDocument};+ let mut d = Document::new(&NewDocument::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "1".into(), family: "Source Sans 3".into(), ..Default::default() },+ ],+ });+ let mut story = Story::new(StoryId(d.alloc()));+ let mut table = Table::new(1, 1, 1, 0, 0, 100.0);+ let cell = &mut table.cells[0].text;+ cell.insert_note(0, "1", ParaFormat::default());+ Arc::make_mut(&mut cell.notes[0]).text.format_chars(0..1, |f| f.over.font_family = Some("Mixed".into()));+ story.insert_table(0, table);+ d.stories.insert(story.id, Arc::new(story));+ let fonts = list(&d);+ assert!(fonts.iter().any(|f| f["family"] == "Source Sans 3" && f["characters"] == 1));+ assert!(!fonts.iter().any(|f| f["family"] == "Mixed"));+ }++ #[test]+ fn preflight_and_font_list_follow_used_composite_entries_in_notes() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect": [20,20,400,600], "content":"text", "text":"Body"})).unwrap();+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "1".into(), family: "Missing Note Digits".into(), ..Default::default() },+ CompositeFontEntry { characters: "2".into(), family: "Unused Missing Digits".into(), ..Default::default() },+ ],+ });+ let sid = *d.stories.keys().next().unwrap();+ let st = d.story_mut(sid).unwrap();+ st.insert_note(4, "A1", ParaFormat::default());+ Arc::make_mut(&mut st.notes[0]).text.format_chars(0..2, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let list = s.execute("font.list", &json!({})).unwrap();+ assert!(list.as_array().unwrap().iter().any(|f| f["family"] == "Missing Note Digits" && f["characters"] == 1));+ assert!(!list.to_string().contains("Unused Missing Digits"));+ let issues = s.execute("preflight.run", &json!({})).unwrap();+ let fonts: Vec<_> = issues["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "missingFont").collect();+ assert_eq!(fonts.len(), 1, "{issues}");+ assert!(fonts[0]["message"].as_str().unwrap().contains("Missing Note Digits"));+ s.execute("font.replace", &json!({"family":"Missing Note Digits", "toFamily":"Source Sans 3", "toStyle":"Regular"})).unwrap();+ let issues = s.execute("preflight.run", &json!({})).unwrap();+ assert!(issues["issues"].as_array().unwrap().iter().all(|i| i["kind"] != "missingFont"));+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].characters, "1");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].family, "Missing Note Digits");+ }+}++#[cfg(test)]+mod resolution_tests {+ use super::*;++ #[test]+ fn inventory_distinguishes_missing_styles_and_replacement_chooses_an_available_style() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect":[20,20,300,400],"content":"text","text":"Body"})).unwrap();+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.font_style = Some("Unavailable Style".into());+ });+ let before = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(before[0]["matchStatus"], "styleSubstitute");+ assert_eq!(before[0]["missing"], false);+ assert_eq!(before[0]["styleMissing"], true);+ assert_eq!(before[0]["resolvedStyle"], "Regular");+ let preflight = s.execute("preflight.run", &json!({})).unwrap();+ assert!(preflight["issues"].as_array().unwrap().iter().any(|i| i["kind"] == "missingFontStyle"));+ s.execute("font.replace", &json!({"family":"Source Sans 3","toFamily":"Source Serif 4"})).unwrap();+ let after = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(after[0]["matchStatus"], "exact");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(before, s.execute("font.list", &json!({})).unwrap());+ }+}diff --cc crates/engine/src/cmd/interchange.rsindex 39bf923be,d8daab858..d53905b54--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@@ -223,12 -222,11 +231,12 @@@ fn read_packaged_link(link: &str, dir:}pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {- let (bytes, dir, name) = if let Some(b) = str_param(p, "base64") {- (base64_decode(b), None, str_param(p, "name").map(|n| n.trim_end_matches(".idml").to_string()))+ let (bytes, dir, file, title) = if let Some(b) = str_param(p, "base64") {+ let name = str_param(p, "name").unwrap_or_default();+ (base64_decode(b), None, name.to_string(), without_document_extension(name).to_string())} else if let Some(path) = str_param(p, "path") {#[cfg(not(target_arch = "wasm32"))]- let b = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ let b = crate::io::read_file(path).map_err(EngineError::Other)?;#[cfg(target_arch = "wasm32")]let b: Vec<u8> = Vec::new();let pp = std::path::Path::new(path);diff --cc crates/engine/src/cmd/layout.rsindex 749932954,a241915e5..22c9f433b--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@@ -99,8 -107,8 +118,8 @@@ pub fn specs() -> Vec<CommandSpec>let count = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 9999) as usize;let st = s.doc()?;let n = st.doc.page_count();- let after = p.get("after").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(n - 1);+ let after = p.get("after").and_then(Value::as_u64).map(|v| usize::try_from(v).unwrap_or(usize::MAX)).unwrap_or(n.saturating_sub(1));- let parent = parent_ref(&st.doc, p.get("parent")).unwrap_or_else(|| st.doc.parents.first().map(|x| x.id));+ let parent = parent_ref("layout.pages.insert", &st.doc, p.get("parent"))?.unwrap_or_else(|| st.doc.parents.first().map(|x| x.id));s.edit(|d, _| {let ids = d.insert_pages(Some(after), count, parent)?;Ok(json!({"pages": ids.len(), "total": d.page_count()}))@@@ -997,213 -889,7 +997,217 @@@ fn document_setup(d: &designcraft_doc::let st = &d.settings;let start = d.sections.iter().find(|x| x.start == 0).and_then(|x| x.start_number).unwrap_or(1);json!({"width": st.page_width, "height": st.page_height, "pages": d.page_count(), "startPage": start, "facingPages": st.facing_pages,- "binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug})+ "binding": if st.right_to_left_binding { "rightToLeft" } else { "leftToRight" }, "intent": st.intent, "bleed": st.bleed, "slug": st.slug,+ "margins": d.page(0).map(|p| p.margins), "primaryTextFrame": st.primary_text_frame})+}++/// The largest chapter number (as for page numbers).+const MAX_CHAPTER: u64 = designcraft_doc::MAX_PAGE_NUMBER as u64;++/// A `layout.section` edit, checked before the document changes.+struct SectionEdit {+ /// Absolute index of the section's first page.+ start: usize,+ remove: bool,+ /// Some(None): continue from the previous section.+ start_number: Option<Option<u32>>,+ style: Option<designcraft_doc::NumberStyle>,+ prefix: Option<String>,+ include_prefix: Option<bool>,+ marker: Option<String>,+}++impl SectionEdit {+ fn parse(cmd: &str, s: &Session, p: &Value) -> Result<Self> {+ let page = p.get("page").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "missing page"))?;+ let n = s.doc()?.doc.page_count() as u64;+ if page == 0 || page > n {+ return Err(bad(cmd, format!("no page {page}")));+ }+ let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string);+ if prefix.as_ref().is_some_and(|x| x.chars().count() > 8 || x.contains(['+', ','])) {+ return Err(bad(cmd, "section prefix: up to 8 characters, without + or ,"));+ }+ let start_number = match p.get("startNumber") {+ None => None,+ Some(Value::Null) => Some(None),+ Some(v) => Some(Some(start_number(cmd, "startNumber", v)?)),+ };+ let style = match p.get("style") {+ None => None,+ Some(v) => match serde_json::from_value(v.clone()) {+ Ok(designcraft_doc::NumberStyle::Symbols) => return Err(bad(cmd, "symbols don't number pages")),+ Ok(style) => Some(style),+ Err(e) => return Err(bad(cmd, e.to_string())),+ },+ };+ Ok(SectionEdit {+ start: (page - 1) as usize,+ remove: p.get("remove").and_then(Value::as_bool).unwrap_or(false),+ start_number,+ style,+ prefix,+ include_prefix: p.get("includePrefix").and_then(Value::as_bool),+ marker: p.get("marker").and_then(Value::as_str).map(str::to_string),+ })+ }++ fn apply(&self, d: &mut designcraft_doc::Document) {+ let start = self.start;+ // Page 1 always starts a section.+ if self.remove && start != 0 {+ d.sections.retain(|x| x.start != start);++ // The pages after it follow the previous section's numbers again.++ d.repaginate();+ return;+ }+ let mut sec = d.sections.iter().find(|x| x.start == start).cloned().unwrap_or(designcraft_doc::Section {+ start,+ start_number: None,+ style: Default::default(),+ prefix: String::new(),+ marker: String::new(),+ include_prefix: false,+ });+ if let Some(n) = self.start_number {+ sec.start_number = n;+ }+ if let Some(style) = self.style {+ sec.style = style;+ }+ if let Some(prefix) = &self.prefix {+ sec.prefix = prefix.clone();+ }+ if let Some(on) = self.include_prefix {+ sec.include_prefix = on;+ }+ if let Some(marker) = &self.marker {+ sec.marker = marker.clone();+ }+ d.sections.retain(|x| x.start != start);+ d.sections.push(sec);+ d.sections.sort_by_key(|x| x.start);++ // Facing pages take their sides from their numbers: odd on the right.++ d.repaginate();+ }+}++/// A `layout.chapterNumbering` edit, checked before the document changes.+struct ChapterEdit {+ style: Option<designcraft_doc::NumberStyle>,+ source: Option<designcraft_doc::ChapterSource>,+ start: Option<u32>,+}++impl ChapterEdit {+ fn parse(cmd: &str, p: &Value) -> Result<Self> {+ let style = match p.get("style") {+ Some(v) => match serde_json::from_value::<designcraft_doc::NumberStyle>(v.clone()) {+ Ok(designcraft_doc::NumberStyle::Symbols) | Err(_) => return Err(bad(cmd, format!("unknown chapter style {v}"))),+ Ok(style) => Some(style),+ },+ None => None,+ };+ let mut source = match p.get("source") {+ Some(v) => Some(+ serde_json::from_value::<designcraft_doc::ChapterSource>(v.clone())+ .map_err(|_| bad(cmd, format!("unknown chapter number source {v}")))?,+ ),+ None => None,+ };+ let start = match p.get("start") {+ Some(v) => {+ Some(v.as_u64().filter(|n| (1..=MAX_CHAPTER).contains(n)).ok_or_else(|| bad(cmd, format!("chapter start: 1 to {MAX_CHAPTER}")))?+ as u32)+ }+ None => None,+ };+ // A start number alone means Start Chapter Numbering at.+ if start.is_some() && source.is_none() {+ source = Some(designcraft_doc::ChapterSource::UserDefined);+ }+ Ok(ChapterEdit { style, source, start })+ }++ fn apply(&self, d: &mut designcraft_doc::Document) {+ if let Some(style) = self.style {+ d.settings.chapter_style = style;+ }+ if let Some(source) = self.source {+ d.settings.chapter_source = source;+ }+ if let Some(n) = self.start {+ d.settings.chapter_number = n;+ }+ }+}++/// The active document's chapter numbering, and the open book that holds it (what+/// `layout.chapterNumbering {}` reports, read without running a command).+pub fn chapter_numbering(s: &Session) -> Result<Value> {+ let st = s.doc()?;+ let set = &st.doc.settings;+ let book = s+ .book+ .as_ref()+ .filter(|b| st.path.as_deref().is_some_and(|p| b.documents.iter().any(|d| std::path::Path::new(d) == std::path::Path::new(p))))+ .map(|b| std::path::Path::new(&b.path).file_stem().map_or_else(|| b.path.clone(), |n| n.to_string_lossy().to_string()));+ Ok(+ json!({"chapterNumber": set.chapter_number.max(1), "label": st.doc.chapter_label(), "style": set.chapter_style, "source": set.chapter_source, "book": book}),+ )+}++/// Layer Options: every field in one undo step; a bad name or colour changes nothing.+fn set_layer(s: &mut Session, p: &Value) -> Result<Value> {+ const ID: &str = "layer.set";+ let id = LayerId(p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(ID, "missing id"))?);+ let name = match p.get("name") {+ Some(v) => Some(v.as_str().map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(ID, "a layer needs a name"))?.to_string()),+ None => None,+ };+ let color: Option<[u8; 3]> = match p.get("color") {+ None => None,+ Some(Value::String(n)) => Some(+ LAYER_COLORS+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case(n))+ .map(|(_, c)| *c)+ .ok_or_else(|| bad(ID, format!("unknown layer colour `{n}`")))?,+ ),+ Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad(ID, "color is [r,g,b] (0–255) or a layer colour name"))?),+ };+ let flag = |k: &str| match p.get(k) {+ None => Ok(None),+ Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))),+ };+ let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?);+ let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?);+ s.edit(|d, _| {+ if let Some(n) = &name+ && d.layers.iter().any(|l| l.id != id && l.name == *n)+ {+ return Err(bad(ID, format!("a layer named `{n}` exists")));+ }+ let l = d.layer_mut(id).ok_or_else(|| bad(ID, "no such layer"))?;+ if let Some(n) = name {+ l.name = n;+ }+ if let Some(c) = color {+ l.color = c;+ }+ for (slot, v) in [+ (&mut l.visible, visible),+ (&mut l.locked, locked),+ (&mut l.printable, printable),+ (&mut l.show_guides, guides),+ (&mut l.suppress_wrap_when_hidden, wrap),+ ] {+ if let Some(v) = v {+ *slot = v;+ }+ }+ ok()+ })}#[cfg(test)]@@@ -1496,66 -1080,27 +1500,88 @@@ mod page_numbering_view_testsassert_eq!(s.resolve_page("9"), None);}+ #[test]+ fn section_start_numbers_are_bounded() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ for n in [json!(0), json!(100_000), json!(u32::MAX), json!(u64::from(u32::MAX) + 2), json!(-1), json!(2.5), json!("7")] {+ let e = s.execute("layout.section", &json!({"page": 1, "startNumber": n})).unwrap_err().to_string();+ assert!(e.contains("startNumber"), "{n}: {e}");+ assert!(s.execute("layout.documentSetup", &json!({"startPage": n})).is_err(), "{n}");+ }+ assert_eq!((0..2).map(|i| s.page_label(i)).collect::<Vec<_>>(), ["1", "2"]);+ let r = s.execute("layout.section", &json!({"page": 1, "startNumber": 99_999})).unwrap();+ assert_eq!(r["names"], json!(["99999", "100000"]));+ }++ #[test]+ fn numbering_options_apply_in_one_undo_step_or_not_at_all() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ let names = |s: &crate::Session| (0..4).map(|i| s.doc().unwrap().doc.page_name(i)).collect::<Vec<_>>();+ let r = s+ .execute(+ "layout.numberingOptions",+ &json!({"page": 3, "startNumber": 5, "style": "lowerRoman", "prefix": "A-", "includePrefix": true, "chapter": {"start": 4, "style": "upperRoman"}}),+ )+ .unwrap();+ assert_eq!((r["names"].clone(), r["chapter"].clone()), (json!(["1", "2", "A-v", "A-vi"]), json!("IV")));+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(names(&s), ["1", "2", "3", "4"], "one undo reverts the section…");+ assert_eq!(s.doc().unwrap().doc.chapter_label(), "1", "…and the chapter numbering");+ // A refused part leaves the other undone too.+ for bad in [+ json!({"page": 3, "startNumber": 5, "chapter": {"start": 100_000}}),+ json!({"page": 3, "startNumber": 4_294_967_295u64, "chapter": {"start": 2}}),+ json!({"page": 3, "prefix": "A+B", "chapter": {"start": 2}}),+ json!({"page": 9, "chapter": {"start": 2}}),+ ] {+ assert!(s.execute("layout.numberingOptions", &bad).is_err(), "{bad}");+ assert_eq!(names(&s), ["1", "2", "3", "4"], "{bad}");+ assert_eq!(s.doc().unwrap().doc.settings.chapter_source, designcraft_doc::ChapterSource::Automatic, "{bad}");+ }+ // Removing a section keeps the chapter part.+ s.execute("layout.section", &json!({"page": 3, "startNumber": 1})).unwrap();+ s.execute("layout.numberingOptions", &json!({"page": 3, "remove": true, "chapter": {"source": "userDefined", "start": 2}})).unwrap();+ assert_eq!(names(&s), ["1", "2", "3", "4"]);+ assert_eq!(s.doc().unwrap().doc.chapter_label(), "2");+ }++ #[test]+ fn section_prefixes_are_short_and_avoid_plus_and_comma() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ for prefix in ["A-", "Appendix", "§ 1"] {+ s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).unwrap();+ }+ for prefix in ["Appendix1", "A+", "1,2"] {+ assert!(s.execute("layout.section", &json!({"page": 2, "prefix": prefix})).is_err(), "{prefix}");+ }+ assert!(s.execute("layout.section", &json!({"page": 2, "style": "symbols"})).is_err());+ assert_eq!(s.doc().unwrap().doc.sections.iter().find(|x| x.start == 1).unwrap().prefix, "§ 1", "a refused prefix changes nothing");+ }+++ /// `layout.section` edits one named setting; the others stay as the section was (#717).+ #[test]+ fn updating_a_section_keeps_settings_the_command_does_not_name() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 4})).unwrap();+ s.execute(+ "layout.section",+ &json!({"page": 2, "startNumber": 1, "style": "lowerRoman", "prefix": "A-", "includePrefix": true, "marker": "First"}),+ )+ .unwrap();+ assert_eq!(s.page_label(1), "A-i");+ s.execute("layout.section", &json!({"page": 2, "marker": "Second"})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sec = d.sections.iter().find(|x| x.start == 1).expect("the page-2 section is still the only one there");+ assert_eq!(sec.marker, "Second");+ assert_eq!(sec.start_number, Some(1), "startNumber is kept");+ assert_eq!(sec.style, designcraft_doc::NumberStyle::LowerRoman, "style is kept");+ assert_eq!(sec.prefix, "A-", "prefix is kept");+ assert!(sec.include_prefix, "includePrefix is kept");+ assert_eq!(s.page_label(1), "A-i");+ }}#[cfg(test)]diff --cc crates/engine/src/cmd/links.rsindex ea472a7e7,8abe7b6c8..69c9d8073--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@@ -126,21 -123,6 +126,21 @@@ fn uses(d: &Document, aid: AssetId) ->out}+/// Whether an asset's linked file is gone ([`status`] "missing" without reading the file). An+/// asset can hold data while its file is missing: the document's preview of it.+pub fn link_missing(a: &designcraft_doc::Asset) -> bool {+ let Some(path) = &a.link else { return false };+ #[cfg(not(target_arch = "wasm32"))]+ {- std::fs::metadata(path).is_err()++ !crate::io::exists(path)+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = path;+ false+ }+}+/// Link status of an asset.pub fn status(a: &designcraft_doc::Asset) -> &'static str {let Some(path) = &a.link else { return "embedded" };diff --cc crates/engine/src/cmd/object.rsindex 825cb301c,066c82ae5..352ad0e39--- a/crates/engine/src/cmd/object.rs+++ b/crates/engine/src/cmd/object.rs@@@ -1066,8 -1085,14 +1067,14 @@@ fn transform_move(s: &mut Session, p: &if it.locked {continue;}- it.xf = Affine::translate((dx, dy)) * it.xf;+ it.xf = Affine::translate(v) * it.xf;}+ // An object dragged inside a Flex Layout takes the place it was dropped on.+ if !copy {+ for id in &ids {+ super::flex::drop_in_container(d, *id);+ }+ }Ok(json!({"moved": ids.len(), "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))})}@@@ -4982,81 -3465,56 +5030,114 @@@ mod ungroup_testsuse super::*;#[test]- fn creating_on_a_parent_spread_and_rejecting_unknown_spreads() {+ fn ungroup_leaves_frames_with_pasted_in_items_whole() {let mut s = Session::new();- s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();- let parent = json!({"kind": "parent", "index": 0});- let r = s.execute("frame.create", &json!({"spread": parent, "rect": [0, 0, 100, 100]})).unwrap();- let id = ItemId(r["id"].as_u64().unwrap());- assert_eq!(s.doc().unwrap().doc.find(id).unwrap().spread, SpreadRef::Parent(0));- s.execute("line.create", &json!({"spread": parent, "a": [0, 0], "b": [50, 50]})).unwrap();- assert_eq!(s.doc().unwrap().doc.parents[0].items.len(), 2);+ s.execute("file.new", &json!({})).unwrap();+ let id = |r: Value| ItemId(r["id"].as_u64().unwrap());+ let sq = id(s.execute("frame.create", &json!({"rect": [100, 100, 200, 200]})).unwrap());+ let ell = id(s.execute("frame.create", &json!({"rect": [90, 90, 210, 210], "shape": "ellipse"})).unwrap());+ s.execute("selection.set", &json!({"ids": [sq.0]})).unwrap();+ s.execute("edit.cut", &json!({})).unwrap();+ s.execute("selection.set", &json!({"ids": [ell.0]})).unwrap();+ s.execute("edit.pasteInto", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert_eq!(d.item(ell).unwrap().default_label(), "<ellipse>", "named by its shape, not <group>");+ // Ungroup: the frame keeps its content and stays selected.+ s.execute("object.ungroup", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(d.item(ell).unwrap().has_nested_items());+ assert_eq!(d.spreads[0].items.len(), 1);+ assert_eq!(s.doc().unwrap().selection.items, vec![ell]);+ // A real group with the frame in it still comes apart, the frame whole.+ let other = id(s.execute("frame.create", &json!({"rect": [300, 100, 400, 200]})).unwrap());+ s.execute("selection.set", &json!({"ids": [ell.0, other.0]})).unwrap();+ let g = id(s.execute("object.group", &json!({})).unwrap());+ assert_eq!(s.doc().unwrap().doc.item(g).unwrap().default_label(), "<group>");+ s.execute("object.ungroup", &json!({})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ assert!(d.item(g).is_none());+ assert!(d.item(ell).unwrap().has_nested_items());+ assert_eq!(s.doc().unwrap().selection.items.len(), 2);+ d.check().unwrap();+ }+}- // Each of these used to land on the first body page.- for bad in- [json!("A-Parent"), json!("0"), json!(-1), json!(1.5), json!({"kind": "master", "index": 0}), json!({"kind": "parent"}), json!([0])]- {- assert!(s.execute("frame.create", &json!({"spread": bad, "rect": [0, 0, 100, 100]})).is_err(), "frame.create spread {bad}");- assert!(s.execute("line.create", &json!({"spread": bad, "a": [0, 0], "b": [50, 50]})).is_err(), "line.create spread {bad}");+#[cfg(test)]+mod fixed_width_tests {+ use super::*;++ #[test]+ fn fixed_width_columns_set_the_frame_width() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "Hello"})).unwrap();+ let id = ItemId(r["id"].as_u64().unwrap());+ let p = json!({"ids": [id.0], "columns": 2, "gutter": 12, "inset": 0, "columnsKind": "fixedWidth", "columnWidth": 120});+ s.execute("object.textFrameOptions", &p).unwrap();+ let b = s.doc().unwrap().doc.item(id).unwrap().inner_bounds();+ assert!((b.width() - (2.0 * 120.0 + 12.0)).abs() < 1e-6, "{b:?}");+ assert!((b.x0 - 36.0).abs() < 1e-6 && (b.height() - 264.0).abs() < 1e-6, "{b:?}");+ // Widths beyond the largest page are refused and change nothing.+ for (k, v) in [("columnWidth", 1e9), ("columnWidth", -1.0), ("firstBaselineMin", 1e9)] {+ assert!(s.execute("object.textFrameOptions", &json!({"ids": [id.0], k: v})).is_err(), "{k} {v}");}- assert!(s.doc().unwrap().doc.spreads[0].items.is_empty());+ assert!((s.doc().unwrap().doc.item(id).unwrap().inner_bounds().width() - 252.0).abs() < 1e-6);+ }+}++#[cfg(test)]+mod glow_feather_options_tests {+ use serde_json::json;++ #[test]+ fn glow_mode_technique_and_feather_options_are_kept() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute(+ "object.effects",+ &json!({"ids": [id], "effects": {"innerGlow": {"on": true, "mode": "Multiply", "technique": "precise"}, "feather": 4.5, "featherOptions": {"choke": 140, "corners": "sharp"}}}),+ )+ .unwrap();+ let e = s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().effects.clone();+ assert_eq!((e.inner_glow.mode, e.inner_glow.technique), (designcraft_color::BlendMode::Multiply, designcraft_doc::GlowTechnique::Precise));+ assert_eq!((e.feather_options.choke, e.feather_options.corners), (100.0, designcraft_doc::FeatherCorners::Sharp), "choke is a percentage");+ // InDesign's defaults: Screen and Softer; Diffused corners, no choke.+ let d = designcraft_doc::Effects::default();+ assert_eq!((d.inner_glow.mode, d.inner_glow.technique), (designcraft_color::BlendMode::Screen, designcraft_doc::GlowTechnique::Softer));+ assert_eq!((d.feather_options.choke, d.feather_options.corners), (0.0, designcraft_doc::FeatherCorners::Diffused));}}++ #[cfg(test)]+ mod fill_tint_tests {+ use super::*;++ #[test]+ fn a_tint_alone_keeps_each_objects_own_swatch() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let a = s.execute("frame.create", &json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("frame.create", &json!({"rect": [136, 36, 200, 100]})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.fill", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();+ s.execute("object.fill", &json!({"ids": [b], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();+ s.execute("object.fill", &json!({"ids": [a, b], "tint": 0.4})).unwrap();+ let fill_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().fill.clone();+ assert_eq!((fill_of(&s, a).swatch.as_str(), fill_of(&s, a).tint), ("C=100 M=0 Y=0 K=0", 0.4));+ assert_eq!((fill_of(&s, b).swatch.as_str(), fill_of(&s, b).tint), ("C=0 M=100 Y=0 K=0", 0.4));+ // A swatch without a tint is at 100 %, as before.+ s.execute("object.fill", &json!({"ids": [a], "swatch": "[Black]"})).unwrap();+ assert_eq!(fill_of(&s, a).tint, 1.0);+ // Neither, or a tint out of range: refused.+ assert!(s.execute("object.fill", &json!({"ids": [a]})).is_err());+ assert!(s.execute("object.fill", &json!({"ids": [a], "tint": 2})).is_err());+ assert!(s.execute("object.fill", &json!({"ids": [a], "tint": "x"})).is_err());+ // A stroke tint alone: stroked objects take it, an object without a stroke keeps none.+ s.execute("object.stroke", &json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0", "weight": 2})).unwrap();+ s.execute("object.stroke", &json!({"ids": [b], "swatch": "[None]"})).unwrap();+ s.execute("object.stroke", &json!({"ids": [a, b], "tint": 0.5})).unwrap();+ let stroke_of = |s: &Session, id: u64| s.doc().unwrap().doc.item(ItemId(id)).unwrap().stroke.clone();+ assert_eq!((stroke_of(&s, a).swatch.as_str(), stroke_of(&s, a).tint, stroke_of(&s, a).weight), ("C=100 M=0 Y=0 K=0", 0.5, 2.0));+ assert!(stroke_of(&s, b).is_none());+ }+ }diff --cc crates/engine/src/cmd/scripts.rsindex d4a03606b,1719f5e3e..0a891ee4a--- a/crates/engine/src/cmd/scripts.rs+++ b/crates/engine/src/cmd/scripts.rs@@@ -8,17 -10,23 +10,25 @@@ use crate::Resultfn run(s: &mut crate::Session, p: &Value) -> Result<Value> {let text = str_param(p, "text").ok_or_else(|| bad("script.run", "`text` required"))?;let steps = crate::script::parse(text).map_err(|e| bad("script.run", e))?;- // The steps' own undo entries collapse into this command's single one. A step that fails- // rolls the successful prefix back (document, selection and history), so a half-run script- // never strands edits that can't be undone (#709).+ // The steps record undo entries of their own while the script runs (one of them may be- // Undo); they collapse into this command's single one.++ // Undo); they collapse into this command's single one. A step that fails rolls the++ // successful prefix back (document, selection and history), so a half-run script never++ // strands edits that can't be undone (#709).+ s.in_undo_step = false;- let uid = s.active().map(|d| d.uid);- let before = s.active().map_or(0, |d| d.history.undo.len());+ let before = s.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.history.clone()));let report = s.run_script(&steps);if let Some(st) = s.active_mut()- && Some(st.uid) == uid- && st.history.undo.len() > before+ && let Some((uid, doc, selection, history)) = &before+ && st.uid == *uid{- st.history.undo.truncate(before);+ if report.failed.is_some() {+ st.doc = Arc::clone(doc);+ st.selection = selection.clone();+ st.history = history.clone();+ st.bump_revision();+ } else if st.history.undo.len() > history.undo.len() {+ st.history.undo.truncate(history.undo.len());+ }}let out = json!({"results": report.results, "steps": steps.len()});match report.failed {diff --cc crates/engine/src/cmd/style.rsindex 04ed1e53a,1cccc7fd1..7e04bb676--- a/crates/engine/src/cmd/style.rs+++ b/crates/engine/src/cmd/style.rs@@@ -628,37 -518,42 +628,58 @@@ fn edit_para(s: &mut Session, p: &Value/// Rename a paragraph or character style everywhere it's used.fn rename_style(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) {+ if para {+ for s in &mut d.styles_mut().paragraph {+ if s.name == from {+ s.name = to.to_string();+ }+ }+ } else {+ for s in &mut d.styles_mut().character {+ if s.name == from {+ s.name = to.to_string();+ }+ }+ }+ redirect_style_refs(d, para, from, to);+ }++ /// Point every reference to style `from` at `to`, except the style's own registry entry (its+ /// `name` field) — shared by renaming (which also updates the entry's name) and deletion (which+ /// instead removes the entry, after its former uses point at the replacement).+ fn redirect_style_refs(d: &mut designcraft_doc::Document, para: bool, from: &str, to: &str) {+ let rename = |r: &mut String| {+ if r == from {+ *r = to.to_string();+ }+ };let st = d.styles_mut();+ // A style is never based on itself: when `to` was based on `from`, it takes `from`'s parent.+ let parent_of = |based_on: Option<&String>| based_on.filter(|b| b.as_str() != to).cloned();if para {+ let from_parent = parent_of(st.paragraph.iter().find(|x| x.name == from).and_then(|x| x.based_on.as_ref()));for s in &mut st.paragraph {- if s.name == from {- s.name = to.to_string();+ if s.based_on.as_deref() == Some(from) {+ s.based_on = if s.name == to { from_parent.clone() } else { Some(to.to_string()) };}- for r in [&mut s.based_on, &mut s.next_style] {- if r.as_deref() == Some(from) {- *r = Some(to.to_string());- }+ if s.next_style.as_deref() == Some(from) {+ s.next_style = Some(to.to_string());}}- for o in &mut st.object {- if o.paragraph_style.as_deref() == Some(from) {- o.paragraph_style = Some(to.to_string());+ let objects = st.object.iter_mut().map(|o| &mut o.paragraph_style);+ for r in objects.chain(st.cell.iter_mut().map(|c| &mut c.paragraph_style)) {+ if r.as_deref() == Some(from) {+ *r = Some(to.to_string());+ }+ }+ rename(&mut st.default_paragraph);+ let (fo, eo) = (&mut d.footnote_options, &mut d.endnote_options);+ [&mut fo.para_style, &mut eo.para_style, &mut eo.heading_style].into_iter().for_each(rename);+ d.toc.iter_mut().flat_map(|t| t.entries.iter_mut().map(|e| &mut e.style)).for_each(rename);+ for t in d.toc.iter_mut() {+ let formats = t.entries.iter_mut().map(|e| &mut e.entry_style).chain([&mut t.title_style]);+ for r in formats.filter(|r| r.as_deref() == Some(from)) {+ *r = Some(to.to_string());}}} else {@@@ -744,62 -640,23 +766,62 @@@ fn group_styles(s: &mut Session, p: &Va}fn delete_para(s: &mut Session, p: &Value) -> Result<Value> {- let name = str_param(p, "name").filter(|n| !n.is_empty()).ok_or_else(|| bad("style.paragraph.delete", "missing name"))?.to_string();- let repl = str_param(p, "replaceWith").unwrap_or(designcraft_doc::BASIC_PARAGRAPH).to_string();+ delete_style(s, p, true)+}++fn delete_char(s: &mut Session, p: &Value) -> Result<Value> {+ delete_style(s, p, false)+}++/// Delete a paragraph (`para`) or character style; everything that used it uses `replaceWith`+/// (default [Basic Paragraph] or [None]) instead, in one undo step.+fn delete_style(s: &mut Session, p: &Value, para: bool) -> Result<Value> {+ let (id, default) =+ if para { ("style.paragraph.delete", designcraft_doc::BASIC_PARAGRAPH) } else { ("style.character.delete", designcraft_doc::NO_CHAR_STYLE) };+ let name = str_param(p, "name").filter(|n| !n.is_empty()).ok_or_else(|| bad(id, "missing name"))?.to_string();+ let repl = str_param(p, "replaceWith").unwrap_or(default).to_string();if name.starts_with('[') {- return Err(bad("style.paragraph.delete", "built-in styles can't be deleted"));+ return Err(bad(id, "built-in styles can't be deleted"));}if repl == name {- return Err(bad(id, "a style can't be replaced with itself"));- return Err(bad("style.paragraph.delete", "`replaceWith` can't be the deleted style"));++ return Err(bad(id, "`replaceWith` can't be the deleted style"));}s.edit(|d, _| {- if d.styles.para(&name).is_none() {- return Err(bad("style.paragraph.delete", format!("no paragraph style `{name}`")));- }- if d.styles.para(&repl).is_none() {- return Err(bad("style.paragraph.delete", format!("no paragraph style `{repl}`")));+ let st = &d.styles;+ let exists = |n: &str| if para { st.para(n).is_some() } else { n == designcraft_doc::NO_CHAR_STYLE || st.char_style(n).is_some() };+ if !exists(&name) {+ return Err(bad(id, format!("no style `{name}`")));+ }+ if !exists(&repl) {+ return Err(bad(id, format!("no style `{repl}` to replace it with")));+ }+ // The deleted style's children are based on the replacement, or on the deleted style's+ // own parent when the replacement descends from it (so no based-on chain loops).+ let (own_parent, descends) = if para {+ (st.para(&name).and_then(|x| x.based_on.clone()), st.para_based_on_cycles(&name, &repl))+ } else {+ (st.char_style(&name).and_then(|x| x.based_on.clone()), st.char_based_on_cycles(&name, &repl))+ };+ let parent = if descends {+ own_parent.filter(|b| *b != name)+ } else if repl == designcraft_doc::NO_CHAR_STYLE || repl == designcraft_doc::NO_PARA_STYLE {+ None+ } else {+ Some(repl.clone())+ };+ let st = d.styles_mut();+ let based = if para {+ st.paragraph.retain(|x| x.name != name);+ st.paragraph.iter_mut().map(|x| &mut x.based_on).collect::<Vec<_>>()+ } else {+ st.character.retain(|x| x.name != name);+ st.character.iter_mut().map(|x| &mut x.based_on).collect()+ };+ for b in based.into_iter().filter(|b| b.as_deref() == Some(name.as_str())) {+ *b = parent.clone();}- redirect_style_refs(d, true, &name, &repl);- d.styles_mut().paragraph.retain(|x| x.name != name);+ // Every other use: styles, stories, table cells, nested and GREP styles, notes, defaults.+ rename_style(d, para, &name, &repl);ok()})}@@@ -998,24 -801,20 +1020,24 @@@ pub fn parse_color(v: &Value) -> Optionuse designcraft_color::Color;match v {Value::String(s) => Color::from_hex(s),+ // `{model, …}` is the colour's own form (as `color.convert` takes it): fractions, never guessed.+ Value::Object(o) if o.contains_key("model") => model_color(v),- // One scale per colour, not per component: {c: 0.7, y: 12.2} is C 0.7 %, Y 12.2 %. Only a colour whose+ // One scale per colour, not per component: [1, 128, 255] is 0..255. Only an RGB array whose// components are all within 0..1 is read as fractions (the older form).Value::Array(a) if a.len() >= 3 => {let v = [a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?];let scale = if v.iter().any(|&x| x > 1.0) { 255.0 } else { 1.0 };Some(Color::rgb((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32))}- // `{model, …}` is the colour's own form (as `color.convert` takes and returns it): fractions.- Value::Object(o) if o.contains_key("model") => serde_json::from_value(v.clone()).ok(),+ // Bare CMYK is always 0..100, as documented: C 1 % is a real tint, so values of 1 or less can't+ // mean fractions (#910).Value::Object(o) => {+ if o.contains_key("gray") {+ let gray = o.get("gray").and_then(Value::as_f64)?;+ return Some(Color::gray(if gray > 1.0 { gray / 100.0 } else { gray } as f32));+ }- let g = |k: &str| o.get(k).and_then(Value::as_f64);- let v = [g("c")?, g("m")?, g("y")?, g("k")?];- let scale = if v.iter().any(|&x| x > 1.0) { 100.0 } else { 1.0 };- Some(Color::cmyk((v[0] / scale) as f32, (v[1] / scale) as f32, (v[2] / scale) as f32, (v[3] / scale) as f32))+ let g = |k: &str| o.get(k).and_then(Value::as_f64).map(|x| (x / 100.0) as f32);+ Some(Color::cmyk(g("c")?, g("m")?, g("y")?, g("k")?))}_ => None,}@@@ -1938,51 -1555,35 +1956,80 @@@ mod color_testsassert!((r - 1.0 / 255.0).abs() < 1e-6 && (g - 128.0 / 255.0).abs() < 1e-6 && (b - 1.0).abs() < 1e-6);}+ /// #910: `{c: 1, m: 0, y: 0, k: 0}` is a 1 % cyan tint, not solid cyan, though every component is within 0..1.+ #[test]+ fn cmyk_percentages_of_one_or_less_stay_percent() {+ use designcraft_color::Color;+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute("swatch.create", &json!({"name": "Tint1", "color": {"c": 1, "m": 0, "y": 0, "k": 0}})).unwrap();+ s.execute("object.fill", &json!({"ids": [id], "swatch": "Tint1"})).unwrap();+ let d = &s.doc().unwrap().doc;+ let Some(Color::Cmyk { c, m, y, k }) = d.resolve_color("Tint1", 1.0) else { panic!("not CMYK") };+ assert!((c - 0.01).abs() < 1e-6 && m == 0.0 && y == 0.0 && k == 0.0, "got {c} {m} {y} {k}");+ let pdf = designcraft_pdf::export_pdf(d, &s.cache, &designcraft_pdf::PdfOptions { compress: false, ..Default::default() }).unwrap();+ let text = String::from_utf8_lossy(&pdf);+ // Operands of every `k` (DeviceCMYK fill), last first: [k, y, m, c]. Inks are written in 1/255 steps (C 1 % is 3/255).+ let fills: Vec<Vec<f32>> =+ text.split(" k ").filter_map(|before| before.rsplit(' ').take(4).map(|x| x.parse().ok()).collect::<Option<Vec<f32>>>()).collect();+ let cyan = |want: f32| fills.iter().any(|f| (f[3] - want).abs() < 0.5 / 255.0 + 1e-6 && f[..3] == [0.0; 3]);+ assert!(cyan(0.01), "C 1 % in the PDF: {fills:?}");+ assert!(!cyan(1.0), "no solid cyan: {fills:?}");+ // A light tint whose components are all 1 or less, through object.color.+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ s.execute("object.color", &json!({"color": {"c": 0.5, "m": 0.5, "y": 0, "k": 0}})).unwrap();+ let d = &s.doc().unwrap().doc;+ let fill = &d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch;+ let Some(Color::Cmyk { c, m, .. }) = d.resolve_color(fill, 1.0) else { panic!("not CMYK") };+ assert!((c - 0.005).abs() < 1e-6 && (m - 0.005).abs() < 1e-6, "got {c} {m}");+ }++ #[test]+ fn a_colour_with_a_model_is_read_as_fractions_without_guessing() {+ use designcraft_color::Color;+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let fill = |s: &Session| {+ let d = &s.doc().unwrap().doc;+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()+ };+ // M 1 % from the Color panel: not M 100 % (magenta), though every component is within 0..1.+ s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0, "m": 0.01, "y": 0, "k": 0}})).unwrap();+ let Color::Cmyk { c, m, y, k } = fill(&s) else { panic!("not CMYK") };+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && y == 0.0 && k == 0.0, "got {c} {m} {y} {k}");+ // R 1 of 255 is a near black, not pure red.+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 1.0 / 255.0, "g": 0, "b": 0}})).unwrap();+ let Color::Rgb { r, g, b } = fill(&s) else { panic!("not RGB") };+ assert!((r - 1.0 / 255.0).abs() < 1e-6 && g == 0.0 && b == 0.0, "got {r} {g} {b}");+ // Out of range or not a model: refused rather than guessed.+ assert!(s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0, "m": 50, "y": 0, "k": 0}})).is_err());+ assert!(s.execute("object.color", &json!({"color": {"model": "hsb", "h": 0, "s": 0, "b": 0}})).is_err());+ }++ #[test]+ fn colours_that_round_to_the_same_name_share_one_swatch() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 50, 50]})).unwrap()["id"].as_u64().unwrap();+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let n = |s: &Session| s.doc().unwrap().doc.swatches.len();+ let first = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": 0.5, "y": 1, "k": 0}})).unwrap();+ let before = n(&s);+ for m in [0.501, 0.499, 0.5041] {+ let r = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": m, "y": 1, "k": 0}})).unwrap();+ assert_eq!(r["swatch"], first["swatch"], "M {m}");+ }+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 0.5, "g": 0.25, "b": 0}})).unwrap();+ s.execute("object.color", &json!({"color": {"model": "rgb", "r": 0.5005, "g": 0.25, "b": 0}})).unwrap();+ assert_eq!(n(&s), before + 1, "no hidden twins for values a fraction of a step apart");+ // A whole percent apart is a different colour.+ let r = s.execute("object.color", &json!({"color": {"model": "cmyk", "c": 0.1, "m": 0.51, "y": 1, "k": 0}})).unwrap();+ assert_eq!(r["swatch"], "C=10 M=51 Y=100 K=0");+ }+#[test]fn style_groups_rename_every_use() {let mut s = Session::new();@@@ -2895,83 -2085,24 +2942,99 @@@ mod radial_gradient_testslet (c, side, top) = sides(&r.render_page(&d, &p.cache, 0, 1.0, false, &Default::default()).unwrap());assert!(c < 30 && side > 220 && top > 220, "pdf: centre {c}, side {side}, top {top}");}++ #[test]+ fn a_box_with_no_height_or_width_has_a_circle_across_its_length() {+ let f = designcraft_doc::Fill::swatch("g");+ let line = designcraft_geom::Rect::new(20.0, 60.0, 180.0, 60.0);+ let (c, rx, ry) = f.radial_ellipse(line);+ assert_eq!((c.x, c.y, rx, ry), (100.0, 60.0, 80.0, 80.0));+ let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(10.0, 0.0, 10.0, 50.0));+ assert_eq!((rx, ry), (25.0, 25.0));+ // A point: a tiny circle, never a zero radius.+ let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(5.0, 5.0, 5.0, 5.0));+ assert!(rx > 0.0 && rx == ry);+ // A box keeps its ellipse.+ let (_, rx, ry) = f.radial_ellipse(designcraft_geom::Rect::new(0.0, 0.0, 100.0, 200.0));+ assert_eq!((rx, ry), (50.0, 100.0));+ }}+#[cfg(test)]+mod gradient_swatch_tests {+ use designcraft_color::SwatchValue;+ use serde_json::json;++ fn doc() -> crate::Session {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s+ }++ #[test]+ fn a_gradient_swatch_from_colour_swatches() {+ let mut s = doc();+ // As the Gradient panel's stops take swatches dragged onto them.+ let r = s+ .execute(+ "swatch.create",+ &json!({"gradient": {"stops": [{"location": 100, "swatch": "C=100 M=0 Y=0 K=0"}, {"location": 0, "swatch": "C=0 M=100 Y=0 K=0"}]}}),+ )+ .unwrap();+ assert_eq!(r["name"], "New Gradient Swatch");+ let d = &s.doc().unwrap().doc;+ let w = d.swatch("New Gradient Swatch").unwrap();+ assert!(w.named && !w.hidden);+ let SwatchValue::Gradient { gradient } = &w.value else { panic!("{w:?}") };+ assert_eq!(gradient.stops[0].color, d.resolve_color("C=0 M=100 Y=0 K=0", 1.0).unwrap(), "sorted: magenta first");+ assert_eq!(gradient.stops[1].color, d.resolve_color("C=100 M=0 Y=0 K=0", 1.0).unwrap());+ // A second one gets its own name; bad stops are refused.+ let r = s+ .execute(+ "swatch.create",+ &json!({"gradient": {"kind": "radial", "stops": [{"color": "#ff0000"}, {"location": 100, "color": "#0000ff"}]}}),+ )+ .unwrap();+ assert_eq!(r["name"], "New Gradient Swatch 2");+ for bad in [+ json!({"stops": [{"swatch": "C=0 M=100 Y=0 K=0"}]}),+ json!({"stops": [{"swatch": "Nope"}, {"swatch": "[Black]"}]}),+ json!({"stops": [{"swatch": "New Gradient Swatch"}, {"swatch": "[Black]"}]}),+ json!({"kind": "conic", "stops": [{"color": "#000000"}, {"color": "#ffffff"}]}),+ ] {+ assert!(s.execute("swatch.create", &json!({"gradient": bad})).is_err(), "{bad}");+ }+ }++ #[test]+ fn new_swatch_names_the_selections_gradient_or_duplicates_a_swatch() {+ let mut s = doc();+ let id = s.execute("frame.create", &json!({"rect": [0, 0, 100, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ // A gradient made in the Gradient panel is unnamed (and not listed) …+ s.execute("object.gradient", &json!({"ids": [id], "stops": [{"location": 0, "color": {"c": 0, "m": 100, "y": 0, "k": 0}}, {"location": 100, "color": {"c": 100, "m": 0, "y": 0, "k": 0}}]})).unwrap();+ let fill = |s: &crate::Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch.clone();+ assert!(s.doc().unwrap().doc.swatch(&fill(&s)).unwrap().hidden);+ // … until New Swatch: "New Gradient Swatch", listed, still the object's fill.+ s.execute("selection.set", &json!({"ids": [id]})).unwrap();+ assert_eq!(s.execute("swatch.new", &json!({})).unwrap()["name"], "New Gradient Swatch");+ assert_eq!(fill(&s), "New Gradient Swatch");+ let w = s.doc().unwrap().doc.swatch("New Gradient Swatch").unwrap().clone();+ assert!(w.named && !w.hidden && matches!(w.value, SwatchValue::Gradient { .. }));+ // A named swatch: a copy.+ assert_eq!(s.execute("swatch.new", &json!({})).unwrap()["name"], "New Gradient Swatch copy");+ assert_eq!(s.execute("swatch.new", &json!({"swatch": "C=100 M=0 Y=0 K=0"})).unwrap()["name"], "C=100 M=0 Y=0 K=0 copy");+ assert!(s.execute("swatch.new", &json!({"swatch": "[None]"})).is_err());+ // The stroke in front: the stroke's swatch.+ s.execute("object.stroke", &json!({"ids": [id], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();+ assert_eq!(s.execute("swatch.new", &json!({"target": "stroke"})).unwrap()["name"], "C=100 M=0 Y=0 K=0 copy 2");+ // Nothing selected, no swatch given: a new colour swatch.+ s.execute("edit.deselectAll", &json!({})).unwrap();+ let n = s.execute("swatch.new", &json!({})).unwrap()["name"].as_str().unwrap().to_string();+ let w = s.doc().unwrap().doc.swatch(&n).unwrap();+ assert!(w.named && !w.hidden && matches!(w.value, SwatchValue::Color { .. }), "{w:?}");+ }+}+#[cfg(test)]mod gradient_stroke_tests {use serde_json::json;diff --cc crates/engine/src/cmd/text.rsindex ea8d60ffb,2b34bb484..3205530a9--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -326,15 -300,17 +344,25 @@@ pub fn specs() -> Vec<CommandSpec>has_text_or_frames,break_link),- cmd!(query "type.selectionAttrs", "Selection Attributes", [], None, "{} → resolved character/paragraph attributes at the text selection, and its start as `selectedText` (one line, up to 60 characters)", has_doc, selection_attrs),+ cmd!(+ query "type.selectionAttrs",+ "Selection Attributes",+ [],+ None,+ "{mixed?: bool} → resolved character/paragraph attributes at the text selection; with mixed, paraMixed lists the paragraph attributes that differ across the selected paragraphs; the selection's start as `selectedText` (one line, up to 60 characters)",+ has_doc,+ selection_attrs+ ),+ cmd!(query "type.openTypeFeatures", "OpenType Features", [], None, "{} → the OpenType features and stylistic sets the selected text's fonts offer, each with its applied and available state (none, some or all of the selection)", has_doc, open_type_features),+ cmd!(+ "type.feature",+ "Set OpenType Features",+ [],+ None,+ "{features: {tag: true|false, …}} — turns OpenType features on or off across the selected text, keeping each run's other features",+ has_doc,+ set_features+ ),]}@@@ -612,8 -587,7 +646,8 @@@ fn insert(s: &mut Session, p: &Value) -if tracking && t.cell.is_none() {// Track Changes: the replaced text is marked deleted, the typing inserted after it.let at = super::changes::mark_deleted(st, r.clone());+ reserve_command_text(st, text.len())?;- let mut fmt = st.char_format_at(at).clone();+ let mut fmt = st.insert_format_at(at).clone();if let Some(f) = &typing {apply_typing_format(&mut fmt, f);}@@@ -1018,322 -1044,26 +1108,330 @@@ fn warichu_cmd(s: &mut Session, p: &Valformat_chars(s, &Value::Object(body))}-pub(crate) fn validate_char_fill(document: &designcraft_doc::Document, attrs: &CharAttrs, command_id: &str) -> Result<()> {- if let Some(fill) = &attrs.fill- && document.swatch(fill).is_none()+// Kenten, shatai, auto tate-chu-yoko and grid settings: validated settings for the CJK commands.++/// Longest font, style or swatch name taken from parameters, in characters.+const NAME_MAX_CHARS: usize = 256;++/// A number parameter: absent or `null` → `None`; anything but a finite number is an error.+fn finite_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v.as_f64().filter(|v| v.is_finite()).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite number"))),+ }+}++/// A text parameter, cut to `max` characters: absent or `null` → `None`; not text is an error.+fn text_param(p: &Value, key: &str, cmd: &str, max: usize) -> Result<Option<String>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(t)) => Ok(Some(t.chars().take(max).collect())),+ Some(_) => Err(bad(cmd, format!("`{key}` must be text"))),+ }+}++/// A boolean parameter: absent or `null` → `None`; not a boolean is an error.+fn bool_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))),+ }+}++/// An enumeration parameter checked against `T`, as its JSON value.+fn enum_param<T: serde::de::DeserializeOwned + serde::Serialize>(p: &Value, key: &str, cmd: &str) -> Result<Option<Value>> {+ match p.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(v) => {+ let t: T = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("`{key}`: {e}")))?;+ serde_json::to_value(t).map(Some).map_err(|e| bad(cmd, format!("`{key}`: {e}")))+ }+ }+}++/// A ruby enum parameter, checked against its type.+fn ruby_enum<T: serde::de::DeserializeOwned>(p: &Value, key: &str) -> Result<Option<Value>> {+ let Some(v) = p.get(key) else { return Ok(None) };+ serde_json::from_value::<T>(v.clone()).map_err(|e| bad("type.ruby", format!("{key}: {e}")))?;+ Ok(Some(v.clone()))+}++/// A ruby number parameter clamped to `lo..=hi`, then divided by `div` (100 for percentages);+/// `null` gives `Value::Null` (automatic).+fn ruby_num(p: &Value, key: &str, lo: f64, hi: f64, div: f64) -> Result<Option<Value>> {+ match p.get(key) {+ None => Ok(None),+ Some(Value::Null) => Ok(Some(Value::Null)),+ Some(v) => {+ let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("type.ruby", format!("{key}: expected a finite number")))?;+ Ok(Some(json!(x.clamp(lo, hi) / div)))+ }+ }+}++/// Is `flag` on in the character format at the start of the first formatting target?+fn char_flag_on(s: &Session, flag: impl Fn(&CharAttrs) -> Option<bool>) -> bool {+ format_targets(s).first().is_some_and(|t| {+ s.doc()+ .ok()+ .and_then(|d| d.doc.text_story(t.story, t.cell))+ .is_some_and(|st| flag(&st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over) == Some(true))+ })+}++fn kenten_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KENTEN_MARK_MAX_CHARS, KentenAlignment, KentenKind, KentenPosition};+ const CMD: &str = "type.kenten";+ let mut body = serde_json::Map::new();+ let mut set = |k: &str, v: Value| {+ body.insert(k.to_string(), v);+ };+ // Validate every setting first, so a bad one changes nothing.+ if let Some(v) = enum_param::<KentenKind>(p, "kind", CMD)? {+ // A preset stores its mark as the character too, as IDML import does, so a custom+ // character left from before isn't drawn in its place.+ if let Some(mark) = serde_json::from_value::<KentenKind>(v.clone()).ok().and_then(KentenKind::mark) {+ set("kentenCharacter", json!(mark));+ }+ set("kentenKind", v);+ }+ if let Some(c) = text_param(p, "character", CMD, KENTEN_MARK_MAX_CHARS)? {+ set("kentenCharacter", json!(c.chars().filter(|c| !c.is_control()).collect::<String>()));+ }+ for (key, attr) in [("font", "kentenFont"), ("fontStyle", "kentenFontStyle"), ("fill", "kentenFill"), ("stroke", "kentenStroke")] {+ if let Some(t) = text_param(p, key, CMD, NAME_MAX_CHARS)? {+ set(attr, json!(t));+ }+ }+ if let Some(v) = finite_param(p, "size", CMD)? {+ set("kentenSize", json!(v.clamp(0.1, 1296.0)));+ }+ if let Some(v) = finite_param(p, "distance", CMD)? {+ set("kentenDistance", json!(v.clamp(-1296.0, 1296.0)));+ }+ for (key, attr) in [("xScale", "kentenXScale"), ("yScale", "kentenYScale")] {+ if let Some(v) = finite_param(p, key, CMD)? {+ set(attr, json!(v.clamp(1.0, 1000.0) / 100.0));+ }+ }+ for (key, attr) in [("fillTint", "kentenFillTint"), ("strokeTint", "kentenStrokeTint")] {+ if let Some(v) = finite_param(p, key, CMD)? {+ set(attr, json!(v.clamp(0.0, 100.0) / 100.0));+ }+ }+ if let Some(v) = finite_param(p, "strokeWeight", CMD)? {+ set("kentenStrokeWeight", json!(v.clamp(0.0, 1000.0)));+ }+ if let Some(v) = enum_param::<KentenPosition>(p, "position", CMD)? {+ set("kentenPosition", v);+ }+ if let Some(v) = enum_param::<KentenAlignment>(p, "alignment", CMD)? {+ set("kentenAlignment", v);+ }+ for (key, attr) in [("overprintFill", "kentenOverprintFill"), ("overprintStroke", "kentenOverprintStroke")] {+ if let Some(v) = enum_param::<AdornmentOverprint>(p, key, CMD)? {+ set(attr, v);+ }+ }+ // `null` returns a setting to the style's (size: half the text size by default).+ for (key, attr) in+ [("size", "kentenSize"), ("fillTint", "kentenFillTint"), ("strokeTint", "kentenStrokeTint"), ("strokeWeight", "kentenStrokeWeight")]{- return Err(bad(- command_id,- format!("unknown character fill `{fill}`; create a swatch with `swatch.create` and use its returned name as `fill`"),- ));+ if p.get(key).is_some_and(Value::is_null) {+ set(attr, Value::Null);+ }+ }+ let on = match bool_param(p, "on", CMD)? {+ Some(v) => v,+ None if !body.is_empty() => true,+ None => !char_flag_on(s, |f| f.kenten),+ };+ if !on {+ // Off keeps the settings for the next time kenten are switched on.+ body = serde_json::Map::new();+ }+ body.insert("kenten".into(), json!(on));+ format_chars(s, &Value::Object(body))+}++fn shatai_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "type.shatai";+ let mut body = serde_json::Map::new();+ if let Some(v) = finite_param(p, "magnification", CMD)? {+ body.insert("shataiMagnification".into(), json!(v.clamp(0.0, 90.0)));+ }+ if let Some(v) = finite_param(p, "angle", CMD)? {+ body.insert("shataiAngle".into(), json!(v.rem_euclid(180.0)));+ }+ if let Some(v) = bool_param(p, "adjustRotation", CMD)? {+ body.insert("shataiAdjustRotation".into(), json!(v));+ }+ if let Some(v) = bool_param(p, "adjustTsume", CMD)? {+ body.insert("shataiAdjustTsume".into(), json!(v));+ }+ if body.is_empty() {+ return Err(bad(CMD, "nothing to set: magnification, angle, adjustRotation or adjustTsume"));+ }+ format_chars(s, &Value::Object(body))+}++fn auto_tcy_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ const CMD: &str = "type.autoTateChuYoko";+ let mut body = serde_json::Map::new();+ if let Some(v) = finite_param(p, "digits", CMD)? {+ let max = f64::from(designcraft_compose::shape::AUTO_TCY_MAX);+ body.insert("autoTcy".into(), json!(v.round().clamp(0.0, max) as u32));+ }+ if let Some(v) = bool_param(p, "includeRoman", CMD)? {+ body.insert("autoTcyIncludeRoman".into(), json!(v));+ }+ if body.is_empty() {+ return Err(bad(CMD, "nothing to set: digits or includeRoman"));+ }+ format_paras(s, &Value::Object(body))+}++fn grid_settings_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ use designcraft_doc::cjk::CharacterAlignment as R;+ const CMD: &str = "type.gridSettings";+ let mut body = serde_json::Map::new();+ let first_only = bool_param(p, "firstLineOnly", CMD)?;+ match text_param(p, "alignment", CMD, 32)?.as_deref() {+ None => {+ if let Some(f) = first_only {+ body.insert("gridAlign".into(), json!(if f { "firstLineOnly" } else { "allLines" }));+ }+ }+ Some("none") => {+ body.insert("gridAlign".into(), json!("none"));+ }+ Some(name) => {+ let reference = match name {+ "romanBaseline" | "baseline" => R::Baseline,+ "emTop" => R::EmTop,+ "emCenter" => R::EmCenter,+ "emBottom" => R::EmBottom,+ "icfTop" => R::IcfTop,+ "icfBottom" => R::IcfBottom,+ other => return Err(bad(CMD, format!("unknown alignment `{other}`"))),+ };+ body.insert("gridAlign".into(), json!(if first_only == Some(true) { "firstLineOnly" } else { "allLines" }));+ body.insert("gridReference".into(), json!(reference));+ }+ }+ if let Some(v) = finite_param(p, "gyoudori", CMD)? {+ let max = 100.0;+ body.insert("gridGyoudori".into(), json!(v.round().clamp(0.0, max) as u32));+ }+ if let Some(v) = bool_param(p, "paragraphGyoudori", CMD)? {+ body.insert("paragraphGyoudori".into(), json!(v));+ }+ if body.is_empty() {+ return Err(bad(CMD, "nothing to set: alignment, firstLineOnly, gyoudori or paragraphGyoudori"));+ }+ format_paras(s, &Value::Object(body))+}++/// Switch a paragraph attribute of the selected paragraphs: `on`, else the opposite of the+/// first one's.+fn para_toggle(s: &mut Session, p: &Value, cmd: &str, attr: &str, get: impl Fn(&designcraft_doc::ParaProps) -> bool) -> Result<Value> {+ let on = match bool_param(p, "on", cmd)? {+ Some(v) => v,+ None => !format_targets(s).first().is_some_and(|t| {+ s.doc().ok().is_some_and(|d| {+ d.doc+ .text_story(t.story, t.cell)+ .and_then(|st| st.paras.get(st.para_at(t.range.start)))+ .is_some_and(|pf| get(&d.doc.styles.resolve_para(pf).0))+ })+ }),+ };+ let mut body = serde_json::Map::new();+ body.insert(attr.to_string(), json!(on));+ format_paras(s, &Value::Object(body))+}++fn ruby_text<'a>(p: &'a Value, key: &str) -> Result<Option<&'a str>> {+ let Some(v) = p.get(key) else { return Ok(None) };+ let t = v.as_str().ok_or_else(|| bad("type.ruby", format!("{key}: expected a string")))?;+ if t.chars().count() > designcraft_doc::ruby::MAX_RUBY_CHARS {+ return Err(bad("type.ruby", format!("{key}: longer than {} characters", designcraft_doc::ruby::MAX_RUBY_CHARS)));+ }+ Ok(Some(t))+}++fn ruby_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ use designcraft_doc::cjk_settings::AdornmentOverprint;+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};+ let mut body = serde_json::Map::new();+ let mut put = |attr: &str, v: Option<Value>| {+ if let Some(v) = v {+ body.insert(attr.into(), v);+ }+ };+ put("ruby", ruby_text(p, "text")?.map(|t| json!(t)));+ put("rubyType", ruby_enum::<RubyType>(p, "type")?);+ put("rubyAlignment", ruby_enum::<RubyAlignment>(p, "alignment")?);+ put("rubyPosition", ruby_enum::<RubyPosition>(p, "position")?);+ put("rubyOverhangAmount", ruby_enum::<RubyOverhang>(p, "overhang")?);+ put("rubyParentSpacing", ruby_enum::<RubyParentSpacing>(p, "parentSpacing")?);+ put("rubyOverprintFill", ruby_enum::<AdornmentOverprint>(p, "overprintFill")?);+ put("rubyOverprintStroke", ruby_enum::<AdornmentOverprint>(p, "overprintStroke")?);+ put("rubyXOffset", ruby_num(p, "xOffset", -1000.0, 1000.0, 1.0)?.filter(|v| !v.is_null()));+ put("rubyYOffset", ruby_num(p, "yOffset", -1000.0, 1000.0, 1.0)?.filter(|v| !v.is_null()));+ put("rubyFontSize", ruby_num(p, "size", 0.1, 1296.0, 1.0)?);+ put("rubyXScale", ruby_num(p, "xScale", 1.0, 1000.0, 100.0)?.filter(|v| !v.is_null()));+ put("rubyYScale", ruby_num(p, "yScale", 1.0, 1000.0, 100.0)?.filter(|v| !v.is_null()));+ put("rubyScalingMin", ruby_num(p, "scalingPercent", 10.0, 100.0, 100.0)?.filter(|v| !v.is_null()));+ put("rubyFillTint", ruby_num(p, "fillTint", 0.0, 100.0, 100.0)?);+ put("rubyStrokeTint", ruby_num(p, "strokeTint", 0.0, 100.0, 100.0)?);+ put("rubyStrokeWeight", ruby_num(p, "strokeWeight", 0.0, 800.0, 1.0)?);+ put(+ "rubyAutoTcyDigits",+ ruby_num(p, "autoTcyDigits", 0.0, 9.0, 1.0)?.filter(|v| !v.is_null()).and_then(|v| v.as_f64()).map(|v| json!(v.round() as u32)),+ );+ for (key, attr) in [+ ("openTypePro", "rubyOpenTypePro"),+ ("autoTcyIncludeRoman", "rubyAutoTcyIncludeRoman"),+ ("autoTcyAutoScale", "rubyAutoTcyAutoScale"),+ ("autoAlign", "rubyAutoAlign"),+ ("autoScaling", "rubyAutoScaling"),+ ] {+ if let Some(v) = p.get(key) {+ let b = v.as_bool().ok_or_else(|| bad("type.ruby", format!("{key}: expected true or false")))?;+ put(attr, Some(json!(b)));+ }+ }+ put("rubyFont", ruby_text(p, "font")?.map(|t| json!(t)));+ put("rubyFontStyle", ruby_text(p, "fontStyle")?.map(|t| json!(t)));+ for (key, attr) in [("fill", "rubyFill"), ("stroke", "rubyStroke")] {+ if let Some(name) = ruby_text(p, key)? {+ let known = name.is_empty() || name == designcraft_doc::color::swatch::NONE || s.doc()?.doc.swatch(name).is_some();+ if !known {+ return Err(bad("type.ruby", format!("{key}: no swatch `{name}`")));+ }+ put(attr, Some(json!(name)));+ }+ }+ format_chars(s, &Value::Object(body))+}++/// A character fill must name a swatch of the document.+pub(crate) fn validate_char_fill(document: &designcraft_doc::Document, attrs: &CharAttrs, command_id: &str) -> Result<()> {+ match &attrs.fill {+ Some(fill) => super::object::known_swatch(document, fill, command_id, "fill"),+ None => Ok(()),}- Ok(())}+ /// Byte `pos` is the hidden paragraph mark of an *empty* paragraph: the only character on that+ /// line, and so the one a line-affecting attribute like leading can land on right away instead of+ /// waiting for the next typed character (otherwise an empty line could never get its own leading).+ fn empty_para_mark(story: &designcraft_doc::Story, pos: usize) -> bool {+ let ranges = story.para_ranges();+ ranges.get(story.para_at(pos)).is_some_and(|r| r.start == pos && r.end == pos) && story.text.as_bytes().get(pos) == Some(&b'\n')+ }+pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {let mut a = CharAttrs::default();if let Some(o) = attrs.as_object() {@@@ -1370,12 -1149,21 +1517,21 @@@ pub(crate) fn apply_char_attrs(d: &mutlet r = &t.range;let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };if r.is_empty() {- // An empty story: its one (empty) run is the format typing takes.- if st.is_empty()- && let Some(run) = st.chars.first_mut()- {- run.format.over.merge(a);- st.rev = st.rev.wrapping_add(1);+ if st.is_empty() {+ // An empty story: its one (empty) run is the format typing takes.+ if let Some(run) = st.chars.first_mut() {+ run.format.over.merge(a);- st.rev += 1;++ st.rev = st.rev.wrapping_add(1);+ }+ } else if empty_para_mark(st, r.start) {+ // An empty paragraph elsewhere in the story: its hidden paragraph mark is its only+ // character, and the one that carries line-affecting attributes like leading.+ st.format_chars(r.start..r.start + 1, |f| {+ f.over.merge(a);+ for k in cleared {+ let _ = f.over.set_json(k, &Value::Null);+ }+ });}continue;}diff --cc crates/engine/src/dtd.rsindex 30a573c23,7f752efaa..6b48ba3ab--- a/crates/engine/src/dtd.rs+++ b/crates/engine/src/dtd.rs@@@ -165,65 -162,6 +169,64 @@@ fn parse_model(s: &str) -> Result<ModelOk(Model::Children(cp))}- const MAX_PARAMETER_ENTITY_EXPANSION: usize = 16 * 1024 * 1024;+/// How deeply parameter entities may nest: a reference in the DTD is level 1, a reference in its+/// value level 2, and so on.+const MAX_PARAMETER_ENTITY_DEPTH: usize = 64;++/// Expand `%name;` references, one level per round, until a round changes nothing.+fn expand_parameter_entities(src: &str, ents: &[(String, String)]) -> Result<String, String> {+ let mut entities = HashMap::new();+ for (name, value) in ents {+ entities.entry(name.as_str()).or_insert(value.as_str());+ }- let limit = MAX_PARAMETER_ENTITY_EXPANSION.max(src.len());++ let limit = src.len().saturating_add(MAX_EXPANDED_BYTES);+ let append = |out: &mut String, value: &str| -> Result<(), String> {+ if value.len() > limit.saturating_sub(out.len()) {- return Err(format!("parameter entities expand to more than {limit} bytes"));++ return Err(format!("parameter entities expand the DTD beyond {limit} bytes"));+ }+ out.push_str(value);+ Ok(())+ };+ let too_deep = || format!("parameter entities refer to themselves or nest deeper than {MAX_PARAMETER_ENTITY_DEPTH} levels");+ let mut text = src.to_string();+ // The round after the deepest level changes nothing, hence one more round than levels.+ for _ in 0..=MAX_PARAMETER_ENTITY_DEPTH {+ let mut out = String::with_capacity(text.len());+ let mut rest = text.as_str();+ let mut changed = false;+ while let Some(i) = rest.find('%') {+ let (prefix, reference) = rest.split_at(i);+ append(&mut out, prefix)?;+ // `find` points to an ASCII `%`, so both split positions are UTF-8 boundaries.+ rest = reference.split_at(1).1;+ // A name has no whitespace and no `%` (`parse` ends a name at whitespace), whatever its+ // length: the search for the closing `;` stops at the first of those, so the searches of+ // a round never overlap and a round stays linear in the text.+ let end =+ rest.bytes().position(|b| matches!(b, b';' | b'%') || b.is_ascii_whitespace()).filter(|&k| rest.as_bytes().get(k) == Some(&b';'));+ if let Some(end) = end+ && let Some(value) = rest.get(..end).and_then(|name| entities.get(name))+ {+ // A value that is its own reference (`<!ENTITY % a "%a;">`) never gets anywhere.+ if reference.get(..end + 2) == Some(*value) {+ return Err(too_deep());+ }+ append(&mut out, value)?;+ changed = true;+ rest = rest.split_at(end + 1).1;+ continue;+ }+ append(&mut out, "%")?;+ }+ append(&mut out, rest)?;+ text = out;+ if !changed {+ return Ok(text);+ }+ }+ Err(too_deep())+}+/// Parse a DTD (its element and attribute-list declarations; parameter entities are expanded).pub fn parse(src: &str) -> Result<Dtd, String> {// Parameter entities first, then expand references and read the declarations again.diff --cc crates/engine/src/guard.rsindex 4f8c17a31,92ef1332f..2ac6bb63c--- a/crates/engine/src/guard.rs+++ b/crates/engine/src/guard.rs@@@ -35,8 -35,11 +35,12 @@@ pub fn install_panic_hook()impl Session {/// Run command `id` (`f`) inside the guard.pub(crate) fn guarded(&mut self, id: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {- let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone()));+ // The whole command transaction: every open document with its undo/redo history and+ // selection, which one is active, and the journal (nested commands journal too).+ let docs = self.docs.clone();+ let active = self.active;+ let journal = self.journal.len();+ let in_undo_step = self.in_undo_step;match catch_unwind(AssertUnwindSafe(|| f(self))) {Ok(r) => r,Err(payload) => {@@@ -90,38 -92,46 +95,81 @@@ mod testss.execute("frame.create", &json!({"rect": [36, 236, 200, 400]})).unwrap();}+ /// An undoable command that panics is no longer running: the next command records its own+ /// undo step.+ #[test]+ fn a_panicking_command_does_not_swallow_later_undo_steps() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let panicked = s.guarded("test.panic", |s| {+ s.in_undo_step = true;+ panic!("boom");+ });+ assert!(panicked.is_err());+ s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();+ assert_eq!(s.active().unwrap().history.undo.len(), 1);+ }++ /// A command that panics inside an undoable one leaves that one running: what it runs next+ /// is still part of its undo step.+ #[test]+ fn a_panic_in_a_command_run_by_another_leaves_the_outer_undo_step() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ // An undoable command that runs one that panics, carries on and runs another.+ s.guarded("test.outer", |s| {+ s.in_undo_step = true;+ assert!(s.guarded("test.panic", |_| panic!("boom")).is_err());+ let made = s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]}));+ s.in_undo_step = false;+ made+ })+ .unwrap();+ let st = s.active().unwrap();+ assert_eq!(st.doc.spreads[0].items.len(), 1);+ assert_eq!(st.history.undo.len(), 0, "the frame is left to the outer command's step");+ }+++ /// A nested edit that succeeded before the panic is rolled back with its history entry, and+ /// the redo it cleared is back (#742).+ #[test]+ fn a_panicking_command_restores_history_with_the_document() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();+ s.execute("edit.undo", &json!({})).unwrap();+ let (undo, redo) = {+ let h = &s.active().unwrap().history;+ (h.undo.len(), h.redo.len())+ };+ assert_eq!(redo, 1, "there is redo to lose");+ let err = s+ .guarded("test.panic", |s| {+ s.execute("frame.create", &json!({"rect": [36, 236, 200, 400]}))?;+ panic!("boom");+ })+ .unwrap_err();+ assert!(err.to_string().contains("boom"), "{err}");+ let st = s.active().unwrap();+ assert_eq!(st.history.undo.len(), undo, "the nested edit's undo entry is gone with the edit");+ assert_eq!(st.history.redo.len(), redo, "the redo the nested edit cleared is back");+ assert_eq!(st.doc.spreads[0].items.len(), 0, "the document is the one from before the command");+ }++ /// A command that opens another document and then panics leaves none of it behind (#742).+ #[test]+ fn a_panicking_command_restores_the_document_set() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let err = s+ .guarded("test.panic", |s| {+ s.execute("file.new", &json!({}))?;+ assert_eq!(s.docs.len(), 2);+ panic!("boom");+ })+ .unwrap_err();+ assert!(err.to_string().contains("boom"), "{err}");+ assert_eq!(s.docs.len(), 1, "the document the command opened is gone");+ assert_eq!(s.active, Some(0), "the document from before the command is active");+ }}diff --cc crates/engine/src/lib.rsindex 5dff5c32a,8598123b4..959677650--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@@ -9,10 -9,11 +9,12 @@@#[cfg(not(target_arch = "wasm32"))]pub mod atomic;+pub mod autosize;pub mod cmd;pub mod dtd;+ pub mod file_access;pub mod guard;+ pub mod io;pub mod links;pub mod math;pub mod recovery;@@@ -328,10 -290,8 +330,11 @@@ pub struct Sessionpub cache: Arc<Cache>,pub(crate) tool: Box<dyn designcraft_tools::Tool>,pub journal: Vec<(String, Value)>,+ pub(crate) find_context: Option<cmd::find::FindContext>,pub clipboard: Option<Arc<Document>>,+ /// The x the clipboard's objects are measured from on their spread: its spine, or the left edge of+ /// single-sided pages. Paste keeps their distance from it.+ pub clipboard_origin: f64,/// Crash-recovery folder (the app sets it; saving or closing a document removes its entry).pub recovery_dir: Option<std::path::PathBuf>,/// Copied text with its formatting (a frameless story slice) and its plain text.@@@ -385,8 -336,8 +388,9 @@@ impl Sessioncache: Arc::new(Cache::new()),tool: designcraft_tools::create("selection"),journal: vec![],+ find_context: None,clipboard: None,+ clipboard_origin: 0.0,recovery_dir: None,text_clipboard: None,text_link_checks: Default::default(),@@@ -484,13 -447,9 +501,14 @@@recovery::discard_document(self, i, recovery_dir.as_deref());}if i < self.docs.len() {+ self.reset_find_scope();self.docs.remove(i);self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) };+ if self.docs.is_empty() {+ // Retire this document generation's cache. In-flight render jobs may still+ // own it, but must not repopulate the idle session's cache after closing.+ self.cache = Arc::new(Cache::new());+ }}}@@@ -530,20 -484,10 +548,22 @@@if id != "data.preview" && (spec.undoable || spec.journal) {self.stop_data_preview();}+ // Preview restoration can replace the document before a Find handler resolves bounds.+ self.discard_stale_find_scope();- let before = self.active().map(|d| (d.uid, d.doc.clone()));- let r = (spec.run)(self, params)?;+ let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone()));+ // What an undoable command runs is part of its undo step.+ let nested = self.in_undo_step;+ self.in_undo_step = nested || spec.undoable;+ let ran = (spec.run)(self, params);+ self.in_undo_step = nested;+ let r = match ran {+ Ok(r) => r,+ Err(e) => {+ // What it did before it failed can be undone too.+ self.record_undo_step(spec, before, nested);+ return Err(e);+ }+ };// Undo, redo or deleting layers can take the active layer away: new objects would land on// a layer that isn't there (invisible, not exported). Fall back to the top layer.if let Some(st) = self.active_mut()@@@ -702,12 -630,12 +725,16 @@@ pub(crate) use push_undo as record_undo#[cfg(test)]mod tests;#[cfg(test)]+mod tests_autosize;+#[cfg(test)]+ mod tests_file_guard;+ #[cfg(test)]mod tests_idml;#[cfg(test)]mod tests_ime;#[cfg(test)]+mod tests_params;+#[cfg(test)]+ mod tests_roots;+ #[cfg(test)]mod tests_table;diff --cc crates/engine/src/tests.rsindex 41ffba0ba,616a86398..0b4a06a29--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -1118,147 -681,73 +1118,214 @@@ fn character_style_delete_rejects_builtassert!(r.is_err(), "built-in styles can't be deleted");}+#[test]+fn direct_selection_drag_and_arrow_keys_move_placed_content() {+ use designcraft_tools::{Mods, PointerEvent, PointerKind, SnapView, ToolKey};+ let mut s = session();+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ let f = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();+ s.execute("place.load", &json!({"base64": cmd::base64_encode(&png)})).unwrap();+ s.execute("place.drop", &json!({"frame": f})).unwrap();+ let xfs = |s: &Session| {+ let it = s.doc().unwrap().doc.item(designcraft_doc::ItemId(f)).unwrap().clone();+ (it.xf, it.graphic().unwrap().xf.translation())+ };+ let (frame0, g0) = xfs(&s);+ let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };+ let at = s.layout().to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(150.0, 150.0));+ s.set_tool("directSelection");+ s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 10.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 30.0, at.y + 10.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, at.x + 30.0, at.y + 10.0), v).unwrap();+ assert!(s.doc().unwrap().selection.content);+ let (frame1, g1) = xfs(&s);+ assert_eq!(frame1, frame0, "the frame stays");+ assert_eq!(g1 - g0, designcraft_geom::Vec2::new(30.0, 10.0));+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(xfs(&s).1, g0, "one undo step");+ // Arrow keys nudge the selected content; Shift nudges ten times as far.+ s.set_tool("selection");+ s.tool_key(ToolKey::Right, Mods::default(), v).unwrap();+ s.tool_key(ToolKey::Down, Mods { shift: true, ..Default::default() }, v).unwrap();+ let (frame2, g2) = xfs(&s);+ assert_eq!(frame2, frame0);+ assert_eq!(g2 - g0, designcraft_geom::Vec2::new(1.0, 10.0));+}++#[test]+fn preflight_notes_an_assumed_mojikumi_base_set_without_calling_the_table_unapplied() {+ let mut s = session();+ s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "text", "text": "中文 A1"})).unwrap();+ let story = s.doc().unwrap().doc.stories.keys().next().unwrap().0;+ let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ std::sync::Arc::make_mut(&mut d.styles)+ .mojikumi_tables+ .push(designcraft_doc::cjk::MojikumiTable { name: "Baseless".into(), ..Default::default() });+ s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 1})).unwrap();+ s.execute("type.para", &json!({"attrs": {"mojikumi": "MojikumiTable/Baseless"}})).unwrap();+ let result = s.execute("preflight.run", &json!({})).unwrap();+ let messages: Vec<_> =+ result["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "unsupportedTypography").filter_map(|i| i["message"].as_str()).collect();+ assert!(messages.iter().any(|m| m.contains("Baseless") && m.contains("no base set")), "{messages:?}");+ assert!(!messages.iter().any(|m| m.contains("not applied")), "{messages:?}");+}++#[test]+fn live_corner_gestures_are_one_undo_step_each() {+ use designcraft_geom::corners::CornerShape;+ use designcraft_tools::{Mods, PointerEvent, PointerKind};+ let mut s = session();+ s.execute("frame.create", &json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap();+ let id = s.doc().unwrap().doc.spreads[0].items[0].id;+ s.execute("selection.set", &json!({"ids": [id.0]})).unwrap();+ s.set_tool("selection");+ let v = ViewInfo::at_zoom(1.0);+ let undo = |s: &Session| s.doc().unwrap().history.undo.len();+ let corners = |s: &Session| s.doc().unwrap().doc.item(id).unwrap().corners.corners;+ let before = undo(&s);+ // Click the widget, then drag the top-left diamond 20 pt toward the centre.+ s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 111.5), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 111.5), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Down, 112.0, 100.0), v).unwrap();+ for x in [116.0, 124.0, 132.0] {+ s.pointer(&PointerEvent::new(PointerKind::Drag, x, 100.0), v).unwrap();+ }+ s.pointer(&PointerEvent::new(PointerKind::Up, 132.0, 100.0), v).unwrap();+ assert_eq!(undo(&s), before + 1);+ assert!(corners(&s).iter().all(|c| c.shape == CornerShape::Rounded && (c.size - 20.0).abs() < 1e-9), "{:?}", corners(&s));+ // Alt-click the top-left diamond, now 20 pt along the edge.+ let alt = Mods { alt: true, ..Default::default() };+ s.pointer(&PointerEvent::new(PointerKind::Down, 120.0, 100.0).with_mods(alt), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, 120.0, 100.0).with_mods(alt), v).unwrap();+ assert_eq!(undo(&s), before + 2);+ assert_eq!(corners(&s)[0].shape, CornerShape::InverseRounded);+ assert_eq!(corners(&s)[1].shape, CornerShape::Rounded);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(corners(&s)[0].shape, CornerShape::Rounded);+ // Malformed per-corner parameters are errors, not silent defaults.+ let c = json!({"shape": "rounded", "size": 5});+ assert!(s.execute("object.cornerOptions", &json!({"corners": [c, c, c]})).is_err());+ assert!(s.execute("object.cornerOptions", &json!({"corners": [c, c, c, {"shape": "rounded", "size": -1}]})).is_err());+ assert!(s.execute("object.cornerOptions", &json!({"corners": "rounded"})).is_err());+}++#[test]+fn alt_arrows_kern_at_the_caret_and_track_a_selection() {+ use designcraft_doc::{Kerning, StoryId};+ use designcraft_tools::{Mods, ToolKey};+ let mut s = session();+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": "Hello world"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ s.set_tool("type");+ let v = ViewInfo::at_zoom(1.0);+ let alt = Mods { alt: true, ..Default::default() };+ let story = |s: &Session| s.doc().unwrap().doc.story(StoryId(sid)).unwrap().clone();+ let caret = |s: &mut Session, at: usize| s.execute("text.select", &json!({"story": sid, "anchor": at, "focus": at})).unwrap();+ // Caret between "e" and "l": Alt+Right kerns the pair by the increment; the caret stays.+ caret(&mut s, 2);+ assert!(s.tool_key(ToolKey::Right, alt, v).unwrap());+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(20.0)));+ assert_eq!(s.doc().unwrap().selection.text.unwrap().focus, 2);+ s.tool_key(ToolKey::Right, alt, v).unwrap();+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(40.0)));+ // One undo step per press.+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(20.0)));+ // Alt+Cmd (Alt+Ctrl elsewhere) steps five increments.+ caret(&mut s, 4);+ s.tool_key(ToolKey::Left, Mods { cmd: true, ..alt }, v).unwrap();+ assert_eq!(story(&s).format_after(3).over.kerning, Some(Kerning::Manual(-100.0)));+ // The increment is the document's Kerning/Tracking preference.+ s.execute("document.preferences", &json!({"kerningIncrement": 10})).unwrap();+ caret(&mut s, 2);+ s.tool_key(ToolKey::Right, alt, v).unwrap();+ assert_eq!(story(&s).format_after(1).over.kerning, Some(Kerning::Manual(30.0)));+ // A selection: tracking of the selected text.+ s.execute("text.select", &json!({"story": sid, "anchor": 6, "focus": 11})).unwrap();+ s.tool_key(ToolKey::Right, alt, v).unwrap();+ let st = story(&s);+ assert_eq!((st.format_after(6).over.tracking, st.format_after(10).over.tracking), (Some(10.0), Some(10.0)));+ assert_eq!(st.format_after(4).over.tracking, None);+ s.tool_key(ToolKey::Left, Mods { cmd: true, ctrl: true, ..alt }, v).unwrap();+ assert_eq!(story(&s).format_after(8).over.tracking, Some(-40.0));+ // Words: Cmd+Right (Ctrl+Right elsewhere); Alt+Shift+Right extends by a word.+ caret(&mut s, 0);+ s.tool_key(ToolKey::Right, Mods { cmd: true, ..Default::default() }, v).unwrap();+ assert_eq!(s.doc().unwrap().selection.text.unwrap().focus, 5);+ caret(&mut s, 0);+ s.tool_key(ToolKey::Right, Mods { alt: true, shift: true, ..Default::default() }, v).unwrap();+ let t = s.doc().unwrap().selection.text.unwrap();+ assert_eq!((t.anchor, t.focus), (0, 5));+}++ #[test]+ fn character_style_delete_rejects_missing_unknown_and_self_replacement() {+ let mut s = session();+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ assert!(s.execute("style.character.delete", &json!({"name": ""})).is_err(), "empty name is rejected");+ assert!(s.execute("style.character.delete", &json!({"name": "No Such Style"})).is_err(), "unknown name is rejected");+ assert!(s.execute("style.character.delete", &json!({"name": name, "replaceWith": "No Such Style"})).is_err(), "unknown replaceWith is rejected");+ assert!(s.execute("style.character.delete", &json!({"name": name, "replaceWith": name})).is_err(), "replaceWith can't be the deleted style");+ }++ #[test]+ fn paragraph_style_delete_rejects_missing_unknown_and_self_replacement() {+ let mut s = session();+ let name = s.execute("style.paragraph.create", &json!({"name": "Caption"})).unwrap()["name"].as_str().unwrap().to_string();+ assert!(s.execute("style.paragraph.delete", &json!({"name": ""})).is_err(), "empty name is rejected");+ assert!(s.execute("style.paragraph.delete", &json!({"name": "No Such Style"})).is_err(), "unknown name is rejected");+ assert!(s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": "No Such Style"})).is_err(), "unknown replaceWith is rejected");+ assert!(s.execute("style.paragraph.delete", &json!({"name": name, "replaceWith": name})).is_err(), "replaceWith can't be the deleted style");+ }++ #[test]+ fn deleting_a_style_never_leaves_its_replacement_based_on_itself() {+ let mut s = session();+ let para = |s: &Session, n: &str| s.doc().unwrap().doc.styles.para(n).unwrap().based_on.clone();+ s.execute("style.paragraph.create", &json!({"name": "Head"})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Sub", "basedOn": "Head"})).unwrap();+ s.execute("style.paragraph.create", &json!({"name": "Minor", "basedOn": "Sub"})).unwrap();+ // Minor is based on Sub; deleting Sub in favour of Minor gives Minor Sub's parent.+ s.execute("style.paragraph.delete", &json!({"name": "Sub", "replaceWith": "Minor"})).unwrap();+ assert_eq!(para(&s, "Minor").as_deref(), Some("Head"));+ s.execute("style.character.create", &json!({"name": "Strong"})).unwrap();+ s.execute("style.character.create", &json!({"name": "Stronger", "basedOn": "Strong"})).unwrap();+ s.execute("style.character.delete", &json!({"name": "Strong", "replaceWith": "Stronger"})).unwrap();+ let based = s.doc().unwrap().doc.styles.character.iter().find(|c| c.name == "Stronger").unwrap().based_on.clone();+ assert_ne!(based.as_deref(), Some("Stronger"));+ }++ #[test]+ fn character_style_delete_reassigns_every_kind_of_reference() {+ let mut s = session();+ let name = s.execute("style.character.create", &json!({"name": "Key Term"})).unwrap()["name"].as_str().unwrap().to_string();+ let repl = s.execute("style.character.create", &json!({"name": "Emphasis"})).unwrap()["name"].as_str().unwrap().to_string();+ // Another character style's basedOn.+ let based = s.execute("style.character.create", &json!({"name": "Strong", "basedOn": name})).unwrap()["name"].as_str().unwrap().to_string();+ // A paragraph style's nested, nested line, GREP and drop cap styles, and the footnote reference style.+ s.execute(+ "style.paragraph.create",+ &json!({"name": "Body", "para": {+ "nestedStyles": [{"style": name, "through": true, "count": 1, "until": {"kind": "words"}}],+ "grepStyles": [{"style": name, "pattern": "x"}],+ "nestedLineStyles": [{"style": name, "lines": 1}],+ "dropCapStyle": name}}),+ )+ .unwrap();+ s.execute("footnote.options", &json!({"refCharStyle": name})).unwrap();+ s.execute("style.character.delete", &json!({"name": name, "replaceWith": repl})).unwrap();+ let st = s.doc().unwrap();+ assert!(st.doc.styles.char_style(&name).is_none(), "deleted style is gone");+ assert_eq!(st.doc.styles.char_style(&based).unwrap().based_on.as_deref(), Some(repl.as_str()), "basedOn redirected");+ let body = st.doc.styles.para("Body").unwrap();+ assert_eq!(body.para.nested_styles.as_ref().unwrap()[0].style, repl, "nested style redirected");+ assert_eq!(body.para.nested_line_styles.as_ref().unwrap()[0].style, repl, "nested line style redirected");+ assert_eq!(body.para.grep_styles.as_ref().unwrap()[0].style, repl, "grep style redirected");+ assert_eq!(body.para.drop_cap_style.as_deref(), Some(repl.as_str()), "drop cap style redirected");+ assert_eq!(st.doc.footnote_options.ref_char_style, repl, "footnote reference style redirected");+ }+#[test]fn page_tool_selects_a_page_and_its_handles_preview_or_resize_it() {use designcraft_tools::{CanvasLayout, Mods, PointerEvent, PointerKind};@@@ -1441,28 -1056,57 +1508,83 @@@ fn duplicating_a_page_to_an_index_is_onassert_eq!(widths(&s), [300.0, 400.0, 500.0]);}+#[test]+fn duplicating_a_page_keeps_its_own_size_rule_guides_and_objects() {+ // Chris Cicchino's Page Tool video (2:06): the letterhead page is duplicated, then resized.+ let mut s = Session::new();+ s.execute("file.new", &json!({"width": 252, "height": 144, "facingPages": false})).unwrap();+ s.execute("layout.pages.insert", &json!({"count": 1})).unwrap();+ s.execute("layout.pageSize", &json!({"pages": [2], "width": 612, "height": 792})).unwrap();+ s.execute("liquid.pageRule", &json!({"rule": "scale", "pages": [2]})).unwrap();+ s.execute("guide.add", &json!({"spread": 1, "page": 0, "orientation": "vertical", "position": 300})).unwrap();+ s.execute("frame.create", &json!({"spread": 1, "rect": [100, 100, 200, 200]})).unwrap();+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 1})).unwrap();+ assert_eq!(r["page"], 2);+ let d = s.doc().unwrap().doc.clone();+ let (si, pi) = d.page_loc(2).unwrap();+ let pg = &d.spreads[si].pages[pi];+ assert_eq!((pg.width, pg.height, pg.liquid), (612.0, 792.0, designcraft_doc::LiquidRule::Scale));+ assert_eq!(pg.guides.len(), 1);+ assert_eq!(d.spreads[si].items.len(), 1);+ // At the end of the document (the New Page button): the business card, not the last page's size.+ let r = s.execute("layout.pages.duplicateSpread", &json!({"spread": 0, "atEnd": true})).unwrap();+ assert_eq!(r["page"], 3);+ let d = s.doc().unwrap().doc.clone();+ let (si, pi) = d.page_loc(3).unwrap();+ assert_eq!((d.spreads[si].pages[pi].width, d.spreads[si].pages[pi].height), (252.0, 144.0));+}+++ #[test]+ fn the_type_tool_draws_a_text_frame_over_a_locked_frame() {+ // Adobe's "Set up a modern magazine layout" (4:03): with the page frame locked (Cmd+L), the+ // Type tool draws text frames on top of it; the locked frame stays an empty frame.+ use designcraft_tools::{PointerEvent, PointerKind, SnapView};+ let mut s = Session::new();+ s.execute("file.new", &json!({"width": 612, "height": 792, "facingPages": false})).unwrap();+ let big = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.stroke", &json!({"ids": [big], "swatch": "[Black]", "weight": 6})).unwrap();+ s.execute("object.lock", &json!({"ids": [big]})).unwrap();+ s.execute("edit.deselectAll", &json!({})).unwrap();+ s.set_tool("type");+ let v = ViewInfo { snap: SnapView::OFF, ..ViewInfo::at_zoom(1.0) };+ let layout = s.layout();+ let at = |x: f64, y: f64| layout.to_canvas(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Point::new(x, y));+ let (a, b) = (at(100.0, 100.0), at(300.0, 200.0));+ s.pointer(&PointerEvent::new(PointerKind::Down, a.x, a.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0 + a.x - 100.0, a.y + 50.0), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Drag, b.x, b.y), v).unwrap();+ s.pointer(&PointerEvent::new(PointerKind::Up, b.x, b.y), v).unwrap();+ let d = &s.doc().unwrap().doc;+ let it = d.item(designcraft_doc::ItemId(big)).unwrap();+ assert!(matches!(it.content, designcraft_doc::Content::Unassigned), "the locked frame stays empty");+ let frames: Vec<_> = d.spreads[0].items.iter().filter(|i| i.is_text_frame()).collect();+ assert_eq!(frames.len(), 1, "a new text frame");+ let r = frames[0].bounds();+ assert!((r.x0 - 100.0).abs() < 1e-6 && (r.y1 - 200.0).abs() < 1e-6, "{r:?}");+ // The engine refuses to turn a locked empty frame into a text frame.+ assert!(s.execute("text.placeCaret", &json!({"frame": big, "point": [300, 400]})).is_err());+ // Unlocked, a press inside converts it, as before.+ s.execute("object.unlockAll", &json!({})).unwrap();+ s.execute("text.placeCaret", &json!({"frame": big, "point": [300, 400]})).unwrap();+ assert!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(big)).unwrap().is_text_frame());+ }++ /// A line is set when its baseline fits in the frame; its descenders may hang below the frame, as+ /// in InDesign. A 103 pt heading in a 78.5 pt frame (Cap Height first baseline) was overset.+ #[test]+ fn a_line_fits_when_its_baseline_does() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let overset = |s: &mut Session, height: f64| {+ let r = s.execute("frame.create", &json!({"rect": [36, 36, 400, 36.0 + height], "content": "text", "text": "Gyp"})).unwrap();+ s.execute("object.textFrameOptions", &json!({"ids": [r["id"]], "firstBaseline": "capHeight", "inset": 0})).unwrap();+ s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 3})).unwrap();+ s.execute("type.char", &json!({"attrs": {"size": 103}})).unwrap();+ let st = s.execute("story.get", &json!({"story": r["story"]})).unwrap();+ !st["overset"].is_null()+ };+ // Cap height of the default font at 103 pt is about 70 pt: the baseline fits in 78.5 pt, the+ // descent (about 25 pt more) doesn't.+ assert!(!overset(&mut s, 78.5), "the line is set; its descenders hang below the frame");+ assert!(overset(&mut s, 50.0), "a baseline below the frame still oversets the line");+ }diff --cc crates/epub/src/lib.rsindex e7b7bab26,16084535d..6ee272f61--- a/crates/epub/src/lib.rs+++ b/crates/epub/src/lib.rs@@@ -1982,6 -1939,9 +1982,9 @@@ mod testsassert_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"));++ 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();@@@ -2203,4 -2129,4 +2206,22 @@@);assert!(html.contains(&expected), "{html}");}++++ /// 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_name_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>");++ }}diff --cc crates/fonts/src/fontdb.rsindex 4aee90692,60ec3d6f6..a7e40c39c--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -386,9 -371,9 +390,10 @@@ struct CatalogEntrystruct ScannedFace {family: String,style: String,+ wws: Option<(String, String)>,group: FontGroup,native: Option<String>,+ aliases: Vec<String>,postscript: Option<String>,}@@@ -698,14 -677,8 +728,16 @@@ fn file_face_names(path: &std::path::Pa}};let postscript = name(&f, &[StringId::POSTSCRIPT_NAME]);+ let wws = wws_names(&f, &family, &style);- Some(ScannedFace { family, style, wws, group, native, postscript })+ Some(ScannedFace {+ family,+ style,++ wws,+ group,+ native,+ aliases: aliases(&f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME]),+ postscript,+ })}).collect()}@@@ -1218,21 -1150,6 +1259,22 @@@ impl FontDb}}}+ // Font services name their files as they like (no extension, say): the face names read+ // decide what is a font.+ for p in unscanned_font_files((self.font_files)(), &mut scanned) {+ for f in file_face_names(&p) {+ found.push(CatalogEntry {+ family: f.family,+ style: f.style,++ wws: f.wws,+ path: p.clone(),+ group: f.group,+ native: f.native,+ aliases: f.aliases,+ postscript: f.postscript,+ });+ }+ }let n = found.len();log::debug!("cataloged {n} system font faces");*self.catalog.write().unwrap_or_else(|e| e.into_inner()) = found;@@@ -1388,9 -1320,8 +1445,9 @@@self.scoped(0).has_family(family)}+ #[cfg(not(target_arch = "wasm32"))]fn is_loaded(&self, family: &str) -> bool {- self.read_faces().iter().any(|f| f.family.eq_ignore_ascii_case(family))+ self.read_faces().iter().any(|f| f.family.eq_ignore_ascii_case(family) || has_wws_family(f, family))}/// A shared variable font's axes (see [`ScopedFonts::axes`]).@@@ -1516,89 -1435,6 +1573,97 @@@ impl ScopedFonts<'_>self.own.as_deref().unwrap_or(&[])}+ /// Resolve localized and legacy family names without confusing replacement fonts with+ /// installed originals. Document-local aliases take precedence over shared fonts.+ pub fn canonical_family(&self, family: &str) -> Option<String> {+ let matches =+ |f: &&Arc<FontFace>| f.family.eq_ignore_ascii_case(family) || f.family_aliases.iter().any(|alias| alias.eq_ignore_ascii_case(family));+ if let Some(face) = self.own().iter().find(matches) {+ return Some(face.family.clone());+ }+ if let Some(face) = self.db.read_faces().iter().find(matches) {+ return Some(face.family.clone());+ }+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(face) = self+ .db+ .read_catalog()+ .iter()+ .find(|f| f.family.eq_ignore_ascii_case(family) || f.aliases.iter().any(|alias| alias.eq_ignore_ascii_case(family)))+ {+ return Some(face.family.clone());+ }++ // A WWS family name (an optical-size face's, see `find`) names its faces as it is.++ if let Some(face) = self.own().iter().chain(self.db.read_faces().iter()).find(|f| has_wws_family(f, family)) {++ return face.wws.as_ref().map(|w| w.0.clone());++ }++ #[cfg(not(target_arch = "wasm32"))]++ if let Some(c) = self.db.read_catalog().iter().find(|c| c.wws.as_ref().is_some_and(|w| w.0.eq_ignore_ascii_case(family))) {++ return c.wws.as_ref().map(|w| w.0.clone());++ }+ None+ }++ /// Whether the requested style exists, including localized names and axis instances.+ pub fn has_style(&self, family: &str, style: &str) -> bool {+ if !self.has_family(family) {+ return false;+ }+ let face = self.face(family, style);+ norm(&face.style) == norm(style) || (face.coords.is_empty() && face.style_aliases.iter().any(|alias| norm(alias) == norm(style)))+ }++ /// Prefer known metric-compatible substitutes, then an appropriate script family. This+ /// never changes `has_family`: a usable substitute is still a missing original font.+ pub fn substitute_family(&self, family: &str) -> String {+ let lower = family.to_lowercase();+ let candidates: &[&str] = match lower.as_str() {+ "calibri" | "calibri light" => &["Carlito", "Liberation Sans"],+ "cambria" | "cambria math" => &["Caladea", "Liberation Serif"],+ "arial" | "helvetica" => &["Liberation Sans", "Arial", "Helvetica"],+ "times new roman" | "times" => &["Liberation Serif", "Times New Roman", "Times"],+ "courier new" | "courier" => &["Liberation Mono", "Courier New", "Courier"],+ _ if lower.contains("arabic") || lower.contains("naskh") => &["Amiri", "Noto Naskh Arabic", "Geeza Pro"],+ _ if family.contains('楷') => &["Kaiti SC", "STKaiti", "KaiTi", "Songti SC"],+ _ if family.contains("仿宋") => &["STFangsong", "FangSong", "Songti SC"],+ _ if family.contains('宋') || family.contains("明朝") => &["Songti SC", "Noto Serif CJK SC", "SimSun"],+ _ if family.contains('黑') || family.contains("雅黑") => &["PingFang SC", "Noto Sans CJK SC", "Microsoft YaHei"],+ _ if family.chars().any(|c| ('\u{3400}'..='\u{9fff}').contains(&c)) => &["Songti SC", "Noto Serif CJK SC", "PingFang SC"],+ _ => &[],+ };+ candidates.iter().find_map(|name| self.canonical_family(name)).unwrap_or_else(|| FALLBACK_FAMILY.to_string())+ }++ /// A replacement suggestion must cover the text being replaced, not just its main script.+ /// Ties retain the preferred substitute; this does not install or redefine any font.+ pub fn replacement_face(&self, family: &str, style: &str, characters: &[char]) -> Arc<FontFace> {+ let mut best = self.face(family, style);+ let coverage = |face: &FontFace| characters.iter().filter(|&&c| c.is_whitespace() || c.is_control() || face.covers(c)).count();+ let mut score = coverage(&best);+ let candidates: &[&str] = if characters.iter().any(|c| ('\u{0600}'..='\u{08ff}').contains(c)) {+ &["Amiri", "Noto Naskh Arabic", "Al Bayan", "Damascus", "Geeza Pro", "Arial"]+ } else if characters.iter().any(|c| ('\u{3400}'..='\u{9fff}').contains(c)) {+ &["Songti SC", "Kaiti SC", "Noto Serif CJK SC", "PingFang SC", "Noto Sans CJK SC"]+ } else {+ &["Source Serif 4", "Source Sans 3", "Inter"]+ };+ for candidate in candidates {+ if score == characters.len() {+ break;+ }+ if !self.has_family(candidate) {+ continue;+ }+ let face = self.face(candidate, style);+ let next = coverage(&face);+ if next > score {+ best = face;+ score = next;+ }+ }+ best+ }+/// Family names available (the document's, loaded and cataloged system fonts), sorted and/// deduplicated.pub fn families(&self) -> Vec<String> {@@@ -1685,8 -1521,14 +1750,16 @@@}fn exact_style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {+ let canonical = self.canonical_family(family);+ let family = canonical.as_deref().unwrap_or(family);+ let v = self.named_style_traits(family, false);+ // No face of that typographic family: the family may be a WWS name (see `find`).+ if v.is_empty() { self.named_style_traits(family, true) } else { v }+ }++ /// [`ScopedFonts::exact_style_traits`] by the faces' typographic names, or by their WWS names+ /// when `by_wws`.+ fn named_style_traits(&self, family: &str, by_wws: bool) -> Vec<(bool, f32, String)> {let mut v: Vec<(bool, f32, String)> = self.own().iter()@@@ -1853,19 -1707,20 +1931,28 @@@let faces = self.db.read_faces();// The document's fonts first: they stand in for other fonts of the same name.let named = |f: &&Arc<FontFace>| f.family.eq_ignore_ascii_case(family);- let mut cands: Vec<&Arc<FontFace>> = self.own().iter().filter(named).chain(faces.iter().filter(named)).collect();+ let own: Vec<&Arc<FontFace>> = self.own().iter().filter(named).collect();- let cands: Vec<&Arc<FontFace>> = if own.is_empty() { faces.iter().filter(named).collect() } else { own };++ let mut cands: Vec<&Arc<FontFace>> = if own.is_empty() { faces.iter().filter(named).collect() } else { own };+ // No face of that typographic family: the family may be a WWS name, whose faces carry+ // their WWS style names.+ let by_wws = cands.is_empty();+ if by_wws {+ let aliased = |f: &&Arc<FontFace>| has_wws_family(f, family);- cands = self.own().iter().filter(aliased).chain(faces.iter().filter(aliased)).collect();++ let own: Vec<&Arc<FontFace>> = self.own().iter().filter(aliased).collect();++ cands = if own.is_empty() { faces.iter().filter(aliased).collect() } else { own };+ }if cands.is_empty() {return None;}+ let style_of = |f: &FontFace| -> String { norm(f.wws.as_ref().filter(|_| by_wws).map_or(&f.style, |w| &w.1)) };let ns = norm(style);- if let Some(f) = cands.iter().find(|f| style_of(f) == ns) {+ // A face's own style name first: another face's legacy subfamily ("Black" faces named+ // "Regular" in their RIBBI family) or localized name must not shadow it.+ if let Some(f) = cands+ .iter()- .find(|f| norm(&f.style) == ns)++ .find(|f| style_of(f) == ns)+ .or_else(|| cands.iter().find(|f| f.coords.is_empty() && f.style_aliases.iter().any(|alias| norm(alias) == ns)))+ {return Some((*f).clone());}let (tw, ti) = (style_weight(style), style_italic(style));diff --cc crates/format/src/lib.rsindex fce6921c3,a1ceb24d6..3fc4ea8a2--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@@ -712,114 -649,78 +745,189 @@@ mod testsassert!(matches!(load(&buf.into_inner()), Err(FormatError::TooNew(99))));}+ fn r7a_nullable_document(local_clear: bool, style_clear: bool) -> Document {+ use designcraft_doc::{CharAttrs, ParaAttrs};+ let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });+ let base = d.styles.default_paragraph.clone();+ let chars = CharAttrs {+ leading_aki: Some(Some(4.0)),+ trailing_aki: Some(Some(3.0)),+ underline_weight: Some(Some(2.0)),+ underline_offset: Some(Some(1.0)),+ strikethrough_weight: Some(Some(2.0)),+ strikethrough_offset: Some(Some(1.0)),+ ..Default::default()+ };+ // Legacy JSON loads as format 1, whose upgrade pins Keep Lines Together and Align Left+ // Edge where a style chain leaves them unset; the base style sets them so both+ // formats resolve the same.+ let para = ParaAttrs {+ start_at: Some(Some(7)),+ paragraph_kashida_width: Some(Some(0.5)),+ kinsoku: Some(Some(Default::default())),+ keep_all_lines: Some(true),+ drop_cap_align_left: Some(true),+ ..Default::default()+ };+ let style = std::sync::Arc::make_mut(&mut d.styles).paragraph.iter_mut().find(|s| s.name == base).unwrap();+ style.chars = chars;+ style.para = para;+ let clear_chars = CharAttrs {+ leading_aki: Some(None),+ trailing_aki: Some(None),+ underline_weight: Some(None),+ underline_offset: Some(None),+ strikethrough_weight: Some(None),+ strikethrough_offset: Some(None),+ ..Default::default()+ };+ let clear_para = ParaAttrs { start_at: Some(None), paragraph_kashida_width: Some(None), kinsoku: Some(None), ..Default::default() };+ let selected = if style_clear {+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(designcraft_doc::styles::ParagraphStyle {+ name: "Defaults".into(),+ based_on: Some(base.clone()),+ next_style: None,+ para: clear_para.clone(),+ chars: clear_chars.clone(),+ shortcut: String::new(),+ });+ "Defaults".to_string()+ } else {+ base+ };+ let format = ParaFormat {+ style: selected,+ para: if local_clear { clear_para } else { ParaAttrs::default() },+ chars: if local_clear { clear_chars } else { CharAttrs::default() },+ table: None,+ };+ let layer = d.default_layer();+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 400.0), layer, "clear", format).unwrap();+ d+ }++ fn r7a_nullable_resolution(d: &Document) -> (designcraft_doc::ParaProps, designcraft_doc::CharProps) {+ let s = d.stories.values().find(|s| s.text == "clear").unwrap();+ d.styles.resolve_para(s.paras.first().unwrap())+ }++ fn r7a_assert_nullable_defaults_survive(d: &Document) {+ let expected = r7a_nullable_resolution(d);+ assert_eq!(expected.0.start_at, None);+ assert_eq!(expected.0.paragraph_kashida_width, None);+ assert_eq!(expected.0.kinsoku, None);+ assert_eq!(expected.1.leading_aki, None);+ // Legacy JSON is format 1: its upgrade pins older defaults on the other styles, so only+ // the native ZIP compares as the whole document.+ for (bytes, native) in [(save(d).unwrap(), true), (serde_json::to_vec(d).unwrap(), false)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), expected, "saved explicit defaults must not become inherited values");+ if native {+ assert_eq!(back, *d, "the native ZIP preserves the complete document");+ }+ }+ }++ #[test]+ fn r7a_native_local_default_text_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(true, false));+ }++ #[test]+ fn r7a_native_named_style_default_overrides_survive_zip_and_legacy_json() {+ r7a_assert_nullable_defaults_survive(&r7a_nullable_document(false, true));+ }++ #[test]+ fn r7a_native_nullable_missing_and_explicit_value_controls() {+ let d = r7a_nullable_document(false, false);+ assert_eq!(r7a_nullable_resolution(&d).0.start_at, Some(7));+ assert_eq!(r7a_nullable_resolution(&d).1.leading_aki, Some(4.0));+ for (bytes, native) in [(save(&d).unwrap(), true), (serde_json::to_vec(&d).unwrap(), false)] {+ let back = load(&bytes).unwrap();+ assert_eq!(r7a_nullable_resolution(&back), r7a_nullable_resolution(&d));+ if native {+ assert_eq!(back, d);+ }+ }+ let attrs: designcraft_doc::CharAttrs = serde_json::from_value(json!({"size":null})).unwrap();+ assert!(attrs.size.is_none(), "nonnullable fields retain their existing null contract");+ let props: designcraft_doc::CharProps = serde_json::from_value(json!({"leadingAki":null})).unwrap();+ assert_eq!(props.leading_aki, None);+ }+++ /// Write `len` bytes of `fill` to the current entry of `z`.+ fn write_fill(z: &mut zip::ZipWriter<Cursor<Vec<u8>>>, len: usize, fill: u8) {+ let chunk = vec![fill; 1 << 20];+ let mut left = len;+ while left > 0 {+ let n = left.min(chunk.len());+ z.write_all(&chunk[..n]).unwrap();+ left -= n;+ }+ }++ /// Make the archive claim that entry `name` expands to `size` bytes, in both its local header+ /// and its central directory record (the archive has no ZIP64 fields or data descriptors).+ fn claim_size(bytes: &mut [u8], name: &str, size: u32) {+ 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(name.as_bytes()) {+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&size.to_le_bytes());+ patched += 1;+ }+ }+ assert_eq!(patched, 2, "{name} not found in both headers");+ }++ /// A small archive whose `document.json` expands past the 256 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_document_json_is_refused() {+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (256 << 20) + 1, b' ');+ let mut bytes = z.finish().unwrap().into_inner();+ assert!(bytes.len() < 4 << 20, "{}", bytes.len());+ claim_size(&mut bytes, "document.json", 1);+ let Err(err) = load(&bytes) else { panic!("an oversized document.json loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An embedded file that expands past the 1 GiB limit (and says so) is refused too.+ #[test]+ fn oversized_asset_is_refused() {+ let mut d = Document::new(&NewDocument::default());+ let aid = png_asset(&mut d, &[1]);+ place(&mut d, aid, 0.0);+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ z.start_file("document.json", zip::write::SimpleFileOptions::default()).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ z.start_file(format!("assets/{}.png", aid.0), zip::write::SimpleFileOptions::default()).unwrap();+ write_fill(&mut z, (1 << 30) + 1, 0);+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an oversized asset loaded") };+ assert!(err.to_string().contains("limit"), "{err}");+ }++ /// An archive with more entries than any document needs is refused before any is read.+ #[test]+ fn too_many_entries_are_refused() {+ let d = Document::new(&NewDocument::default());+ let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));+ let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);+ z.start_file("document.json", stored).unwrap();+ z.write_all(&serde_json::to_vec(&d).unwrap()).unwrap();+ for i in 0..100_000 {+ z.start_file(format!("junk/{i}"), stored).unwrap();+ }+ let Err(err) = load(&z.finish().unwrap().into_inner()) else { panic!("an archive with 100 001 entries loaded") };+ assert!(err.to_string().contains("entries"), "{err}");+ }}diff --cc crates/idml/src/import.rsindex a87c65f22,6d399f5a8..ffdaf9a40--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -7,10 -7,10 +7,11 @@@ use std::sync::Arcuse designcraft_color::cms::lab;use designcraft_color::{Color, ColorType, Gradient, GradientKind, GradientStop, Swatch, SwatchValue, swatch};use designcraft_doc::{- Asset, AssetId, BaselineGrid, CellRange, CharAttrs, CharFormat, CharRun, CharacterStyle, Columns, ColumnsKind, Content, DocSettings, Document,- DropShadow, Effects, Fill, GridAlign, GridRelative, Guide, Item, ItemId, Kerning, LAYER_COLORS, Layer, LayerId, ListType, Margins, ObjectStyle,- Orientation, Page, PageId, PageSide, ParaAttrs, ParaFormat, ParagraphStyle, ParentInfo, RowHeightMode, Rule, Section, Shape, SpanColumns, Spread,- SpreadId, Story, StoryId, Stroke, Styles, TabStop, Table, TextFrame, TextFrameOptions, TextWrap, story as st,+ Asset, AssetId, BaselineGrid, CellRange, CharAttrs, CharFormat, CharRun, CharacterStyle, Columns, ColumnsKind, Content, DirectionalFeather,+ DocSettings, Document, DropShadow, Effects, Fill, GradientFeather, GridAlign, GridRelative, Guide, Item, ItemId, Kerning, LAYER_COLORS, Layer,- LayerId, ListType, Margins, ObjectStyle, Page, PageId, PageSide, ParaAttrs, ParaFormat, ParagraphStyle, ParentInfo, RowHeightMode, Rule, Section,- Shape, SpanColumns, Spread, SpreadId, Story, StoryId, Stroke, Styles, TabStop, Table, TextFrame, TextFrameOptions, TextWrap, story as st,++ LayerId, ListType, Margins, ObjectStyle, Orientation, Page, PageId, PageSide, ParaAttrs, ParaFormat, ParagraphStyle, ParentInfo, RowHeightMode,++ Rule, Section, Shape, SpanColumns, Spread, SpreadId, Story, StoryId, Stroke, Styles, TabStop, Table, TextFrame, TextFrameOptions, TextWrap,++ story as st,};use designcraft_geom::corners::{Corner, CornerOptions};use designcraft_geom::{Affine, Anchor, PathData, Point, Rect, SubPath};@@@ -26,32 -26,14 +27,22 @@@ fn uniform_cell_stroke(edges: &[designcif edges.iter().any(|edge| edge != first) {return None;}- Some(designcraft_doc::CellStroke { weight: first.weight?, color: first.color.clone()?, tint: first.tint?, kind: first.kind.clone()? })+ let mut stroke = designcraft_doc::CellStroke {+ weight: first.weight?,+ color: first.color.clone()?,+ tint: first.tint?,+ kind: first.kind.clone()?,+ ..Default::default()+ };+ first.apply_to(&mut stroke);+ Some(stroke)}- /// Import an IDML package. Linked images are read from disk when available (not on wasm).+ /// Import an IDML package without reading its linked images from disk: this crate never touches+ /// the file system, so a caller that wants the links brings its own reader+ /// ([`import_idml_with`]). The engine passes one that checks the automation roots.pub fn import_idml(bytes: &[u8]) -> Result<Document> {- import_idml_with(bytes, &default_reader)- }-- fn default_reader(path: &str) -> Option<Vec<u8>> {- #[cfg(not(target_arch = "wasm32"))]- {- std::fs::read(path).ok()- }- #[cfg(target_arch = "wasm32")]- {- let _ = path;- None- }+ import_idml_with(bytes, &|_| None)}/// Import with a custom reader for linked files (`path` → bytes).@@@ -70,41 -52,14 +61,25 @@@ pub struct Imported/// Import with a custom reader for linked files, reporting the problems that did not stop it.pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Imported> {+ import_idml_report_with_previews(bytes, read_link, &HashMap::new())+}++/// [`import_idml_report`], with stand-in images for graphics whose file neither the package nor+/// `read_link` provides: `previews` maps a graphic's `Self` to an image (an InDesign document's+/// screen preview of a linked file). The graphic keeps its link, so relinking replaces it.+pub fn import_idml_report_with_previews(+ bytes: &[u8],+ read_link: &dyn Fn(&str) -> Option<Vec<u8>>,+ previews: &HashMap<String, Arc<Vec<u8>>>,+) -> Result<Imported> {- let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;- let mut files: HashMap<String, Vec<u8>> = HashMap::new();- // Normalised part name → entry name, first entry wins (zip order, so the choice is stable).- let mut lenient: HashMap<String, String> = HashMap::new();- for i in 0..zip.len() {- let mut f = zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;- if f.is_dir() {- continue;- }- let name = f.name().to_string();- // The size is what the archive claims: don't reserve more than a sane part up front.- let mut buf = Vec::with_capacity((f.size() as usize).min(1 << 24));- f.read_to_end(&mut buf).map_err(|e| IdmlError::Part { part: name.clone(), msg: e.to_string() })?;- lenient.entry(normalize_part_name(&name)).or_insert_with(|| name.clone());- files.insert(name, buf);- }- let part = |name: &str| files.get(name).or_else(|| lenient.get(&normalize_part_name(name)).and_then(|n| files.get(n)));- if let Some(m) = part("mimetype")- && String::from_utf8_lossy(m).trim() != MIMETYPE+ let mut pkg = Package::open(bytes)?;+ if let Some(m) = pkg.part("mimetype")?+ && String::from_utf8_lossy(&m).trim() != MIMETYPE{- return Err(IdmlError::NotIdml(format!("unexpected mimetype `{}`", String::from_utf8_lossy(m).trim())));+ return Err(IdmlError::NotIdml(format!("unexpected mimetype `{}`", String::from_utf8_lossy(&m).trim())));}- let dm = part("designmap.xml").ok_or_else(|| IdmlError::NotIdml("missing designmap.xml".into()))?;- let root = parse(dm).map_err(|msg| IdmlError::Part { part: "designmap.xml".into(), msg })?;+ let dm = pkg.part("designmap.xml")?.ok_or_else(|| IdmlError::NotIdml("missing designmap.xml".into()))?;+ let root = parse(&dm).map_err(|msg| IdmlError::Part { part: "designmap.xml".into(), msg })?;if root.local() != "Document" {return Err(IdmlError::NotIdml(format!("designmap root is <{}>", root.name)));}@@@ -124,24 -79,9 +99,24 @@@top.push(c.clone());}}- let mut im = Importer::new(read_link);+ let mut im = Importer::new(read_link, previews);- if let Some(m) = files.get("META-INF/metadata.xml") {- let m = String::from_utf8_lossy(m);++ if let Some(m) = pkg.part("META-INF/metadata.xml")? {++ let m = String::from_utf8_lossy(&m);+ im.created = xmp_date(&m, "xmp:CreateDate");+ im.modified = xmp_date(&m, "xmp:ModifyDate");+ }im.run(&root, &top)?;- let document = im.finish(&root).map_err(|e| match e {+ if im.repaired_tab_lists > 0 {+ warnings.push(format!(+ "tab lists repaired to fit the limits (at most {} stops, finite positions up to {} in, leaders of at most {} characters, one stop per position): {}",+ designcraft_doc::MAX_TAB_STOPS,+ designcraft_doc::MAX_TAB_POSITION / 72.0,+ designcraft_doc::MAX_TAB_LEADER,+ im.repaired_tab_lists,+ ));+ }+ warnings.append(&mut im.warnings);+ let mut document = im.finish(&root).map_err(|e| match e {// Without its spread parts there is nothing to open: say which parts were missing.IdmlError::Invalid(msg) if !warnings.is_empty() => IdmlError::Invalid(format!("{msg} ({})", warnings.join("; "))),e => e,@@@ -151,19 -90,76 +126,81 @@@Ok(Imported { document, warnings })}-/// View Preferences › Ruler Origin.-#[derive(Clone, Copy, PartialEq, Eq)]-enum RulerOrigin {- Spread,- Page,- Spine,+/// Whether sanitizing a file's tab list dropped, moved or shortened a stop. Sorting, and the `.`+/// a char stop with no character aligns on, change nothing.+fn tab_list_repaired(read: &[TabStop], sanitized: &[TabStop]) -> bool {+ let kept = |t: &TabStop| {+ sanitized.iter().any(|o| {+ o.position == t.position+ && o.leader == t.leader+ && (o.align_on == t.align_on || (t.align_on.is_empty() && o.align == designcraft_doc::TabAlign::Char))+ })+ };+ read.len() != sanitized.len() || !read.iter().all(kept)}+ /// Most entries an IDML package may hold.+ const MAX_ENTRIES: usize = 100_000;+ /// Most bytes one package part may expand to.+ const MAX_PART_BYTES: u64 = 512 << 20;+ /// Most bytes all the parts read from one package may expand to together.+ const MAX_TOTAL_BYTES: u64 = 2 << 30;++ /// An IDML package whose parts are decompressed only when the import asks for them, within+ /// byte budgets that don't trust the sizes the archive claims.+ struct Package<'a> {+ zip: zip::ZipArchive<std::io::Cursor<&'a [u8]>>,+ /// Normalised part name → entry name, first entry wins (zip order, so the choice is stable).+ lenient: HashMap<String, String>,+ /// Bytes the parts still to be read may expand to.+ left: u64,+ }++ impl<'a> Package<'a> {+ fn open(bytes: &'a [u8]) -> Result<Self> {+ let zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;+ if zip.len() > MAX_ENTRIES {+ return Err(IdmlError::NotIdml(format!("{} entries (at most {MAX_ENTRIES})", zip.len())));+ }+ let mut lenient: HashMap<String, String> = HashMap::new();+ for i in 0..zip.len() {+ let Some(name) = zip.name_for_index(i) else { continue };+ if name.ends_with('/') {+ continue;+ }+ lenient.entry(normalize_part_name(name)).or_insert_with(|| name.to_string());+ }+ Ok(Package { zip, lenient, left: MAX_TOTAL_BYTES })+ }++ /// The bytes of part `name` (matched exactly, then leniently), or `None` if the package has+ /// no such part.+ fn part(&mut self, name: &str) -> Result<Option<Vec<u8>>> {+ let exact = self.zip.index_for_name(name).filter(|_| !name.ends_with('/'));+ let Some(i) = exact.or_else(|| self.lenient.get(&normalize_part_name(name)).and_then(|n| self.zip.index_for_name(n))) else {+ return Ok(None);+ };+ let f = self.zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;+ let part = f.name().to_string();+ let limit = MAX_PART_BYTES.min(self.left);+ let too_big = || IdmlError::Part {+ part: part.clone(),+ msg: format!("larger than the {MAX_PART_BYTES}-byte part limit (or the package is larger than {MAX_TOTAL_BYTES} bytes)"),+ };+ if f.size() > limit {+ return Err(too_big());+ }+ let mut buf = Vec::new();+ f.take(limit.saturating_add(1)).read_to_end(&mut buf).map_err(|e| IdmlError::Part { part: part.clone(), msg: e.to_string() })?;+ let n = buf.len() as u64;+ if n > limit {+ return Err(too_big());+ }+ self.left = self.left.saturating_sub(n);+ Ok(Some(buf))+ }+ }+/// A package part name in the form the lookup compares: InDesign and other IDML writers differ/// in percent-encoding, case, path separators and a leading `./` or `/`.fn normalize_part_name(name: &str) -> String {@@@ -2355,6 -2059,33 +2430,33 @@@ impl<'r> Importer<'r>// ---------- spreads and items ----------+ /// Ruler guides of a `<Page>` (its `<Guide>` children), `page` its rectangle in our spread+ /// coordinates. A guide's Location is measured from the ruler origin: the spread's top left, the+ /// page's, or the spine. Fit to Page off: the guide crosses the spread.+ fn guides_of(&self, p: &El, page: Rect, spine: f64) -> Vec<Guide> {+ p.find_all("Guide")+ .filter_map(|g| {+ let at = g.num("Location").filter(|v| v.is_finite() && v.abs() < 1e7)?;+ let orientation = if g.get("Orientation") == Some("Horizontal") { Orientation::Horizontal } else { Orientation::Vertical };- let position = match (orientation, self.ruler_origin) {- (Orientation::Horizontal, RulerOrigin::Page) => page.y0 + at,++ let position = match (orientation, self.settings.ruler_origin) {++ (Orientation::Horizontal, designcraft_doc::RulerOrigin::Page) => page.y0 + at,+ (Orientation::Horizontal, _) => at,- (Orientation::Vertical, RulerOrigin::Page) => page.x0 + at,- (Orientation::Vertical, RulerOrigin::Spine) => spine + at,- (Orientation::Vertical, RulerOrigin::Spread) => at,++ (Orientation::Vertical, designcraft_doc::RulerOrigin::Page) => page.x0 + at,++ (Orientation::Vertical, designcraft_doc::RulerOrigin::Spine) => spine + at,++ (Orientation::Vertical, designcraft_doc::RulerOrigin::Spread) => at,+ };+ Some(Guide {+ orientation,+ position,+ spread: g.get("FitToPage") == Some("false"),+ locked: g.get("Locked") == Some("true"),+ layer: g.get("ItemLayer").and_then(|l| self.layer_ids.get(l)).copied(),+ liquid: false,+ })+ })+ .collect()+ }+fn spread(&mut self, e: &El, id: SpreadId, master: bool) -> Spread {let facing = self.settings.facing_pages;// Page rectangles in IDML spread coordinates.@@@ -2372,9 -2103,11 +2474,12 @@@let min_y = pages.iter().map(|(r, _)| r.y0).fold(f64::INFINITY, f64::min);let (min_x, min_y) = if min_x.is_finite() { (min_x, min_y) } else { (0.0, 0.0) };let shift = Affine::translate((-min_x, -min_y));+ // The spine: between a left and a right page (else the spread's left edge).+ let spine = pages.iter().map(|(r, _)| r.x0 - min_x).filter(|x| *x > 1e-6).fold(f64::INFINITY, f64::min);+ let spine = if spine.is_finite() && facing { spine } else { 0.0 };let show = e.get("ShowMasterItems") != Some("false");let first_abs: usize = self.spreads.iter().map(|s| s.pages.len()).sum();+ let view_rotation = if master { 0 } else { spread_view_rotation(e.get("ItemTransform")) };let mut out_pages = Vec::new();for (i, (r, p)) in pages.iter().enumerate() {let pid = PageId(self.alloc());@@@ -2418,11 -2151,11 +2523,11 @@@parent,side,overridden: vec![],- guides: Vec::<Guide>::new(),+ guides: self.guides_of(p, Rect::new(r.x0 - min_x, r.y0 - min_y, r.x1 - min_x, r.y1 - min_y), spine),show_parent_items: show,- liquid: Default::default(),+ liquid: names::liquid_rule_in(p.get("LayoutRule").unwrap_or("Off")),transition: None,- view_rotation: 0,+ view_rotation: if i == 0 { view_rotation } else { 0 },show_parent_overlay: false,});}@@@ -2887,16 -2516,9 +2992,13 @@@None => (0.0, 0.0, 0.0, 0.0),};let size = ((r - l).abs(), (b - t).abs());+ let wrap =+ if g.get("AppliedObjectStyle").is_some() { self.with_style(g, "TextWrapPreference") } else { g.find("TextWrapPreference").cloned() };+ let wrap = wrap.map(|w| text_wrap(&w)).unwrap_or_default();+ let clip = clipping_path(g, Affine::translate((-l, -t)));let link = g.find("Link");let uri = link.and_then(|k| k.get("LinkResourceURI")).map(uri_to_path);- 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);- let graphic = |asset| {+ let graphic = |asset, size| {Content::Graphic(designcraft_doc::Graphic {asset,size,@@@ -2921,13 -2545,13 +3029,16 @@@}if let Some(d) = (self.read_link)(p) {data = d;- read_from = Some(p.clone());+ read_from = Some(key);}}+ // A linked file that can't be read shows the document's preview of it, if it has one. The+ // preview only stands in for the file: format and pixel size still describe the link.+ let preview = data.is_empty().then(|| g.get("Self").and_then(|s| self.previews.get(s))).flatten();+ // 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, px) = if preview.is_some() { (None, None) } else { 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(),f if f.contains("TIFF") => "image/tiff".into(),@@@ -2945,22 -2569,12 +3056,22 @@@let link_path = uri.filter(|p| p.contains('/') || p.contains('\\'));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() },+ Asset {+ page,+ id: fresh,+ name,+ mime,+ link: link_path,+ data: preview.cloned().unwrap_or_else(|| Arc::new(data)),+ pixels,+ pdf_crop,+ ..Default::default()+ },);- if let Some(p) = read_from {- self.linked_assets.insert((p, page, pdf_crop), id);+ if let Some(key) = read_from {+ self.linked_assets.insert(key, id);}- graphic(id)+ graphic(id, size)}fn link_threads(&mut self) {@@@ -3518,51 -2970,21 +3629,61 @@@ fn path_capped(pg: &El, max: usize) ->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)}+/// Anchors a custom text wrap boundary may have.+const MAX_WRAP_PATH_ANCHORS: usize = 4096;++/// A custom text wrap boundary (`TextWrapPreference/Properties/PathGeometry`), in the item's inner+/// space like its own path. Hostile input is an error: too many anchors, a malformed or non-finite+/// point, or no points at all.+fn wrap_path_of(pg: &El) -> std::result::Result<PathData, &'static str> {+ let finite = |s: Option<&str>| -> std::result::Result<Option<Point>, &'static str> {+ let Some(s) = s else { return Ok(None) };+ let v = nums(s);+ match (v.first(), v.get(1)) {+ (Some(&x), Some(&y)) if v.len() == 2 && x.is_finite() && y.is_finite() => Ok(Some(Point::new(x, y))),+ _ => Err("malformed or non-finite point"),+ }+ };+ let mut subs = Vec::new();+ let mut n = 0usize;+ for g in pg.find_all("GeometryPathType") {+ let closed = g.get("PathOpen") != Some("true");+ let mut anchors = Vec::new();+ for p in g.find("PathPointArray").into_iter().flat_map(|arr| arr.find_all("PathPointType")) {+ n = n.saturating_add(1);+ if n > MAX_WRAP_PATH_ANCHORS {+ return Err("too many points");+ }+ let a = finite(p.get("Anchor"))?.ok_or("point without an anchor")?;+ let hin = finite(p.get("LeftDirection"))?.unwrap_or(a);+ let hout = finite(p.get("RightDirection"))?.unwrap_or(a);+ anchors.push(Anchor::with_handles(a, hin, hout));+ }+ if !anchors.is_empty() {+ subs.push(SubPath::new(anchors, closed));+ }+ }+ if subs.is_empty() {+ return Err("no points");+ }+ Ok(PathData::new(subs))+}+/// 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.rsindex 6de2985b0,780b596e8..8bc4a7cf9--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1544,178 -618,187 +1544,203 @@@ fn automatic_kerning_does_not_import_in}#[test]-fn round_trips_tables() {- let mut d = Document::new(&NewDocument::default());- d.swatches.push(Swatch::color("Brand", Color::rgb(1.0, 0.0, 0.0)));- let lid = d.default_layer();- let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Intro\nOutro", ParaFormat::default()).unwrap();- let mut t = designcraft_doc::Table::new(d.alloc(), 3, 3, 1, 0, 300.0);- t.cell_mut(0, 0).unwrap().text.insert(0, "Head");- t.cell_mut(0, 0).unwrap().fill = "Brand".into();- t.cell_mut(1, 2).unwrap().text.insert(0, "Body\nTwo");- t.cell_mut(2, 1).unwrap().vj = designcraft_doc::VerticalJustification::Center;- t.rows[2].mode = designcraft_doc::RowHeightMode::Exactly;- t.rows[2].height = 30.0;- t.columns[0].width = 50.0;- t.merge(designcraft_doc::CellRange::new(2, 1, 3, 2)).unwrap();- t.options.alt_rows = Some(designcraft_doc::AltFills { first: 1, first_color: "Brand".into(), first_tint: 0.2, ..Default::default() });- d.story_mut(sid).unwrap().insert_table(5, t.clone());- d.check().unwrap();+fn cjk_composite_fonts_and_custom_kinsoku_are_document_resources() {+ let map = DESIGNMAP.replace("</Document>", r#"+ <KinsokuTable Self="KinsokuTable/Test" Name="Test" CantBeginLineChars="乙" CantEndLineChars="甲" CantBeSeparatedChars="—" HangingPunctuationChars="。"/>+ <CompositeFont Self="CompositeFont/Mixed" Name="Mixed"><CompositeFontEntry Self="cf1" Name="Base" FontStyle="Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>+ <CompositeFontEntry Self="cf2" Name="Digits" CustomCharacters="0123456789" FontStyle="Regular" RelativeSize="80" BaselineShift="10"><Properties><AppliedFont type="string">$ID/Source Sans 3</AppliedFont></Properties></CompositeFontEntry></CompositeFont>+ </Document>"#);+ let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange KinsokuSet=\"KinsokuTable/Test\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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(&bytes).unwrap();+ let f = &d.styles.composite_fonts[0];+ assert_eq!(f.entry('1').unwrap().family, "Source Sans 3");+ assert_eq!(f.entry('甲').unwrap().family, "Source Serif 4");+ assert_eq!(f.entry('1').unwrap().relative_size, 0.8);let back = import_idml(&export_idml(&d)).unwrap();- back.check().unwrap();- let s = back.stories.values().next().unwrap();- assert_eq!(s.text, format!("Intro\n{}\nOutro", st::TABLE_ANCHOR));- let bt = s.tables.values().next().unwrap();- assert_eq!((bt.nrows(), bt.ncols(), bt.header_rows()), (4, 3, 1));- assert_eq!(bt.cell(0, 0).unwrap().text.text, "Head");- assert_eq!(bt.cell(0, 0).unwrap().fill, "Brand");- assert_eq!(bt.cell(1, 2).unwrap().text.text, "Body\nTwo");- assert_eq!(bt.cell(2, 1).unwrap().vj, designcraft_doc::VerticalJustification::Center);- assert_eq!((bt.cell(2, 1).unwrap().row_span, bt.cell(2, 1).unwrap().col_span), (2, 2));- assert_eq!(bt.rows[2].mode, designcraft_doc::RowHeightMode::Exactly);- assert!((bt.rows[2].height - 30.0).abs() < 1e-6);- assert!((bt.columns[0].width - 50.0).abs() < 1e-6);- assert_eq!(bt.options.alt_rows.as_ref().map(|a| a.first_color.as_str()), Some("Brand"));+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);+ assert!(+ back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.kinsoku.as_ref().and_then(Option::as_ref).is_some_and(|k| k.no_start == "乙"))+ );}+ #[test]-fn imports_and_round_trips_explicit_cell_border_overrides() {- // Hand-written IDML: the outer cell edge may explicitly suppress or replace the- // table border. An absent/zero priority keeps the table border's precedence.- let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">-<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange>-<Table HeaderRowCount="0" FooterRowCount="0" TopBorderStrokeWeight="2">- <Row Name="0" MinimumHeight="24"/>- <Column Name="0" SingleColumnWidth="60"/><Column Name="1" SingleColumnWidth="60"/>- <Cell Name="0:0" TopEdgeStrokeColor="Swatch/None" TopEdgeStrokePriority="1"- LeftEdgeStrokeColor="Color/Brand" LeftEdgeStrokeWeight="3" LeftEdgeStrokePriority="2"- BottomEdgeStrokeWeight="0" BottomEdgeStrokePriority="0" RightEdgeStrokeColor="Swatch/None">- <ParagraphStyleRange><CharacterStyleRange><Content>A</Content></CharacterStyleRange></ParagraphStyleRange>- </Cell>- <Cell Name="1:0"><ParagraphStyleRange><CharacterStyleRange><Content>B</Content></CharacterStyleRange></ParagraphStyleRange></Cell>-</Table></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;- let d = import_idml(&fixture_with_story(story)).unwrap();- d.check().unwrap();- let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();- let cell = table.cell(0, 0).unwrap();- assert_eq!(cell.border_overrides, [true, true, false, false]);- assert!(!cell.strokes[0].is_visible(), "explicit None is retained");- assert_eq!(cell.strokes[1].color, "Brand");- assert_eq!(cell.strokes[1].weight, 3.0);- assert_eq!(table.options.border.weight, 2.0);- assert_eq!(table.cell(0, 1).unwrap().border_overrides, [false; 4]);++fn cjk_unsupported_mojikumi_is_preserved_instead_of_silently_dropped() {++ let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="MojikumiTable/Spacing" Name="Spacing" BasedOnMojikumiSet="SimpChineseDefault"><Properties><OverrideMojikumiAkiList>++ <OverrideMojikumiAkiType TargetMojikumiClass="1" SideMojikumiClass="23" SideIsAfterTarget="false" Minimum="-0.1" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="true"/>++ </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);++ let story =++ STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"MojikumiTable/Spacing\" KinsokuType=\"KinsokuPushOutFirst\" ");++ let bytes = zip_files(&[++ ("designmap.xml", &map),++ ("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(&bytes).unwrap();++ let t = &d.styles.mojikumi_tables[0];++ assert_eq!(t.overrides[0].minimum, -0.1);++ assert!(t.overrides[0].does_not_float);++ let back = import_idml(&export_idml(&d)).unwrap();++ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);++ assert!(back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.mojikumi.as_deref() == Some("MojikumiTable/Spacing")));++}++#[test]+fn cjk_mojikumi_overrides_and_priority_round_trip() {+ let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="uMojikumi1" Name="Spacing" BasedOnMojikumiSet="SimpChineseDefault"><Properties><OverrideMojikumiAkiList>+ <OverrideMojikumiAkiType TargetMojikumiClass="1" SideMojikumiClass="23" SideIsAfterTarget="false" Minimum="-0.1" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="true"/>+ </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);+ let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"uMojikumi1\" KinsokuType=\"KinsokuPushOutFirst\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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(&bytes).unwrap();+ let t = &d.styles.mojikumi_tables[0];+ assert_eq!(t.overrides[0].minimum, -0.1);+ assert!(t.overrides[0].does_not_float);let back = import_idml(&export_idml(&d)).unwrap();- let roundtrip = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();- assert_eq!(roundtrip.cell(0, 0).unwrap().border_overrides, cell.border_overrides);- assert_eq!(roundtrip.cell(0, 0).unwrap().strokes, cell.strokes);- assert_eq!(roundtrip.cell(0, 1).unwrap().border_overrides, [false; 4]);+ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);+ assert!(back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.mojikumi.as_deref() == Some("MojikumiTable/Spacing")));}+/// A custom table with no `BasedOnMojikumiSet` keeps its own rows on the+/// default half-em set, and the attribute stays absent on export.#[test]-fn round_trips_footnotes_and_options() {- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Body text here.", ParaFormat::default()).unwrap();- {- let s = d.story_mut(sid).unwrap();- s.insert_note(4, "First note.", ParaFormat::default());- s.insert_note(9, "Second\nnote.", ParaFormat::default());- }- d.footnote_options.style = designcraft_doc::NumberStyle::LowerRoman;- d.footnote_options.restart = designcraft_doc::notes::NoteRestart::Page;- d.footnote_options.affix_in = designcraft_doc::notes::AffixIn::Both;- d.footnote_options.prefix = "[".into();- d.footnote_options.rule.width = 100.0;- d.footnote_options.space_before = 4.0;- d.check().unwrap();- let bytes = export_idml(&d);- let back = import_idml(&bytes).unwrap();- back.check().unwrap();- let s = back.stories.values().next().unwrap();- assert_eq!(s.text, d.story(sid).unwrap().text);- assert_eq!(s.notes.len(), 2);- assert_eq!(s.notes[0].text.text, "First note.");- assert_eq!(s.notes[1].text.text, "Second\nnote.");- assert_eq!(back.footnote_options, d.footnote_options);+fn cjk_mojikumi_table_without_base_set_applies_its_rows() {+ let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="uMojikumi2" Name="Baseless"><Properties><OverrideMojikumiAkiList>+ <OverrideMojikumiAkiType TargetMojikumiClass="12" SideMojikumiClass="18" SideIsAfterTarget="true" Minimum="0.25" Desired="0.75" Maximum="1" CompressionPriority="2" AkiDoesNotFloat="false"/>+ </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);+ let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"uMojikumi2\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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(&bytes).unwrap();+ let name = d.stories.values().flat_map(|s| &s.paras).find_map(|p| p.para.mojikumi.clone()).unwrap();+ assert_eq!(name, "MojikumiTable/Baseless");+ let rules = designcraft_doc::mojikumi::Rules::resolve(&d.styles, &name).unwrap().unwrap();+ assert!(rules.assumed_base());+ let pair = rules.pair(12, 18);+ assert_eq!((pair.min, pair.desired, pair.max, pair.priority), (0.25, 0.75, 1.0, 2));+ // Pairs the table does not list use the half-em set: no blank at line start.+ assert_eq!(rules.pair(22, designcraft_doc::mojikumi::class('(')).desired, 0.0);+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);}-/// The structure InDesign writes: the footnote in its own superscript range, its text starting-/// with the number marker and the separator.+/// `BasedOnMojikumiSet="Nothing"` names no base set: the table resolves as one+/// without the attribute, and the value survives export.#[test]-fn imports_indesign_style_footnote() {- let story = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>-<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">-<Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">-<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Body text with a</Content></CharacterStyleRange>-<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" Position="Superscript"><Footnote>-<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content><?ACE 4?>	A source note.</Content></CharacterStyleRange></ParagraphStyleRange>-</Footnote></CharacterStyleRange>-<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content> note here.</Content></CharacterStyleRange>-</ParagraphStyleRange></Story></idPkg:Story>"#;- let d = import_idml(&fixture_with_story(story)).unwrap();- d.check().unwrap();- let s = d.stories.values().find(|s| !s.notes.is_empty()).expect("story with a footnote");- assert_eq!(s.text, format!("Body text with a{} note here.", designcraft_doc::FOOTNOTE_REF));- assert_eq!(s.notes[0].text.text, "A source note.");- // One run: the reference takes its position from the options, not an override.- assert_eq!(s.chars.len(), 1);+fn cjk_mojikumi_table_based_on_nothing_matches_a_table_without_base_set() {+ let row = r#"<OverrideMojikumiAkiType TargetMojikumiClass="12" SideMojikumiClass="18" SideIsAfterTarget="true" Minimum="0.25" Desired="0.75" Maximum="1" CompressionPriority="2" AkiDoesNotFloat="false"/>"#;+ let map = DESIGNMAP.replace("</Document>", &format!(r#"<MojikumiTable Self="uMojikumi2" Name="Baseless"><Properties><OverrideMojikumiAkiList>{row}</OverrideMojikumiAkiList></Properties></MojikumiTable>+ <MojikumiTable Self="uMojikumi3" Name="NoBase" BasedOnMojikumiSet="Nothing"><Properties><OverrideMojikumiAkiList>{row}</OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#));+ let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"uMojikumi3\" ");+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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(&bytes).unwrap();+ let name = d.stories.values().flat_map(|s| &s.paras).find_map(|p| p.para.mojikumi.clone()).unwrap();+ assert_eq!(name, "MojikumiTable/NoBase");+ let nothing = designcraft_doc::mojikumi::Rules::resolve(&d.styles, &name).unwrap().unwrap();+ let missing = designcraft_doc::mojikumi::Rules::resolve(&d.styles, "MojikumiTable/Baseless").unwrap().unwrap();+ assert!(nothing.assumed_base());+ let close = designcraft_doc::mojikumi::class('。');+ for (l, r) in [(12, 18), (22, designcraft_doc::mojikumi::class('(')), (close, 22), (close, 12)] {+ let (a, b) = (missing.pair(l, r), nothing.pair(l, r));+ assert_eq!((a.min, a.desired, a.max, a.priority), (b.min, b.desired, b.max, b.priority), "{l}/{r}");+ }+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);+ assert_eq!(back.styles.mojikumi_tables[1].based_on, "Nothing");}+/// The built-in `LineEndAllOneEmEnum` set applies directly and as a custom+/// table's base: closing punctuation at line end keeps its full em.#[test]-fn round_trips_cross_references() {- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let (_, sid) =- d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Results: found\nSee .", ParaFormat::default()).unwrap();- let target = d.paragraph_anchor(sid, 0).unwrap();- let at = d.story(sid).unwrap().text.find(" .").unwrap() + 1;- d.story_mut(sid).unwrap().insert_xref(at, designcraft_doc::CrossRef { target, format: "Paragraph Text".into() });- d.xref_formats.push(designcraft_doc::XrefFormat {- name: "Mine".into(),- definition: "(<partialPara delim=\":\" includeDelim=\"true\" />, p. <pageNum />)".into(),- });- d.check().unwrap();+fn cjk_mojikumi_line_end_all_one_em_set_applies_and_round_trips() {+ let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="uMojikumi4" Name="OneEm" BasedOnMojikumiSet="LineEndAllOneEmEnum"><Properties><OverrideMojikumiAkiList>+ <OverrideMojikumiAkiType TargetMojikumiClass="12" SideMojikumiClass="18" SideIsAfterTarget="true" Minimum="0.25" Desired="0.75" Maximum="1" CompressionPriority="2" AkiDoesNotFloat="false"/>+ </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);+ let story = STORY.replacen("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"$ID/LineEndAllOneEmEnum\" ", 1);+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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(&bytes).unwrap();+ let name = d.stories.values().flat_map(|s| &s.paras).find_map(|p| p.para.mojikumi.clone()).unwrap();+ let close = designcraft_doc::mojikumi::class('。');+ for name in [name.as_str(), "MojikumiTable/OneEm"] {+ let rules = designcraft_doc::mojikumi::Rules::resolve(&d.styles, name).unwrap().unwrap();+ assert!(!rules.assumed_base(), "{name}");+ assert_eq!(rules.pair(close, 22).desired, 0.5, "{name}");+ assert_eq!(rules.pair(22, designcraft_doc::mojikumi::class('(')).desired, 0.0, "{name}");+ }let back = import_idml(&export_idml(&d)).unwrap();- back.check().unwrap();- let s = back.stories.values().next().unwrap();- assert_eq!(s.text, d.story(sid).unwrap().text);- assert_eq!(s.xrefs.len(), 1);- assert_eq!(s.xrefs[0].format, "Paragraph Text");- let (tsid, tpos) = back.find_anchor(s.xrefs[0].target).expect("target resolves");- assert_eq!((tsid, tpos), (s.id, 0));- let mine = back.xref_format("Mine").unwrap();- assert_eq!(mine.definition, d.xref_format("Mine").unwrap().definition);- assert_eq!(back.xref_formats.len(), d.xref_formats.len());+ assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);+ let back_name = back.stories.values().flat_map(|s| &s.paras).find_map(|p| p.para.mojikumi.clone()).unwrap();+ assert_eq!(back_name, name);}-/// A cross-reference source sits either inside a character range (holding the text directly) or at-/// paragraph level around a range. Both give the generated text the paragraph's and the range's-/// attributes, so both set the same text at the same width.#[test]-fn cross_reference_source_nesting_keeps_formatting() {- let story = |body: &str| {- 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"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" PointSize="11">{body}</ParagraphStyleRange></Story></idPkg:Story>"#- )- };- const CSR: &str = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" Tracking="200">"#;- let inside = story(&format!(- r#"{CSR}<Content>See section </Content><CrossReferenceSource Self="x1" AppliedFormat="n"><Content>11.</Content></CrossReferenceSource><Content>, then a few more words to wrap.</Content></CharacterStyleRange>"#- ));- let around = story(&format!(- r#"{CSR}<Content>See section </Content></CharacterStyleRange><CrossReferenceSource Self="x1" AppliedFormat="n">{CSR}<Content>11.</Content></CharacterStyleRange></CrossReferenceSource>{CSR}<Content>, then a few more words to wrap.</Content></CharacterStyleRange>"#- ));- let compose = |xml: &str| {- let d = import_idml(&fixture_with_story(xml)).unwrap();- d.check().unwrap();- let s = d.stories.values().find(|s| !s.xrefs.is_empty()).expect("story with a cross-reference").clone();- let cs = designcraft_compose::compose_story(&d, s.id, &Default::default());- let glyphs: Vec<_> = cs.frames.iter().flat_map(|f| &f.lines).flat_map(|l| l.glyphs.iter().map(move |g| (g.byte, g.x, l.baseline))).collect();- (s, glyphs)- };- let (a, ga) = compose(&inside);- let (b, gb) = compose(&around);- assert!(ga.len() > a.text.chars().count() / 2, "the story composes");- assert_eq!(a.text, b.text);- assert_eq!(a.chars, b.chars);- assert_eq!(a.chars.len(), 1, "the generated text shares its neighbours' format");- assert_eq!(a.chars[0].format.over.tracking, Some(200.0));- assert_eq!(a.chars[0].format.over.size, Some(11.0));- assert_eq!(ga, gb);+fn arabic_controls_import_independent_xml_and_round_trip() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" ParagraphDirection="RightToLeftDirection" Kashidas="KashidasOff" ParagraphJustification="NaskhJustification" ParagraphKashidaWidth="2">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" CharacterDirection="LeftToRightDirection" Kashidas="KashidasOff" DiacriticPosition="OpentypePosition" XOffsetDiacritic="150" YOffsetDiacritic="-100" PositionalForm="Medial"><Properties><DigitsType type="enumeration">FarsiDigits</DigitsType></Properties><Content>بَ123</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let d = import_idml(&fixture_with_story(story)).unwrap();+ let st = d.stories.values().find(|s| s.text.contains('ب')).unwrap();+ assert_eq!(st.paras[0].para.kashidas, Some(false));+ assert_eq!(st.paras[0].para.arabic_justification.as_deref(), Some("NaskhJustification"));+ let a = &st.runs().next().unwrap().1.over;+ assert_eq!(a.character_direction, Some(designcraft_doc::arabic::CharacterDirection::LeftToRight));+ assert_eq!(a.allow_kashidas, Some(false));+ assert_eq!(a.diacritic_x_offset, Some(150.0));+ assert_eq!(a.diacritic_y_offset, Some(-100.0));+ assert_eq!(a.digits, Some(designcraft_doc::Digits::Farsi));+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains('ب')).unwrap();+ let attrs = &b.runs().next().unwrap().1.over;+ assert_eq!(attrs.character_direction, a.character_direction);+ assert_eq!(attrs.diacritic_x_offset, a.diacritic_x_offset);+ assert_eq!(attrs.diacritic_y_offset, a.diacritic_y_offset);+ assert_eq!(attrs.allow_kashidas, a.allow_kashidas);+ assert_eq!(attrs.positional_form, a.positional_form);+ assert_eq!(b.paras[0].para.paragraph_kashida_width, Some(Some(2.0)));}#[test]@@@ -3768,3 -2300,409 +3793,371 @@@ fn frame_preference_property_color_resoassert_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}");+ }++ /// A package whose [No paragraph style] carries the space-below leading model+ /// (`LeadingModelAkiBelow`, written on every IDML) and applies `composer` in the+ /// `<Properties><Composer>` form, with a 32 pt paragraph above a 24 pt one.+ fn aki_below_doc(composer: &str) -> Document {+ let styles = STYLES.replace(+ r#"Name="$ID/[No paragraph style]" PointSize="12">+ <Properties>"#,+ &format!(+ r#"Name="$ID/[No paragraph style]" PointSize="12" LeadingModel="LeadingModelAkiBelow">+ <Properties><Composer type="string">{composer}</Composer>"#+ ),+ );+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" PointSize="32"><Content>Big</Content><Br/></CharacterStyleRange>+ </ParagraphStyleRange>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" PointSize="24"><Content>Small</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let pkg = 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),+ ]);+ import_idml(&pkg).unwrap()+ }++ /// The distance from the first baseline of [`aki_below_doc`]'s story to the second.+ fn second_line_gap(d: &Document) -> f64 {+ let sid = d.stories.values().find(|s| s.text.contains("Big")).unwrap().id;+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ let baselines: Vec<f64> = cs.frames.iter().flat_map(|f| &f.lines).map(|l| l.baseline).collect();+ assert_eq!(baselines.len(), 2, "{baselines:?}");+ baselines[1] - baselines[0]+ }++ /// The leading model on [No paragraph style] of every IDML takes effect only under the Japanese+ /// composers: with the others, a 24 pt paragraph after a 32 pt one sits a Roman 28.8 pt (its auto+ /// leading) below it.+ #[test]+ fn the_default_cjk_leading_model_applies_only_with_a_japanese_composer() {+ for composer in ["$ID/HL Composer", "$ID/HL Single", "$ID/HL Composer Optyca"] {+ let d = aki_below_doc(composer);+ let root = d.styles.para(designcraft_doc::NO_PARA_STYLE).unwrap();+ assert_eq!(root.chars.leading_model, Some(designcraft_doc::cjk::LeadingModel::AkiBelow), "the import keeps the file's model");+ let gap = second_line_gap(&d);+ assert!((gap - 28.8).abs() < 0.01, "{composer}: {gap}");+ }+ for composer in ["$ID/HL Composer J", "$ID/HL Single J"] {+ let gap = second_line_gap(&aki_below_doc(composer));+ assert!(gap > 28.8 + 1.0, "{composer}: the upper line's leading sits below it, not the lower line's ({gap})");+ }+ }++ /// A Japanese-composer document keeps its composer and leading model through export and+ /// reimport, and lays out the same.+ #[test]+ fn a_japanese_composer_and_its_leading_model_round_trip() {+ use designcraft_doc::Composer as C;+ let d = aki_below_doc("$ID/HL Composer J");+ let back = import_idml(&export_idml(&d)).unwrap();+ for doc in [&d, &back] {+ let root = doc.styles.para(designcraft_doc::NO_PARA_STYLE).unwrap();+ assert_eq!(root.para.composer, Some(C::Japanese));+ assert_eq!(root.chars.leading_model, Some(designcraft_doc::cjk::LeadingModel::AkiBelow));+ }+ assert!((second_line_gap(&d) - second_line_gap(&back)).abs() < 0.01);+ }++ 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;+ // Without a parent there are no margins to follow, so they aren't local either.+ pages[0].local_margins = false;+ 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/images/src/lib.rsindex fa1533ccd,28a42522d..db9a197e3--- a/crates/images/src/lib.rs+++ b/crates/images/src/lib.rs@@@ -592,13 -602,59 +691,66 @@@ mod testsassert_eq!(decode_cmyk_tiff(&b[..b.len() / 2]), None, "truncated");}+ /// Indexed colour (PhotometricInterpretation 3), which the `tiff` encoder has no type for.+ struct Palette<const BITS: u16>;+ impl<const BITS: u16> tiff::encoder::colortype::ColorType for Palette<BITS> {+ type Inner = u8;+ const TIFF_VALUE: tiff::tags::PhotometricInterpretation = tiff::tags::PhotometricInterpretation::RGBPalette;+ const BITS_PER_SAMPLE: &'static [u16] = &[BITS];+ const SAMPLE_FORMAT: &'static [tiff::tags::SampleFormat] = &[tiff::tags::SampleFormat::Uint];+ fn horizontal_predict(row: &[u8], result: &mut Vec<u8>) {+ result.extend_from_slice(row);+ }+ }++ /// A palette TIFF as Photoshop and Pillow write it: 16-bit ColorMap entries (reds, then+ /// greens, then blues), each 8-bit value times 256.+ fn palette_tiff<const BITS: u16>(w: u32, h: u32, px: &[u8], colours: &[[u8; 3]], lzw: bool) -> Vec<u8> {+ let n = 1usize << BITS;+ let mut map = vec![0u16; 3 * n];+ for (i, c) in colours.iter().enumerate() {+ for (ch, &v) in c.iter().enumerate() {+ map[ch * n + i] = u16::from(v) << 8;+ }+ }+ let mut b = Vec::new();+ let mut enc = tiff::encoder::TiffEncoder::new(std::io::Cursor::new(&mut b)).unwrap();+ if lzw {+ enc = enc.with_compression(tiff::encoder::Compression::Lzw);+ }+ let mut img = enc.new_image::<Palette<BITS>>(w, h).unwrap();+ img.encoder().write_tag(tiff::tags::Tag::ColorMap, &map[..]).unwrap();+ img.write_data(px).unwrap();+ b+ }++ /// Indexed-colour TIFFs (an old GIF logo saved from Photoshop) are sized and drawn through+ /// their palette, uncompressed or LZW, 8- or 4-bit.+ #[test]+ fn palette_tiff_decodes_through_its_colormap() {+ let colours = [[0, 128, 255], [255, 0, 0], [10, 20, 30]];+ for lzw in [false, true] {+ let b = palette_tiff::<8>(3, 1, &[2, 0, 1], &colours, lzw);+ assert_eq!(pixel_size(&b), Some((3, 1)), "lzw {lzw}");+ let img = decode_rgba(&b).expect("decodes");+ let px: Vec<_> = img.pixels().map(|p| p.0).collect();+ assert_eq!(px, [[10, 20, 30, 255], [0, 128, 255, 255], [255, 0, 0, 255]], "lzw {lzw}");+ }+ // Two indices per byte, high nibble first: 2, 1 | 0, 2 (the encoder counts samples, not+ // bytes, so the strip carries two spare bytes the decoder doesn't read).+ let b = palette_tiff::<4>(2, 2, &[0x21, 0x02, 0, 0], &colours, false);+ assert_eq!(pixel_size(&b), Some((2, 2)));+ let px: Vec<_> = decode_rgba(&b).expect("decodes").pixels().map(|p| p.0).collect();+ assert_eq!(px, [[10, 20, 30, 255], [255, 0, 0, 255], [0, 128, 255, 255], [10, 20, 30, 255]]);+ }++ #[test]+ fn cmyk_tiff_with_alpha_reports_its_pixel_size() {+ use tiff::encoder::colortype::CMYKA8;+ let b = tiff_of::<CMYKA8>(2, 1, &[0, 0, 0, 255, 255, 0, 0, 0, 0, 0], true);+ assert_eq!(pixel_size(&b), Some((2, 1)));+ }+#[test]fn bmp_decodes() {let mut bmp = Vec::new();diff --cc crates/mcp/src/backend.rsindex ca4f588d9,57db5c8ba..4f6ea5af4--- a/crates/mcp/src/backend.rs+++ b/crates/mcp/src/backend.rs@@@ -172,8 -178,7 +178,8 @@@ mod testsErr(e) => panic!("accept failed: {e}"),}};- // Accepted sockets can inherit the listener's nonblocking mode. The server- // waits for both requests with timeouts, rather than reading before they arrive.- // The listener polls accept; the connection blocks while waiting for its request.++ // The listener polls accept, and accepted sockets can inherit its nonblocking mode. The++ // connection blocks with timeouts while waiting for its requests.stream.set_nonblocking(false).unwrap();stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();stream.set_write_timeout(Some(Duration::from_secs(2))).unwrap();diff --cc crates/pdf/src/export.rsindex d29676ffa,15c55cc54..d72e74fe1--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@@ -137,40 -113,22 +142,23 @@@ fn export_pdf_with_report_inner(doc: &DStandard::PdfX4 => (PdfVersion::Pdf16, None),Standard::PdfA2b => (PdfVersion::Pdf17, Some(Archival::A2_B)),};- let mut cb = ConfigurationBuilder::new().with_version(version);- if let Some(a) = archival {- cb = cb.with_archival_validator(a);- }- let configuration = cb.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;+ let configuration = write::configuration(version, archival)?;let settings = krilla::SerializeSettings { compress_content_streams: opts.compress, configuration, ..Default::default() };- let mut pdf = krilla::Document::new_with(settings);-let title = opts.title.clone().unwrap_or_else(|| doc.title.clone());- let mut meta = Metadata::new().creator("DesignCraft".into()).producer("DesignCraft".into());- if !title.is_empty() {- meta = meta.title(title.clone());- }- if let Some(a) = &opts.author {- meta = meta.authors(vec![a.clone()]);- }let created = opts.created.or_else(now_unix);- if let Some(t) = created {- let c = civil(t);- meta = meta.creation_date(- krilla::metadata::DateTime::new(c.0.clamp(0, 9999) as u16)- .month(c.1)- .day(c.2)- .hour(c.3)- .minute(c.4)- .second(c.5)- .utc_offset_hour(0)- .utc_offset_minute(0),- );- }- pdf.set_metadata(meta);+ let metadata = Metadata {+ creator: "DesignCraft".into(),+ producer: "DesignCraft".into(),+ title: Some(title.clone()),+ authors: opts.author.iter().cloned().collect(),+ created: created.map(date_time),+ ..Default::default()+ };+ let mut writer = Writer::new(settings, metadata);+ let pdf = writer.document_mut();let mut ex = Exporter {+ drawing_items: Vec::new(),doc,cache,opts,@@@ -343,15 -311,11 +340,12 @@@ fn export_booklet_inner(doc: &Document}let pdf_opts = PdfOptions { title: opts.title.clone(), ..PdfOptions::default() };let settings = krilla::SerializeSettings { compress_content_streams: true, ..Default::default() };- let mut pdf = krilla::Document::new_with(settings);let title = opts.title.clone().unwrap_or_else(|| doc.title.clone());- let mut meta = Metadata::new().creator("DesignCraft".into()).producer("DesignCraft".into());- if !title.is_empty() {- meta = meta.title(title);- }- pdf.set_metadata(meta);+ let metadata = Metadata { creator: "DesignCraft".into(), producer: "DesignCraft".into(), title: Some(title), ..Default::default() };+ let mut writer = Writer::new(settings, metadata);+ let pdf = writer.document_mut();let mut ex = Exporter {+ drawing_items: Vec::new(),doc,cache,opts: &pdf_opts,diff --cc crates/pdf/src/lib.rsindex c9c7bae82,d22098cb8..ad1123897--- a/crates/pdf/src/lib.rs+++ b/crates/pdf/src/lib.rs@@@ -200,8 -200,12 +200,14 @@@ pub fn parse_page_range(s: &str, countOk(out)}+ impl From<craft_pdf::write::WriteError> for PdfError {+ fn from(error: craft_pdf::write::WriteError) -> Self {+ Self::Write(error.to_string())+ }+ }++#[cfg(test)]+mod rtl_tests;#[cfg(test)]mod tests;diff --cc crates/pdf/src/tests.rsindex aa5b3a5f3,5982cfaf4..bfa6c4032--- a/crates/pdf/src/tests.rs+++ b/crates/pdf/src/tests.rs@@@ -578,175 -545,25 +578,198 @@@ fn column_rules_are_drawn()assert!(rules(false).is_empty());}+#[test]+fn ruby_overprint_is_reported_as_not_exported() {+ use designcraft_doc::cjk_settings::AdornmentOverprint;+ let mut d = doc_with_text("漢字です");+ let sid = *d.stories.keys().next().unwrap();+ let clean = export_pdf_with_report(&d, &Cache::new(), &PdfOptions::default()).unwrap();+ assert!(!clean.warnings.iter().any(|w| w.contains("overprint")), "{:?}", clean.warnings);+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {+ f.over.ruby = Some("かんじ".into());+ f.over.ruby_overprint_fill = Some(AdornmentOverprint::On);+ });+ let r = export_pdf_with_report(&d, &Cache::new(), &PdfOptions::default()).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("overprint is not exported yet")), "{:?}", r.warnings);+}++#[test]+fn small_caps_and_small_cap_figures_extract_as_typed() {+ // Source Sans 3 substitutes letters and figures under `smcp` / `c2sc` (`one` → `one.s`),+ // in typed text, in a page number and in a list label alike (each with its own figures, so+ // one's mapping can't stand in for another's).+ use designcraft_doc::{Capitalization, ListType, story::PAGE_NUMBER};+ for caps in [Capitalization::SmallCaps, Capitalization::OpenTypeAllSmallCaps] {+ let text = format!("Abc 234 x{PAGE_NUMBER}\nItem");+ let mut d = doc_with_text(&text);+ let sid = *d.stories.keys().next().unwrap();+ let st = d.story_mut(sid).unwrap();+ st.format_paras(0..text.len(), |f| {+ f.chars.font_family = Some("Source Sans 3".into());+ f.chars.capitalization = Some(caps);+ });+ st.format_paras(text.len() - 1..text.len(), |f| {+ f.para.list_type = Some(ListType::Numbers);+ f.para.start_at = Some(Some(5));+ });+ let got = extract_text(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap()).concat();+ assert!(!got.contains('\u{FFFD}'), "{caps:?}: {got:?}");+ assert_eq!(got.split_whitespace().collect::<Vec<_>>(), ["Abc", "234", "x15.Item"], "{caps:?}: {got:?}");+ }+ // All small caps draws `A` and `a` with one glyph, which one ToUnicode entry can't cover: the+ // second spelling goes out as ActualText (which this extractor doesn't read).+ let mut d = doc_with_text("Aa");+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.capitalization = Some(Capitalization::OpenTypeAllSmallCaps);+ });+ assert!(uncompressed(&d, PdfOptions::default()).contains("/ActualText"));+}++/// A clipping path on a placed image becomes a clip in the page content, inside the frame's.+#[test]+fn clipping_path_clips_the_image() {+ let png = |d: &mut Document| {+ let mut b = Vec::new();+ image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))+ .write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)+ .unwrap();+ place(d, b, (4, 4));+ };+ let clips = |s: &str| s.lines().filter(|l| matches!(l.trim(), "W" | "W*")).count();+ let mut d = doc_with_text("x");+ png(&mut d);+ let plain = uncompressed(&d, PdfOptions::default());+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;+ let triangle = designcraft_geom::PathData::single(designcraft_geom::path::SubPath::polyline(+ &[designcraft_geom::Point::new(0.0, 4.0), designcraft_geom::Point::new(2.0, 0.0), designcraft_geom::Point::new(4.0, 4.0)],+ true,+ ));+ let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, triangle);+ let set = |d: &mut Document, c: &designcraft_doc::ClippingPath| {+ if let Some(designcraft_doc::Content::Graphic(g)) = d.item_mut(id).map(|it| &mut it.content) {+ g.clip = Some(std::sync::Arc::new(c.clone()));+ }+ };+ set(&mut d, &clip);+ let clipped = uncompressed(&d, PdfOptions::default());+ assert_eq!(clips(&clipped), clips(&plain) + 1, "{clipped}");+ // The triangle's apex: graphic (2, 0) → page (172, 72) → PDF y = page height − 72.+ let apex_y = d.spreads[0].pages[0].height - 72.0;+ assert!(clipped.contains(&format!("172 {apex_y} l")), "{clipped}");+ clip.invert = true;+ set(&mut d, &clip);+ assert!(uncompressed(&d, PdfOptions::default()).lines().any(|l| l.trim() == "W*"), "an inverted clip is even-odd");+}++/// A page whose parent B is based on A carries A's items, then B's.+#[test]+fn based_on_parent_items_export_base_first() {+ let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..NewDocument::default() });+ d.swatches.push(Swatch::color("Base Cyan", Color::cmyk(1.0, 0.0, 0.0, 0.0)));+ d.swatches.push(Swatch::color("Parent Magenta", Color::cmyk(0.0, 1.0, 0.0, 0.0)));+ let a = d.parents[0].id;+ let b = d.add_parent("B", "Opening", 1, 12.0, designcraft_doc::Margins::uniform(36.0));+ std::sync::Arc::make_mut(&mut d.parents[1]).parent.as_mut().unwrap().based_on = Some(a);+ d.apply_parent(&[0], Some(b)).unwrap();+ let lid = d.default_layer();+ for (pi, swatch, r) in [(0, "Base Cyan", Rect::new(36.0, 36.0, 136.0, 136.0)), (1, "Parent Magenta", Rect::new(200.0, 36.0, 300.0, 136.0))] {+ let mut it = Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));+ it.fill = Fill::swatch(swatch);+ d.insert_item(SpreadRef::Parent(pi), it, None).unwrap();+ }+ let s = uncompressed(&d, PdfOptions::default());+ let (cyan, magenta) = (s.find("1 0 0 0 k"), s.find("0 1 0 0 k"));+ assert!(cyan.is_some() && magenta.is_some(), "both parents' items are on the page");+ assert!(cyan < magenta, "the base parent's item is drawn first");+}++/// Form fields and buttons that don't print stay out of the PDF: inside a hidden group, on a+/// hidden or non-printing layer, or non-printing themselves (#726).+#[test]+fn only_printed_fields_and_buttons_export() {+ use designcraft_doc::{ButtonAction, Content, FieldKind, FormField, LayerId, Shape};+ use designcraft_geom::shapes::rectangle;+ fn control(d: &mut Document, layer: LayerId, y: f64, name: &str, button: bool) -> Item {+ let r = Rect::new(if button { 300.0 } else { 72.0 }, y, if button { 400.0 } else { 250.0 }, y + 24.0);+ let mut it = Item::new(ItemId(d.alloc()), layer, Shape::Rectangle, rectangle(r));+ if button {+ it.button = Some(ButtonAction::GoToUrl { url: format!("https://example.com/{name}") });+ } else {+ it.form_field = Some(FormField {+ kind: FieldKind::TextField,+ name: name.into(),+ value: String::new(),+ options: Vec::new(),+ multiline: false,+ required: false,+ font_size: 0.0,+ });+ }+ it+ }+ let export = |unprinted: bool| {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ for b in [false, true] {+ let it = control(&mut d, lid, 72.0, "shown", b);+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ }+ if unprinted {+ let mut layers = Vec::new();+ for (visible, printable) in [(false, true), (true, false)] {+ let mut l = d.layers[0].clone();+ l.id = LayerId(d.alloc());+ l.visible = visible;+ l.printable = printable;+ d.layers.push(l.clone());+ layers.push(l.id);+ }+ for (i, layer) in layers.into_iter().enumerate() {+ for b in [false, true] {+ let it = control(&mut d, layer, 120.0 + 48.0 * i as f64, &format!("unprinted-layer-{i}"), b);+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ }+ }+ for b in [false, true] {+ let mut it = control(&mut d, lid, 240.0, "unprinted-item", b);+ it.nonprinting = true;+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ }+ let children: Vec<_> = [false, true].map(|b| std::sync::Arc::new(control(&mut d, lid, 288.0, "unprinted-group", b))).into();+ let mut group = Item::new(ItemId(d.alloc()), lid, Shape::Group, rectangle(Rect::new(72.0, 288.0, 400.0, 312.0)));+ group.content = Content::Group { items: children };+ group.hidden = true;+ d.insert_item(SpreadRef::Doc(0), group, None).unwrap();+ }+ uncompressed(&d, PdfOptions::default())+ };+ let (shown, all) = (export(false), export(true));+ assert_eq!(all.matches("/Subtype/Widget").count(), 1, "one field");+ assert!(all.contains("(shown)") && !all.contains("unprinted"), "only the shown field and button");+ assert_eq!(all.matches("/Link").count(), shown.matches("/Link").count(), "only the shown button");+}+++ #[test]+ fn extreme_page_selection_is_a_page_error_without_overflow() {+ let doc = doc_with_text("Bounded page selection");+ let opts = PdfOptions { pages: Some(vec![usize::MAX]), ..Default::default() };+ assert_eq!(export_pdf(&doc, &Cache::new(), &opts), Err(PdfError::BadPage(usize::MAX)));+ }++ #[test]+ fn empty_and_populated_export_metadata_preserve_key_presence() {+ let mut d = Document::new(&NewDocument::default());+ d.title.clear();+ let s = uncompressed(&d, PdfOptions::default());+ for key in ["/Title", "/Author", "<dc:title>", "<dc:creator>"] {+ assert!(!s.contains(key), "unexpected empty metadata {key}");+ }+ d.title = "Synthetic title".into();+ let s = uncompressed(&d, PdfOptions { author: Some("Test author".into()), created: Some(1_700_000_000), ..Default::default() });+ for key in ["/Title", "/Author", "/CreationDate", "<dc:title>", "<dc:creator>"] {+ assert!(s.contains(key), "missing populated metadata {key}");+ }+ assert!(s.contains("Synthetic title") && s.contains("Test author"));+ }diff --cc crates/render/src/fx.rsindex ee4e4a05a,527b09c00..6147c9cf5--- a/crates/render/src/fx.rs+++ b/crates/render/src/fx.rs@@@ -136,25 -136,20 +137,27 @@@ impl Rendererctx.set_transform(Affine::IDENTITY);ctx.push_layer(None, None, None, None, None);}- // The object, feathered or not.+ // The object, feathered or not. Choke keeps that much of the width opaque (a shorter+ // fade); Sharp and Rounded corners follow the inset shape more tightly than Diffused.if e.feather > 0.0 && it.path.is_closed() {- let w = e.feather;+ let fo = &e.feather_options;+ let w = e.feather * (1.0 - fo.choke.clamp(0.0, 100.0) / 100.0).max(0.01);+ let (sigma, join) = match fo.corners {+ designcraft_doc::FeatherCorners::Diffused => (w / 4.0, kurbo::Join::Round),+ designcraft_doc::FeatherCorners::Rounded => (w / 3.0, kurbo::Join::Round),+ designcraft_doc::FeatherCorners::Sharp => (w / 6.0, kurbo::Join::Miter),+ };- self.with_filters(ctx, f, reach, sigma, |me, c, fr| {- c.set_transform(fr.view * xf);- c.push_clip_layer(bp);- me.draw_body(c, fr, it, bp, xf, page);- // Keep the body where the blurred inset silhouette is.- c.set_transform(Affine::IDENTITY);- c.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None);+ // The body and its clip stay at device resolution; only the blurred mask may be drawn+ // offscreen at a lower one.+ ctx.set_transform(f.view * xf);+ ctx.push_clip_layer(bp);+ self.draw_body(ctx, f, it, bp, xf, page);+ // Keep the body where the blurred inset silhouette is.+ ctx.set_transform(Affine::IDENTITY);+ ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None);- self.with_filters(ctx, f, reach, w / 4.0, None, |_, c, fr| {++ self.with_filters(ctx, f, reach, sigma, None, |_, c, fr| {c.set_transform(fr.view);- c.push_layer(None, None, None, None, Some(blur(w / 4.0)));+ c.push_layer(None, None, None, None, Some(blur(sigma)));c.set_transform(fr.view * xf);c.set_paint(peniko::Color::BLACK);c.fill_path(bp);@@@ -223,14 -218,9 +226,12 @@@{let g = &e.inner_glow;let (sigma, choke) = split(g.size, g.choke);+ // Precise keeps the glow close to the edge: a tighter blur.+ let sigma = if g.technique == designcraft_doc::GlowTechnique::Precise { sigma * 0.4 } else { sigma };+ let mix = crate::blend_mode(g.mode).mix;let paint = color_of(&c, g.opacity.clamp(0.0, 1.0));if g.center {- self.with_blended_filters(ctx, f, reach, sigma, mix, |_, c, fr| {- c.set_transform(fr.view * xf);- c.push_clip_layer(bp);- self.with_blended_filters(ctx, f, reach, sigma, Mix::Screen, (bp, xf), |_, c, fr| {++ self.with_blended_filters(ctx, f, reach, sigma, mix, (bp, xf), |_, c, fr| {c.set_transform(fr.view);c.push_layer(None, None, None, None, Some(blur(sigma)));c.set_transform(fr.view * xf);@@@ -245,10 -235,9 +246,9 @@@c.stroke_path(bp);c.pop_layer();c.pop_layer();- c.pop_layer();});} else {- self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, Mix::Screen);+ self.inner_edge(ctx, f, reach, bp, xf, Vec2::ZERO, sigma, choke, paint, mix);}}// Satin: the shape shifted both ways along the angle, blurred, where exactly one covers.diff --cc crates/render/src/text.rsindex 547dd9057,656d76582..70f31b4f6--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@@ -545,49 -513,44 +545,47 @@@ fn paint_glyphsweight: f64,behind: bool,) {- let has_fill = fill.is_some();+ // A gradient paint runs across `area`; reset its transform after each use.let paint_fill = |ctx: &mut RenderContext| {let Some((c, overprint)) = &fill else { return };- if *overprint {- ctx.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Multiply, peniko::Compose::SrcOver)), None, None, None);- }- c.set(ctx, doc, area);- ctx.fill_path(bp);- ctx.reset_paint_transform();- if *overprint {- ctx.pop_layer();- }+ overprinting(ctx, *overprint, |ctx| {+ c.set(ctx, doc, area);+ ctx.fill_path(bp);+ ctx.reset_paint_transform();+ });};- let Some(sc) = stroke else {+ let Some((sc, stroke_overprint)) = stroke else {paint_fill(ctx);return;};- if !behind {- paint_fill(ctx);+ let paint_stroke = |ctx: &mut RenderContext, width: f64| {- sc.set(ctx, doc, area);- ctx.set_stroke(kurbo::Stroke::new(width));- ctx.stroke_path(bp);- ctx.reset_paint_transform();+ overprinting(ctx, stroke_overprint, |ctx| {+ sc.set(ctx, doc, area);- ctx.set_stroke(kurbo::Stroke::new(weight));++ ctx.set_stroke(kurbo::Stroke::new(width));+ ctx.stroke_path(bp);+ ctx.reset_paint_transform();+ });+ };+ if !behind {+ paint_fill(ctx);+ paint_stroke(ctx, weight);return;}- if has_fill {- overprinting(ctx, stroke_overprint, |ctx| {- sc.set(ctx, doc, area);- ctx.set_stroke(kurbo::Stroke::new(weight * 2.0));- ctx.stroke_path(bp);- ctx.reset_paint_transform();- });+ if fill.is_some() {+ paint_stroke(ctx, weight * 2.0);paint_fill(ctx);} else {- ctx.push_layer(None, None, None, None, None);- paint_stroke(ctx, weight * 2.0);- ctx.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestOut)), None, None, None);- ctx.fill_path(bp);- ctx.pop_layer();- ctx.pop_layer();+ overprinting(ctx, stroke_overprint, |ctx| {+ ctx.push_layer(None, None, None, None, None);+ sc.set(ctx, doc, area);+ ctx.set_stroke(kurbo::Stroke::new(weight * 2.0));+ ctx.stroke_path(bp);+ ctx.push_layer(None, Some(peniko::BlendMode::new(peniko::Mix::Normal, peniko::Compose::DestOut)), None, None, None);+ ctx.fill_path(bp);+ ctx.pop_layer();+ ctx.pop_layer();+ ctx.reset_paint_transform();+ });}}diff --cc crates/render/tests/placed_pdf.rsindex 696164d1d,0b713af84..9e49cb874--- a/crates/render/tests/placed_pdf.rs+++ b/crates/render/tests/placed_pdf.rs@@@ -10,9 -10,8 +10,9 @@@ use std::sync::mpsc::{self, RecvTimeoutuse std::time::Duration;use designcraft_compose::Cache;+use designcraft_doc::PdfCrop;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_crop_box, pdf_page_size};use hayro::hayro_interpret::Function;diff --cc crates/tools/src/lib.rsindex e2749e94c,46175dda6..23a888c2e--- a/crates/tools/src/lib.rs+++ b/crates/tools/src/lib.rs@@@ -31,9 -30,8 +31,9 @@@ use designcraft_geom::{Affine, BezPathuse serde::{Deserialize, Serialize};use serde_json::Value;- pub use catalog::{TOOL_GROUPS, ToolInfo, tool_for_shortcut, tool_info};+ pub use catalog::{SPLIT_IN_TWO_COLUMNS, TOOL_GROUPS, ToolInfo, tool_for_shortcut, tool_info};pub use layout::CanvasLayout;+pub use nav::ZoomTool;#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Mods {diff --cc crates/tools/src/text.rsindex 17d0660d3,9e6a8506c..046853e01--- a/crates/tools/src/text.rs+++ b/crates/tools/src/text.rs@@@ -220,13 -143,8 +224,15 @@@ impl Tool for TypeToolself.selecting = None;self.cell_drag = None;self.unit_selected = false;+ self.border = None;+ if ev.kind == PointerKind::Down+ && let Some(b) = border_at(cx, ev.pos)+ {+ self.border = Some(b);+ return vec![];+ }+ // Text frames take the caret (locked ones too, as in InDesign); an empty frame+ // becomes one, unless it's locked: then the press draws a new text frame over it.if let Some((_, id)) = cx.hit(ev.pos)&& let Some(it) = cx.doc.item(id)&& !matches!(it.content, designcraft_doc::Content::Graphic(_) | designcraft_doc::Content::Group { .. })diff --cc crates/ui-egui/src/canvas.rsindex b0b033498,a98fdfec7..a2d6f0fd3--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -3365,412 -2557,120 +3380,558 @@@ mod tests}}+ /// The live-corner widget draws on a selected rectangle frame; clicking it draws the diamonds.+ #[test]+ fn live_corner_widget_and_diamonds_draw() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [100, 100, 300, 250], "content": "graphic"})).unwrap();+ let id = app.session.doc().unwrap().doc.spreads[0].items[0].id;+ app.run("selection.set", json!({"ids": [id.0]})).unwrap();+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(1.0).wgpu().build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ let screen = |h: &Harness<'_, DesignApp>, x: f64, y: f64| {+ let app = h.state();+ let layout = CanvasLayout::new(&app.session.doc().unwrap().doc, false);+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(layout.to_canvas(SpreadRef::Doc(0), Point::new(x, y)))+ };+ let widget = screen(&h, 300.0, 100.0) + vec2(0.0, 11.5);+ let diamond = screen(&h, 100.0, 100.0) + vec2(12.0, 0.0);+ let yellow = |h: &mut Harness<'_, DesignApp>, p: Pos2| -> Option<bool> {+ let img = match h.render() {+ Ok(img) => img,+ Err(e) => {+ eprintln!("skipped: no offscreen renderer ({e})");+ return None;+ }+ };+ let px = img.get_pixel(p.x.round() as u32, p.y.round() as u32).0;+ Some(px[0] > 200 && px[1] > 180 && px[2] < 100)+ };+ let Some(w) = yellow(&mut h, widget) else { return };+ assert!(w, "no widget at {widget:?}");+ assert_eq!(yellow(&mut h, diamond), Some(false));+ h.hover_at(widget);+ h.step();+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: widget, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ h.run_steps(3);+ assert_eq!(yellow(&mut h, diamond), Some(true), "no diamond at {diamond:?}");+ assert_eq!(yellow(&mut h, widget), Some(false));+ }++ /// A harness whose frames are 1 ms apart, so two clicks make a double-click.+ fn fast_harness(app: DesignApp) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(0.001).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ h+ }++ fn primary(h: &mut Harness<'_, DesignApp>, pos: Pos2, pressed: bool) {+ h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.run_steps(2);+ }++ fn corner_drag(h: &mut Harness<'_, DesignApp>, from: Pos2, to: Pos2) {+ h.hover_at(from);+ h.step();+ primary(h, from, true);+ h.event(egui::Event::PointerMoved(from + (to - from) / 2.0));+ h.run_steps(2);+ h.event(egui::Event::PointerMoved(to));+ h.run_steps(2);+ primary(h, to, false);+ }++ fn corner_click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ h.hover_at(p);+ h.step();+ primary(h, p, true);+ primary(h, p, false);+ }++ /// Where the rulers measure from (canvas coordinates): the document's zero point on the+ /// spread in view (its first page, for a page origin).+ fn ruler_zero(app: &DesignApp, doc: &Document, layout: &CanvasLayout) -> Option<Point> {+ ruler_pieces(app, doc, layout, doc.zero_point()).first().map(|p| p.2)+ }++ fn zero_point(h: &Harness<'_, DesignApp>) -> [f64; 2] {+ h.state().session.doc().unwrap().doc.settings.zero_point+ }++ #[test]+ fn the_ruler_corner_drags_resets_and_locks_the_zero_point() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3})).unwrap();+ let mut h = fast_harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ // A click that stays in the corner leaves the zero point.+ corner_click(&mut h, corner);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Dragged out, it lands where released, measured from the spread in view.+ let dest = rect.min + vec2(80.0, 50.0);+ let expected = {+ let app = h.state();+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let slot = layout.slots[current_slot(app, &layout).unwrap()];+ let sp = slot.to_spread(Xf::new(rect, app.view().unwrap()).to_canvas(dest));+ let b = st.doc.spread(slot.spread).unwrap().bounds();+ [sp.x - b.x0, sp.y - b.y0]+ };+ corner_drag(&mut h, corner, dest);+ let zp = zero_point(&h);+ assert!((zp[0] - expected[0]).abs() < 0.5 && (zp[1] - expected[1]).abs() < 0.5, "{zp:?} vs {expected:?}");+ assert!(zp[0].abs() > 1.0 && zp[1].abs() > 1.0, "moved: {zp:?}");+ // The rulers measure from the point it was dropped on.+ {+ let app = h.state();+ let st = app.session.active().unwrap();+ let layout = CanvasLayout::new(&st.doc, false);+ let o = ruler_zero(app, &st.doc, &layout).unwrap();+ let on_screen = Xf::new(rect, app.view().unwrap()).to_screen(o);+ assert!((on_screen - dest).length() < 0.5, "{on_screen:?} vs {dest:?}");+ }+ // A double-click resets it.+ corner_click(&mut h, corner);+ corner_click(&mut h, corner);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Locked from the corner's context menu, the corner ignores drags and double-clicks.+ right_click(&mut h, corner);+ h.get_by_label("Lock Zero Point").click();+ h.run_steps(3);+ assert!(h.state().session.doc().unwrap().doc.settings.zero_point_locked);+ corner_drag(&mut h, corner, dest);+ assert_eq!(zero_point(&h), [0.0, 0.0]);+ // Unlocked again from the same menu.+ right_click(&mut h, corner);+ h.get_by_label("Unlock Zero Point").click();+ h.run_steps(3);+ corner_drag(&mut h, corner, dest);+ assert_ne!(zero_point(&h), [0.0, 0.0]);+ h.state_mut().run("view.lockZeroPoint", json!({"on": true})).unwrap();+ corner_click(&mut h, corner);+ corner_click(&mut h, corner);+ assert_ne!(zero_point(&h), [0.0, 0.0], "a locked zero point isn't reset");+ }++ #[test]+ fn cmd_dragging_the_ruler_corner_makes_a_guide_each_way() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ let corner = rect.min - vec2(RULER / 2.0, RULER / 2.0);+ let dest = rect.min + vec2(120.0, 90.0);+ let (r, at) = {+ let app = h.state();+ let st = app.session.active().unwrap();+ CanvasLayout::new(&st.doc, false).spread_at(Xf::new(rect, app.view().unwrap()).to_canvas(dest)).unwrap()+ };+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));+ h.step();+ corner_drag(&mut h, corner, dest);+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ h.step();+ let doc = h.state().session.doc().unwrap().doc.clone();+ let guides: Vec<_> = doc.spread(r).unwrap().pages.iter().flat_map(|p| p.guides.clone()).collect();+ assert_eq!(guides.len(), 2, "{guides:?}");+ let pos = |o: designcraft_doc::Orientation| guides.iter().find(|g| g.orientation == o).map(|g| g.position).unwrap();+ assert!((pos(designcraft_doc::Orientation::Horizontal) - at.y).abs() < 0.5);+ assert!((pos(designcraft_doc::Orientation::Vertical) - at.x).abs() < 0.5);+ assert!(guides.iter().all(|g| g.spread));+ assert_eq!(doc.settings.zero_point, [0.0, 0.0], "the zero point stays");+ }++ #[test]+ fn rulers_and_xy_fields_measure_from_the_zero_point_on_every_spread() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ // Spread 0: page 1; spread 1: pages 2 and 3.+ app.run("file.new", json!({"pages": 3})).unwrap();+ app.run("view.zeroPoint", json!({"at": [100, 50]})).unwrap();+ app.session.prefs.dimensions_include_stroke = false;+ let mut h = harness(app);+ let rect = h.state().canvas_rect.unwrap();+ for (spread, x0) in [(0usize, 136.0), (1, 736.0)] {+ let app = h.state_mut();+ let id = app.run("frame.create", json!({"spread": spread, "rect": [x0, 70, x0 + 50.0, 120]})).unwrap()["id"].clone();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ // X/Y (Control, Properties and Info panels).+ let r = crate::panels::sel_info(app).unwrap().page_rect;+ assert!((r.x0 - (x0 - 100.0)).abs() < 1e-6 && (r.y0 - 20.0).abs() < 1e-6, "spread {spread}: {r:?}");+ // The rulers, with that spread in view.+ let layout = CanvasLayout::new(&app.session.active().unwrap().doc, false);+ let slot = layout.slots[spread];+ let v = app.view_mut().unwrap();+ let zoom = v.zoom;+ let c = slot.bounds.center();+ v.origin = Point::new(c.x - rect.width() as f64 / 2.0 / zoom, c.y - rect.height() as f64 / 2.0 / zoom);+ h.run_steps(2);+ let app = h.state();+ let doc = app.session.active().unwrap().doc.clone();+ assert_eq!(current_slot(app, &layout), Some(spread));+ let o = ruler_zero(app, &doc, &layout).unwrap();+ assert!((o.x - slot.bounds.x0 - 100.0).abs() < 1e-6 && (o.y - slot.bounds.y0 - 50.0).abs() < 1e-6, "spread {spread}: {o:?}");+ }+ }++ /// Screen position of spread 0's point (x, y).+ fn screen_of(h: &Harness<'_, DesignApp>, x: f64, y: f64) -> Pos2 {+ let app = h.state();+ let st = app.session.active().unwrap();+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ xf.to_screen(CanvasLayout::new(&st.doc, st.editing_parents).xf(SpreadRef::Doc(0)) * Point::new(x, y))+ }++ /// A menu row: a button that isn't a toggle, named by its label, then its shortcut if it has+ /// one. Toggle buttons with the same name (the Task Bar's icons) don't match.+ fn menu_row<'h>(h: &'h Harness<'_, DesignApp>, label: &'h str) -> Option<egui_kittest::Node<'h>> {+ h.query_by(move |n| {+ n.role() == egui::accesskit::Role::Button+ && n.toggled().is_none()+ && n.label().is_some_and(|l| l == label || l.strip_prefix(label).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.contains(' ')))+ })+ }++ fn enabled(h: &Harness<'_, DesignApp>, label: &str) -> bool {+ use egui_kittest::kittest::NodeT;+ !menu_row(h, label).unwrap_or_else(|| panic!("no menu row {label}")).accesskit_node().is_disabled()+ }++ fn spread_items(h: &Harness<'_, DesignApp>) -> Vec<u64> {+ h.state().session.doc().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect()+ }++ fn selected(h: &Harness<'_, DesignApp>) -> Vec<u64> {+ h.state().session.doc().unwrap().selection.items.iter().map(|i| i.0).collect()+ }++ #[test]+ fn right_clicking_an_object_selects_it_and_its_menu_arranges_it() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [150, 150, 300, 300]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ assert_eq!(selected(&h), [b]);+ let on_a = screen_of(&h, 60.0, 60.0);+ right_click(&mut h, on_a);+ assert_eq!(selected(&h), [a], "the object under the pointer is selected first");+ // An empty frame's menu: Content, but no Fitting (nothing to fit) and no text frame entries.+ assert!(menu_row(&h, "Content").is_some());+ assert!(menu_row(&h, "Fitting").is_none() && menu_row(&h, "Text Frame Options…").is_none());+ // Paste is available with nothing copied here: the system clipboard may hold another app's text.+ assert!(enabled(&h, "Copy") && enabled(&h, "Paste"));+ menu_row(&h, "Arrange").unwrap().click();+ h.run_steps(3);+ menu_row(&h, "Bring to Front").unwrap().click();+ h.run_steps(3);+ assert_eq!(spread_items(&h), [b, a]);+ assert!(menu_row(&h, "Arrange").is_none(), "choosing an entry closes the menu");+ }++ #[test]+ fn right_clicking_empty_canvas_offers_paste_after_a_copy() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("edit.copy", json!({})).unwrap();+ app.select_tool("rectangleFrame");+ let mut h = harness(app);+ let empty = screen_of(&h, 400.0, 500.0);+ right_click(&mut h, empty);+ assert_eq!(selected(&h), [a], "a right-click on nothing keeps the selection");+ assert!(menu_row(&h, "Arrange").is_none(), "the page menu, not the object menu");+ assert!(enabled(&h, "Paste in Place"));+ assert!(menu_row(&h, "✓ Show/Hide Rulers").is_some(), "toggles show their state");+ // Escape closes the menu and does nothing else: the tool would deselect, the shortcuts+ // would switch to the Selection tool.+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert!(menu_row(&h, "Paste in Place").is_none());+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));+ right_click(&mut h, empty);+ menu_row(&h, "Paste").unwrap().click();+ h.run_steps(3);+ assert_eq!(spread_items(&h).len(), 2);+ }++ #[test]+ fn right_clicking_another_object_while_the_menu_is_open_reopens_it_there() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [36, 600, 200, 760]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ // The menu opens down from A, with the pointer on its first row (no submenu open); B is below it.+ let (on_a, on_b) = (screen_of(&h, 60.0, 60.0), screen_of(&h, 50.0, 700.0));+ right_click(&mut h, on_a);+ assert_eq!(selected(&h), [a]);+ assert!(menu_row(&h, "Arrange").is_some());+ right_click(&mut h, on_b);+ assert_eq!(selected(&h), [b]);+ assert!(menu_row(&h, "Arrange").is_some(), "the menu reopens at the new click");+ }++ #[test]+ fn a_context_menu_in_one_pane_keeps_the_keys_from_the_other() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100]})).unwrap()["id"].as_u64().unwrap();+ app.select_tool("rectangleFrame");+ app.split = true;+ let mut h = harness(app);+ // The focused pane is the left one; this point is near its right edge, away from the frame.+ let left = h.state().canvas_rect.unwrap();+ right_click(&mut h, pos2(left.max.x - 40.0, left.center().y));+ assert!(menu_row(&h, "Paste in Place").is_some());+ // Escape closes the left pane's menu before the right pane handles the keys.+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert!(menu_row(&h, "Paste in Place").is_none());+ assert_eq!((h.state().session.tool_id(), selected(&h)), ("rectangleFrame", vec![a]));+ }++ #[test]+ fn right_clicking_text_keeps_the_selected_text_or_places_the_caret() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 400, 200], "content": "text"})).unwrap();+ app.select_tool("type");+ app.run("text.insert", json!({"text": "Hello world"})).unwrap();+ let sid = *app.session.doc().unwrap().doc.stories.keys().next().unwrap();+ app.run("text.select", json!({"story": sid.0, "anchor": 0, "focus": 5})).unwrap();+ let mut h = harness(app);+ let text_sel = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().selection.text.as_ref().map(|t| (t.anchor, t.focus));+ // Inside "Hello": the selection stays.+ let inside = screen_of(&h, 45.0, 44.0);+ right_click(&mut h, inside);+ assert_eq!(text_sel(&h), Some((0, 5)));+ assert!(menu_row(&h, "Paste without Formatting").is_some(), "the text menu");+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ // Past the end of the line: the caret goes there.+ let past_end = screen_of(&h, 300.0, 44.0);+ right_click(&mut h, past_end);+ assert_eq!(text_sel(&h), Some((11, 11)));+ assert!(menu_row(&h, "Paste without Formatting").is_some());+ }++ #[test]+ fn rows_hidden_in_the_menu_bar_are_hidden_in_context_menus() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap();+ app.ui.hidden_menu_items.push(crate::menus::menu_key("Object/Arrange", "Bring to Front"));+ let mut h = harness(app);+ let on_frame = screen_of(&h, 60.0, 60.0);+ right_click(&mut h, on_frame);+ menu_row(&h, "Arrange").unwrap().click();+ h.run_steps(3);+ assert!(menu_row(&h, "Bring to Front").is_none());+ assert!(menu_row(&h, "Send to Back").is_some());+ assert!(h.query_by_label("Show All Menu Items").is_some());+ }++ #[test]+ fn a_secondary_drag_neither_moves_marquees_nor_draws() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let mut h = harness(app);+ // A secondary-button drag between spread points.+ let drag = |h: &mut Harness<'_, DesignApp>, from: (f64, f64), to: (f64, f64)| {+ let (from, to) = (screen_of(h, from.0, from.1), screen_of(h, to.0, to.1));+ h.hover_at(from);+ h.step();+ h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() });+ h.step();+ for t in [0.25, 0.5, 0.75, 1.0] {+ h.event(egui::Event::PointerMoved(from + (to - from) * t));+ h.step();+ }+ h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ };+ let xf = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.item(designcraft_doc::ItemId(a)).unwrap().xf;+ let before = xf(&h);+ // Selection tool: on the object (no move), and from empty page across it (no marquee).+ drag(&mut h, (100.0, 100.0), (300.0, 300.0));+ assert_eq!(xf(&h), before);+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ drag(&mut h, (400.0, 400.0), (20.0, 20.0));+ assert!(selected(&h).is_empty());+ // Rectangle Frame tool: no frame.+ h.state_mut().select_tool("rectangleFrame");+ drag(&mut h, (300.0, 300.0), (500.0, 500.0));+ assert_eq!(spread_items(&h), [a]);+ }++ /// A text frame holding `text`, the Type tool, and a harness stepping at 60 fps (clicks in a+ /// row must land within the double-click delay).+ fn typing(text: &str) -> (Harness<'static, DesignApp>, u64) {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "text": text})).unwrap();+ let id = r["id"].as_u64().unwrap();+ app.run("tool.select", json!({"tool": "type"})).unwrap();+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ (h, id)+ }++ /// The screen point over the first line of frame `id` where a click puts the caret at a byte+ /// in `bytes`.+ fn screen_at(h: &mut Harness<'_, DesignApp>, id: u64, bytes: std::ops::Range<usize>) -> Pos2 {+ let mut x = 74.0;+ let p = loop {+ assert!(x < 400.0, "no point on the first line hits {bytes:?}");+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [x, 80.0]})).unwrap();+ if h.state().session.doc().unwrap().selection.text.is_some_and(|t| bytes.contains(&t.focus)) {+ break Point::new(x, 80.0);+ }+ x += 1.0;+ };+ h.state_mut().run("edit.deselectAll", json!({})).unwrap();+ let app = h.state();+ let c = app.session.layout().to_canvas(SpreadRef::Doc(0), p);+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)+ }++ fn click(h: &mut Harness<'_, DesignApp>, p: Pos2) {+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });+ h.step();+ }+ }+- fn selected(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {++ fn selected_range(h: &Harness<'_, DesignApp>) -> std::ops::Range<usize> {+ h.state().session.doc().unwrap().selection.text.map(|t| t.range()).unwrap_or_default()+ }++ #[test]+ fn clicks_in_a_row_select_word_line_paragraph_with_return_and_story() {+ let text = "One two. Three four! Five six.\nSecond para here.";+ let (mut h, id) = typing(text);+ // Inside "Three": double-click selects the word, then line and paragraph with return.+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ let mut got = vec![];+ for _ in 0..5 {+ click(&mut h, p);- let r = selected(&h);++ let r = selected_range(&h);+ got.push(text[r].to_string());+ }+ assert_eq!(got[1..], ["Three", "One two. Three four! Five six.", "One two. Three four! Five six.\n", text], "{got:?}");+ assert!(got[0].is_empty(), "one click places the caret: {got:?}");+ }++ #[test]+ fn slow_clicks_do_not_add_up() {+ let (mut h, id) = typing("One two. Three four!");+ let p = screen_at(&mut h, id, 10..14);+ h.hover_at(p);+ h.step();+ for _ in 0..3 {+ click(&mut h, p);+ h.run_steps(30);+ }- assert!(selected(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected(&h));++ assert!(selected_range(&h).is_empty(), "three clicks half a second apart leave a caret: {:?}", selected_range(&h));++ }++++ /// A viewport wider than the GPU's largest texture: the canvas texture is sampled down, and an++ /// edit repaints it whole. A region repainted in view pixels would land in the wrong place,++ /// or outside the texture (a wgpu validation error). A view that fits is still patched.++ #[test]++ fn an_edit_repaints_a_canvas_texture_sampled_down_to_the_gpu_limit_whole() {++ for (width, sampled_down) in [(1440.0, false), (2600.0, true)] {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({})).unwrap();++ let frame = app.run("frame.create", json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Text"})).unwrap();++ let mut h = Harness::builder().with_size(vec2(width, 900.0)).build_ui_state(++ |ui, app: &mut DesignApp| {++ let ctx = ui.ctx().clone();++ app.logic(&ctx);++ app.ui(ui);++ },++ app,++ );++ h.run_steps(6);++ let limit = h.ctx.input(|i| i.max_texture_side);++ let size = h.state().canvas.texture.as_ref().map(|t| t.size()).unwrap();++ assert!(size[0] <= limit && size[1] <= limit, "{size:?}");++ let shown = h.state().canvas.shown.unwrap().size;++ assert_eq!(shown.0 > limit as f32, sampled_down, "view {shown:?}, limit {limit}");++ let patches = h.state().canvas.patches;++ // A small edit: one more character in the frame.++ h.state_mut().run("text.insert", json!({"story": frame["story"], "at": 4, "text": "s"})).unwrap();++ h.run_steps(6);++ assert_eq!(h.state().canvas.patches == patches, sampled_down, "width {width}");++ assert_eq!(h.state().canvas.texture.as_ref().map(|t| t.size()), Some(size));++ }+ }++ /// ⌥E then I types "í" on a Mac: the input method composes the dead key's accent, which+ /// it does only for a window that turned it on. The canvas never did, so ⌥E typed "e".+ #[test]+ fn dead_keys_compose_through_the_input_method() {+ let (mut h, id) = typing("T");+ h.state_mut().run("text.placeCaret", json!({"frame": id, "point": [390.0, 80.0]})).unwrap();+ h.run_steps(2);+ assert!(h.output().platform_output.ime.is_some(), "a text caret turns the input method on");+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "´".into(), active_range_chars: None }));+ h.run_steps(2);+ let text = |h: &Harness<'_, DesignApp>| h.state().session.doc().unwrap().doc.stories.values().map(|s| s.text.clone()).collect::<String>();+ assert_eq!(text(&h), "T´", "the accent being composed shows in the story");+ assert!(h.state().session.tool_composing(), "and is marked as composed, not typed");+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None }));+ h.event(egui::Event::Ime(egui::ImeEvent::Commit("í".into())));+ h.run_steps(2);+ assert_eq!(text(&h), "Tí");+ assert!(!h.state().session.tool_composing());+ // Moving the caret mid-composition keeps the accent as typed and tells the input method+ // to drop its copy.+ h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "˜".into(), active_range_chars: None }));+ h.run_steps(2);+ h.state_mut().run("text.move", json!({"dir": "left"})).unwrap();+ h.step();+ assert_eq!(text(&h), "Tí˜");+ assert!(!h.state().session.tool_composing());+ assert!(h.output().platform_output.ime.as_ref().is_some_and(|i| i.should_interrupt_composition));+ assert!(h.state_mut().take_ime_discard());+ // Another tool takes no text: the input method is off.+ h.state_mut().run("tool.select", json!({"tool": "selection"})).unwrap();+ h.run_steps(2);+ assert!(h.output().platform_output.ime.is_none());+ }+#[test]fn tools_show_their_own_cursors_over_the_page() {let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());@@@ -4075,63 -2854,22 +4236,77 @@@let typed = story_text(&mut app, &sid);assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}");}++ #[test]+ fn baseline_grid_lines_are_the_ones_on_the_page() {+ // A start far above the page used to be walked line by line, without end.+ for start in [-1e9, -1e17] {+ let mut far = baseline_grid_lines(start, 12.0, 792.0);+ assert_eq!((far.next(), far.count()), (Some(8.0), 65));+ }+ let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::<Vec<_>>();+ assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line");+ assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm");+ assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]);+ assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES);+ }}+#[cfg(test)]+mod pencil_preview_tests {+ use egui::{Pos2, pos2, vec2};++ /// Lines painted in `color` (egui paths) and the points they pass through.+ fn lines_in(h: &egui_kittest::Harness<'static, crate::test_window::Window>, color: egui::Color32) -> Vec<Vec<Pos2>> {+ fn walk(s: &egui::Shape, color: egui::Color32, out: &mut Vec<Vec<Pos2>>) {+ match s {+ egui::Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(color) && p.points.len() >= 2 => out.push(p.points.clone()),+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, color, out)),+ _ => {}+ }+ }+ let mut out = vec![];+ h.output().shapes.iter().for_each(|s| walk(&s.shape, color, &mut out));+ out+ }++ #[test]+ fn the_pencil_stroke_shows_while_drawing() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({})).unwrap();+ app.run("tool.select", serde_json::json!({"tool": "pencil"})).unwrap();+ let mut h = crate::test_window::open(app, vec2(1400.0, 900.0));+ let doc = &h.state().app.session.doc().unwrap().doc;+ let layer = doc.layers[0].color;+ let color = egui::Color32::from_rgb(layer[0], layer[1], layer[2]);+ let items = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| h.state().app.session.doc().unwrap().doc.spreads[0].items.len();+ let before = items(&h);+ // Press on the page and drag, without letting go.+ let start = pos2(520.0, 380.0);+ h.hover_at(start);+ h.drag_at(start);+ h.run_steps(2);+ let path: Vec<Pos2> = (1..=12).map(|i| start + vec2(i as f32 * 12.0, (i as f32 * 0.6).sin() * 30.0)).collect();+ for p in &path {+ h.hover_at(*p);+ h.run_steps(1);+ }+ let drawn = lines_in(&h, color);+ let stroke = drawn.iter().max_by_key(|l| l.len()).expect("the stroke is painted while the button is down");+ let near = |a: Pos2, b: Pos2| (a - b).length() < 2.0;+ assert!(near(stroke[0], start), "it starts where the press was: {:?}", stroke[0]);+ assert!(path.iter().all(|p| stroke.iter().any(|q| near(*p, *q))), "it follows the pointer: {stroke:?}");+ assert_eq!(items(&h), before, "nothing is made before the release");+ // Letting go makes the path and ends the preview.+ h.drop_at(*path.last().unwrap());+ h.run_steps(3);+ assert_eq!(items(&h), before + 1);+ let app = &mut h.state_mut().app;+ let view = app.view_info();+ assert!(app.session.overlays(view).is_empty(), "the preview is gone");+ }+}+#[cfg(test)]mod scrollbar_tests {use egui::{Event, Modifiers, PointerButton};diff --cc crates/ui-egui/src/control.rsindex dd5bd47af,ac4b2fc29..1142be0c5--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -540,12 -520,10 +545,15 @@@ mod automation_contract_testsfn pointer_gestures_accept_the_exact_event_budget() {let mut app = app();let ctx = egui::Context::default();-- for (method, params) in- [("ui.click", json!({"count": 255})), ("ui.drag", json!({"steps": 10000})), ("ui.drag", json!({"steps": 9998, "count": 2}))]- [("ui.drag", json!({"steps": 9492, "count": 255})), ("ui.drag", json!({"steps": 10000})), ("ui.drag", json!({"steps": 9998, "count": 2}))]-- {- app.control_synthetic.clear();++ for (method, params) in [++ ("ui.click", json!({"count": 255})),++ ("ui.drag", json!({"steps": 9492, "count": 255})),++ ("ui.drag", json!({"steps": 10000})),++ ("ui.drag", json!({"steps": 9998, "count": 2})),++ ] {+ // A full click count fits on top of 9,492 pending events.+ let pending = if method == "ui.click" { 10_003 - 511 } else { 0 };+ app.control_synthetic = vec![egui::Event::PointerMoved(egui::pos2(12.0, 34.0)); pending];assert_eq!(call(&mut app, &ctx, method, params)["ok"], true, "{method}");assert_eq!(app.control_synthetic.len(), 10003);assert!(matches!(app.control_synthetic.last(), Some(egui::Event::PointerButton { pressed: false, .. })));diff --cc crates/ui-egui/src/dialogs.rsindex 0b33cfcc9,d6d3b872d..935d88d26--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -79,9 -80,19 +84,19 @@@ impl Dialog}}}- Dialog { id: id.into(), fields }+ Dialog { id: id.into(), fields, unit: Unit::Picas }}+ /// Set a field and report a genuine Find domain/mode transition to the caller.+ pub(crate) fn set_field(&mut self, key: &str, value: Value) -> bool {+ let before =+ (self.id == "findChange" && matches!(key, "scope" | "story" | "objectMode")).then(|| (self.b("objectMode"), find_change_params(self)));+ self.fields.insert(key.into(), value);+ before.is_some_and(|(object_mode, params)| {+ object_mode != self.b("objectMode") || !designcraft_engine::cmd::same_find_domain(¶ms, &find_change_params(self))+ })+ }+- fn s(&self, k: &str) -> String {+ pub(crate) fn s(&self, k: &str) -> String {match self.fields.get(k) {Some(Value::String(s)) => s.clone(),Some(v) => v.to_string(),@@@ -1609,10 -1495,10 +1976,12 @@@ pub fn show(app: &mut DesignApp, ctx: &"frameSize" => crate::i18n::tr(&app.ui.language, "Rectangle"),"goToPage" => crate::i18n::tr(&app.ui.language, "Go to Page"),"insertTable" => crate::i18n::tr(&app.ui.language, "Create Table"),+ "cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"),+ "createGuides" => crate::i18n::tr(&app.ui.language, "Create Guides"),+ "marginsAndColumns" => crate::i18n::tr(&app.ui.language, "Margins and Columns"),"textFrameOptions" => crate::i18n::tr(&app.ui.language, "Text Frame Options"),"documentSetup" => crate::i18n::tr(&app.ui.language, "Document Setup"),+ "numberingSection" => crate::i18n::tr(&app.ui.language, "Numbering & Section Options…").trim_end_matches('…'),"findChange" => crate::i18n::tr(&app.ui.language, "Find/Change"),"paragraphStyleOptions" => crate::i18n::tr(&app.ui.language, "Paragraph Style Options"),"deleteParagraphStyle" => crate::i18n::tr(&app.ui.language, "Delete Paragraph Style"),@@@ -1694,529 -1563,651 +2063,646 @@@ui.add_space(10.0);// Keep the title and action buttons outside the scrollable body. Oversized// 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);+ // Numbering & Section Options keeps OK and Cancel in a column beside the options, as+ // InDesign does; other dialogs have them in a footer.+ let side_actions = d.id == "numberingSection";+ let footer_height = if side_actions {+ 0.0+ } else {+ 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);+ let mut body_width = width;+ if side_actions {+ // The column is beside the options, not in the layout: keep the window wide enough.+ ui.set_min_width(width);+ body_width = (width - crate::section_options::ACTIONS_W - 12.0).max(1.0);+ let top = ui.cursor().min;+ // On the right in every language, like the other dialogs' OK.- let column = egui::Rect::from_min_size(egui::pos2(top.x + width - crate::section_options::ACTIONS_W, top.y), egui::vec2(crate::section_options::ACTIONS_W, 60.0));++ let column = egui::Rect::from_min_size(++ egui::pos2(top.x + width - crate::section_options::ACTIONS_W, top.y),++ egui::vec2(crate::section_options::ACTIONS_W, 60.0),++ );+ let mut actions = ui.new_child(egui::UiBuilder::new().max_rect(column).layout(egui::Layout::top_down_justified(egui::Align::Center)));+ if let Some(ok) = crate::section_options::actions(app, &mut actions) {+ result = Some(ok);+ }+ if !popup_open && ui.input(|i| i.key_pressed(egui::Key::Enter)) {+ result = Some(true);+ }+ if !popup_open && ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ result = Some(false);+ }+ }+ // A centred window only offers its body last frame's height: let this one grow to its+ // options' height (the screen still caps it).+ let min_body = if side_actions { body_height.min(crate::section_options::BODY_H) } else { 1.0 };- egui::ScrollArea::both().id_salt(("dialog_body", &d.id)).min_scrolled_width(1.0).min_scrolled_height(min_body).max_width(body_width).max_height(body_height).show(ui, |ui| {- match d.id.as_str() {- "newDocument" => {- // A double-clicked preset creates the document at once.- let create = crate::new_document::body(app, ui, &mut d, width, body_height);- if create {- result = Some(true);- }- }- "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));+ egui::ScrollArea::both()+ .id_salt(("dialog_body", &d.id))+ .min_scrolled_width(1.0)- .min_scrolled_height(1.0)- .max_width(width)++ .min_scrolled_height(min_body)++ .max_width(body_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);- }- });- });++ .show(ui, |ui| {++ match d.id.as_str() {++ "newDocument" => {++ // A double-clicked preset creates the document at once.++ let create = crate::new_document::body(app, ui, &mut d, width, body_height);++ if create {++ result = Some(true);}- } else {- egui::Grid::new("nd").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {+ }- 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));++ "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", 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"));++ text_field(ui, &mut d, "width", 90.0);+ 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"));++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Height"));++ text_field(ui, &mut d, "height", 90.0);+ ui.end_row();+ });}- });- 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() { crate::i18n::tr(&app.ui.language, 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));- }- "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();++ "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));}- 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 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)++ 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 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() { crate::i18n::tr(&app.ui.language, 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() { crate::i18n::tr(&app.ui.language, "(any)") } else { cur.as_str() })+ .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 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));++ }+ }- for w in &swatches {- if ui.selectable_label(*w == cur, w).clicked() {- d.fields.insert(key.into(), json!(w));++ });++ ui.end_row();+ });- 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() { crate::i18n::tr(&app.ui.language, "(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));++ 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| {++ 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) => crate::i18n::tr(&app.ui.language, "No matches").to_string(),++ Ok(_) => crate::i18n::tr(&app.ui.language, "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) => crate::i18n::tr(&app.ui.language, "{count} replacement(s) made")++ .replace("{count}", &v["count"].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, "Count"))).clicked() {++ let msg = match app.run("find.find", params()) {++ Ok(v) => crate::i18n::tr(&app.ui.language, "{count} match(es)")++ .replace("{count}", &v.as_array().map_or(0, |a| a.len()).to_string()),++ 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));}- });- ui.end_row();- });- let mut crit = json!({});- if !d.s("objFill").is_empty() {- crit["fill"] = json!(d.s("objFill"));- 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(++ }+ }- if !d.s("objKind").is_empty() {- crit["kind"] = json!(d.s("objKind"));++ "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, "", ¤t);+ }- ui.horizontal(|ui| {- 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")));++ "paragraphLocal" => paragraph_local(app, ui, &mut d),++ "justification" => {++ let current = d.fields.get("current").cloned().unwrap_or_default();++ justification(&app.ui.language, ui, &mut d, "", ¤t);++ }++ "insertXref" => insert_xref(app, ui, &mut d),++ "findFont" => find_font(app, ui, &mut d),++ "colorPicker" => color_picker(ui, &mut d),++ "swatchOptions" => options::swatch_options(app, ui, &mut d),++ "colorGroupOptions" => options::color_group_options(app, ui, &mut d),++ "layerSettings" => options::layer_options(app, ui, &mut d),++ crate::effects_dialog::ID => crate::effects_dialog::show(app, 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,- |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));- }- }- },++ crate::i18n::tr(&app.ui.language, "Page (1–{count}):").replace("{count}", &d.n("pages").unwrap_or(1.0).to_string()),+ );- ui.end_row();++ text_field(ui, &mut d, "page", 60.0);+ });- 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| {- 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()++ 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 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."));+ }- });- 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.fields.insert("scope".into(), json!(v));++ 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()++ && let Some(o) = l.as_object_mut()+ {- 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")));++ o.insert("visible".into(), json!(on));}- });- 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)))+ }- });- 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 = json!({"find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope")});- 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) => crate::i18n::tr(&app.ui.language, "No matches").to_string(),- Ok(_) => crate::i18n::tr(&app.ui.language, "Found").to_string(),- Err(e) => e,- };- d.fields.insert("status".into(), json!(msg));++ d.fields.insert("layers".into(), json!(layers));+ }- 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) => crate::i18n::tr(&app.ui.language, "{count} replacement(s) made").replace("{count}", &v["count"].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, "Count"))).clicked() {- let msg = match app.run("find.find", params()) {- Ok(v) => crate::i18n::tr(&app.ui.language, "{count} match(es)").replace("{count}", &v.as_array().map_or(0, |a| a.len()).to_string()),- 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));- }- }- }- "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, "", ¤t);- }- "paragraphLocal" => paragraph_local(app, ui, &mut d),- "justification" => {- let current = d.fields.get("current").cloned().unwrap_or_default();- justification(&app.ui.language, ui, &mut d, "", ¤t);- }- "insertXref" => insert_xref(app, ui, &mut d),- "findFont" => find_font(app, ui, &mut d),- "colorPicker" => color_picker(ui, &mut d),- "swatchOptions" => options::swatch_options(app, ui, &mut d),- "colorGroupOptions" => options::color_group_options(app, ui, &mut d),- "layerSettings" => options::layer_options(app, ui, &mut d),- crate::effects_dialog::ID => crate::effects_dialog::show(app, 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 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));++ "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(("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));++ }++ }++ });++ ui.end_row();++ }++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));++ let cur = d.s("intent");++ egui::ComboBox::from_id_salt("ws_intent")++ .selected_text(crate::rtl::widget(++ ui,++ crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label())),++ ))+ .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))++ for i in designcraft_color::cms::Intent::ALL {++ if ui++ .selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label())))++ .clicked()+ {- app.session.reset_find_scope();++ d.fields.insert("intent".into(), json!(i.id()));+ }+ }+ });+ 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));++ check(ui, &mut d, "bpc", crate::i18n::tr(&app.ui.language, "Use Black Point Compensation"));++ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load Profile…"))).clicked()++ && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("icc"))++ {++ match app.session.execute("color.loadProfile", &json!({"path": path})) {++ Ok(_) => {++ let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();++ d.fields.insert("profiles".into(), f["profiles"].clone());++ }++ Err(e) => app.status_error("Color Settings", e),}- });- 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));}- });- });- }- "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."));- }- 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()- && let Some(o) = l.as_object_mut()- {- o.insert("visible".into(), json!(on));}-- }- 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(("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));- "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, "", ¤t);- }- "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 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));++ "keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),++ "userDictionary" => user_dictionary(app, ui, &mut d),++ "menus" => {++ text_field(ui, &mut d, "query", 260.0);++ let q = d.s("query").to_lowercase();++ egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {++ for (menu, label) in crate::menus::all_menu_items()++ .into_iter()++ .filter(|(m, l)| q.is_empty() || m.to_lowercase().contains(&q) || l.to_lowercase().contains(&q))++ {++ let key = crate::menus::menu_key(&menu, &label);++ let mut visible = !app.ui.hidden_menu_items.contains(&key);++ if ui++ .checkbox(++ &mut visible,++ crate::rtl::widget(++ ui,++ format!("{} › {}", crate::i18n::tr(&app.ui.language, &menu), crate::i18n::tr(&app.ui.language, &label)),++ ),++ )++ .changed()++ {++ let _ = app.run("window.hideMenuItem", json!({"item": key, "hidden": !visible}));}}});- ui.end_row();- });- }- "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."));}- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));- let cur = d.s("intent");- egui::ComboBox::from_id_salt("ws_intent")- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label()))))- .show_ui(ui, |ui| {- for i in designcraft_color::cms::Intent::ALL {- if ui.selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label()))).clicked() {- d.fields.insert("intent".into(), json!(i.id()));- 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);- }- }- 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(("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));++ "importOptions" => {++ ui.label(egui::RichText::new(d.s("path")).size(10.5));++ check(ui, &mut d, "removeStyles", crate::i18n::tr(&app.ui.language, "Remove Styles and Formatting from Text and Tables"));++ if !d.b("removeStyles") {++ crate::rtl::label(++ ui,++ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Name Conflicts")).font(semibold(12.0)),++ );++ let conflicts: Vec<String> = d++ .fields++ .get("conflicts")++ .and_then(Value::as_array)++ .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())++ .unwrap_or_default();++ ui.label(if conflicts.is_empty() {++ crate::i18n::tr(&app.ui.language, "No conflicts").to_string()++ } else {++ crate::i18n::tr(&app.ui.language, "{count} conflict(s): {names}")++ .replace("{count}", &conflicts.len().to_string())++ .replace("{names}", &conflicts.join(", "))++ });++ let cur = d.s("styleConflicts");++ ui.horizontal(|ui| {++ for (v, l) in [++ ("useExisting", "Use Document Style Definition"),++ ("redefine", "Redefine Document Style"),++ ("autoRename", "Auto Rename"),++ ] {++ if ui.radio(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() {++ d.fields.insert("styleConflicts".into(), json!(v));+ }}- }- });- ui.end_row();- });- check(ui, &mut d, "bpc", crate::i18n::tr(&app.ui.language, "Use Black Point Compensation"));- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load Profile…"))).clicked()- && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("icc"))- {- match app.session.execute("color.loadProfile", &json!({"path": path})) {- Ok(_) => {- let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();- d.fields.insert("profiles".into(), f["profiles"].clone());+ });- ui.end_row();- }- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Intent:"));- let cur = d.s("intent");- egui::ComboBox::from_id_salt("ws_intent")- .selected_text(crate::rtl::widget(- ui,- crate::i18n::tr(&app.ui.language, designcraft_color::cms::Intent::parse(&cur).map_or("", |i| i.label())),- ))- .show_ui(ui, |ui| {- for i in designcraft_color::cms::Intent::ALL {- if ui- .selectable_label(i.id() == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, i.label())))- .clicked()- {- d.fields.insert("intent".into(), json!(i.id()));++ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Mapping")).font(semibold(12.0)));++ let names: Vec<String> =++ app.session.active().map(|s| s.doc.styles.paragraph.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();++ let imported: Vec<String> = d++ .fields++ .get("styles")++ .and_then(Value::as_array)++ .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())++ .unwrap_or_default();++ egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {++ egui::Grid::new("imp_map").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {++ for w in &imported {++ ui.label(w);++ let mapped = d.fields.get("map").and_then(|m| m.get(w)).and_then(Value::as_str).unwrap_or("").to_string();++ let shown = if mapped.is_empty() {++ crate::i18n::tr(&app.ui.language, "(import)").to_string()++ } else {++ mapped.clone()++ };++ egui::ComboBox::from_id_salt(("imp_map", w))++ .selected_text(crate::rtl::widget(ui, &shown))++ .width(170.0)++ .show_ui(ui, |ui| {++ if ui++ .selectable_label(++ mapped.is_empty(),++ crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "(import)")),++ )++ .clicked()++ && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)++ {++ m.remove(w);++ }++ for n in &names {++ if ui.selectable_label(*n == mapped, n).clicked()++ && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)++ {++ m.insert(w.clone(), json!(n));++ }++ }++ });++ ui.end_row();+ }- }++ });+ });- ui.end_row();- });- check(ui, &mut d, "bpc", crate::i18n::tr(&app.ui.language, "Use Black Point Compensation"));- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Load Profile…"))).clicked()- && let Some(path) = app.services.pick_open.as_mut().and_then(|f| f("icc"))- {- match app.session.execute("color.loadProfile", &json!({"path": path})) {- Ok(_) => {- let f = app.session.execute("color.settings", &json!({})).unwrap_or_default();- d.fields.insert("profiles".into(), f["profiles"].clone());- }- Err(e) => app.status(format!("Color Settings: {e}")),}- Err(e) => app.status_error("Color Settings", e),}-- }- }- "keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),- "userDictionary" => user_dictionary(app, ui, &mut d),- "menus" => {- text_field(ui, &mut d, "query", 260.0);- let q = d.s("query").to_lowercase();- egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {- for (menu, label) in crate::menus::all_menu_items().into_iter().filter(|(m, l)| q.is_empty() || m.to_lowercase().contains(&q) || l.to_lowercase().contains(&q)) {- let key = crate::menus::menu_key(&menu, &label);- let mut visible = !app.ui.hidden_menu_items.contains(&key);- if ui.checkbox(&mut visible, crate::rtl::widget(ui, format!("{} › {}", crate::i18n::tr(&app.ui.language, &menu), crate::i18n::tr(&app.ui.language, &label)))).changed() {- let _ = app.run("window.hideMenuItem", json!({"item": key, "hidden": !visible}));- "keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),- "userDictionary" => user_dictionary(app, ui, &mut d),- "menus" => {- text_field(ui, &mut d, "query", 260.0);- let q = d.s("query").to_lowercase();- egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {- for (menu, label) in crate::menus::all_menu_items()- .into_iter()- .filter(|(m, l)| q.is_empty() || m.to_lowercase().contains(&q) || l.to_lowercase().contains(&q))- {- let key = crate::menus::menu_key(&menu, &label);- let mut visible = !app.ui.hidden_menu_items.contains(&key);- if ui- .checkbox(- &mut visible,- crate::rtl::widget(- ui,- format!("{} › {}", crate::i18n::tr(&app.ui.language, &menu), crate::i18n::tr(&app.ui.language, &label)),- ),- )- .changed()- {- let _ = app.run("window.hideMenuItem", json!({"item": key, "hidden": !visible}));- }-- }- });- }- "importOptions" => {- ui.label(egui::RichText::new(d.s("path")).size(10.5));- check(ui, &mut d, "removeStyles", crate::i18n::tr(&app.ui.language, "Remove Styles and Formatting from Text and Tables"));- if !d.b("removeStyles") {- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Name Conflicts")).font(semibold(12.0)));- let conflicts: Vec<String> = d- .fields- .get("conflicts")- .and_then(Value::as_array)- .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())- .unwrap_or_default();- ui.label(if conflicts.is_empty() {- crate::i18n::tr(&app.ui.language, "No conflicts").to_string()- } else {- format!("{} conflict(s): {}", conflicts.len(), conflicts.join(", "))++ "loadStyles" => load_styles(app, ui, &mut d),++ "closeDocument" => {++ let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?")++ .replace("{}", &d.s("title"));++ crate::rtl::label(ui, text);+ }- });- }- "importOptions" => {- ui.label(egui::RichText::new(d.s("path")).size(10.5));- check(ui, &mut d, "removeStyles", crate::i18n::tr(&app.ui.language, "Remove Styles and Formatting from Text and Tables"));- if !d.b("removeStyles") {- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Name Conflicts")).font(semibold(12.0)));- let conflicts: Vec<String> = d.fields.get("conflicts").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();- ui.label(if conflicts.is_empty() { crate::i18n::tr(&app.ui.language, "No conflicts").to_string() } else { crate::i18n::tr(&app.ui.language, "{count} conflict(s): {names}").replace("{count}", &conflicts.len().to_string()).replace("{names}", &conflicts.join(", ")) });- let cur = d.s("styleConflicts");- ui.horizontal(|ui| {- for (v, l) in [("useExisting", "Use Document Style Definition"), ("redefine", "Redefine Document Style"), ("autoRename", "Auto Rename")] {- if ui.radio(cur == v, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() {- d.fields.insert("styleConflicts".into(), json!(v));- }- }- });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Mapping")).font(semibold(12.0)));- let names: Vec<String> = app.session.active().map(|s| s.doc.styles.paragraph.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();- let imported: Vec<String> = d.fields.get("styles").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default();- egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {- egui::Grid::new("imp_map").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {- for w in &imported {- ui.label(w);- let mapped = d.fields.get("map").and_then(|m| m.get(w)).and_then(Value::as_str).unwrap_or("").to_string();- let shown = if mapped.is_empty() { crate::i18n::tr(&app.ui.language, "(import)").to_string() } else { mapped.clone() };- egui::ComboBox::from_id_salt(("imp_map", w)).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(ui, |ui| {- if ui.selectable_label(mapped.is_empty(),crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "(import)"))).clicked()- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)- {- m.remove(w);++ "updateLink" => {++ let text = crate::i18n::tr(++ &app.ui.language,++ "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.",++ )++ .replace("{}", &d.s("files"));++ crate::rtl::label(ui, text);++ }++ "newWorkspace" => {++ ui.horizontal(|ui| {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));++ text_field(ui, &mut d, "name", 220.0);+ });- let cur = d.s("styleConflicts");++ crate::rtl::label(++ ui,++ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5),++ );++ }++ "fittingOptions" => {++ check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));++ ui.add_space(4.0);++ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));++ let cur = d.s("fitting");++ let label = |v: &str| match v {++ "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),++ "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),++ "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),++ "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),++ _ => crate::i18n::tr(&app.ui.language, "None"),++ };+ ui.horizontal(|ui| {- for (v, l) in [- ("useExisting", "Use Document Style Definition"),- ("redefine", "Redefine Document Style"),- ("autoRename", "Auto Rename"),- ] {- if ui.radio(cur == v, l).clicked() {- d.fields.insert("styleConflicts".into(), json!(v));- }- }++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));++ egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(++ ui,++ |ui| {++ for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {++ if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {++ d.fields.insert("fitting".into(), json!(v));++ }+ }- for n in &names {- if ui.selectable_label(*n == mapped, n).clicked()- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)- {- m.insert(w.clone(), json!(n));++ },++ );+ });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Style Mapping")).font(semibold(12.0)));- let names: Vec<String> =- app.session.active().map(|s| s.doc.styles.paragraph.iter().map(|p| p.name.clone()).collect()).unwrap_or_default();- let imported: Vec<String> = d- .fields- .get("styles")- .and_then(Value::as_array)- .map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())- .unwrap_or_default();- egui::ScrollArea::vertical().max_height(180.0).show(ui, |ui| {- egui::Grid::new("imp_map").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| {- for w in &imported {- ui.label(w);- let mapped = d.fields.get("map").and_then(|m| m.get(w)).and_then(Value::as_str).unwrap_or("").to_string();- let shown = if mapped.is_empty() { "(import)".to_string() } else { mapped.clone() };- egui::ComboBox::from_id_salt(("imp_map", w)).selected_text(crate::rtl::widget(ui, &shown)).width(170.0).show_ui(- ui,- |ui| {- if ui- .selectable_label(- mapped.is_empty(),- crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "(import)")),- )- .clicked()- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)- {- m.remove(w);- }- for n in &names {- if ui.selectable_label(*n == mapped, n).clicked()- && let Some(m) = d.fields.get_mut("map").and_then(Value::as_object_mut)- {- m.insert(w.clone(), json!(n));- }- }- },- );++ ui.horizontal(|ui| {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));++ let a = d.n("align").unwrap_or(4.0) as u8;++ egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {++ for row in 0..3u8 {++ for col in 0..3u8 {++ let i = row * 3 + col;++ let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());++ let c = ui.visuals().text_color();++ if a == i {++ ui.painter().rect_filled(r.shrink(2.0), 1.0, c);++ } else {++ ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);++ }++ if resp.clicked() {++ d.fields.insert("align".into(), json!(i));+ }+ }- });- ui.end_row();- }+ ui.end_row();+ }+ });});- });- }-- }- }- "loadStyles" => load_styles(app, ui, &mut d),- "closeDocument" => {- let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?").replace("{}", &d.s("title"));- crate::rtl::label(ui, text);- }- "updateLink" => {- let text = crate::i18n::tr(&app.ui.language, "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.")- "closeDocument" => {- let text = crate::i18n::tr(&app.ui.language, "“{}” has changes that are not saved. Save them before closing?")- .replace("{}", &d.s("title"));- crate::rtl::label(ui, text);- }- "updateLink" => {- let text = crate::i18n::tr(- &app.ui.language,- "“{}” has been edited in this layout. Updating replaces those edits with the text from the file.",- )-- .replace("{}", &d.s("files"));- crate::rtl::label(ui, text);- }- "newWorkspace" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));- text_field(ui, &mut d, "name", 220.0);- });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5));- }- "fittingOptions" => {- check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));- ui.add_space(4.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));- let cur = d.s("fitting");- let label = |v: &str| match v {- "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),- "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),- "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),- "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),- _ => crate::i18n::tr(&app.ui.language, "None"),- };- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));- egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(ui, |ui| {- for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("fitting".into(), json!(v));- crate::rtl::label(ui, text);- }- "newWorkspace" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Name:"));- text_field(ui, &mut d, "name", 220.0);- });- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Saves which bars show and where the panels are.")).size(10.5),- );- }- "fittingOptions" => {- check(ui, &mut d, "autoFit", crate::i18n::tr(&app.ui.language, "Auto-Fit"));- ui.add_space(4.0);- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Content Fitting")).font(semibold(12.0)));- let cur = d.s("fitting");- let label = |v: &str| match v {- "fillProportionally" => crate::i18n::tr(&app.ui.language, "Fill Frame Proportionally"),- "fitProportionally" => crate::i18n::tr(&app.ui.language, "Fit Content Proportionally"),- "fitContentToFrame" => crate::i18n::tr(&app.ui.language, "Fit Content to Frame"),- "centerContent" => crate::i18n::tr(&app.ui.language, "Center Content"),- _ => crate::i18n::tr(&app.ui.language, "None"),- };- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fitting:"));- egui::ComboBox::from_id_salt("ff_fit").selected_text(crate::rtl::widget(ui, label(&cur))).width(200.0).show_ui(ui, |ui| {- for v in ["none", "fillProportionally", "fitProportionally", "fitContentToFrame", "centerContent"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("fitting".into(), json!(v));- }++ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));++ egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {++ for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));++ text_field(ui, &mut d, k, 70.0);+ }- }- });- });- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));- let a = d.n("align").unwrap_or(4.0) as u8;- egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {- for row in 0..3u8 {- for col in 0..3u8 {- let i = row * 3 + col;- let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());- let c = ui.visuals().text_color();- if a == i {- ui.painter().rect_filled(r.shrink(2.0), 1.0, c);- } else {- ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);- }- if resp.clicked() {- d.fields.insert("align".into(), json!(i));- }++ ui.end_row();++ for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));++ text_field(ui, &mut d, k, 70.0);}+ ui.end_row();- }- });- });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));- egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);- }- ui.end_row();- for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);+ });- });- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Align From:"));- let a = d.n("align").unwrap_or(4.0) as u8;- egui::Grid::new("ff_align").spacing([2.0, 2.0]).show(ui, |ui| {- for row in 0..3u8 {- for col in 0..3u8 {- let i = row * 3 + col;- let (r, resp) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::click());- let c = ui.visuals().text_color();- if a == i {- ui.painter().rect_filled(r.shrink(2.0), 1.0, c);- } else {- ui.painter().rect_stroke(r.shrink(3.0), 1.0, egui::Stroke::new(1.0, c), egui::StrokeKind::Inside);- }- if resp.clicked() {- d.fields.insert("align".into(), json!(i));+ }- ui.end_row();- });- }- "qrCode" => {- let cur = d.s("type");- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));- let label = |v: &str| match v {- "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),- "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),- "email" => crate::i18n::tr(&app.ui.language, "Email"),- "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),- _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),- };- egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(ui, |ui| {- for v in ["url", "text", "sms", "email", "vcard"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("type".into(), json!(v));++ "qrCode" => {++ let cur = d.s("type");++ ui.horizontal(|ui| {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));++ let label = |v: &str| match v {++ "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),++ "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),++ "email" => crate::i18n::tr(&app.ui.language, "Email"),++ "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),++ _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),++ };++ egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(++ ui,++ |ui| {++ for v in ["url", "text", "sms", "email", "vcard"] {++ if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {++ d.fields.insert("type".into(), json!(v));++ }+ }- }- ui.end_row();- }++ },++ );+ });- });- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Crop Amount")).font(semibold(12.0)));- egui::Grid::new("ff_crop").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in [("cropTop", "Top:"), ("cropLeft", "Left:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);- }- ui.end_row();- for (k, l) in [("cropBottom", "Bottom:"), ("cropRight", "Right:")] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 70.0);- }- ui.end_row();- });- }- "qrCode" => {- let cur = d.s("type");- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Type:"));- let label = |v: &str| match v {- "text" => crate::i18n::tr(&app.ui.language, "Plain Text"),- "sms" => crate::i18n::tr(&app.ui.language, "Text Message"),- "email" => crate::i18n::tr(&app.ui.language, "Email"),- "vcard" => crate::i18n::tr(&app.ui.language, "Business Card"),- _ => crate::i18n::tr(&app.ui.language, "Web Hyperlink"),++ let fields: &[(&str, &str)] = match cur.as_str() {++ "sms" => &[("number", "Cell Number:"), ("message", "Message:")],++ "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],++ "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],++ "text" => &[("content", "Text:")],++ _ => &[("content", "URL:")],+ };- egui::ComboBox::from_id_salt("qr_type").selected_text(crate::rtl::widget(ui, label(&cur))).width(160.0).show_ui(ui, |ui| {- for v in ["url", "text", "sms", "email", "vcard"] {- if ui.selectable_label(cur == v, crate::rtl::widget(ui, label(v))).clicked() {- d.fields.insert("type".into(), json!(v));- }++ egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {++ for (k, l) in fields {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));++ text_field(ui, &mut d, k, 260.0);++ ui.end_row();}++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));++ text_field(ui, &mut d, "color", 160.0);++ ui.end_row();+ });- });- let fields: &[(&str, &str)] = match cur.as_str() {- "sms" => &[("number", "Cell Number:"), ("message", "Message:")],- "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],- "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],- "text" => &[("content", "Text:")],- _ => &[("content", "URL:")],- };- egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in fields {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 260.0);++ }++ "polygonSettings" => {++ egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));++ text_field(ui, &mut d, "sides", 60.0);+ ui.end_row();- }- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));- text_field(ui, &mut d, "color", 160.0);- ui.end_row();- });- }- "polygonSettings" => {- egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));- text_field(ui, &mut d, "sides", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));++ ui.horizontal(|ui| {++ text_field(ui, &mut d, "starInset", 60.0);++ ui.label("%");++ });++ ui.end_row();++ });++ }++ STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),++ TOC => toc_dialog(app, ui, &mut d),++ id if id.starts_with("cmd:") => command_form(app, ui, &mut d),++ "goToPage" => {+ ui.horizontal(|ui| {- text_field(ui, &mut d, "starInset", 60.0);- ui.label("%");++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));++ text_field(ui, &mut d, "page", 80.0);+ });- ui.end_row();- });- }- STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),- TOC => toc_dialog(app, ui, &mut d),- id if id.starts_with("cmd:") => command_form(app, ui, &mut d),- "goToPage" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));- text_field(ui, &mut d, "page", 80.0);- });- }- "ruby" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Ruby:"));- text_field(ui, &mut d, "text", 200.0);- });- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Set over the selected text; empty removes it.")).size(11.0),- );- }- "insertTable" => {- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));- egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));- text_field(ui, &mut d, "bodyRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));- text_field(ui, &mut d, "columns", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));- text_field(ui, &mut d, "headerRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));- text_field(ui, &mut d, "footerRows", 60.0);- ui.end_row();- });- }- "createGuides" => create_guides_dialog(app, ui, &mut d),- "marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),- "textFrameOptions" => {- seed_text_frame_options(app, &mut d);- text_frame_options_dialog(app, ui, &mut d);- }- "documentSetup" => document_setup(app, ui, &mut d),- "pdfExport" => pdf_export(app, ui, &mut d),- "alert" => {- let file = d.s("file");- if !file.is_empty() {- crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));- ui.add_space(4.0);+ }- crate::rtl::label(ui, d.s("message"));++ "ruby" => style_cjk::ruby_dialog(app, ui, &mut d),++ "insertTable" => {++ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));++ egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));++ text_field(ui, &mut d, "bodyRows", 60.0);++ crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));++ text_field(ui, &mut d, "columns", 60.0);++ ui.end_row();++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));++ text_field(ui, &mut d, "headerRows", 60.0);++ crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));++ text_field(ui, &mut d, "footerRows", 60.0);++ ui.end_row();++ });++ }++ "cellOptions" => cell_options(app, ui, &mut d),++ "createGuides" => create_guides_dialog(app, ui, &mut d),++ "marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),++ "textFrameOptions" => {++ seed_text_frame_options(app, &mut d);++ text_frame_options_dialog(app, ui, &mut d);++ }++ "documentSetup" => {++ // Adjust Layout applies at once.++ let adjust = document_setup(app, ui, &mut d);++ if adjust {++ result = Some(true);+ }- });- });- let fields: &[(&str, &str)] = match cur.as_str() {- "sms" => &[("number", "Cell Number:"), ("message", "Message:")],- "email" => &[("to", "Email Address:"), ("subject", "Subject:"), ("body", "Message:")],- "vcard" => &[("name", "Name:"), ("org", "Organization:"), ("phone", "Phone:"), ("email", "Email:"), ("url", "URL:")],- "text" => &[("content", "Text:")],- _ => &[("content", "URL:")],- };- egui::Grid::new("qr_fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- for (k, l) in fields {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, l));- text_field(ui, &mut d, k, 260.0);- ui.end_row();+ }- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Color:"));- text_field(ui, &mut d, "color", 160.0);- ui.end_row();- });- }- "polygonSettings" => {- egui::Grid::new("poly").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Number of Sides:"));- text_field(ui, &mut d, "sides", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Star Inset:"));- ui.horizontal(|ui| {- text_field(ui, &mut d, "starInset", 60.0);- ui.label("%");- });- ui.end_row();- });- }- STEP_AND_REPEAT => step_and_repeat_dialog(app, ui, &mut d),- TOC => toc_dialog(app, ui, &mut d),- id if id.starts_with("cmd:") => command_form(app, ui, &mut d),- "goToPage" => {- ui.horizontal(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Page"));- text_field(ui, &mut d, "page", 80.0);- });- }- "ruby" => style_cjk::ruby_dialog(app, ui, &mut d),- "insertTable" => {- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Table Dimensions")).font(semibold(12.0)));- egui::Grid::new("ins_table").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Body Rows"));- text_field(ui, &mut d, "bodyRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr_context(&app.ui.language, "Columns", "table"));- text_field(ui, &mut d, "columns", 60.0);- ui.end_row();- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Header Rows"));- text_field(ui, &mut d, "headerRows", 60.0);- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Footer Rows"));- text_field(ui, &mut d, "footerRows", 60.0);- ui.end_row();- });- }- "cellOptions" => cell_options(app, ui, &mut d),- "textFrameOptions" => {- seed_text_frame_options(app, &mut d);- text_frame_options_dialog(app, ui, &mut d);- }- "documentSetup" => {- // Adjust Layout applies at once.- let adjust = document_setup(app, ui, &mut d);- if adjust {- result = Some(true);- }- }- "numberingSection" => crate::section_options::body(app, ui, &mut d),- "pdfExport" => pdf_export(app, ui, &mut d),- "alert" => {- let file = d.s("file");- if !file.is_empty() {- crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));- ui.add_space(4.0);++ "numberingSection" => crate::section_options::body(app, ui, &mut d),++ "pdfExport" => pdf_export(app, ui, &mut d),++ "alert" => {++ let file = d.s("file");++ if !file.is_empty() {++ crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0)));++ ui.add_space(4.0);++ }++ crate::rtl::label(ui, d.s("message"));++ }++ _ => {}}- crate::rtl::label(ui, d.s("message"));- }- _ => {}- }- });- _ => {}+ });+ if side_actions {+ return;+ }ui.add_space(12.0);let ok_label = match d.id.as_str() {- "closeDocument" => " Save ",- "updateLink" => " Update ",- _ => " OK ",+ "closeDocument" => crate::i18n::tr(&app.ui.language, " Save ").to_string(),+ "updateLink" => crate::i18n::tr(&app.ui.language, " Update ").to_string(),+ "findFont" => crate::i18n::tr(&app.ui.language, "Replace All").to_string(),+ "newDocument" => format!(" {} ", crate::i18n::tr(&app.ui.language, "Create")),+ _ => crate::i18n::tr(&app.ui.language, " OK ").to_string(),+ };+ let cancel_label = match d.id.as_str() {+ "newDocument" => "Close",+ "findFont" => "Done",+ _ => "Cancel",};ui.horizontal(|ui| {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {@@@ -2269,129 -2246,29 +2755,143 @@@}}+/// Cell Options keys (`table.getCellStroke` names) and whether each belongs to the stroke.+const CELL_OPTION_KEYS: [(&str, bool); 8] =+ [("weight", true), ("type", true), ("color", true), ("tint", true), ("gapColor", true), ("gapTint", true), ("fill", false), ("fillTint", false)];++/// Table › Cell Options › Strokes and Fills… for the target cells. The fields start from the+/// cells' values (`seed`); OK applies the fields that differ from it.+pub fn open_cell_options(app: &mut DesignApp) -> Result<Value, String> {+ let edges = crate::panels::cell_stroke::edges_param(&[true; 6]);+ let cur = app.session.execute("table.getCellStroke", &json!({"edges": edges})).map_err(|e| e.to_string())?;+ let mut fields = Map::new();+ for (k, _) in CELL_OPTION_KEYS {+ fields.insert(k.into(), cur[k].clone());+ }+ fields.insert("seed".into(), Value::Object(fields.clone()));+ fields.insert("edges".into(), edges);+ app.ui.dialog = Some(Dialog::new("cellOptions", Value::Object(fields)));+ Ok(Value::Null)+}++/// Cell Options › Strokes and Fills: the edge proxy and stroke fields, then the cell fill.+fn cell_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ use crate::panels::cell_stroke;+ let lang = app.ui.language.clone();+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Cell Stroke")).font(semibold(12.0)));+ let mut edges = cell_stroke::edges_from(d.fields.get("edges").unwrap_or(&Value::Null));+ if cell_stroke::edge_proxy(ui, "cell_options", &mut edges, &lang) {+ cell_options_edges_changed(app, d, &edges);+ }+ ui.add_space(6.0);+ let values = Value::Object(d.fields.clone());+ let any = edges.iter().any(|on| *on);+ if let Some((k, v)) = ui.add_enabled_ui(any, |ui| cell_stroke::stroke_fields(app, ui, "cell_options", &values)).inner {+ d.fields.insert(k.into(), v);+ }+ ui.add_space(10.0);+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Cell Fill")).font(semibold(12.0)));+ egui::Grid::new("cell_fill").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Color:"));+ let mut picked = None;+ crate::panels::swatch_picker(app, ui, "cell_fill_color", values["fill"].as_str().map(str::to_string), |_, n| picked = Some(n));+ if let Some(n) = picked {+ d.fields.insert("fill".into(), json!(n));+ }+ ui.end_row();+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Tint:"));+ let tint = values["fillTint"].as_f64().map(|t| (t * 100.0).round());+ if let Some(t) = crate::widgets::NumField::number("cell_fill_tint", tint, "%", 0).width(60.0).range(0.0, 100.0).show(ui) {+ d.fields.insert("fillTint".into(), json!(t / 100.0));+ }+ ui.end_row();+ });+}++/// Cell Options with a new edge choice: the stroke fields the user hasn't changed show the+/// chosen edges' values, and every stroke field's seed becomes those values, so OK applies+/// exactly the fields that differ from what the chosen edges show.+fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate::panels::cell_stroke::Edges) {+ d.fields.insert("edges".into(), crate::panels::cell_stroke::edges_param(edges));+ let cur = crate::panels::cell_stroke::current(app, edges);+ let mut seed = d.fields.get("seed").and_then(Value::as_object).cloned().unwrap_or_default();+ for (k, stroke) in CELL_OPTION_KEYS {+ if !stroke {+ continue;+ }+ let v = cur.get(k).cloned().unwrap_or(Value::Null);+ // Null shows mixed values; the user can't type it.+ let field = d.fields.get(k).filter(|f| !f.is_null());+ if field.is_none() || field == seed.get(k) {+ d.fields.insert(k.into(), v.clone());+ }+ seed.insert(k.into(), v);+ }+ d.fields.insert("seed".into(), Value::Object(seed));+}++/// Apply the Cell Options fields that differ from the cells' values, as one `table.setCell`.+fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {+ let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);+ let mut stroke = Map::new();+ let mut params = Map::new();+ for (k, is_stroke) in CELL_OPTION_KEYS {+ let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && seed.get(k) != Some(*v)) else { continue };+ match (is_stroke, k) {+ (true, _) => {+ stroke.insert(k.into(), v.clone());+ }+ (false, "fillTint") => {+ params.insert("tint".into(), v.clone());+ }+ _ => {+ params.insert(k.into(), v.clone());+ }+ }+ }+ if !stroke.is_empty() {+ stroke.insert("edges".into(), d.fields.get("edges").cloned().unwrap_or(json!("all")));+ params.insert("stroke".into(), Value::Object(stroke));+ }+ if params.is_empty() {+ return Ok(Value::Null);+ }+ app.run("table.setCell", Value::Object(params))+}+/// Close the open dialog without applying it (Cancel, Esc, the control channel): a previewing-/// dialog puts the document back as it was.+/// dialog puts the document back as it was, and Preferences puts back the interface language it+/// opened with, since choosing one previews it at once.pub fn cancel(app: &mut DesignApp) {+ if app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") {+ app.session.reset_find_scope();+ }- if app.ui.dialog.take().is_some_and(|d| d.fields.contains_key(PREVIEWED)) {+ let d = app.ui.dialog.take();+ crate::new_document::end_preview(app);+ if d.as_ref().is_some_and(|d| d.fields.contains_key(PREVIEWED)) {app.session.cancel_interaction();}app.cancel_pdf_import();+ if let Some(d) = d+ && d.id == "preferences"+ && let Some(lang) = d.fields.get("openedLanguage").and_then(Value::as_str)+ && lang != app.ui.language+ {+ let _ = app.run("app.language", json!({"lang": lang}));+ }}+ fn find_change_params(d: &Dialog) -> Value {+ let mut p = json!({+ "find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"),+ "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope"),+ });+ if let Some(story) = d.fields.get("story") {+ p["story"] = story.clone();+ }+ p+ }+/// Apply the open dialog.pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {let Some(d) = app.ui.dialog.take() else { return Err("no dialog open".into()) };@@@ -2399,7 -2276,31 +2899,23 @@@app.cancel_pdf_import();}match d.id.as_str() {+ "createGuides" | "marginsAndColumns" => {+ // The preview goes; the change is made once, as one undo step.+ if d.fields.contains_key(PREVIEWED) {+ app.session.cancel_interaction();+ }+ let cmd = if d.id == "createGuides" { "layout.createGuides" } else { "layout.marginsAndColumns" };+ let r = layout_dialog_params(&d).and_then(|p| app.run(cmd, p));+ if let Err(e) = &r {+ // A value that does not parse, or a refused one, keeps the dialog open to be fixed.+ let mut d = d.clone();+ d.fields.remove(PREVIEWED);+ d.fields.insert("status".into(), json!(e));+ app.ui.dialog = Some(d);+ }+ r+ }- "newDocument" => {- let margins = json!({"top": d.m("marginTop").unwrap_or(36.0), "bottom": d.m("marginBottom").unwrap_or(36.0), "inside": d.m("marginInside").unwrap_or(36.0), "outside": d.m("marginOutside").unwrap_or(36.0)});- app.run(- "file.new",- json!({"width": d.m("width"), "height": d.m("height"), "pages": d.n("pages").unwrap_or(1.0) as u64, "facingPages": d.b("facingPages"),- "columns": d.n("columns").unwrap_or(1.0) as u64, "gutter": d.m("gutter").unwrap_or(12.0), "margins": margins, "bleed": d.m("bleed").unwrap_or(0.0),- "primaryTextFrame": d.b("primaryTextFrame")}),- )- }+ "newDocument" => crate::new_document::create(app, d),"frameSize" => {let x = d.fields.get("x").and_then(Value::as_f64).unwrap_or(0.0);let y = d.fields.get("y").and_then(Value::as_f64).unwrap_or(0.0);@@@ -2885,9 -2729,12 +3401,13 @@@app.run("footnote.options", p)}"alert" => Ok(Value::Null),+ crate::effects_dialog::ID => crate::effects_dialog::confirm(app, &d),- "findChange" if d.b("objectMode") => Ok(Value::Null),- "findChange" => app.run("find.change", json!({"find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope")})),+ "findChange" => {+ let result = if d.b("objectMode") { Ok(Value::Null) } else { app.run("find.change", find_change_params(&d)) };+ // Confirmation consumes retained bounds before closing, even on an error.+ app.session.reset_find_scope();+ result+ }STEP_AND_REPEAT => {// The preview goes; the copies are made once, as one undo step.if d.fields.contains_key(PREVIEWED) {@@@ -7914,51 -6772,74 +9261,122 @@@ mod testsdrag(&mut h, title, title - vec2(900.0, 0.0));assert!((rect(&h).right() - 100.0).abs() < 2.0, "{:?}", rect(&h));}++ #[test]+ fn the_new_document_window_drags_mostly_aside_and_keeps_its_preview() {+ use egui::{Event, Modifiers, PointerButton, vec2};+ use egui_kittest::{Harness, kittest::Queryable};+ let rect = |h: &Harness<'static, DesignApp>| h.ctx.memory(|m| m.area_rect(egui::Id::new("dialog"))).unwrap();+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "A"})).unwrap();+ app.ui.new_document_preview = true;+ app.run("app.newDocumentDialog", json!({})).unwrap();+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), &app.ui.language);+ crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::default()));+ ready = true;+ return;+ }+ show(app, ui.ctx());+ },+ app,+ );+ h.run_steps(6);+ let preview = h.state().session.new_document_preview();+ assert!(preview.is_some(), "Preview is on");+ let centred = rect(&h);+ assert!(centred.width() > 900.0, "{centred:?}");+ let from = h.get_all_by_label("New Document").map(|n| n.rect().center()).min_by(|a, b| a.y.total_cmp(&b.y)).unwrap();+ let to = from + vec2(1300.0, 0.0);+ h.event(Event::PointerMoved(from));+ h.run_steps(1);+ h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });+ h.run_steps(1);+ for step in 1..=8 {+ h.event(Event::PointerMoved(from + (to - from) * (step as f32 / 8.0)));+ h.run_steps(1);+ }+ h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });+ h.run_steps(3);+ // All but 100 px of the window's width is past the right edge, over the preview.+ assert!((rect(&h).left() - 1300.0).abs() < 2.0, "{:?}", rect(&h));+ let app = h.state();+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("newDocument"));+ assert_eq!(app.session.new_document_preview(), preview, "moving the window keeps the preview");+ assert_eq!(app.session.documents().len(), 2);+ }+++ #[test]+ fn margins_dialog_reads_bare_numbers_in_the_ruler_unit() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "15"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let top = app.session.active().unwrap().doc.page(0).unwrap().margins.top;+ assert!((top - 15.0 * 72.0 / 25.4).abs() < 0.01, "top margin was {top} pt");+ }+ fn facing_app(pages: u64) -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": pages, "facingPages": true})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));+ app+ }++ fn guide_counts(app: &DesignApp) -> Vec<usize> {+ let doc = &app.session.active().unwrap().doc;+ (0..doc.page_count()).map(|abs| doc.page(abs).unwrap().guides.len()).collect()+ }++ #[test]+ fn create_guides_dialog_targets_the_page_in_view() {+ let mut app = facing_app(6);+ crate::canvas::go_to_page(&mut app, 4);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "3"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 0, 0, 0, 4, 0]);+ // "Both pages of the spread" covers the facing pair.+ crate::canvas::go_to_page(&mut app, 1);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ ctl(&mut app, "ui.dialog.set", json!({"field": "target", "value": "spread"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ assert_eq!(guide_counts(&app), vec![0, 2, 2, 0, 4, 0]);+ }++ #[test]+ fn parent_dialogs_cover_both_pages_of_the_parent_spread_by_default() {+ let mut app = facing_app(4);+ app.run("layout.parents.edit", json!({"on": true})).unwrap();+ crate::menus::activate(&mut app, "layout.marginsAndColumns", &Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().s("target"), "spread");+ for k in ["marginTop", "marginBottom", "marginInside", "marginOutside"] {+ ctl(&mut app, "ui.dialog.set", json!({"field": k, "value": "20 pt"}));+ }+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ crate::menus::activate(&mut app, "layout.createGuides", &Value::Null);+ ctl(&mut app, "ui.dialog.set", json!({"field": "columns", "value": "2"}));+ assert_eq!(ctl(&mut app, "ui.dialog.confirm", json!({}))["ok"], true);+ let doc = &app.session.active().unwrap().doc;+ for pg in &doc.parents[0].pages {+ assert_eq!((pg.margins.top, pg.margins.outside, pg.guides.len()), (20.0, 20.0, 2));+ }+ // Every document page shows the parent's guides.+ assert!((0..doc.page_count()).all(|abs| doc.inherited_guides(abs).len() == 2));+ }++ #[test]+ fn other_dialogs_keep_reading_bare_numbers_as_picas() {+ let mut app = facing_app(2);+ app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap();+ app.ui.dialog = Some(Dialog::new("newDocument", json!({"width": "15"})));+ assert_eq!(app.ui.dialog.as_ref().unwrap().m("width"), Some(180.0));+ }}diff --cc crates/ui-egui/src/i18n.rsindex 312e1e5d1,74cda4520..6c7afdb9a--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -5,14 -4,11 +5,15 @@@use std::{collections::HashMap, sync::OnceLock};mod ar;+mod cs;mod de;+mod fr;mod it;mod ja;+ mod ka;+mod pl;mod pt_br;+mod ru;mod uk;/// Supported interface languages: (code, name in that language).@@@ -27,9 -23,7 +28,10 @@@ pub const LANGUAGES: &[(&str, &str)] =("pt-br", "Português (Brasil)"),("it", "Italiano"),("uk", "Українська"),+ ("ru", "Русский"),+ ("cs", "Čeština"),+ ("pl", "Polski"),+ ("ka", "ქართული"),];/// English → [German, French, Spanish, Japanese, Simplified Chinese].@@@ -87,60 -58,121 +89,172 @@@ const TABLE: &[(&str, [&str; 5])] = &("Cut", ["Ausschneiden", "Couper", "Cortar", "カット", "剪切"]),("Copy", ["Kopieren", "Copier", "Copiar", "コピー", "复制"]),("Paste", ["Einfügen", "Coller", "Pegar", "ペースト", "粘贴"]),+ (+ "Paste Vector Art",+ ["Vektorgrafik einfügen", "Coller l’illustration vectorielle", "Pegar ilustración vectorial", "ベクトルアートをペースト", "粘贴矢量图稿"],+ ),+ (+ "Bulleted & Numbered Lists",+ [+ "Aufzählungszeichen und nummerierte Listen",+ "Listes à puces et numérotées",+ "Listas con viñetas y numeradas",+ "箇条書き",+ "项目符号列表和编号列表",+ ],+ ),+ ("Current Page Number", ["Aktuelle Seitenzahl", "Numéro de page actuelle", "Número de página actual", "現在のページ番号", "当前页码"]),+ ("Apply Color (,)", ["Farbe anwenden (,)", "Appliquer la couleur (,)", "Aplicar color (,)", "カラーを適用 (,)", "应用颜色 (,)"]),+ ("Apply Gradient (.)", ["Verlauf anwenden (.)", "Appliquer le dégradé (.)", "Aplicar degradado (.)", "グラデーションを適用 (.)", "应用渐变 (.)"]),+ ("View Options", ["Ansichtsoptionen", "Options d’affichage", "Opciones de visualización", "表示オプション", "视图选项"]),+ ("Frame Edges", ["Rahmenkanten", "Bords du bloc", "Bordes del marco", "フレーム枠", "框架边缘"]),+ ("Rulers", ["Lineale", "Règles", "Reglas", "定規", "标尺"]),+ ("Hidden Characters", ["Verborgene Zeichen", "Caractères masqués", "Caracteres ocultos", "制御文字", "隐藏字符"]),+ ("Flex Layout", ["Flex-Layout", "Mise en page flexible", "Diseño flexible", "フレックスレイアウト", "弹性布局"]),+ (+ "Create Flex Layout",+ ["Flex-Layout erstellen", "Créer une mise en page flexible", "Crear diseño flexible", "フレックスレイアウトを作成", "创建弹性布局"],+ ),+ (+ "Add to Flex Layout",+ [+ "Zu Flex-Layout hinzufügen",+ "Ajouter à la mise en page flexible",+ "Añadir a diseño flexible",+ "フレックスレイアウトに追加",+ "添加到弹性布局",+ ],+ ),+ (+ "Convert to Flex Layout",+ [+ "In Flex-Layout umwandeln",+ "Convertir en mise en page flexible",+ "Convertir en diseño flexible",+ "フレックスレイアウトに変換",+ "转换为弹性布局",+ ],+ ),+ (+ "Remove Flex Layout",+ ["Flex-Layout entfernen", "Supprimer la mise en page flexible", "Quitar diseño flexible", "フレックスレイアウトを削除", "移除弹性布局"],+ ),+ (+ "Show Flex Controls",+ [+ "Flex-Steuerelemente einblenden",+ "Afficher les commandes flexibles",+ "Mostrar controles flexibles",+ "フレックスコントロールを表示",+ "显示弹性控件",+ ],+ ),+ (+ "Flex Layout Options",+ ["Flex-Layout-Optionen", "Options de mise en page flexible", "Opciones de diseño flexible", "フレックスレイアウトオプション", "弹性布局选项"],+ ),+ (+ "Reorder in Flex Layout",+ [+ "Im Flex-Layout umordnen",+ "Réorganiser dans la mise en page flexible",+ "Reordenar en diseño flexible",+ "フレックスレイアウト内で並べ替え",+ "在弹性布局中重新排序",+ ],+ ),+ ("Flex Start", ["Flex-Anfang", "Début flexible", "Inicio flexible", "フレックス開始", "弹性起点"]),+ ("Flex End", ["Flex-Ende", "Fin flexible", "Fin flexible", "フレックス終了", "弹性终点"]),+ ("Space Between", ["Abstand dazwischen", "Espace entre", "Espacio entre", "間隔を均等", "两端对齐"]),+ ("Space Around", ["Abstand ringsum", "Espace autour", "Espacio alrededor", "周囲に間隔", "周围间距"]),+ ("Space Evenly", ["Gleichmäßig verteilen", "Espace uniforme", "Espacio uniforme", "均等に配置", "均匀分布"]),+ ("Row", ["Zeile", "Ligne", "Fila", "行", "行"]),+ ("Reverse Row", ["Zeile umgekehrt", "Ligne inversée", "Fila invertida", "行(逆方向)", "反向行"]),+ ("Reverse Column", ["Spalte umgekehrt", "Colonne inversée", "Columna invertida", "列(逆方向)", "反向列"]),+ ("Wrap Content", ["Inhalt umbrechen", "Renvoyer le contenu à la ligne", "Ajustar contenido", "コンテンツを折り返す", "内容换行"]),+ ("Spacing", ["Abstände", "Espacement", "Espaciado", "間隔", "间距"]),+ ("Horizontal Spacing", ["Horizontaler Abstand", "Espacement horizontal", "Espaciado horizontal", "水平方向の間隔", "水平间距"]),+ ("Vertical Spacing", ["Vertikaler Abstand", "Espacement vertical", "Espaciado vertical", "垂直方向の間隔", "垂直间距"]),+ ("Constrain proportions", ["Proportionen beibehalten", "Conserver les proportions", "Restringir proporciones", "縦横比を固定", "约束比例"]),+ ("Auto", ["Automatisch", "Automatique", "Automático", "自動", "自动"]),+ ("W:", ["B:", "L :", "An.:", "幅:", "宽:"]),+ ("H:", ["H:", "H :", "Al.:", "高さ:", "高:"]),+ ("Number:", ["Anzahl:", "Nombre :", "Número:", "数:", "数量:"]),+ ("Gutter:", ["Steg:", "Gouttière :", "Medianil:", "間隔:", "栏间距:"]),+ ("Fit Guides to:", ["Hilfslinien einpassen in:", "Ajuster les repères à :", "Ajustar guías a:", "ガイドの適用先:", "参考线适合:"]),+ ("Top:", ["Oben:", "Haut :", "Superior:", "天:", "上:"]),+ ("Bottom:", ["Unten:", "Bas :", "Inferior:", "地:", "下:"]),+ ("Inside:", ["Innen:", "Intérieur :", "Interior:", "ノド:", "内:"]),+ ("Outside:", ["Außen:", "Extérieur :", "Exterior:", "小口:", "外:"]),+ ("Left:", ["Links:", "Gauche :", "Izquierda:", "左:", "左:"]),+ ("Right:", ["Rechts:", "Droite :", "Derecha:", "右:", "右:"]),+ ("Paths:", ["Pfade:", "Tracés :", "Trazados:", "パス:", "路径:"]),+ ("Pathfinder:", ["Pathfinder:", "Pathfinder :", "Buscatrazos:", "パスファインダー:", "路径查找器:"]),+ ("Convert Shape:", ["Form konvertieren:", "Convertir la forme :", "Convertir forma:", "シェイプを変換:", "转换形状:"]),+ ("Convert Point:", ["Punkt konvertieren:", "Convertir le point :", "Convertir punto:", "ポイントを変換:", "转换点:"]),+ ("Join Path", ["Pfad zusammenfügen", "Joindre le tracé", "Unir trazado", "パスを連結", "连接路径"]),+ ("Open Path", ["Pfad öffnen", "Ouvrir le tracé", "Abrir trazado", "パスをオープン", "开放路径"]),+ ("Plain", ["Einfach", "Simple", "Normal", "プレーン", "普通"]),+ ("Symmetrical", ["Symmetrisch", "Symétrique", "Simétrico", "対称", "对称"]),+ (+ "The stroke isn't a gradient.",+ [+ "Die Kontur ist kein Verlauf.",+ "Le contour n’est pas un dégradé.",+ "El trazo no es un degradado.",+ "線はグラデーションではありません。",+ "描边不是渐变。",+ ],+ ),+ ("Baseline Options", ["Grundlinienoptionen", "Options de ligne de base", "Opciones de línea de base", "ベースラインオプション", "基线选项"]),+ ("Fixed Number", ["Feste Anzahl", "Nombre fixe", "Número fijo", "固定数", "固定数字"]),+ ("Fixed Width", ["Feste Breite", "Largeur fixe", "Anchura fija", "固定幅", "固定宽度"]),- ("Gutter:", ["Spaltenabstand:", "Gouttière :", "Medianil:", "間隔:", "栏间距:"]),+ ("Inset Spacing", ["Versatzabstand", "Marge intérieure", "Espaciado de margen interior", "フレーム内マージン", "内边距"]),+ ("Vertical Justification", ["Vertikale Ausrichtung", "Justification verticale", "Justificación vertical", "垂直比率", "垂直对齐"]),+ ("Align:", ["Ausrichten:", "Alignement :", "Alinear:", "整列:", "对齐:"]),+ ("Ignore Text Wrap", ["Textumfluss ignorieren", "Ignorer l’habillage", "Ignorar ceñir texto", "テキストの回り込みを無視", "忽略文本绕排"]),+ ("Technique:", ["Technik:", "Technique :", "Técnica:", "テクニック:", "方法:"]),+ ("Softer", ["Weicher", "Plus flou", "Más suave", "さらにソフトに", "柔和"]),+ ("Precise", ["Präzise", "Précis", "Precisa", "精細", "精确"]),+ ("Corners:", ["Ecken:", "Angles :", "Esquinas:", "角:", "角点:"]),+ ("Sharp", ["Spitz", "Vifs", "Nítidas", "シャープ", "锐利"]),+ ("Diffused", ["Weich", "Diffus", "Difusas", "拡散", "扩散"]),("Reverse Path", ["Pfadrichtung umkehren", "Inverser le tracé", "Invertir trazado", "パスの方向反転", "反转路径"]),("Set Anchor", ["Ankerpunkt festlegen", "Définir le point d’ancrage", "Definir punto de ancla", "アンカーポイントを設定", "设置锚点"]),+ ("Effects…", ["Effekte…", "Effets…", "Efectos…", "効果…", "效果…"]),+ ("Settings for:", ["Einstellungen für:", "Paramètres pour :", "Ajustes para:", "設定対象:", "设置:"]),+ ("Transparency", ["Transparenz", "Transparence", "Transparencia", "透明", "透明度"]),+ ("Transparency…", ["Transparenz…", "Transparence…", "Transparencia…", "透明…", "透明度…"]),+ ("Basic Blending", ["Grundlegendes Füllen", "Fusion de base", "Fusión básica", "基本的な描画モード", "基本混合"]),+ ("Opacity:", ["Deckkraft:", "Opacité :", "Opacidad:", "不透明度:", "不透明度:"]),+ ("Blending", ["Füllmethode", "Fusion", "Fusión", "描画モード", "混合"]),+ ("Distance:", ["Abstand:", "Distance :", "Distancia:", "距離:", "距离:"]),+ ("X Offset:", ["X-Versatz:", "Décalage X :", "Desplazamiento X:", "X オフセット:", "X 位移:"]),+ ("Y Offset:", ["Y-Versatz:", "Décalage Y :", "Desplazamiento Y:", "Y オフセット:", "Y 位移:"]),+ ("Spread:", ["Größe ändern:", "Étendue :", "Extensión:", "スプレッド:", "扩展:"]),+ ("Choke:", ["Unterfüllen:", "Contraction :", "Contracción:", "チョーク:", "收缩:"]),+ ("Source:", ["Quelle:", "Source :", "Origen:", "ソース:", "源:"]),+ ("Edge", ["Kante", "Contour", "Borde", "エッジ", "边缘"]),+ ("Depth:", ["Tiefe:", "Profondeur :", "Profundidad:", "深さ:", "深度:"]),+ ("Highlight:", ["Lichter:", "Lumière :", "Iluminación:", "ハイライト:", "高光:"]),+ ("Shadow:", ["Tiefen:", "Ombre :", "Sombra:", "シャドウ:", "阴影:"]),+ ("Feather Width:", ["Breite der weichen Kante:", "Largeur du contour progressif :", "Anchura de desvanecimiento:", "ぼかしの幅:", "羽化宽度:"]),+ ("Feather Widths", ["Breiten der weichen Kante", "Largeurs du contour progressif", "Anchuras de desvanecimiento", "ぼかしの幅", "羽化宽度"]),+ ("Gradient Stops", ["Verlaufsregler", "Arrêts de dégradé", "Paradas de degradado", "グラデーション分岐点", "渐变色标"]),+ ("Start Opacity:", ["Anfangsdeckkraft:", "Opacité de début :", "Opacidad inicial:", "開始の不透明度:", "起始不透明度:"]),+ ("End Opacity:", ["Enddeckkraft:", "Opacité de fin :", "Opacidad final:", "終了の不透明度:", "结束不透明度:"]),+ ("(no effects)", ["(keine Effekte)", "(aucun effet)", "(sin efectos)", "(効果なし)", "(无效果)"]),+ ("OBJECT", ["OBJEKT", "OBJET", "OBJETO", "オブジェクト", "对象"]),+ (+ "Add an object effect to the selected target",+ [+ "Dem ausgewählten Ziel einen Objekteffekt hinzufügen",+ "Ajouter un effet d’objet à la cible sélectionnée",+ "Añadir un efecto de objeto al destino seleccionado",+ "選択した対象にオブジェクト効果を追加",+ "为所选目标添加对象效果",+ ],+ ),("Clear", ["Löschen", "Effacer", "Borrar", "消去", "清除"]),("Duplicate", ["Duplizieren", "Dupliquer", "Duplicar", "複製", "重复"]),("Select All", ["Alles auswählen", "Tout sélectionner", "Seleccionar todo", "すべてを選択", "全选"]),@@@ -176,242 -207,6 +290,241 @@@("Ruby…", ["Ruby …", "Ruby…", "Ruby…", "ルビ…", "旁注…"]),("Kenten", ["Kenten", "Kenten", "Kenten", "圏点", "圈点"]),("Warichu", ["Warichu", "Warichu", "Warichu", "割り注", "割注"]),+ // Style Options: CJK sections.+ ("Tate-chu-yoko Settings", ["Tate-Chu-Yoko-Einstellungen", "Paramètres Tate-Chu-Yoko", "Ajustes de Tate-Chu-Yoko", "縦中横設定", "纵中横设置"]),+ ("Kenten Settings", ["Kenten-Einstellungen", "Paramètres Kenten", "Ajustes de Kenten", "圏点設定", "圈点设置"]),+ (+ "Japanese Composition Settings",+ ["Japanischer Satz", "Paramètres de composition japonaise", "Ajustes de composición japonesa", "日本語文字組版", "日文排版设置"],+ ),+ ("Grid Settings", ["Rastereinstellungen", "Paramètres de grille", "Ajustes de cuadrícula", "グリッド設定", "网格设置"]),+ ("Warichu Settings", ["Warichu-Einstellungen", "Paramètres Warichu", "Ajustes de Warichu", "割注設定", "割注设置"]),+ (+ "Auto Tate-chu-yoko Settings",+ [+ "Automatische Tate-Chu-Yoko-Einstellungen",+ "Paramètres Tate-Chu-Yoko automatiques",+ "Ajustes de Tate-Chu-Yoko automático",+ "自動縦中横設定",+ "自动纵中横设置",+ ],+ ),+ (+ "Ruby Placement and Spacing",+ ["Ruby-Position und -Abstand", "Position et espacement ruby", "Posición y espaciado de ruby", "ルビの位置と間隔", "注音位置和间距"],+ ),+ (+ "Ruby Font and Size",+ ["Ruby-Schrift und -Größe", "Police et taille ruby", "Fuente y tamaño de ruby", "ルビのフォントとサイズ", "注音字体和大小"],+ ),+ (+ "Adjustment When Ruby Is Longer Than Parent",+ [+ "Anpassung bei Ruby länger als Grundtext",+ "Ajustement si le ruby dépasse le texte parent",+ "Ajuste cuando el ruby es más largo que la base",+ "ルビが親文字より長い時の調整",+ "注音长于基础文字时的调整",+ ],+ ),+ ("Ruby Color", ["Ruby-Farbe", "Couleur ruby", "Color de ruby", "ルビカラー", "注音颜色"]),+ ("Kenten Color", ["Kenten-Farbe", "Couleur kenten", "Color de kenten", "圏点カラー", "圈点颜色"]),+ ("Shatai", ["Shatai", "Shatai", "Shatai", "斜体", "斜体"]),+ ("Tate-chu-yoko Digits:", ["Tate-Chu-Yoko-Ziffern:", "Chiffres Tate-Chu-Yoko:", "Dígitos Tate-Chu-Yoko:", "組数字(桁まで):", "纵中横位数:"]),+ (+ "Include Roman Characters",+ ["Lateinische Zeichen einbeziehen", "Inclure les caractères latins", "Incluir caracteres latinos", "欧文も含める", "包括罗马字符"],+ ),+ ("Ruby Type:", ["Ruby-Art:", "Type de ruby:", "Tipo de ruby:", "種類:", "注音类型:"]),+ ("Per-Character Ruby", ["Einzelzeichen-Ruby", "Ruby par caractère", "Ruby por carácter", "モノルビ", "单字注音"]),+ ("Group Ruby", ["Gruppen-Ruby", "Ruby de groupe", "Ruby de grupo", "グループルビ", "组注音"]),+ ("Left/Top", ["Links/oben", "Gauche/haut", "Izquierda/arriba", "肩付き", "左/上"]),+ ("Centered", ["Zentriert", "Centré", "Centrado", "中付き", "居中"]),+ ("Right/Bottom", ["Rechts/unten", "Droite/bas", "Derecha/abajo", "右/下揃え", "右/下"]),+ ("Full Justify", ["Blocksatz", "Justifié", "Justificado", "両端揃え", "两端对齐"]),+ ("1-2-1 (JIS) Rule", ["1-2-1-Regel (JIS)", "Règle 1-2-1 (JIS)", "Regla 1-2-1 (JIS)", "1-2-1(JIS)ルール", "1-2-1 (JIS) 规则"]),+ ("Equal Aki", ["Gleicher Abstand", "Espacement égal", "Espaciado igual", "均等アキ", "均等间距"]),+ (+ "1 Ruby Character Aki",+ ["1 Ruby-Zeichen Abstand", "Espace de 1 caractère ruby", "Espacio de 1 carácter ruby", "1ルビ文字アキ", "1注音字符间距"],+ ),+ ("Above/Right", ["Oben/rechts", "Au-dessus/à droite", "Arriba/derecha", "上/右", "上/右"]),+ ("Below/Left", ["Unten/links", "En dessous/à gauche", "Abajo/izquierda", "下/左", "下/左"]),+ (+ "Offset from Parent",+ [+ "Versatz zum Grundtext",+ "Décalage par rapport au texte parent",+ "Desplazamiento respecto a la base",+ "親文字からのオフセット",+ "与基础文字的偏移",+ ],+ ),+ ("Across the Line:", ["Quer zur Zeile:", "Perpendiculaire à la ligne:", "Perpendicular a la línea:", "横組み上下/縦組み左右:", "垂直于行:"]),+ ("Along the Line:", ["Entlang der Zeile:", "Le long de la ligne:", "A lo largo de la línea:", "横組み左右/縦組み上下:", "沿行方向:"]),+ ("Parent's Font", ["Schrift des Grundtexts", "Police du texte parent", "Fuente de la base", "親文字と同じ", "基础文字的字体"]),+ (+ "Use OpenType Pro Ruby Glyphs",+ [+ "OpenType-Pro-Ruby-Glyphen verwenden",+ "Utiliser les glyphes ruby OpenType Pro",+ "Usar glifos ruby de OpenType Pro",+ "OpenType Pro のルビ字形を使用",+ "使用 OpenType Pro 注音字形",+ ],+ ),+ ("Fit to Width", ["An Breite anpassen", "Ajuster à la largeur", "Ajustar al ancho", "幅に合わせる", "适合宽度"]),+ ("Ruby Overhang:", ["Ruby-Überhang:", "Débordement ruby:", "Desbordamiento de ruby:", "文字かけ処理:", "注音悬挂:"]),+ ("1 Ruby Character", ["1 Ruby-Zeichen", "1 caractère ruby", "1 carácter ruby", "ルビ1文字分", "1个注音字符"]),+ ("1/2 Ruby Character", ["1/2 Ruby-Zeichen", "1/2 caractère ruby", "1/2 carácter ruby", "ルビ半文字分", "1/2个注音字符"]),+ ("1 Parent Character", ["1 Grundzeichen", "1 caractère parent", "1 carácter base", "親1文字分", "1个基础字符"]),+ ("1/2 Parent Character", ["1/2 Grundzeichen", "1/2 caractère parent", "1/2 carácter base", "親半文字分", "1/2个基础字符"]),+ ("Unlimited", ["Unbegrenzt", "Illimité", "Ilimitado", "無制限", "无限制"]),+ (+ "Parent Character Spacing:",+ ["Abstand im Grundtext:", "Espacement du texte parent:", "Espaciado de la base:", "親文字間の調整:", "基础文字间距调整:"],+ ),+ ("No Adjustment", ["Keine Anpassung", "Aucun ajustement", "Sin ajuste", "調整しない", "不调整"]),+ ("Both Sides", ["Beide Seiten", "Des deux côtés", "Ambos lados", "両サイド", "两侧"]),+ ("1-2-1 Aki", ["1-2-1-Abstand", "Espacement 1-2-1", "Espaciado 1-2-1", "1-2-1アキ", "1-2-1 间距"]),+ (+ "Shrink Ruby Width Automatically",+ [+ "Ruby-Breite automatisch verringern",+ "Réduire automatiquement la largeur ruby",+ "Reducir automáticamente el ancho de ruby",+ "ルビの文字幅を自動的に詰める",+ "自动压缩注音宽度",+ ],+ ),+ ("Minimum Scale:", ["Minimale Skalierung:", "Échelle minimale:", "Escala mínima:", "最小比率:", "最小比例:"]),+ (+ "Auto Align at Line Start/End",+ [+ "Am Zeilenanfang/-ende automatisch ausrichten",+ "Alignement auto en début/fin de ligne",+ "Alinear automáticamente al inicio/fin de línea",+ "自動行頭/行末揃え",+ "行首/行尾自动对齐",+ ],+ ),+ ("Text Color", ["Textfarbe", "Couleur du texte", "Color del texto", "[自動]", "文字颜色"]),+ (+ "Distance from Parent:",+ ["Abstand zum Grundtext:", "Distance au texte parent:", "Distancia a la base:", "親文字からの間隔:", "与基础文字的距离:"],+ ),+ ("Fisheye", ["Fischauge", "Œil de poisson", "Ojo de pez", "蛇の目", "蛇目"]),+ ("Magnification:", ["Verkleinerung:", "Réduction:", "Reducción:", "縮小率:", "缩小率:"]),+ ("Adjust Rotation", ["Drehung anpassen", "Ajuster la rotation", "Ajustar rotación", "ライン揃え", "调整旋转"]),+ ("Adjust Tsume", ["Tsume anpassen", "Ajuster le tsume", "Ajustar tsume", "ツメの調整", "调整字距压缩"]),+ (+ "Rotate Roman Characters in Vertical Text",+ [+ "Lateinische Zeichen in vertikalem Text drehen",+ "Faire pivoter les caractères latins en texte vertical",+ "Girar caracteres latinos en texto vertical",+ "縦組み中の欧文回転",+ "直排中旋转罗马字符",+ ],+ ),+ (+ "Roman Word Break",+ ["Lateinische Wörter beliebig trennen", "Coupure libre des mots latins", "Corte libre de palabras latinas", "欧文泣き別れ", "西文单词断开"],+ ),+ ("ICF Top", ["ICF oben", "Haut ICF", "Parte superior ICF", "平均字面の上", "平均字面上"]),+ ("ICF Bottom", ["ICF unten", "Bas ICF", "Parte inferior ICF", "平均字面の下", "平均字面下"]),+ ("Gyoudori:", ["Gyoudori:", "Gyoudori:", "Gyoudori:", "行取り:", "行取:"]),+ (+ "Use Paragraph Gyoudori",+ ["Absatz-Gyoudori verwenden", "Utiliser le gyoudori de paragraphe", "Usar gyoudori de párrafo", "段落行取りを使用", "使用段落行取"],+ ),+ ("Up/Down Position:", ["Position oben/unten:", "Position haut/bas:", "Posición arriba/abajo:", "上下位置:", "上下位置:"]),+ ("Left/Right Position:", ["Position links/rechts:", "Position gauche/droite:", "Posición izquierda/derecha:", "左右位置:", "左右位置:"]),+ ("Kenten Type:", ["Kenten-Art:", "Type de kenten:", "Tipo de kenten:", "圏点種類:", "圈点类型:"]),+ ("Sesame Dot", ["Sesampunkt", "Point sésame", "Punto de sésamo", "ゴマ", "芝麻点"]),+ ("White Sesame Dot", ["Weißer Sesampunkt", "Point sésame blanc", "Punto de sésamo blanco", "白ゴマ", "空心芝麻点"]),+ ("Bullseye", ["Zielscheibe", "Cible", "Diana", "蛇の目", "靶心"]),+ ("Black Circle", ["Schwarzer Kreis", "Cercle noir", "Círculo negro", "黒丸", "实心圆"]),+ ("Small Black Circle", ["Kleiner schwarzer Kreis", "Petit cercle noir", "Círculo negro pequeño", "小さい黒丸", "小实心圆"]),+ ("Double Circle", ["Doppelkreis", "Double cercle", "Círculo doble", "二重丸", "双圆"]),+ ("Black Triangle", ["Schwarzes Dreieck", "Triangle noir", "Triángulo negro", "黒三角", "实心三角"]),+ ("White Triangle", ["Weißes Dreieck", "Triangle blanc", "Triángulo blanco", "白三角", "空心三角"]),+ ("White Circle", ["Weißer Kreis", "Cercle blanc", "Círculo blanco", "白丸", "空心圆"]),+ ("Small White Circle", ["Kleiner weißer Kreis", "Petit cercle blanc", "Círculo blanco pequeño", "小さい白丸", "小空心圆"]),+ ("Character:", ["Zeichen:", "Caractère:", "Carácter:", "文字:", "字符:"]),+ ("Kinsoku Set:", ["Kinsoku-Satz:", "Jeu kinsoku:", "Conjunto kinsoku:", "禁則処理セット:", "避头尾集:"]),+ ("Default Rules", ["Standardregeln", "Règles par défaut", "Reglas predeterminadas", "既定の規則", "默认规则"]),+ ("Hard Kinsoku", ["Hartes Kinsoku", "Kinsoku strict", "Kinsoku estricto", "強い禁則", "严格避头尾"]),+ ("Soft Kinsoku", ["Weiches Kinsoku", "Kinsoku souple", "Kinsoku flexible", "弱い禁則", "宽松避头尾"]),+ (+ "Simplified Chinese Kinsoku",+ ["Kinsoku für vereinfachtes Chinesisch", "Kinsoku chinois simplifié", "Kinsoku de chino simplificado", "簡体中国語禁則", "简体中文避头尾"],+ ),+ (+ "Traditional Chinese Kinsoku",+ ["Kinsoku für traditionelles Chinesisch", "Kinsoku chinois traditionnel", "Kinsoku de chino tradicional", "繁体中国語禁則", "繁体中文避头尾"],+ ),+ ("Korean Kinsoku", ["Koreanisches Kinsoku", "Kinsoku coréen", "Kinsoku coreano", "韓国語禁則", "韩文避头尾"]),+ ("Kinsoku Type:", ["Kinsoku-Methode:", "Type de kinsoku:", "Tipo de kinsoku:", "禁則調整方式:", "避头尾调整方式:"]),+ ("Push In First", ["Zuerst einziehen", "Rentrer d'abord", "Primero hacia dentro", "追い込み優先", "先推入"]),+ ("Push Out First", ["Zuerst hinausschieben", "Repousser d'abord", "Primero hacia fuera", "追い出し優先", "先推出"]),+ ("Push Out Only", ["Nur hinausschieben", "Repousser uniquement", "Solo hacia fuera", "追い出しのみ", "仅推出"]),+ (+ "Prioritize Adjustment Amount",+ ["Anpassungsbetrag bevorzugen", "Priorité à la valeur d'ajustement", "Priorizar la cantidad de ajuste", "調整量を優先", "优先调整量"],+ ),+ ("Hanging Type:", ["Hängende Interpunktion:", "Ponctuation suspendue:", "Puntuación colgante:", "ぶら下がり方法:", "悬挂方式:"]),+ ("Force", ["Erzwingen", "Forcer", "Forzar", "強制", "强制"]),+ ("Bunri-Kinshi", ["Bunri-Kinshi", "Bunri-Kinshi", "Bunri-Kinshi", "分離禁止処理", "分离禁止"]),+ ("Mojikumi Set:", ["Mojikumi-Satz:", "Jeu mojikumi:", "Conjunto mojikumi:", "文字組み:", "标点挤压集:"]),+ ("Leading Model:", ["Zeilenabstandsmodell:", "Modèle d'interlignage:", "Modelo de interlineado:", "行送りの基準位置:", "行距基准位置:"]),+ (+ "Em Box Top/Right",+ ["Geviert oben/rechts", "Haut/droite du cadratin", "Parte superior/derecha del cuadratín", "仮想ボディの上/右", "全角字框上/右"],+ ),+ ("Em Box Center", ["Geviert Mitte", "Centre du cadratin", "Centro del cuadratín", "仮想ボディの中央", "全角字框居中"]),+ (+ "Em Box Bottom/Left",+ ["Geviert unten/links", "Bas/gauche du cadratin", "Parte inferior/izquierda del cuadratín", "仮想ボディの下/左", "全角字框下/左"],+ ),+ (+ "Em Box Center (Down)",+ ["Geviert Mitte (unten)", "Centre du cadratin (bas)", "Centro del cuadratín (abajo)", "仮想ボディの中央(下)", "全角字框居中(下)"],+ ),+ ("Roman Baseline", ["Lateinische Grundlinie", "Ligne de base romaine", "Línea de base romana", "欧文ベースライン", "罗马字基线"]),+ ("Rensuuji", ["Rensuuji", "Rensuuji", "Rensuuji", "連数字処理", "连数字处理"]),+ (+ "Absorb Ideographic Space at Line End",+ [+ "Ideografisches Leerzeichen am Zeilenende absorbieren",+ "Absorber l'espace idéographique en fin de ligne",+ "Absorber el espacio ideográfico al final de línea",+ "全角スペースを行末吸収",+ "行尾吸收全角空格",+ ],+ ),+ ("Grid Alignment:", ["Am Raster ausrichten:", "Alignement sur la grille:", "Alineación con cuadrícula:", "グリッド揃え:", "网格对齐:"]),+ (+ "Align Only First Line to Grid",+ [+ "Nur erste Zeile am Raster ausrichten",+ "Aligner uniquement la première ligne sur la grille",+ "Alinear solo la primera línea con la cuadrícula",+ "1 行目のみグリッドに揃える",+ "仅首行对齐网格",+ ],+ ),+ ("Warichu Size:", ["Warichu-Größe:", "Taille warichu:", "Tamaño de warichu:", "割注サイズ:", "割注大小:"]),+ ("Line Spacing:", ["Zeilenabstand:", "Interligne:", "Interlineado:", "行の間隔:", "行间距:"]),- ("Auto", ["Auto", "Auto", "Automático", "自動", "自动"]),+ ("Line Break Options", ["Umbruchoptionen", "Options de saut de ligne", "Opciones de salto de línea", "改行オプション", "换行选项"]),+ (+ "Characters Before Break:",+ ["Zeichen vor dem Umbruch:", "Caractères avant le saut:", "Caracteres antes del salto:", "1 行目の最小文字数:", "换行前最少字符数:"],+ ),+ (+ "Characters After Break:",+ ["Zeichen nach dem Umbruch:", "Caractères après le saut:", "Caracteres después del salto:", "最終行の最小文字数:", "换行后最少字符数:"],+ ),("Font", ["Schriftart", "Police", "Fuente", "フォント", "字体"]),("Size", ["Schriftgrad", "Corps", "Tamaño", "サイズ", "大小"]),("Character", ["Zeichen", "Caractère", "Carácter", "文字", "字符"]),@@@ -3764,462 -3126,12 +3877,455 @@@// Paragraph Rules.("Paragraph Rules…", ["Absatzlinien …", "Filets de paragraphe…", "Filetes de párrafo…", "段落境界線…", "段落线…"]),("Paragraph Rules", ["Absatzlinien", "Filets de paragraphe", "Filetes de párrafo", "段落境界線", "段落线"]),- ("Rule Below", ["Linie unterhalb", "Filet après", "Filete después", "後境界線", "下方横线"]),- ("Tint:", ["Farbton:", "Teinte:", "Matiz:", "濃淡:", "色调:"]),+ ("Justification…", ["Blocksatzeinstellungen …", "Justification…", "Justificación…", "両端揃え…", "两端对齐…"]),+ ("Rule Below", ["Linie unterhalb", "Filet au-dessous", "Filete después", "後境界線", "下方横线"]),+ ("Tint:", ["Farbton:", "Teinte :", "Matiz:", "濃淡:", "色调:"]),+ ("Apply To:", ["Anwenden auf:", "Appliquer à :", "Aplicar a:", "適用先:", "应用于:"]),+ ("Frame", ["Rahmen", "Bloc", "Marco", "フレーム", "框架"]),("Slug", ["Infobereich", "Ligne-bloc", "Indicaciones", "印刷可能領域", "辅助信息区"]),("Presentation", ["Präsentation", "Présentation", "Presentación", "プレゼンテーション", "演示文稿"]),- ("Extras", ["Extras", "Options supplémentaires", "Extras", "エクストラ", "附加"]),+ ("Extras", ["Extras", "Extras", "Extras", "エクストラ", "附加"]),("Column", ["Spalte", "Colonne", "Columna", "段", "栏"]),+ // File › New › Document+ ("Recent", ["Zuletzt verwendet", "Récents", "Recientes", "最近使用", "最近"]),+ ("Saved", ["Gespeichert", "Enregistrés", "Guardados", "保存済み", "已保存"]),+ ("[Default]", ["[Standard]", "[Par défaut]", "[Predeterminado]", "[初期設定]", "[默认]"]),+ ("Your Recent Items", ["Zuletzt verwendete Elemente", "Éléments récents", "Elementos recientes", "最近使用した項目", "最近使用的项目"]),+ (+ "Saved Presets",+ ["Gespeicherte Vorgaben", "Paramètres prédéfinis enregistrés", "Ajustes preestablecidos guardados", "保存済みプリセット", "已保存的预设"],+ ),+ (+ "Blank Document Presets",+ [+ "Vorgaben für leere Dokumente",+ "Paramètres prédéfinis de document vierge",+ "Ajustes preestablecidos de documento en blanco",+ "空のドキュメントプリセット",+ "空白文档预设",+ ],+ ),+ (+ "No saved presets yet. Set the details, then click Save Document Preset.",+ [+ "Noch keine gespeicherten Vorgaben. Legen Sie die Details fest und klicken Sie auf Dokumentvorgabe speichern.",+ "Aucun paramètre prédéfini enregistré. Définissez les détails, puis cliquez sur Enregistrer le paramètre prédéfini de document.",+ "Aún no hay ajustes preestablecidos guardados. Defina los detalles y haga clic en Guardar ajuste preestablecido de documento.",+ "保存済みのプリセットはありません。詳細を設定してから「ドキュメントプリセットを保存」をクリックしてください。",+ "尚无已保存的预设。请设置详细信息,然后单击“存储文档预设”。",+ ],+ ),+ ("Delete Preset", ["Vorgabe löschen", "Supprimer le paramètre prédéfini", "Eliminar ajuste preestablecido", "プリセットを削除", "删除预设"]),+ (+ "Preset Details",+ ["Vorgabedetails", "Détails du paramètre prédéfini", "Detalles del ajuste preestablecido", "プリセットの詳細", "预设详细信息"],+ ),+ ("Document Name", ["Dokumentname", "Nom du document", "Nombre del documento", "ドキュメント名", "文档名称"]),+ (+ "Save Document Preset",+ [+ "Dokumentvorgabe speichern",+ "Enregistrer le paramètre prédéfini de document",+ "Guardar ajuste preestablecido de documento",+ "ドキュメントプリセットを保存",+ "存储文档预设",+ ],+ ),+ (+ "Save Document Preset As:",+ [+ "Dokumentvorgabe speichern unter:",+ "Enregistrer le paramètre prédéfini de document sous :",+ "Guardar ajuste preestablecido de documento como:",+ "ドキュメントプリセットの保存名:",+ "存储文档预设为:",+ ],+ ),+ ("Preset Name", ["Vorgabename", "Nom du paramètre prédéfini", "Nombre del ajuste preestablecido", "プリセット名", "预设名称"]),+ ("Save Preset", ["Vorgabe speichern", "Enregistrer le paramètre prédéfini", "Guardar ajuste preestablecido", "プリセットを保存", "存储预设"]),+ ("Start #", ["Startseitennr.", "N° de début", "N.º inicial", "開始ページ番号", "起始页码"]),+ ("Column Gutter", ["Spaltenabstand", "Gouttière", "Medianil", "列間隔", "栏间距"]),+ // Layout › Numbering & Section Options+ ("Start Section", ["Abschnittsanfang", "Début de section", "Iniciar sección", "セクション開始", "开始新章节"]),+ (+ "Automatic Page Numbering",+ [+ "Automatische Seitennummerierung",+ "Numérotation automatique des pages",+ "Numeración de páginas automática",+ "自動ページ番号",+ "自动编排页码",+ ],+ ),+ (+ "Start Page Numbering at:",+ ["Seitennummerierung beginnen bei:", "Commencer la numérotation à :", "Iniciar numeración de páginas en:", "開始ページ番号:", "起始页码:"],+ ),+ ("Section Prefix:", ["Abschnittspräfix:", "Préfixe de section :", "Prefijo de sección:", "セクションプレフィックス:", "章节前缀:"]),+ ("Section Marker:", ["Abschnittsmarke:", "Marqueur de section :", "Marcador de sección:", "セクションマーカー:", "章节标志符:"]),+ (+ "Include Prefix when Numbering Pages",+ [+ "Präfix in Seitennummerierung einschließen",+ "Inclure le préfixe lors de la numérotation des pages",+ "Incluir prefijo al numerar páginas",+ "ページ番号にプレフィックスを含める",+ "编排页码时包含前缀",+ ],+ ),+ (+ "Document Chapter Numbering",+ [+ "Kapitelnummerierung des Dokuments",+ "Numérotation des chapitres du document",+ "Numeración de capítulos del documento",+ "ドキュメントの章番号",+ "文档章节编号",+ ],+ ),+ (+ "Automatic Chapter Numbering",+ [+ "Automatische Kapitelnummerierung",+ "Numérotation automatique des chapitres",+ "Numeración de capítulos automática",+ "自動章番号",+ "自动为章节编号",+ ],+ ),+ (+ "Start Chapter Numbering at:",+ [+ "Kapitelnummerierung beginnen bei:",+ "Commencer la numérotation des chapitres à :",+ "Iniciar numeración de capítulos en:",+ "開始章番号:",+ "起始章节编号:",+ ],+ ),+ (+ "Same as Previous Document in the Book",+ [+ "Wie vorheriges Dokument im Buch",+ "Identique au document précédent du livre",+ "Igual que el documento anterior del libro",+ "ブック内の前のドキュメントと同じ",+ "与书籍中的上一文档相同",+ ],+ ),+ ("Book Name:", ["Buchname:", "Nom du livre :", "Nombre del libro:", "ブック名:", "书籍名称:"]),+ ("N/A", ["–", "S.O.", "N/D", "なし", "不适用"]),+ // Paragraph Style Options: Paragraph Border, Paragraph Shading, Keep Options, Span Columns, Bullets and Numbering.+ ("Paragraph Border", ["Absatzrahmen", "Contour de paragraphe", "Borde de párrafo", "段落囲み罫", "段落边框"]),+ ("Paragraph Shading", ["Absatzschattierung", "Ombrage de paragraphe", "Sombreado de párrafo", "段落の背景色", "段落底纹"]),+ ("Keep Options", ["Umbruchoptionen", "Options d'enchaînement", "Opciones de separación", "段落分離禁止オプション", "保持选项"]),+ ("Span Columns", ["Spalten überspannen", "Étendre sur les colonnes", "Abarcar columnas", "段抜きと段分割", "跨栏"]),- ("Top:", ["Oben:", "Haut :", "Arriba:", "上:", "上:"]),- ("Left:", ["Links:", "Gauche :", "Izquierda:", "左:", "左:"]),- ("Bottom:", ["Unten:", "Bas :", "Abajo:", "下:", "下:"]),- ("Right:", ["Rechts:", "Droite :", "Derecha:", "右:", "右:"]),+ ("Keep with Next:", ["Nicht trennen von nächsten:", "Lier aux suivantes:", "Conservar con siguientes:", "次の段落と分離禁止:", "与下一段保持:"]),+ ("Keep Lines Together", ["Zeilen nicht trennen", "Lignes solidaires", "Conservar líneas juntas", "行を分離しない", "保持各行同页"]),+ (+ "All Lines in Paragraph",+ ["Alle Zeilen im Absatz", "Toutes les lignes du paragraphe", "Todas las líneas del párrafo", "段落のすべての行", "段落中所有行"],+ ),+ (+ "At Start/End of Paragraph",+ ["Am Anfang/Ende des Absatzes", "Au début/à la fin du paragraphe", "Al inicio/final del párrafo", "段落の始めと終わり", "在段落开头/结尾"],+ ),+ ("End:", ["Ende:", "Fin:", "Final:", "終了位置:", "结束:"]),+ ("Start Paragraph:", ["Absatzbeginn:", "Début de paragraphe:", "Inicio de párrafo:", "段落の開始位置:", "段落开始:"]),+ ("Anywhere", ["Überall", "N'importe où", "En cualquier lugar", "任意の位置", "任意位置"]),+ ("In Next Column", ["In nächster Spalte", "Dans la colonne suivante", "En la siguiente columna", "次の段", "于下一栏"]),+ ("In Next Frame", ["In nächstem Rahmen", "Dans le bloc suivant", "En el siguiente marco", "次のフレーム", "于下一框架"]),+ ("On Next Page", ["Auf nächster Seite", "Sur la page suivante", "En la página siguiente", "次のページ", "于下一页"]),+ (+ "On Next Odd Page",+ ["Auf nächster ungerader Seite", "Sur la page impaire suivante", "En la siguiente página impar", "次の奇数ページ", "于下一奇数页"],+ ),+ (+ "On Next Even Page",+ ["Auf nächster gerader Seite", "Sur la page paire suivante", "En la siguiente página par", "次の偶数ページ", "于下一偶数页"],+ ),+ ("Paragraph Layout:", ["Absatzlayout:", "Disposition du paragraphe:", "Diseño de párrafo:", "段落レイアウト:", "段落版面:"]),+ ("Single Column", ["Eine Spalte", "Colonne simple", "Una columna", "単一段", "单栏"]),+ ("Split Column", ["Spalte unterteilen", "Diviser la colonne", "Dividir columna", "段分割", "拆分栏"]),+ ("Columns:", ["Spalten:", "Colonnes :", "Columnas:", "段:", "栏数:"]),+ ("All", ["Alle", "Toutes", "Todas", "すべて", "全部"]),+ ("Inside Gutter:", ["Innerer Spaltenabstand:", "Gouttière intérieure:", "Medianil interior:", "内側の間隔:", "内栏间距:"]),+ ("Outside Gutter:", ["Äußerer Spaltenabstand:", "Gouttière extérieure:", "Medianil exterior:", "外側の間隔:", "外栏间距:"]),+ ("List Type:", ["Listentyp:", "Type de liste:", "Tipo de lista:", "リストタイプ:", "列表类型:"]),+ ("Bullets", ["Aufzählungszeichen", "Puces", "Viñetas", "箇条書き記号", "项目符号"]),+ ("Numbers", ["Nummerierung", "Numéros", "Números", "自動番号", "编号"]),+ ("Bullet Character:", ["Aufzählungszeichen:", "Caractère de puce:", "Carácter de viñeta:", "箇条書き記号:", "项目符号字符:"]),+ ("Text After:", ["Text danach:", "Texte après:", "Texto después:", "後続テキスト:", "后续文本:"]),+ ("Gap Tint:", ["Lückenfarbton:", "Teinte de l'espace:", "Matiz del hueco:", "すき間の濃淡:", "间隙色调:"]),+ (+ "Corner Size and Shape",+ ["Eckengröße und -form", "Taille et forme des angles", "Tamaño y forma de esquinas", "角のサイズとシェイプ", "角大小和形状"],+ ),+ ("Top Left:", ["Oben links:", "En haut à gauche:", "Superior izquierda:", "左上:", "左上:"]),+ ("Top Right:", ["Oben rechts:", "En haut à droite:", "Superior derecha:", "右上:", "右上:"]),+ ("Bottom Right:", ["Unten rechts:", "En bas à droite:", "Inferior derecha:", "右下:", "右下:"]),+ ("Bottom Left:", ["Unten links:", "En bas à gauche:", "Inferior izquierda:", "左下:", "左下:"]),+ ("Rounded", ["Abgerundet", "Arrondi", "Redondeado", "角丸", "圆角"]),+ ("Inverse Rounded", ["Umgekehrt abgerundet", "Arrondi inversé", "Redondeado inverso", "逆角丸", "反向圆角"]),+ ("Inset", ["Eingezogen", "En retrait", "Hundido", "内側に切り欠き", "内凹"]),+ ("Fancy", ["Verziert", "Fantaisie", "Decorativo", "装飾", "花式"]),+ ("Top Edge:", ["Obere Kante:", "Bord supérieur:", "Borde superior:", "上端:", "上边缘:"]),+ ("Bottom Edge:", ["Untere Kante:", "Bord inférieur:", "Borde inferior:", "下端:", "下边缘:"]),+ ("Em Box Top", ["Geviert oben", "Haut du cadratin", "Parte superior del cuadratín", "仮想ボディの上", "全角框顶部"]),+ ("Descent", ["Unterlänge", "Jambage inférieur", "Descendente", "ディセント", "下伸部"]),+ ("Em Box Bottom", ["Geviert unten", "Bas du cadratin", "Parte inferior del cuadratín", "仮想ボディの下", "全角框底部"]),+ (+ "Display Border if Paragraph Splits Across Frames/Columns",+ [+ "Rahmen anzeigen, wenn der Absatz auf Rahmen/Spalten verteilt ist",+ "Afficher le contour si le paragraphe est réparti sur plusieurs blocs/colonnes",+ "Mostrar borde si el párrafo se divide entre marcos/columnas",+ "段落がフレームや段をまたぐときに囲み罫を表示",+ "段落跨框架/栏拆分时显示边框",+ ],+ ),+ (+ "Merge Consecutive Borders and Shading",+ [+ "Aufeinanderfolgende Rahmen und Schattierungen zusammenführen",+ "Fusionner les contours et trames consécutifs",+ "Combinar bordes y sombreados consecutivos",+ "連続する囲み罫と背景色を結合",+ "合并连续的边框和底纹",+ ],+ ),+ ("Clip to Frame", ["Auf Rahmen beschneiden", "Découper selon le bloc", "Recortar al marco", "フレームでクリップ", "剪切到框架"]),+ (+ "Do not Print or Export",+ ["Nicht drucken oder exportieren", "Ne pas imprimer ni exporter", "No imprimir ni exportar", "印刷・書き出ししない", "不打印或导出"],+ ),+ ("Space Before Span:", ["Abstand vor Überspannung:", "Espace avant l'étendue:", "Espacio antes de abarcar:", "段抜き前のアキ:", "跨栏前间距:"]),+ (+ "Space After Span:",+ ["Abstand nach Überspannung:", "Espace après l'étendue:", "Espacio después de abarcar:", "段抜き後のアキ:", "跨栏后间距:"],+ ),+ ("Space Before Split:", ["Abstand vor Teilung:", "Espace avant la division:", "Espacio antes de dividir:", "段分割前のアキ:", "拆分前间距:"]),+ ("Space After Split:", ["Abstand nach Teilung:", "Espace après la division:", "Espacio después de dividir:", "段分割後のアキ:", "拆分后间距:"]),+ ("Level:", ["Ebene:", "Niveau:", "Nivel:", "レベル:", "级别:"]),+ ("Glyphs…", ["Glyphen…", "Glyphes…", "Glifos…", "字形…", "字形…"]),+ ("(Paragraph Font)", ["(Absatzschrift)", "(Police du paragraphe)", "(Fuente del párrafo)", "(段落のフォント)", "(段落字体)"]),+ (+ "Restart Numbers at This Level After:",+ [+ "Nummerierung auf dieser Ebene neu beginnen nach:",+ "Recommencer la numérotation à ce niveau après:",+ "Reiniciar números en este nivel después de:",+ "このレベルの番号を振り直すきっかけ:",+ "在此级别后重新编号:",+ ],+ ),+ (+ "Any Previous Level",+ ["Einer beliebigen höheren Ebene", "Tout niveau précédent", "Cualquier nivel anterior", "任意の上位レベル", "任何上一级别"],+ ),+ ("Tab Position:", ["Tabulatorposition:", "Position de la tabulation:", "Posición de tabulación:", "タブ位置:", "制表符位置:"]),+ (+ "Paragraph Borders and Shading…",+ [+ "Absatzrahmen und -schattierung…",+ "Contours et trames de paragraphe…",+ "Bordes y sombreado de párrafo…",+ "段落囲み罫と段落背景色…",+ "段落边框和底纹…",+ ],+ ),+ (+ "Paragraph Borders and Shading",+ [+ "Absatzrahmen und -schattierung",+ "Contours et trames de paragraphe",+ "Bordes y sombreado de párrafo",+ "段落囲み罫と段落背景色",+ "段落边框和底纹",+ ],+ ),+ ("Span Columns…", ["Spalten überspannen…", "Étendre sur les colonnes…", "Abarcar columnas…", "段抜きと段分割…", "跨栏…"]),+ (+ "Bullets and Numbering…",+ ["Aufzählungszeichen und Nummerierung…", "Puces et numérotation…", "Viñetas y numeración…", "箇条書き記号と番号付け…", "项目符号和编号…"],+ ),+ ("List:", ["Liste:", "Liste:", "Lista:", "リスト:", "列表:"]),- ("Number:", ["Zahl:", "Numéro:", "Número:", "番号:", "编号:"]),+ ("Mode:", ["Modus:", "Mode:", "Modo:", "モード:", "模式:"]),+ (+ "Continue from Previous Number",+ [+ "Ab vorheriger Zahl fortfahren",+ "Continuer à partir du numéro précédent",+ "Continuar desde el número anterior",+ "前の番号から継続",+ "从上一编号继续",+ ],+ ),+ ("Start At", ["Beginnen bei", "Commencer à", "Empezar en", "開始番号", "起始编号"]),+ // Cell strokes.+ ("Strokes and Fills…", ["Konturen und Flächen …", "Contours et fonds…", "Trazos y rellenos…", "線と塗り…", "描边和填色…"]),+ ("Cell Stroke", ["Zellkontur", "Contour de cellule", "Trazo de celda", "セルの線", "单元格描边"]),+ ("Cell Fill", ["Zellfläche", "Fond de cellule", "Relleno de celda", "セルの塗り", "单元格填色"]),+ ("Cell edges", ["Zellkanten", "Bords de cellule", "Bordes de celda", "セルの境界線", "单元格边缘"]),+ (+ "Click a line to include or exclude it. Double-click selects all outer or all inner lines; triple-click selects or clears all.",+ [+ "Klicken Sie auf eine Linie, um sie ein- oder auszuschließen. Doppelklick wählt alle äußeren oder alle inneren Linien; Dreifachklick wählt alle aus oder hebt die Auswahl auf.",+ "Cliquez sur une ligne pour l'inclure ou l'exclure. Un double-clic sélectionne toutes les lignes extérieures ou intérieures ; un triple-clic sélectionne ou désélectionne tout.",+ "Haga clic en una línea para incluirla o excluirla. Doble clic selecciona todas las líneas exteriores o interiores; triple clic selecciona o borra todas.",+ "線をクリックすると、含めるか除外するかを切り替えます。ダブルクリックで外側または内側の線をすべて選択し、トリプルクリックですべてを選択または解除します。",+ "单击线条可将其包含或排除。双击选择所有外侧或所有内侧线条;三击选择或清除全部。",+ ],+ ),+ ("Swatch Options…", ["Farbfeldoptionen …", "Options de nuance…", "Opciones de muestra…", "スウォッチオプション…", "色板选项…"]),+ ("Swatch Options", ["Farbfeldoptionen", "Options de nuance", "Opciones de muestra", "スウォッチオプション", "色板选项"]),+ (+ "Color Group Options…",+ ["Farbgruppenoptionen …", "Options du groupe de couleurs…", "Opciones de grupo de colores…", "カラーグループオプション…", "颜色组选项…"],+ ),+ ("Layer Options", ["Ebenenoptionen", "Options de calque", "Opciones de capa", "レイヤーオプション", "图层选项"]),+ (+ "Layer Options for \"{name}\"…",+ [+ "Ebenenoptionen für „{name}“ …",+ "Options du calque « {name} »…",+ "Opciones de capa para «{name}»…",+ "「{name}」のレイヤーオプション…",+ "“{name}”的图层选项…",+ ],+ ),+ ("Swatch Name:", ["Farbfeldname:", "Nom de la nuance :", "Nombre de muestra:", "スウォッチ名:", "色板名称:"]),+ (+ "Name with Color Value",+ ["Name mit Farbwert", "Nommer d'après la valeur chromatique", "Nombre con valor de color", "カラー値を名前にする", "以颜色值命名"],+ ),+ ("Color Type:", ["Farbtyp:", "Type de couleur :", "Tipo de color:", "カラータイプ:", "颜色类型:"]),+ ("Process", ["Prozessfarbe", "Quadrichromie", "Cuatricromía", "プロセス", "印刷色"]),+ ("Spot", ["Volltonfarbe", "Ton direct", "Tinta plana", "特色", "专色"]),+ ("Color Mode:", ["Farbmodus:", "Mode colorimétrique :", "Modo de color:", "カラーモード:", "颜色模式:"]),+ ("Base Color:", ["Grundfarbe:", "Couleur de base :", "Color base:", "ベースカラー:", "基准颜色:"]),+ (+ "Edit the gradient's stops in the Gradient panel.",+ [+ "Die Verlaufsregler bearbeiten Sie im Verlaufsbedienfeld.",+ "Modifiez les arrêts du dégradé dans le panneau Dégradé.",+ "Edite las paradas del degradado en el panel Degradado.",+ "グラデーションの分岐点はグラデーションパネルで編集します。",+ "在“渐变”面板中编辑渐变的色标。",+ ],+ ),+ (+ "This swatch can't be edited.",+ [+ "Dieses Farbfeld kann nicht bearbeitet werden.",+ "Cette nuance ne peut pas être modifiée.",+ "Esta muestra no se puede editar.",+ "このスウォッチは編集できません。",+ "此色板无法编辑。",+ ],+ ),+ ("Light Blue", ["Hellblau", "Bleu clair", "Azul claro", "ライトブルー", "浅蓝色"]),+ ("Red", ["Rot", "Rouge", "Rojo", "レッド", "红色"]),+ ("Green", ["Grün", "Vert", "Verde", "グリーン", "绿色"]),+ ("Blue", ["Blau", "Bleu", "Azul", "ブルー", "蓝色"]),+ ("Yellow", ["Gelb", "Jaune", "Amarillo", "イエロー", "黄色"]),+ ("Magenta", ["Magenta", "Magenta", "Magenta", "マゼンタ", "洋红色"]),+ ("Cyan", ["Cyan", "Cyan", "Cian", "シアン", "青色"]),+ ("Black", ["Schwarz", "Noir", "Negro", "ブラック", "黑色"]),+ ("Orange", ["Orange", "Orange", "Naranja", "オレンジ", "橙色"]),+ ("Dark Green", ["Dunkelgrün", "Vert foncé", "Verde oscuro", "ダークグリーン", "深绿色"]),+ ("Teal", ["Blaugrün", "Bleu canard", "Verde azulado", "ティール", "蓝绿色"]),+ ("Tan", ["Hellbraun", "Fauve", "Tostado", "タン", "棕褐色"]),+ ("Brown", ["Braun", "Marron", "Marrón", "ブラウン", "褐色"]),+ ("Violet", ["Violett", "Violet", "Violeta", "バイオレット", "紫罗兰色"]),+ ("Gold", ["Gold", "Or", "Dorado", "ゴールド", "金色"]),+ ("Show Layer", ["Ebene einblenden", "Afficher le calque", "Mostrar capa", "レイヤーを表示", "显示图层"]),+ ("Lock Layer", ["Ebene fixieren", "Verrouiller le calque", "Bloquear capa", "レイヤーをロック", "锁定图层"]),+ ("Print Layer", ["Ebene drucken", "Imprimer le calque", "Imprimir capa", "レイヤーをプリント", "打印图层"]),+ (+ "Suppress Text Wrap When Layer is Hidden",+ [+ "Textumfluss bei ausgeblendeter Ebene unterdrücken",+ "Supprimer l'habillage quand le calque est masqué",+ "Suprimir ceñir texto cuando la capa está oculta",+ "非表示レイヤーのテキストの回り込みを無視",+ "图层隐藏时禁止文本绕排",+ ],+ ),+ // Document Setup+ ("Page Size:", ["Seitenformat:", "Format de page :", "Tamaño de página:", "ページサイズ:", "页面大小:"]),+ (+ "Adjust page elements to document changes",+ [+ "Seitenelemente an Dokumentänderungen anpassen",+ "Adapter les éléments de page aux modifications du document",+ "Ajustar los elementos de página a los cambios del documento",+ "ページ要素をドキュメントの変更に合わせて調整",+ "根据文档更改调整页面元素",+ ],+ ),+ (+ "Apply the changes; objects follow the new page size and margins",+ [+ "Änderungen anwenden; Objekte folgen dem neuen Seitenformat und den Rändern",+ "Appliquer les modifications ; les objets suivent le nouveau format et les marges",+ "Aplicar los cambios; los objetos siguen el nuevo tamaño de página y los márgenes",+ "変更を適用し、オブジェクトを新しいページサイズとマージンに合わせます",+ "应用更改;对象跟随新的页面大小和边距",+ ],+ ),- ("Inside:", ["Innen:", "Intérieur :", "Interior:", "ノド:", "内:"]),- ("Outside:", ["Außen:", "Extérieur :", "Exterior:", "小口:", "外:"]),+ ("Bleed:", ["Anschnitt:", "Fond perdu :", "Sangrado:", "裁ち落とし:", "出血:"]),+ ("Slug:", ["Infobereich:", "Ligne-bloc :", "Indicaciones:", "印刷可能領域:", "辅助信息区:"]),+ // Font menu+ ("Filters:", ["Filter:", "Filtres :", "Filtros:", "フィルター:", "过滤器:"]),+ ("All Classes", ["Alle Klassen", "Toutes les classes", "Todas las clases", "すべての分類", "所有分类"]),+ ("Serif", ["Serifenschrift", "Serif", "Con serifa", "セリフ", "衬线"]),+ ("Slab Serif", ["Egyptienne", "Slab serif", "Serifa cuadrada", "スラブセリフ", "粗衬线"]),+ ("Sans Serif", ["Serifenlos", "Sans serif", "Sin serifa", "サンセリフ", "无衬线"]),+ ("Script", ["Schreibschrift", "Script", "Manuscrita", "スクリプト", "手写体"]),+ ("Monospaced", ["Dicktengleich", "Chasse fixe", "Monoespaciada", "等幅", "等宽"]),+ ("Decorative", ["Dekorativ", "Décorative", "Decorativa", "装飾", "装饰"]),+ ("Symbol", ["Symbol", "Symbole", "Símbolo", "記号", "符号"]),+ (+ "Show Recently Added",+ [+ "Zuletzt hinzugefügte anzeigen",+ "Afficher les polices ajoutées récemment",+ "Mostrar añadidas recientemente",+ "最近追加したフォントを表示",+ "显示最近添加的字体",+ ],+ ),+ (+ "Small Sample Text Size",+ ["Kleine Beispieltextgröße", "Petite taille de l'exemple", "Tamaño de muestra pequeño", "サンプルテキスト(小)", "小号示例文本"],+ ),+ (+ "Medium Sample Text Size",+ ["Mittlere Beispieltextgröße", "Taille moyenne de l'exemple", "Tamaño de muestra mediano", "サンプルテキスト(中)", "中号示例文本"],+ ),+ (+ "Large Sample Text Size",+ ["Große Beispieltextgröße", "Grande taille de l'exemple", "Tamaño de muestra grande", "サンプルテキスト(大)", "大号示例文本"],+ ),+ ("Selected Text", ["Ausgewählter Text", "Texte sélectionné", "Texto seleccionado", "選択したテキスト", "所选文本"]),+ ("Sample", ["Beispiel", "Exemple", "Muestra", "サンプル", "示例"]),+ ("Similar to {family}", ["Ähnlich wie {family}", "Semblables à {family}", "Similares a {family}", "{family} に類似", "与 {family} 相似"]),+ (+ "No fonts match",+ ["Keine passenden Schriften", "Aucune police ne correspond", "Ninguna fuente coincide", "一致するフォントはありません", "没有匹配的字体"],+ ),+ (+ "Show Similar Fonts",+ ["Ähnliche Schriften anzeigen", "Afficher les polices semblables", "Mostrar fuentes similares", "類似フォントを表示", "显示相似字体"],+ ),+ ("Loading fonts…", ["Schriften werden geladen…", "Chargement des polices…", "Cargando fuentes…", "フォントを読み込み中…", "正在加载字体…"]),+ ("Show Styles", ["Schnitte einblenden", "Afficher les styles", "Mostrar estilos", "スタイルを表示", "显示样式"]),+ ("Hide Styles", ["Schnitte ausblenden", "Masquer les styles", "Ocultar estilos", "スタイルを隠す", "隐藏样式"]),+ ("TrueType font", ["TrueType-Schrift", "Police TrueType", "Fuente TrueType", "TrueType フォント", "TrueType 字体"]),+ ("OpenType font", ["OpenType-Schrift", "Police OpenType", "Fuente OpenType", "OpenType フォント", "OpenType 字体"]),+ ("Variable font", ["Variable Schrift", "Police variable", "Fuente variable", "バリアブルフォント", "可变字体"]),+ ("Color font", ["Farbschrift", "Police couleur", "Fuente de color", "カラーフォント", "彩色字体"]),];/// Interface direction; independent of document binding and paragraph direction.@@@ -4253,10 -3159,7 +4359,11 @@@ pub fn tr<'a>(lang: &str, s: &'a str) -static UKRAINIAN: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();static PORTUGUESE_BR: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();static ITALIAN: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();+ static POLISH: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();+ static RUSSIAN: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();+ static CZECH: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();+ static FRENCH: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();+ static GEORGIAN: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();if lang == "ar" {return ARABIC.get_or_init(|| ar::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s);}@@@ -4284,9 -3181,9 +4391,12 @@@if lang == "it" {return ITALIAN.get_or_init(|| it::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s);}+ if lang == "pl" {+ return POLISH.get_or_init(|| pl::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s);+ }+ if lang == "ka" {+ return GEORGIAN.get_or_init(|| ka::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s);+ }if lang == "uk" {return UKRAINIAN.get_or_init(|| uk::TABLE.iter().copied().collect()).get(s).copied().unwrap_or(s);}@@@ -4318,35 -3204,11 +4428,36 @@@ pub(crate) fn ukrainian_catalog() -> Veuk::TABLE.iter().map(|(_, text)| *text).chain(uk::CONTEXT.iter().map(|(_, _, text)| *text)).collect()}-/// Count captions in Ukrainian and Georgian put the category before the value so every count-/// uses one grammatical form (Georgian nouns stay singular after numerals: `გვერდი: 5`); other+#[cfg(test)]+pub(crate) fn russian_catalog() -> Vec<&'static str> {+ ru::TABLE.iter().map(|(_, text)| *text).chain(ru::CONTEXT.iter().map(|(_, _, text)| *text)).collect()+}+- /// Ukrainian, Russian and Polish have several plural forms, so their count captions put the- /// category before the value ("сторінок: 5", "страниц: 5", "Strony: 5") and every number stays- /// grammatical; other languages keep the existing value-first caption.++/// Ukrainian, Russian, Polish and Georgian put the category before the value in count captions++/// ("сторінок: 5", "страниц: 5", "Strony: 5", "გვერდი: 5"): every number stays grammatical in the++/// languages with several plural forms, and Georgian nouns stay singular after numerals. Other+ /// languages keep the existing value-first caption.+pub fn category_first(lang: &str) -> bool {- matches!(lang, "uk" | "ru" | "pl")++ matches!(lang, "uk" | "ru" | "pl" | "ka")+}++/// Caption for a counted category, e.g. `count_label("ru", "pages", 5)` is "страниц: 5". Czech+/// picks the plural form for the count (1, 2–4, other).pub fn count_label(lang: &str, noun: &str, count: usize) -> String {- if matches!(lang, "uk" | "ka") { format!("{}: {count}", tr(lang, noun)) } else { format!("{count} {}", tr(lang, noun)) }+ if category_first(lang) {+ return format!("{}: {count}", tr(lang, noun));+ }+ if lang == "cs"+ && let Some((_, [one, few, other])) = cs::PLURALS.iter().find(|(key, _)| *key == noun)+ {+ let form = match count {+ 1 => one,+ 2..=4 => few,+ _ => other,+ };+ return format!("{count} {form}");+ }+ format!("{count} {}", tr(lang, noun))}/// Localize reserved built-in style names only; user-defined names are document data.@@@ -4402,20 -3264,11 +4513,23 @@@ mod testsfor (key, expected) in uk::TABLE {assert_eq!(tr("uk", key), *expected, "uk: {key}");}+ for (key, expected) in ru::TABLE {+ assert_eq!(tr("ru", key), *expected, "ru: {key}");+ }+ for (key, expected) in cs::TABLE {+ assert_eq!(tr("cs", key), *expected, "cs: {key}");+ }+ for (key, expected) in fr::TABLE {+ assert_eq!(tr("fr", key), *expected, "fr: {key}");+ }+ for (key, expected) in pl::TABLE {+ assert_eq!(tr("pl", key), *expected, "pl: {key}");+ }+ for (key, expected) in ka::TABLE {+ assert_eq!(tr("ka", key), *expected, "ka: {key}");+ }let unknown = String::from("A user-defined untranslated label");- for lang in ["pl", "cs", "uk", "ru", "ar", "pt-br", "it", "zh", "ja", "de", "fr", "es", "", "unknown"] {- for lang in ["uk", "ar", "pt-br", "it", "ka", "zh", "ja", "de", "fr", "es", "", "unknown"] {++ for lang in ["pl", "cs", "uk", "ru", "ar", "pt-br", "it", "ka", "zh", "ja", "de", "fr", "es", "", "unknown"] {assert!(std::ptr::eq(tr(lang, &unknown), unknown.as_str()));}}diff --cc crates/ui-egui/src/i18n/ar.rsindex d4684b4ae,d1dcb7acf..ae57fbd4a--- a/crates/ui-egui/src/i18n/ar.rs+++ b/crates/ui-egui/src/i18n/ar.rs@@@ -30,48 -30,55 +30,89 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "قص"),("Copy", "نسخ"),("Paste", "لصق"),+ ("Paste Vector Art", "لصق رسم متجه"),+ ("Baseline Options", "خيارات خط الأساس"),+ ("Fixed Number", "عدد ثابت"),+ ("Fixed Width", "عرض ثابت"),- ("Gutter:", "التباعد:"),++ ("Gutter:", "الفاصل:"),+ ("Balance Columns", "موازنة الأعمدة"),+ ("Inset Spacing", "تباعد الإزاحة الداخلية"),+ ("Vertical Justification", "الضبط العمودي"),+ ("Align:", "المحاذاة:"),+ ("Ignore Text Wrap", "تجاهل التفاف النص"),+ ("Technique:", "التقنية:"),+ ("Softer", "أنعم"),+ ("Precise", "دقيق"),+ ("Corners:", "الزوايا:"),+ ("Sharp", "حادة"),+ ("Diffused", "منتشرة"),+ ("Bulleted & Numbered Lists", "القوائم ذات التعداد النقطي والرقمي"),+ ("Current Page Number", "رقم الصفحة الحالية"),+ ("Apply Color (,)", "تطبيق اللون (,)"),+ ("Apply Gradient (.)", "تطبيق التدرج (.)"),+ ("View Options", "خيارات العرض"),+ ("Frame Edges", "حواف الإطار"),+ ("Hidden Characters", "الأحرف المخفية"),+ ("Create Flex Layout", "إنشاء تخطيط مرن"),+ ("Add to Flex Layout", "إضافة إلى التخطيط المرن"),+ ("Convert to Flex Layout", "تحويل إلى تخطيط مرن"),+ ("Remove Flex Layout", "إزالة التخطيط المرن"),+ ("Show Flex Controls", "إظهار عناصر التحكم المرنة"),+ ("Flex Layout Options", "خيارات التخطيط المرن"),+ ("Reorder in Flex Layout", "إعادة الترتيب في التخطيط المرن"),+ ("Flex Start", "بداية مرنة"),+ ("Flex End", "نهاية مرنة"),+ ("Space Between", "مسافة بينية"),+ ("Space Around", "مسافة حول"),+ ("Space Evenly", "توزيع متساوٍ"),+ ("Reverse Row", "صف معكوس"),+ ("Reverse Column", "عمود معكوس"),+ ("Wrap Content", "التفاف المحتوى"),+ ("Spacing", "التباعد"),+ ("Horizontal Spacing", "التباعد الأفقي"),+ ("Vertical Spacing", "التباعد الرأسي"),+ ("Constrain proportions", "تقييد النسب"),+ ("Auto", "تلقائي"),+ ("W:", "ع:"),+ ("H:", "ا:"),- ("Number:", "العدد:"),- ("Gutter:", "الفاصل:"),+ ("Fit Guides to:", "ملاءمة الأدلة مع:"),- ("Top:", "أعلى:"),- ("Bottom:", "أسفل:"),+ ("Inside:", "الداخل:"),+ ("Outside:", "الخارج:"),- ("Left:", "يسار:"),- ("Right:", "يمين:"),+ ("Paths:", "المسارات:"),+ ("Pathfinder:", "مستكشف المسار:"),+ ("Convert Shape:", "تحويل الشكل:"),+ ("Convert Point:", "تحويل النقطة:"),+ ("Join Path", "ربط المسار"),+ ("Open Path", "فتح المسار"),+ ("Plain", "عادي"),+ ("Symmetrical", "متماثل"),+ ("The stroke isn't a gradient.", "الحد ليس تدرجًا."),("Reverse Path", "عكس المسار"),("Set Anchor", "تعيين نقطة الارتساء"),+ ("Effects…", "التأثيرات…"),+ ("Settings for:", "الإعدادات لـ:"),+ ("Transparency…", "الشفافية…"),+ ("Basic Blending", "المزج الأساسي"),+ ("Opacity:", "العتامة:"),+ ("Blending", "المزج"),+ ("Distance:", "المسافة:"),+ ("X Offset:", "إزاحة X:"),+ ("Y Offset:", "إزاحة Y:"),+ ("Spread:", "الانتشار:"),+ ("Choke:", "الانكماش:"),+ ("Source:", "المصدر:"),+ ("Edge", "الحافة"),+ ("Depth:", "العمق:"),+ ("Highlight:", "الإبراز:"),+ ("Shadow:", "الظل:"),+ ("Feather Width:", "عرض التدرج:"),+ ("Feather Widths", "عروض التدرج"),+ ("Gradient Stops", "نقاط التدرج"),+ ("Start Opacity:", "عتامة البداية:"),+ ("End Opacity:", "عتامة النهاية:"),+ ("(no effects)", "(بلا تأثيرات)"),+ ("OBJECT", "الكائن"),+ ("Add an object effect to the selected target", "إضافة تأثير كائن إلى الهدف المحدد"),("Clear", "مسح"),("Delete", "حذف"),("Duplicate", "تكرار"),@@@ -1747,7 -1614,7 +1787,6 @@@("Copyright Symbol", "رمز حقوق النشر"),("Corner Options", "خيارات الزوايا"),("Create Guides", "إنشاء أدلة"),- ("Current Page Number", "رقم الصفحة الحالية"),- ("Cyan", "سماوي"),("Dark", "داكن"),("Data Merge", "دمج البيانات"),("Define Cross-Reference Format", "تعريف تنسيق المرجع المتصالب"),diff --cc crates/ui-egui/src/i18n/fr.rsindex c45aac04b,000000000..9ccb87a3dmode 100644,000000..100644--- a/crates/ui-egui/src/i18n/fr.rs+++ b/crates/ui-egui/src/i18n/fr.rs@@@ -1,235 -1,0 +1,230 @@@+//! French translations of the strings the shared table in `i18n.rs` has no row for,+//! written from the English source using ordinary French desktop-publishing vocabulary.+pub(super) const TABLE: &[(&str, &str)] = &[+ ("90° CCW", "90° sens antihoraire"),+ ("90° CW", "90° sens horaire"),+ ("Alignment", "Alignement"),+ ("All Documents", "Tous les documents"),+ ("Alpha Channel", "Couche alpha"),+ ("Anchored Object Options", "Options d'objet ancré"),+ ("ArtCraft App Page", "Page de l'application ArtCraft"),+ ("ArtCraft Website", "Site web d'ArtCraft"),+ ("Auto Size", "Taille automatique"),+ ("Binding", "Reliure"),+ ("Bullet Character", "Caractère de puce"),+ ("CMYK:", "CMJN :"),+ ("Change To", "Remplacer par"),+ ("Check Spelling", "Vérifier l'orthographe"),+ ("Clear Rotation", "Effacer la rotation"),+ ("Closed Path", "Tracé fermé"),+ ("Color Blindness – Deuteranopia", "Daltonisme – Deutéranopie"),+ ("Color Blindness – Protanopia", "Daltonisme – Protanopie"),+ ("Colour", "Couleur"),+ ("Colour Picker", "Sélecteur de couleurs"),+ ("Column Break", "Saut de colonne"),+ ("Community", "Communauté"),+ ("Conditional Text", "Texte conditionnel"),+ ("Copyright Symbol", "Symbole du copyright"),+ ("Corner Options", "Options d'arrondi"),+ ("Create Guides", "Créer des repères"),- ("Current Page Number", "Numéro de la page active"),+ ("Dark", "Foncé"),+ ("Define Cross-Reference Format", "Définir un format de référence croisée"),+ ("Define Lists", "Définir des listes"),+ ("Define Text Variable", "Définir une variable de texte"),+ ("Delete Type from Path", "Supprimer le texte curviligne"),+ ("DesignCraft Website", "Site web de DesignCraft"),+ ("DesignCraft on GitHub", "DesignCraft sur GitHub"),+ ("Detect Edges", "Détecter les contours"),+ ("Discretionary Hyphen", "Trait d'union conditionnel"),+ ("Document CMYK", "CMJN du document"),+ ("Document Endnote Options", "Options de notes de fin de document"),+ ("Document Footnote Options", "Options de notes de bas de page du document"),+ ("Document RGB", "RVB du document"),+ ("Done", "Terminé"),+ ("Double Left Quotation Marks", "Guillemets doubles ouvrants"),+ ("Double Right Quotation Marks", "Guillemets doubles fermants"),+ ("Edit/Interface Language", "Édition/Langue de l'interface"),+ ("Edit/Spelling", "Édition/Orthographe"),+ ("Edit/Transparency Blend Space", "Édition/Espace de fusion de la transparence"),+ ("Edit/Transparency Flattener Presets", "Édition/Préréglages d'aplatissement de la transparence"),+ ("Ellipsis", "Points de suspension"),+ ("Em Dash", "Tiret cadratin"),+ ("Em Space", "Espace cadratin"),+ ("En Dash", "Tiret demi-cadratin"),+ ("En Space", "Espace demi-cadratin"),+ ("Export EPUB", "Exporter en EPUB"),+ ("Export EPUB (Fixed Layout)", "Exporter en EPUB (mise en page fixe)"),+ ("Export EPUB (Reflowable)", "Exporter en EPUB (redistribuable)"),+ ("Export HTML", "Exporter en HTML"),+ ("Export IDML", "Exporter en IDML"),+ ("Export PDF (Interactive)", "Exporter en PDF (interactif)"),+ ("Export Page as PNG", "Exporter la page en PNG"),+ ("Export Text", "Exporter le texte"),+ ("Export XML", "Exporter en XML"),+ ("Figure Space", "Espace chiffre"),+ ("File/Export", "Fichier/Exporter"),+ ("Find What", "Rechercher"),+ ("First Page", "Première page"),- ("Flex Layout", "Mise en page flexible"),+ ("Flush Space", "Espace sans alinéa"),+ ("Forced Line Break", "Saut de ligne forcé"),+ ("Frame Break", "Saut de bloc"),+ ("GREP", "GREP"),+ ("Generate Index", "Générer l'index"),+ ("Generate Live Caption", "Générer une légende dynamique"),+ ("Global Light", "Lumière globale"),+ ("Graphic", "Graphique"),+ ("Hair Space", "Espace ultrafine"),+ ("Hide Guides", "Masquer les repères"),+ ("Hide Rulers", "Masquer les règles"),+ ("High Contrast", "Contraste élevé"),+ ("High Resolution", "Haute résolution"),+ ("I, II, III, IV...", "I, II, III, IV..."),+ ("Import XML", "Importer XML"),+ ("Indent", "Retrait"),+ ("Indent to Here", "Retrait jusqu'à ce point"),+ ("Ink Limit 300%", "Limite d'encre 300 %"),+ ("Insert Anchored Object", "Insérer un objet ancré"),+ ("Insert Cross-Reference", "Insérer une référence croisée"),+ ("Insert Math Expression", "Insérer une expression mathématique"),+ ("Insert Pages", "Insérer des pages"),+ ("Internet Standard RGB (sRGB)", "RVB standard Internet (sRGB)"),+ ("Join the ArtCraft Discord", "Rejoindre le Discord d'ArtCraft"),+ ("Join the community", "Rejoindre la communauté"),+ ("Kerning", "Crénage"),+ ("Last Page", "Dernière page"),+ ("Layout/Index", "Page/Index"),+ ("Layout/Pages", "Page/Pages"),+ ("Legacy Macintosh RGB", "RVB Macintosh hérité"),+ ("Light", "Clair"),+ ("Load DTD", "Charger la DTD"),+ ("Load Swatches", "Charger des nuances"),+ ("Low Resolution", "Basse résolution"),+ ("Margins and Columns", "Marges et colonnes"),+ ("Margins:", "Marges :"),+ ("Medium Dark", "Moyennement foncé"),+ ("Medium Light", "Moyennement clair"),+ ("Medium Resolution", "Résolution moyenne"),+ ("Menus", "Menus"),+ ("Monitor RGB", "RVB du moniteur"),+ ("Move Pages", "Déplacer des pages"),+ ("New Condition", "Nouvelle condition"),+ ("New Hyperlink", "Nouvel hyperlien"),+ ("New Hyperlink Destination", "Nouvelle destination d'hyperlien"),+ ("New Layer", "Nouveau calque"),+ ("New Page Reference", "Nouvelle référence de page"),+ ("New Parent", "Nouveau gabarit"),+ ("New Stroke Style", "Nouveau style de contour"),+ ("Next Page", "Page suivante"),+ ("Next Page Number", "Numéro de la page suivante"),+ ("Nonbreaking Hyphen", "Trait d'union insécable"),+ ("Nonbreaking Space", "Espace insécable"),+ ("None (keep transparency)", "Aucun (conserver la transparence)"),+ ("Number of Pages", "Nombre de pages"),+ ("Numbering & Section Options", "Options de numérotation et de section"),+ ("OK", "OK"),+ ("Object Styles", "Styles d'objet"),+ ("Object/Anchored Object", "Objet/Objet ancré"),+ ("Object/Arrange", "Objet/Disposition"),+ ("Object/Captions", "Objet/Légendes"),+ ("Object/Clipping Path", "Objet/Masque"),+ ("Object/Content", "Objet/Contenu"),+ ("Object/Convert Shape", "Objet/Convertir la forme"),+ ("Object/Effects", "Objet/Effets"),+ ("Object/Fitting", "Objet/Ajustement"),+ ("Object/Pathfinder", "Objet/Pathfinder"),+ ("Object/Paths", "Objet/Tracés"),+ ("Object/Select", "Objet/Sélectionner"),+ ("Object/Transform", "Objet/Transformation"),+ ("Object/Transform Again", "Objet/Répéter la transformation"),+ ("On", "Activé"),- ("Open Path", "Tracé ouvert"),+ ("Orientation", "Orientation"),+ ("Package", "Assemblage"),+ ("Page Break", "Saut de page"),+ ("Panels", "Panneaux"),+ ("Paragraph Return", "Retour de paragraphe"),+ ("Paragraph Symbol", "Symbole de paragraphe"),+ ("Picas", "Picas"),+ ("Place with Import Options", "Importer avec les options d'importation"),+ ("Preflight", "Contrôle en amont"),+ ("Previous Page", "Page précédente"),+ ("Previous Page Number", "Numéro de la page précédente"),+ ("Print Booklet", "Imprimer le cahier"),+ ("Punctuation Space", "Espace de ponctuation"),+ ("Quarter Space", "Quart d'espace"),+ ("Quick Apply", "Application rapide"),+ ("RGB:", "RVB :"),+ ("Registered Trademark Symbol", "Symbole de marque déposée"),+ ("Relink", "Rééditer le lien"),+ ("Relink to Folder", "Rééditer le lien au dossier"),+ ("Report an Issue", "Signaler un problème"),+ ("Right Indent Tab", "Tabulation de retrait à droite"),+ ("Rotation", "Rotation"),- ("Row", "Ligne"),- ("Rulers", "Règles"),+ ("Save As", "Enregistrer sous"),+ ("Save Swatches for Exchange", "Enregistrer les nuances pour échange"),+ ("Save a Copy", "Enregistrer une copie"),+ ("Scripts", "Scripts"),+ ("Section Marker", "Marque de section"),+ ("Section Symbol", "Symbole de section"),+ ("Selection", "Sélection"),+ ("Sentence case", "Majuscule en début de phrase"),+ ("Simulate Paper Color", "Simuler la couleur du papier"),+ ("Single Left Quotation Mark", "Guillemet simple ouvrant"),+ ("Single Right Quotation Mark", "Guillemet simple fermant"),+ ("Sixth Space", "Sixième d'espace"),+ ("Smart Guide Options", "Options des repères commentés"),+ ("Space After", "Espace après"),+ ("Space Before", "Espace avant"),+ ("Start Page #", "N° de la première page"),+ ("Step and Repeat", "Exécuter et répéter"),+ ("Story Column Direction", "Sens des colonnes de l'article"),+ ("Straight Double Quotation Marks", "Guillemets droits doubles"),+ ("Straight Single Quotation Mark (Apostrophe)", "Guillemet droit simple (apostrophe)"),+ ("Subscript:", "Indice :"),+ ("Superscript:", "Exposant :"),+ ("Tab", "Tabulation"),+ ("Table of Contents", "Table des matières"),+ ("Table/Convert Cell Type", "Tableau/Convertir le type de cellule"),+ ("Table/Delete", "Tableau/Supprimer"),+ ("Table/Insert", "Tableau/Insérer"),+ ("Table/Select", "Tableau/Sélectionner"),+ ("Thin Space", "Espace fine"),+ ("Third Space", "Tiers d'espace"),+ ("Title Case", "Majuscule à chaque mot"),+ ("Trademark Symbol", "Symbole de marque"),+ ("Transform Again Individually", "Répéter la transformation individuellement"),+ ("Transform Sequence Again", "Répéter la séquence de transformations"),+ ("Transform Sequence Again Individually", "Répéter la séquence de transformations individuellement"),+ ("Type on a Path Options", "Options de texte curviligne"),+ ("Type/Bulleted and Numbered Lists", "Texte/Listes à puces et numérotées"),+ ("Type/Change Case", "Texte/Modifier la casse"),+ ("Type/Hyperlinks & Cross-References", "Texte/Hyperliens et références croisées"),+ ("Type/Insert Break Character", "Texte/Insérer un caractère de saut"),+ ("Type/Insert Special Character/Hyphens and Dashes", "Texte/Insérer un caractère spécial/Traits d'union et tirets"),+ ("Type/Insert Special Character/Markers", "Texte/Insérer un caractère spécial/Marqueurs"),+ ("Type/Insert Special Character/Other", "Texte/Insérer un caractère spécial/Autres"),+ ("Type/Insert Special Character/Quotation Marks", "Texte/Insérer un caractère spécial/Guillemets"),+ ("Type/Insert Special Character/Symbols", "Texte/Insérer un caractère spécial/Symboles"),+ ("Type/Insert White Space", "Texte/Insérer un espace"),+ ("Type/Proof Setup", "Texte/Format d'épreuve"),+ ("Type/Rotate Spread", "Texte/Faire pivoter la planche"),+ ("Type/Separations Preview", "Texte/Aperçu des séparations"),+ ("Type/Story Direction", "Texte/Sens du texte"),+ ("Type/Text Variables", "Texte/Variables de texte"),+ ("Type/Track Changes", "Texte/Suivi des modifications"),+ ("Type/Type on a Path", "Texte/Texte curviligne"),+ ("URL:", "URL :"),+ ("Unassigned", "Non attribué"),+ ("Units", "Unités"),+ ("View/Display Performance", "Affichage/Performances d'affichage"),+ ("View/Grids & Guides", "Affichage/Grilles et repères"),+ ("Window/Arrange", "Fenêtre/Disposition"),+ ("Window/Interactive", "Fenêtre/Interactif"),+ ("Window/Interface Color Theme", "Fenêtre/Thème de couleur de l'interface"),+ ("Window/Output", "Fenêtre/Sortie"),+ ("Window/Panels", "Fenêtre/Panneaux"),+ ("Window/Type & Tables", "Fenêtre/Texte et tableaux"),+ ("Window/Utilities", "Fenêtre/Utilitaires"),+ ("Working CMYK", "CMJN de travail"),+ ("i, ii, iii, iv...", "i, ii, iii, iv..."),+ ("lowercase", "minuscules"),+];diff --cc crates/ui-egui/src/i18n/it.rsindex 6111efdaf,00328ac9f..797126639--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@@ -28,48 -28,55 +28,87 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Taglia"),("Copy", "Copia"),("Paste", "Incolla"),+ ("Paste Vector Art", "Incolla grafica vettoriale"),+ ("Baseline Options", "Opzioni linea di base"),+ ("Fixed Number", "Numero fisso"),+ ("Fixed Width", "Larghezza fissa"),+ ("Gutter:", "Spaziatura:"),+ ("Balance Columns", "Bilancia colonne"),+ ("Inset Spacing", "Spaziatura interna"),+ ("Vertical Justification", "Giustificazione verticale"),+ ("Align:", "Allinea:"),+ ("Ignore Text Wrap", "Ignora contorna con testo"),+ ("Technique:", "Tecnica:"),+ ("Softer", "Più morbido"),+ ("Precise", "Preciso"),+ ("Corners:", "Angoli:"),+ ("Sharp", "Netti"),+ ("Diffused", "Diffusi"),+ ("Bulleted & Numbered Lists", "Elenchi puntati e numerati"),+ ("Current Page Number", "Numero di pagina corrente"),+ ("Apply Color (,)", "Applica colore (,)"),+ ("Apply Gradient (.)", "Applica sfumatura (.)"),+ ("View Options", "Opzioni di visualizzazione"),+ ("Frame Edges", "Bordi cornice"),+ ("Hidden Characters", "Caratteri nascosti"),+ ("Create Flex Layout", "Crea Layout Flex"),+ ("Add to Flex Layout", "Aggiungi a Layout Flex"),+ ("Convert to Flex Layout", "Converti in Layout Flex"),+ ("Remove Flex Layout", "Rimuovi Layout Flex"),+ ("Show Flex Controls", "Mostra controlli Flex"),+ ("Flex Layout Options", "Opzioni Layout Flex"),+ ("Reorder in Flex Layout", "Riordina nel Layout Flex"),+ ("Flex Start", "Inizio Flex"),+ ("Flex End", "Estremità Flex"),+ ("Space Between", "Spazio tra"),+ ("Space Around", "Spazio intorno"),+ ("Space Evenly", "Disponi lo spazio in modo uniforme"),+ ("Reverse Row", "Riga inversa"),+ ("Reverse Column", "Colonna inversa"),+ ("Wrap Content", "Disponi testo"),+ ("Spacing", "Spaziatura"),+ ("Horizontal Spacing", "Spaziatura orizzontale"),+ ("Vertical Spacing", "Spaziatura verticale"),+ ("Constrain proportions", "Vincola proporzioni"),+ ("Auto", "Automatico"),+ ("W:", "L:"),+ ("H:", "A:"),- ("Number:", "Numero:"),- ("Gutter:", "Spaziatura:"),+ ("Fit Guides to:", "Adatta guide a:"),- ("Top:", "Superiore:"),- ("Bottom:", "Inferiore:"),- ("Inside:", "Interno:"),- ("Outside:", "Esterno:"),- ("Left:", "Sinistra:"),- ("Right:", "Destra:"),+ ("Paths:", "Tracciati:"),+ ("Pathfinder:", "Elaborazione tracciati:"),+ ("Convert Shape:", "Converti forma:"),+ ("Convert Point:", "Converti punto:"),+ ("Join Path", "Unisci tracciato"),+ ("Open Path", "Apri tracciato"),+ ("Plain", "Semplice"),+ ("Symmetrical", "Simmetrico"),+ ("The stroke isn't a gradient.", "La traccia non è una sfumatura."),("Reverse Path", "Inverti tracciato"),("Set Anchor", "Imposta ancoraggio"),+ ("Effects…", "Effetti…"),+ ("Settings for:", "Impostazioni per:"),+ ("Transparency…", "Trasparenza…"),+ ("Basic Blending", "Fusione di base"),+ ("Opacity:", "Opacità:"),+ ("Blending", "Fusione"),+ ("Distance:", "Distanza:"),+ ("X Offset:", "Spostamento X:"),+ ("Y Offset:", "Spostamento Y:"),+ ("Spread:", "Estensione:"),+ ("Choke:", "Contrazione:"),+ ("Source:", "Origine:"),+ ("Edge", "Bordo"),+ ("Depth:", "Profondità:"),+ ("Highlight:", "Luce:"),+ ("Shadow:", "Ombra:"),+ ("Feather Width:", "Larghezza sfumatura:"),+ ("Feather Widths", "Larghezze sfumatura"),+ ("Gradient Stops", "Interruzioni sfumatura"),+ ("Start Opacity:", "Opacità iniziale:"),+ ("End Opacity:", "Opacità finale:"),+ ("(no effects)", "(nessun effetto)"),+ ("OBJECT", "OGGETTO"),+ ("Add an object effect to the selected target", "Aggiungi un effetto oggetto all'obiettivo selezionato"),("Clear", "Cancella"),("Duplicate", "Duplica"),("Select All", "Seleziona tutto"),diff --cc crates/ui-egui/src/i18n/ja.rsindex ad3af3349,fe9e213e7..de0d07ff7--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@@ -30,50 -30,49 +30,88 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "カット"),("Copy", "コピー"),("Paste", "ペースト"),+ ("Paste Vector Art", "ベクトルアートをペースト"),+ ("Baseline Options", "ベースラインオプション"),+ ("Column Rules", "段落境界線"),+ ("Insert Column Rule", "段落境界線を挿入"),+ ("Fixed Number", "固定数"),+ ("Fixed Width", "固定幅"),+ ("Gutter:", "間隔:"),+ ("Balance Columns", "段を均等化"),+ ("Inset Spacing", "フレーム内マージン"),+ ("Vertical Justification", "垂直比率"),+ ("Align:", "整列:"),+ ("Ignore Text Wrap", "テキストの回り込みを無視"),+ ("Technique:", "テクニック:"),+ ("Softer", "さらにソフトに"),+ ("Precise", "精細"),+ ("Corners:", "角:"),+ ("Sharp", "シャープ"),+ ("Diffused", "拡散"),+ ("Bulleted & Numbered Lists", "箇条書き"),+ ("Apply Color (,)", "カラーを適用 (,)"),+ ("Apply Gradient (.)", "グラデーションを適用 (.)"),+ ("View Options", "表示オプション"),+ ("Frame Edges", "フレーム枠"),+ ("Hidden Characters", "制御文字"),+ ("Create Flex Layout", "フレックスレイアウトを作成"),+ ("Add to Flex Layout", "フレックスレイアウトに追加"),+ ("Convert to Flex Layout", "フレックスレイアウトに変換"),+ ("Remove Flex Layout", "フレックスレイアウトを削除"),+ ("Show Flex Controls", "フレックスコントロールを表示"),+ ("Flex Layout Options", "フレックスレイアウトオプション"),+ ("Reorder in Flex Layout", "フレックスレイアウト内で並べ替え"),+ ("Flex Start", "フレックス開始"),+ ("Flex End", "フレックス終了"),+ ("Space Between", "間隔を均等"),+ ("Space Around", "周囲に間隔"),+ ("Space Evenly", "均等に配置"),+ ("Reverse Row", "行(逆方向)"),+ ("Reverse Column", "列(逆方向)"),+ ("Wrap Content", "コンテンツを折り返す"),+ ("Spacing", "間隔"),+ ("Horizontal Spacing", "水平方向の間隔"),+ ("Vertical Spacing", "垂直方向の間隔"),+ ("Constrain proportions", "縦横比を固定"),- ("Auto", "自動"),+ ("W:", "幅:"),+ ("H:", "高さ:"),- ("Number:", "数:"),- ("Gutter:", "間隔:"),+ ("Fit Guides to:", "ガイドの適用先:"),+ ("Inside:", "ノド:"),+ ("Outside:", "小口:"),+ ("Paths:", "パス:"),+ ("Pathfinder:", "パスファインダー:"),+ ("Convert Shape:", "シェイプを変換:"),+ ("Convert Point:", "ポイントを変換:"),+ ("Join Path", "パスを連結"),+ ("Plain", "プレーン"),+ ("Symmetrical", "対称"),+ ("The stroke isn't a gradient.", "線はグラデーションではありません。"),("Reverse Path", "パスの方向反転"),("Set Anchor", "アンカーポイントを設定"),+ ("Effects…", "効果…"),+ ("Settings for:", "設定対象:"),+ ("Transparency…", "透明…"),+ ("Basic Blending", "基本的な描画モード"),+ ("Opacity:", "不透明度:"),+ ("Blending", "描画モード"),+ ("Distance:", "距離:"),+ ("X Offset:", "X オフセット:"),+ ("Y Offset:", "Y オフセット:"),+ ("Spread:", "スプレッド:"),+ ("Choke:", "チョーク:"),+ ("Source:", "ソース:"),+ ("Edge", "エッジ"),+ ("Depth:", "深さ:"),+ ("Highlight:", "ハイライト:"),+ ("Shadow:", "シャドウ:"),+ ("Feather Width:", "ぼかしの幅:"),+ ("Feather Widths", "ぼかしの幅"),+ ("Gradient Stops", "グラデーション分岐点"),+ ("Start Opacity:", "開始の不透明度:"),+ ("End Opacity:", "終了の不透明度:"),+ ("(no effects)", "(効果なし)"),+ ("OBJECT", "オブジェクト"),+ ("Add an object effect to the selected target", "選択した対象にオブジェクト効果を追加"),("Clear", "消去"),("Duplicate", "複製"),("Select All", "すべてを選択"),diff --cc crates/ui-egui/src/i18n/pt_br.rsindex c10e197d8,0675a2f66..563a3cd38--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@@ -31,48 -31,60 +31,94 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Recortar"),("Copy", "Copiar"),("Paste", "Colar"),+ ("Paste Vector Art", "Colar arte vetorial"),+ ("Baseline Options", "Opções de linha de base"),+ ("Fixed Number", "Número fixo"),+ ("Fixed Width", "Largura fixa"),+ ("Gutter:", "Medianiz:"),+ ("Balance Columns", "Equilibrar colunas"),+ ("Inset Spacing", "Espaçamento interno"),+ ("Vertical Justification", "Justificação vertical"),+ ("Align:", "Alinhar:"),+ ("Ignore Text Wrap", "Ignorar disposição do texto"),+ ("Technique:", "Técnica:"),+ ("Softer", "Mais suave"),+ ("Precise", "Preciso"),+ ("Corners:", "Cantos:"),+ ("Sharp", "Nítidos"),+ ("Diffused", "Difusos"),+ ("Bulleted & Numbered Lists", "Listas com marcadores e numeradas"),+ ("Show Hidden Characters", "Mostrar caracteres ocultos"),+ ("Current Page Number", "Número da página atual"),+ ("New Note", "Nova nota"),+ ("Insert Endnote", "Inserir nota de fim"),+ ("Apply Color (,)", "Aplicar cor (,)"),+ ("Apply Gradient (.)", "Aplicar degradê (.)"),+ ("View Options", "Opções de visualização"),+ ("Frame Edges", "Bordas do quadro"),+ ("Hidden Characters", "Caracteres ocultos"),+ ("Create Flex Layout", "Criar layout flexível"),+ ("Add to Flex Layout", "Adicionar ao layout flexível"),+ ("Convert to Flex Layout", "Converter em layout flexível"),+ ("Remove Flex Layout", "Remover layout flexível"),+ ("Show Flex Controls", "Mostrar controles flexíveis"),+ ("Flex Layout Options", "Opções de layout flexível"),+ ("Reorder in Flex Layout", "Reordenar no layout flexível"),+ ("Flex Start", "Início flexível"),+ ("Flex End", "Fim flexível"),+ ("Space Between", "Espaço entre"),+ ("Space Around", "Espaço ao redor"),+ ("Space Evenly", "Espaço uniforme"),+ ("Reverse Row", "Linha invertida"),+ ("Reverse Column", "Coluna invertida"),+ ("Wrap Content", "Quebrar conteúdo"),+ ("Spacing", "Espaçamento"),+ ("Horizontal Spacing", "Espaçamento horizontal"),+ ("Vertical Spacing", "Espaçamento vertical"),+ ("Constrain proportions", "Restringir proporções"),+ ("Auto", "Automático"),+ ("W:", "L:"),+ ("H:", "A:"),- ("Number:", "Número:"),- ("Gutter:", "Medianiz:"),+ ("Fit Guides to:", "Ajustar guias a:"),- ("Top:", "Superior:"),- ("Bottom:", "Inferior:"),+ ("Inside:", "Interna:"),+ ("Outside:", "Externa:"),- ("Left:", "Esquerda:"),- ("Right:", "Direita:"),+ ("Paths:", "Demarcadores:"),+ ("Pathfinder:", "Pathfinder:"),+ ("Convert Shape:", "Converter forma:"),+ ("Convert Point:", "Converter ponto:"),+ ("Join Path", "Unir demarcador"),+ ("Open Path", "Abrir demarcador"),+ ("Close Path", "Fechar demarcador"),+ ("Plain", "Simples"),+ ("Smooth", "Suave"),+ ("Symmetrical", "Simétrico"),+ ("The stroke isn't a gradient.", "O traçado não é um gradiente."),("Reverse Path", "Inverter demarcador"),("Set Anchor", "Definir ponto de ancoragem"),+ ("Effects…", "Efeitos…"),+ ("Settings for:", "Configurações para:"),+ ("Transparency…", "Transparência…"),+ ("Basic Blending", "Mesclagem básica"),+ ("Opacity:", "Opacidade:"),+ ("Blending", "Mesclagem"),+ ("Distance:", "Distância:"),+ ("X Offset:", "Deslocamento X:"),+ ("Y Offset:", "Deslocamento Y:"),+ ("Spread:", "Espalhamento:"),+ ("Choke:", "Contração:"),+ ("Source:", "Origem:"),+ ("Edge", "Borda"),+ ("Depth:", "Profundidade:"),+ ("Highlight:", "Realce:"),+ ("Shadow:", "Sombra:"),+ ("Feather Width:", "Largura do difuminado:"),+ ("Feather Widths", "Larguras do difuminado"),+ ("Gradient Stops", "Paradas de gradiente"),+ ("Start Opacity:", "Opacidade inicial:"),+ ("End Opacity:", "Opacidade final:"),+ ("(no effects)", "(sem efeitos)"),+ ("OBJECT", "OBJETO"),+ ("Add an object effect to the selected target", "Adicionar um efeito de objeto ao alvo selecionado"),("Clear", "Limpar"),("Delete", "Excluir"),("Duplicate", "Duplicar"),@@@ -1322,9 -1201,9 +1368,8 @@@("Tate-Chu-Yoko", "Tate-chu-yoko"),("Ruby…", "Ruby…"),("Kenten", "Kenten"),- ("Tabs", "Tabulações"),("Story", "Matéria"),("Create Outlines", "Criar contornos"),- ("Show Hidden Characters", "Mostrar caracteres ocultos"),("Unmerge Cells", "Desfazer mesclagem de células"),("Snap to Guides", "Alinhar às guias"),("Snap to Document Grid", "Alinhar à grade do documento"),diff --cc crates/ui-egui/src/i18n/uk.rsindex 30c77f7c6,8f1d27f84..705cebfb3--- a/crates/ui-egui/src/i18n/uk.rs+++ b/crates/ui-egui/src/i18n/uk.rs@@@ -29,48 -31,55 +29,89 @@@ pub(super) const TABLE: &[(&str, &str)("Cut", "Вирізати"),("Copy", "Копіювати"),("Paste", "Вставити"),+ ("Paste Vector Art", "Вставити векторну графіку"),+ ("Baseline Options", "Параметри базової лінії"),+ ("Fixed Number", "Фіксована кількість"),+ ("Fixed Width", "Фіксована ширина"),+ ("Gutter:", "Проміжок:"),+ ("Balance Columns", "Вирівняти колонки"),+ ("Inset Spacing", "Внутрішні відступи"),+ ("Vertical Justification", "Вертикальне вирівнювання"),+ ("Align:", "Вирівняти:"),+ ("Ignore Text Wrap", "Ігнорувати обтікання текстом"),+ ("Technique:", "Техніка:"),+ ("Softer", "М'якше"),+ ("Precise", "Точно"),+ ("Corners:", "Кути:"),+ ("Sharp", "Гострі"),+ ("Diffused", "Розсіяні"),+ ("Bulleted & Numbered Lists", "Марковані й нумеровані списки"),+ ("Current Page Number", "Номер поточної сторінки"),+ ("Apply Color (,)", "Застосувати колір (,)"),+ ("Apply Gradient (.)", "Застосувати градієнт (.)"),+ ("View Options", "Параметри перегляду"),+ ("Frame Edges", "Краї фреймів"),+ ("Hidden Characters", "Приховані символи"),+ ("Create Flex Layout", "Створити гнучкий макет"),+ ("Add to Flex Layout", "Додати до гнучкого макета"),+ ("Convert to Flex Layout", "Перетворити на гнучкий макет"),+ ("Remove Flex Layout", "Прибрати гнучкий макет"),+ ("Show Flex Controls", "Показати елементи гнучкого макета"),+ ("Flex Layout Options", "Параметри гнучкого макета"),+ ("Reorder in Flex Layout", "Змінити порядок у гнучкому макеті"),+ ("Flex Start", "Початок"),+ ("Flex End", "Кінець"),+ ("Space Between", "Простір між"),+ ("Space Around", "Простір навколо"),+ ("Space Evenly", "Рівномірно"),+ ("Reverse Row", "Рядок у зворотному порядку"),+ ("Reverse Column", "Стовпець у зворотному порядку"),+ ("Wrap Content", "Переносити вміст"),+ ("Spacing", "Відступи"),+ ("Horizontal Spacing", "Горизонтальний відступ"),+ ("Vertical Spacing", "Вертикальний відступ"),+ ("Constrain proportions", "Зберігати пропорції"),+ ("Auto", "Авто"),+ ("W:", "Ш:"),+ ("H:", "В:"),- ("Number:", "Кількість:"),- ("Gutter:", "Проміжок:"),+ ("Fit Guides to:", "Узгодити напрямні з:"),- ("Top:", "Верх:"),- ("Bottom:", "Низ:"),+ ("Inside:", "Внутрішнє:"),+ ("Outside:", "Зовнішнє:"),- ("Left:", "Ліворуч:"),- ("Right:", "Праворуч:"),+ ("Paths:", "Контури:"),+ ("Pathfinder:", "Обробка контурів:"),+ ("Convert Shape:", "Перетворити фігуру:"),+ ("Convert Point:", "Перетворити точку:"),+ ("Join Path", "Об’єднати контур"),+ ("Open Path", "Розімкнути контур"),+ ("Plain", "Простий"),+ ("Symmetrical", "Симетричний"),+ ("The stroke isn't a gradient.", "Обведення не є градієнтом."),("Reverse Path", "Розвернути контур"),("Set Anchor", "Задати прив’язку"),+ ("Effects…", "Ефекти…"),+ ("Settings for:", "Параметри для:"),+ ("Transparency…", "Прозорість…"),+ ("Basic Blending", "Базове змішування"),+ ("Opacity:", "Непрозорість:"),+ ("Blending", "Змішування"),+ ("Distance:", "Відстань:"),+ ("X Offset:", "Зсув X:"),+ ("Y Offset:", "Зсув Y:"),+ ("Spread:", "Розмах:"),+ ("Choke:", "Стискання:"),+ ("Source:", "Джерело:"),+ ("Edge", "Край"),+ ("Depth:", "Глибина:"),+ ("Highlight:", "Світло:"),+ ("Shadow:", "Тінь:"),+ ("Feather Width:", "Ширина розмиття:"),+ ("Feather Widths", "Ширина розмиття"),+ ("Gradient Stops", "Точки градієнта"),+ ("Start Opacity:", "Початкова непрозорість:"),+ ("End Opacity:", "Кінцева непрозорість:"),+ ("(no effects)", "(без ефектів)"),+ ("OBJECT", "ОБ'ЄКТ"),+ ("Add an object effect to the selected target", "Додати ефект об'єкта до вибраної цілі"),("Clear", "Очистити"),("Duplicate", "Дублювати"),("Select All", "Виділити все"),diff --cc crates/ui-egui/src/icons.rsindex 56a8404bb,d123f89d3..a90fe989e--- a/crates/ui-egui/src/icons.rs+++ b/crates/ui-egui/src/icons.rs@@@ -586,16 -564,145 +600,154 @@@ pub fn paint(p: &Painter, r: Rect, name}}}+ // Flex Layout panel (original drawings): direction arrows, wrap, justification, spacing.+ "flex-right" | "flex-left" | "flex-down" | "flex-up" => {+ let pts: [(f32, f32); 5] = match name {+ "flex-right" => [(3.0, 10.0), (16.0, 10.0), (11.5, 6.0), (16.0, 10.0), (11.5, 14.0)],+ "flex-left" => [(17.0, 10.0), (4.0, 10.0), (8.5, 6.0), (4.0, 10.0), (8.5, 14.0)],+ "flex-down" => [(10.0, 3.0), (10.0, 16.0), (6.0, 11.5), (10.0, 16.0), (14.0, 11.5)],+ _ => [(10.0, 17.0), (10.0, 4.0), (6.0, 8.5), (10.0, 4.0), (14.0, 8.5)],+ };+ pen.line(&pts[..2]);+ pen.line(&pts[2..]);+ }+ "flex-wrap" => {+ pen.line(&[(16.0, 4.0), (16.0, 12.0), (5.0, 12.0)]);+ pen.line(&[(8.5, 8.5), (5.0, 12.0), (8.5, 15.5)]);+ }+ "flex-start" | "flex-center" | "flex-end" | "flex-between" | "flex-around" | "flex-evenly" => {+ // Three bars in a box, where the justification puts them.+ pen.rect(1.5, 6.0, 18.5, 14.0);+ let xs: [f32; 3] = match name {+ "flex-start" => [3.0, 6.0, 9.0],+ "flex-center" => [6.5, 9.5, 12.5],+ "flex-end" => [10.0, 13.0, 16.0],+ "flex-between" => [3.0, 9.5, 16.0],+ "flex-around" => [4.5, 9.5, 14.5],+ _ => [5.0, 9.5, 14.0],+ };+ for x in xs {+ pen.frect(x, 7.5, x + 1.8, 12.5);+ }+ }+ "gap-h" => {+ pen.line(&[(3.0, 4.0), (3.0, 16.0)]);+ pen.line(&[(17.0, 4.0), (17.0, 16.0)]);+ pen.line(&[(5.5, 10.0), (14.5, 10.0)]);+ pen.line(&[(8.0, 7.5), (5.5, 10.0), (8.0, 12.5)]);+ pen.line(&[(12.0, 7.5), (14.5, 10.0), (12.0, 12.5)]);+ }+ "gap-v" => {+ pen.line(&[(4.0, 3.0), (16.0, 3.0)]);+ pen.line(&[(4.0, 17.0), (16.0, 17.0)]);+ pen.line(&[(10.0, 5.5), (10.0, 14.5)]);+ pen.line(&[(7.5, 8.0), (10.0, 5.5), (12.5, 8.0)]);+ pen.line(&[(7.5, 12.0), (10.0, 14.5), (12.5, 12.0)]);+ }+ "panel-flex" => {+ pen.rect(2.5, 3.5, 17.5, 16.5);+ pen.frect(5.0, 6.0, 8.5, 14.0);+ pen.frect(11.5, 6.0, 15.0, 14.0);+ pen.line(&[(8.5, 10.0), (11.5, 10.0)]);+ }+ // Pathfinder panel › Paths: a join point, a path opened and one closed, two opposed arrows.+ "path-join" => {+ pen.line(&[(3.0, 16.0), (5.0, 12.0), (10.0, 10.0)]);+ pen.line(&[(10.0, 10.0), (15.0, 8.0), (17.0, 4.0)]);+ pen.fcircle(10.0, 10.0, 2.2);+ }+ "path-open" | "path-close" => {+ let gap = if name == "path-open" { 0.9 } else { 0.0 };+ let n = 28;+ let pts: Vec<(f32, f32)> = (0..=n)+ .map(|i| {+ let a = -std::f32::consts::FRAC_PI_2 + gap / 2.0 + (std::f32::consts::TAU - gap) * i as f32 / n as f32;+ (10.0 + 6.5 * a.cos(), 10.5 + 6.5 * a.sin())+ })+ .collect();+ pen.line(&pts);+ if name == "path-open" {+ pen.frect(11.0, 2.5, 14.0, 5.5);+ pen.frect(6.0, 2.5, 9.0, 5.5);+ } else {+ pen.fcircle(10.0, 4.0, 1.8);+ }+ }+ "path-reverse" => {+ pen.line(&[(3.0, 7.0), (16.0, 7.0)]);+ pen.line(&[(13.0, 4.0), (16.5, 7.0), (13.0, 10.0)]);+ pen.line(&[(17.0, 13.0), (4.0, 13.0)]);+ pen.line(&[(7.0, 10.0), (3.5, 13.0), (7.0, 16.0)]);+ }+ // Pathfinder panel › Convert Shape: the shape outlined.+ "shape-rect" => pen.rect(3.0, 5.0, 17.0, 15.0),+ "shape-rounded" | "shape-beveled" | "shape-inverse" => {+ let (x0, y0, x1, y1, r): (f32, f32, f32, f32, f32) = (3.0, 5.0, 17.0, 15.0, 3.5);+ // Clockwise from the top left: each corner's two ends, and the centre of its arc+ // (inside for a rounded corner, the corner itself for an inverse rounded one).+ let corners = [+ ((x0, y0), (x0, y0 + r), (x0 + r, y0), (x0 + r, y0 + r)),+ ((x1, y0), (x1 - r, y0), (x1, y0 + r), (x1 - r, y0 + r)),+ ((x1, y1), (x1, y1 - r), (x1 - r, y1), (x1 - r, y1 - r)),+ ((x0, y1), (x0 + r, y1), (x0, y1 - r), (x0 + r, y1 - r)),+ ];+ let mut pts = Vec::new();+ for (corner, a, b, inner) in corners {+ if name == "shape-beveled" {+ pts.extend([a, b]);+ continue;+ }+ let c = if name == "shape-inverse" { corner } else { inner };+ let a0 = (a.1 - c.1).atan2(a.0 - c.0);+ let mut d = (b.1 - c.1).atan2(b.0 - c.0) - a0;+ if d > std::f32::consts::PI {+ d -= std::f32::consts::TAU;+ } else if d < -std::f32::consts::PI {+ d += std::f32::consts::TAU;+ }+ pts.extend((0..=6).map(|k| {+ let t = a0 + d * k as f32 / 6.0;+ (c.0 + r * t.cos(), c.1 + r * t.sin())+ }));+ }+ pen.closed(&pts);+ }+ "shape-ellipse" => pen.ellipse(10.0, 10.0, 7.5, 5.0),+ "shape-triangle" => pen.closed(&[(10.0, 3.5), (17.0, 16.0), (3.0, 16.0)]),+ "shape-polygon" => pen.closed(&[(6.5, 4.0), (13.5, 4.0), (17.0, 10.0), (13.5, 16.0), (6.5, 16.0), (3.0, 10.0)]),+ "shape-line" => pen.line(&[(4.0, 16.0), (16.0, 4.0)]),+ "shape-orthogonal" => {+ pen.line(&[(10.0, 3.0), (10.0, 17.0)]);+ pen.line(&[(3.0, 10.0), (17.0, 10.0)]);+ }+ // Pathfinder panel › Convert Point: a point on a path, with its direction handles.+ "point-plain" | "point-corner" | "point-smooth" | "point-symmetrical" => {+ match name {+ "point-plain" | "point-corner" => pen.line(&[(3.0, 16.0), (10.0, 8.0), (17.0, 16.0)]),+ _ => pen.line(&[(3.0, 16.0), (5.5, 11.5), (10.0, 8.0), (14.5, 11.5), (17.0, 16.0)]),+ }+ let handles: &[(f32, f32)] = match name {+ "point-corner" => &[(4.5, 4.0), (16.0, 5.0)],+ "point-smooth" => &[(5.0, 8.0), (17.5, 8.0)],+ "point-symmetrical" => &[(4.0, 8.0), (16.0, 8.0)],+ _ => &[],+ };+ for &(hx, hy) in handles {+ pen.line(&[(10.0, 8.0), (hx, hy)]);+ pen.fcircle(hx, hy, 1.4);+ }+ pen.frect(8.5, 6.5, 11.5, 9.5);+ }// ---- Properties panel glyphs (original drawings)+ "clock" => {+ pen.circle(10.0, 10.0, 7.5);+ pen.line(&[(10.0, 5.5), (10.0, 10.0), (13.5, 12.5)]);+ }+ "preset-save" => {+ pen.line(&[(3.0, 11.0), (3.0, 17.0), (17.0, 17.0), (17.0, 11.0)]);+ pen.line(&[(10.0, 3.0), (10.0, 13.0)]);+ pen.line(&[(6.5, 9.5), (10.0, 13.0), (13.5, 9.5)]);+ }"orient-portrait" => {pen.rect(5.5, 3.0, 14.5, 17.0);pen.fcircle(10.0, 8.0, 1.8);diff --cc crates/ui-egui/src/lib.rsindex 5d635ee7d,68f198b1d..0c4d7a408--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -319,9 -304,12 +320,15 @@@ pub struct UiStatepub palette: Option<String>,#[serde(skip)]pub flyout: Option<usize>,+ /// Type › Tabs: the selected stop and where the panel sits.+ #[serde(skip)]+ pub tabs_panel: panels::tabs::PanelState,+ /// The colour and gradient swatches applied last: what Apply Color (,) and Apply Gradient (.)+ /// apply again.+ #[serde(skip)]+ pub last_color: Option<String>,+ #[serde(skip)]+ pub last_gradient: Option<String>,/// Fill/Stroke proxy (Tools and Color panels): the stroke is in front, so Apply None and the/// Color panel act on it (X toggles).#[serde(skip)]@@@ -408,7 -391,8 +415,9 @@@ impl Default for UiStatedialog: None,palette: None,flyout: None,+ tabs_panel: Default::default(),+ last_color: None,+ last_gradient: None,stroke_front: false,}}@@@ -1700,52 -1547,17 +1717,63 @@@ pub fn drop_key_name_text(raw: &mut egumod tests {use super::*;+ /// The Control panel's two-row groups were centred as if they were one row tall, so the second+ /// row hung below the panel and was cut off.+ #[test]+ fn control_bar_shows_its_second_row() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default());+ app.run("file.newSample", json!({})).unwrap();+ app.ui.control_bar = true;+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ let bar = egui::containers::panel::PanelState::load(&h.ctx, egui::Id::new("control_bar")).unwrap().outer_rect;+ assert!(bar.height() > 40.0, "{bar:?}");+ // The X/Y/W/H group: its second row holds Y: and H:.+ let group = h.ctx.read_response(egui::Id::new(("object_control", "dimensions"))).unwrap().rect;+ assert!(bar.contains(group.left_top()), "the X/Y/W/H group {group:?} is in the Control panel {bar:?}");+ assert!(group.bottom() <= bar.bottom(), "X/Y/W/H group {group:?} hangs below the Control panel {bar:?}");+ }++ #[test]+ fn key_names_sent_as_text_are_dropped() {+ let text = |t: &str| egui::Event::Text(t.to_string());+ let events = || {+ vec![text("AltGraph"), text("é"), text("Dead"), text("A"), text("Unidentified"), text("ß"), text("AudioVolumeUp"), text("ab"), text("Æ")]+ };+ let mut raw = egui::RawInput { events: events(), ..Default::default() };+ drop_key_name_text(&mut raw, false);+ assert_eq!(raw.events, vec![text("é"), text("A"), text("ß"), text("ab"), text("Æ")]);+ assert!(is_key_name("F13") && is_key_name("Escape") && is_key_name("ZoomToggle") && !is_key_name("F") && !is_key_name("Fx"));+ // Capitalised words (mobile autocompletion) are text.+ let words = vec![text("Hello"), text("Tokyo"), text("OK"), text("Hi there")];+ let mut raw = egui::RawInput { events: words.clone(), ..Default::default() };+ drop_key_name_text(&mut raw, false);+ assert_eq!(raw.events, words);+ // A focused text field or a canvas text caret gets its text from the browser's input+ // events, which hold whole words, key-name-like ones too ("Help").+ let mut raw = egui::RawInput { events: events(), ..Default::default() };+ drop_key_name_text(&mut raw, true);+ assert_eq!(raw.events, events());+ }++ /// InDesign shows 100% K as pure black on screen unless Appearance of Black says otherwise+ /// (Display All Blacks as Rich Black is its default); settings saved without the field get it too.+ #[test]+ fn black_shows_as_rich_black_by_default() {+ assert!(UiState::default().rich_black);+ let saved: UiState = serde_json::from_str("{}").unwrap();+ assert!(saved.rich_black);+ let accurate: UiState = serde_json::from_str(r#"{"richBlack": false}"#).unwrap();+ assert!(!accurate.rich_black, "a saved choice is kept");+ }+/// An app with one document that has an unsaved edit.fn app_with_unsaved_document() -> DesignApp {let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default());diff --cc crates/ui-egui/src/menus.rsindex 4cb1b74e9,d6f313990..df44bfd5b--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -64,7 -40,7 +65,7 @@@ pub const UI_COMMANDS: &[(&str, &str, O"app.language","Interface Language",None,- "{lang?: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ru|cs} — menus and panel names (the macOS menu bar follows at once); without lang, opens Preferences, where it is the first setting",- "{lang: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ka} — menus and panel names (the macOS menu bar follows on the next launch)",++ "{lang?: \"\"|de|fr|es|ja|zh|ar|pt-br|it|uk|ru|cs|pl|ka} — menus and panel names (the macOS menu bar follows at once); without lang, opens Preferences, where it is the first setting",),("app.flattener",@@@ -120,7 -76,12 +121,13 @@@("app.deletePage", "Delete Page", None, "{} — deletes the page in view"),("app.duplicateSpread", "Duplicate Spread", None, "{} — duplicates the spread in view (pages and items)"),("app.tablePanel", "Table Panel", Some("Shift+F9"), "{}"),+ ("app.tabsPanel", "Tabs", Some("Cmd+Shift+T"), "{} — show or hide the Tabs panel (it opens above the selected text frame)"),+ ("app.characterPanel", "Character", Some("Cmd+T"), "{} — the Character panel"),+ ("app.paragraphPanel", "Paragraph", Some("Cmd+Alt+T"), "{} — the Paragraph panel"),+ ("app.glyphsPanel", "Glyphs", Some("Alt+Shift+F11"), "{} — the Glyphs panel"),+ ("app.characterStylesPanel", "Character Styles", Some("Cmd+Shift+F11"), "{} — the Character Styles panel"),+ ("app.paragraphStylesPanel", "Paragraph Styles", Some("Cmd+F11"), "{} — the Paragraph Styles panel"),+ ("app.insertCurrentPageNumber", "Current Page Number", Some("Cmd+Alt+Shift+N"), "{} — the Current Page Number marker at the insertion point"),("app.storyEditor", "Edit in Story Editor", Some("Cmd+Y"), "{story?}"),("view.zoomIn", "Zoom In", Some("Cmd+="), "{}"),("view.zoomOut", "Zoom Out", Some("Cmd+-"), "{}"),@@@ -154,15 -109,17 +161,22 @@@"color.swapFillStroke","Swap Fill and Stroke",Some("Shift+X"),- "{} — each selected object's fill and stroke colours (and tints) trade places (object.swapFillStroke)",+ "{} — each selected object's fill and stroke colours (and tints) trade places (object.swapFillStroke), or the text's with Formatting Affects Text",),("color.toggleFillStroke", "Toggle Fill and Stroke", Some("X"), "{} → {strokeFront} — which of fill and stroke the proxy has in front"),- ("color.applyNone", "Apply None", Some("/"), "{} — [None] for the fill or stroke in front of the proxy"),+ (+ "color.applyNone",+ "Apply None",+ Some("/"),+ "{} — [None] for the fill or stroke in front of the proxy, of the objects or the text (Formatting Affects Text)",+ ),+ ("color.applyColor", "Apply Color", Some(","), "{} — the colour applied last ([Black] at first) to the fill or stroke in front of the proxy"),+ (+ "color.applyGradient",+ "Apply Gradient",+ Some("."),+ "{} — the gradient applied last (else the document's first, else white to black) to the fill or stroke in front of the proxy",+ ),("view.frameEdges", "Show/Hide Frame Edges", Some("Cmd+H"), "{}"),("view.rulers", "Show/Hide Rulers", Some("Cmd+R"), "{}"),("view.guides", "Show/Hide Guides", Some("Cmd+;"), "{}"),@@@ -176,9 -133,8 +190,9 @@@"{alignEdges?, alignCenters?, smartDimensions?, smartSpacing?: bool, zone?: px} — what smart guides snap to and how close; returns the current values",),("view.baselineGrid", "Show/Hide Baseline Grid", Some("Cmd+Alt+'"), "{}"),+ ("view.documentGrid", "Show/Hide Document Grid", Some("Cmd+'"), "{}"),("view.textThreads", "Show/Hide Text Threads", Some("Cmd+Alt+Y"), "{}"),- ("view.hiddenCharacters", "Show/Hide Hidden Characters", Some("Cmd+Alt+I"), "{}"),+ ("view.hiddenCharacters", "Show Hidden Characters", Some("Cmd+Alt+I"), "{}"),("view.taggedFrames", "Show/Hide Tagged Frames", None, "{} — XML-tagged frames outlined in their tag colour"),("window.hidePanels", "Show/Hide Panels", Some("Tab"), "{} — every panel, the Tools panel included"),("window.hidePanelsExceptTools", "Show/Hide Panels Except Tools", Some("Shift+Tab"), "{}"),@@@ -399,12 -353,40 +414,41 @@@ pub const MENUS: &[(&str, &[&str])] = &("Type",&[- "ui:app.findFontDialog",+ ">Size",+ "cmd:type.char|6 pt|{\"attrs\": {\"size\": 6}}",+ "cmd:type.char|7 pt|{\"attrs\": {\"size\": 7}}",+ "cmd:type.char|8 pt|{\"attrs\": {\"size\": 8}}",+ "cmd:type.char|9 pt|{\"attrs\": {\"size\": 9}}",+ "cmd:type.char|10 pt|{\"attrs\": {\"size\": 10}}",+ "cmd:type.char|11 pt|{\"attrs\": {\"size\": 11}}",+ "cmd:type.char|12 pt|{\"attrs\": {\"size\": 12}}",+ "cmd:type.char|14 pt|{\"attrs\": {\"size\": 14}}",+ "cmd:type.char|18 pt|{\"attrs\": {\"size\": 18}}",+ "cmd:type.char|24 pt|{\"attrs\": {\"size\": 24}}",+ "cmd:type.char|30 pt|{\"attrs\": {\"size\": 30}}",+ "cmd:type.char|36 pt|{\"attrs\": {\"size\": 36}}",+ "cmd:type.char|48 pt|{\"attrs\": {\"size\": 48}}",+ "cmd:type.char|60 pt|{\"attrs\": {\"size\": 60}}",+ "cmd:type.char|72 pt|{\"attrs\": {\"size\": 72}}",+ "<",+ "-",+ "ui:app.characterPanel",+ "ui:app.paragraphPanel",++ "ui:app.tabsPanel",+ "ui:app.glyphsPanel",+ "-",+ "ui:app.characterStylesPanel",+ "ui:app.paragraphStylesPanel","-","cmd:type.createOutlines",- ">Bulleted and Numbered Lists",- "cmd:list.define",+ "ui:app.findFontDialog",+ ">Change Case",+ "cmd:type.changeCase|UPPERCASE|{\"case\": \"upper\"}",+ "cmd:type.changeCase|lowercase|{\"case\": \"lower\"}",+ "cmd:type.changeCase|Title Case|{\"case\": \"title\"}",+ "cmd:type.changeCase|Sentence case|{\"case\": \"sentence\"}","<",+ "-",">Type on a Path","cmd:type.pathOptions","cmd:type.pathOptions|Delete Type from Path|{\"delete\": true}",@@@ -826,7 -794,7 +862,8 @@@"ui:window.panel|Glyphs|{\"panel\": \"glyphs\"}","ui:window.panel|Paragraph|{\"panel\": \"paragraph\"}","ui:window.panel|Table|{\"panel\": \"table\"}",+ "ui:app.tabsPanel",+ "ui:window.panel|Typography|{\"panel\": \"typography\"}","<",">Utilities","ui:window.panel|Book|{\"panel\": \"book\"}",@@@ -880,22 -848,17 +917,31 @@@ pub fn ui_label(id: &str) -> Option<(&'UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| (c.1, c.2))}+/// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.+fn toggle_tabs_panel(app: &mut DesignApp) {+ if app.ui.floating.iter().any(|(p, _)| p == "tabs") {+ crate::dock::dock_panel(app, "tabs");+ } else {+ let at = app.canvas_rect.map_or(egui::pos2(300.0, 140.0), |r| r.min + egui::vec2(80.0, 60.0));+ crate::dock::float_panel(app, "tabs", at);+ app.ui.tabs_panel.snap_request = 2;+ }+}+/// Run a UI command; `None` if `id` isn't one.pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");+ let result = run_ui_inner(app, id, p);+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {+ app.session.reset_find_scope();+ }+ result+ }++ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value, String>> {+ if matches!(id, "window.minimize" | "window.maximize" | "window.close" | "window.drag" | "window.resize") && !app.custom_titlebar {+ return Some(Err("custom window controls are not available in this host".into()));+ }if let Some(result) = crate::panel_docking::command(app, id, p) {return Some(result);}@@@ -2302,13 -2059,14 +2363,21 @@@ pub fn activate(app: &mut DesignApp, idif waits_for_ime(app, id) {return;}+ let was_find = app.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange");+ activate_inner(app, id, params);+ if was_find && app.ui.dialog.as_ref().is_none_or(|d| d.id != "findChange") {+ app.session.reset_find_scope();+ }+ }++ fn activate_inner(app: &mut DesignApp, id: &str, params: &Value) {+ // Object › Effects › Drop Shadow… (and its shortcut): the Effects dialog on that page.+ if params.is_null()+ && let Some(page) = crate::effects_dialog::page_of_command(id)+ {+ crate::effects_dialog::open(app, page);+ return;+ }if params.is_null() && id == "file.close" {close_document(app, None);return;@@@ -2325,10 -2083,14 +2394,18 @@@crate::dialogs::open_print(app);return;}+ if params.is_null() && id == "layout.section" {+ crate::section_options::open(app);+ return;+ }+ if params.is_null() && id == "layout.createGuides" {+ crate::dialogs::open_create_guides(app);+ return;+ }+ if params.is_null() && id == "layout.marginsAndColumns" {+ crate::dialogs::open_margins_and_columns(app);+ return;+ }if params.is_null() && id == "object.textFrameOptions" {app.ui.dialog = Some(crate::dialogs::Dialog::new("textFrameOptions", json!({})));return;@@@ -3677,7 -3124,7 +3794,7 @@@ mod testscrate::dialogs::confirm(&mut app).unwrap();frame(&mut app);assert_eq!(app.session.documents().len(), 1);- for lang in ["uk", "ru", "zh", "", "ar", "pt-br", "it", "cs", "pl"] {- for lang in ["uk", "zh", "", "ar", "pt-br", "it", "ka"] {++ for lang in ["uk", "ru", "zh", "", "ar", "pt-br", "it", "cs", "pl", "ka"] {app.run("app.language", json!({"lang": lang})).unwrap();frame(&mut app);}@@@ -4471,23 -3862,91 +4613,109 @@@assert!(all.iter().any(|(l, id, _)| l == "Fill Frame Proportionally" && id == "fit.fillFrameProportionally"));}+ #[test]+ fn context_menus_hold_commands_and_menu_bar_submenus() {+ let tree = menu_tree();+ for entries in [CONTEXT_OBJECT, CONTEXT_GRAPHIC_FRAME, CONTEXT_OBJECT_TAIL, CONTEXT_TEXT_FRAME, CONTEXT_TEXT, CONTEXT_CANVAS] {+ for path in entries.iter().filter_map(|e| e.strip_prefix("menu:")) {+ assert!(menu_bar_submenu(&tree, path).is_some(), "no menu bar submenu {path}");+ }+ let mut all = Vec::new();+ for (_, items) in context_parse(entries) {+ walk(&items, &mut all);+ }+ for (label, id, _) in &all {+ assert!(ui_label(id).is_some() || designcraft_engine::find_command(id).is_some(), "context entry {label}: unknown command {id}");+ }+ }+ }++ #[test]+ fn the_type_menu_follows_indesigns_order() {+ // InDesign's Type menu, as Chris Nielsen opens it in "Numbering Page Sections" (2:09).+ let ty = menu_tree().into_iter().find(|(m, _)| *m == "Type").unwrap().1;+ let labels: Vec<String> = ty+ .iter()+ .map(|i| match i {+ Item::Sep => "-".to_string(),+ Item::Sub(n, _) => format!("{n} >"),+ Item::Cmd { label, .. } => label.clone(),+ })+ .collect();+ let expected = [+ "Size >",+ "-",+ "Character",+ "Paragraph",++ "Tabs",+ "Glyphs",+ "-",+ "Character Styles",+ "Paragraph Styles",+ "-",+ "Create Outlines",+ "Find/Replace Font…",+ "Change Case >",+ "-",+ "Type on a Path >",+ "-",+ "Notes >",+ "Track Changes >",+ "-",+ "Insert Footnote",+ "Document Footnote Options…",+ "Insert Endnote",+ ];+ assert_eq!(&labels[..expected.len()], expected, "{labels:?}");+ let pos = |l: &str| labels.iter().position(|x| x == l).unwrap_or_else(|| panic!("{l} in {labels:?}"));+ assert!(pos("Hyperlinks & Cross-References >") < pos("Text Variables >"));+ assert!(pos("Text Variables >") < pos("Bulleted & Numbered Lists >"));+ assert!(pos("Bulleted & Numbered Lists >") < pos("Insert Special Character >"));+ assert!(pos("Insert Special Character >") < pos("Insert White Space >"));+ assert!(pos("Insert Break Character >") < pos("Fill with Placeholder Text"));+ assert!(pos("Fill with Placeholder Text") < pos("Show Hidden Characters"));+ // Alignment, styles and point sizes keep their shortcuts, out of the menu as in InDesign.+ for gone in ["Align Left", "Bold", "Increase Point Size", "Paragraph Rules…"] {+ assert!(!labels.iter().any(|l| l == gone), "{gone}");+ }+ let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let all = effective_shortcuts(&app);+ for (id, sc) in [+ ("type.alignLeft", "Cmd+Shift+L"),+ ("app.characterPanel", "Cmd+T"),+ ("app.paragraphPanel", "Cmd+Alt+T"),+ ("app.insertCurrentPageNumber", "Cmd+Alt+Shift+N"),+ ] {+ assert_eq!(all.iter().find(|(i, _)| i == id).map(|(_, s)| s.as_str()), Some(sc), "{id}");+ }+ // Markers › Current Page Number carries ⌥⇧⌘N.+ let markers = ty+ .iter()+ .find_map(|i| match i {+ Item::Sub(n, c) if n == "Insert Special Character" => {+ c.iter().find_map(|i| if let Item::Sub(n, c) = i { (n == "Markers").then(|| c.clone()) } else { None })+ }+ _ => None,+ })+ .unwrap();+ assert!(matches!(&markers[0], Item::Cmd { label, shortcut: Some("Cmd+Alt+Shift+N"), .. } if label == "Current Page Number"));+ }++ #[test]+ fn type_panel_items_open_their_panels_and_the_marker_shortcut_inserts_a_page_number() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ activate(&mut app, "app.characterPanel", &Value::Null);+ assert_eq!(app.ui.open_panel.as_deref(), Some("character"));+ activate(&mut app, "app.paragraphStylesPanel", &Value::Null);+ assert_eq!(app.ui.open_panel.as_deref(), Some("paragraphStyles"));+ let story = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "Page "})).unwrap()["story"].clone();+ app.run("text.select", json!({"story": story, "anchor": 5, "focus": 5})).unwrap();+ activate(&mut app, "app.insertCurrentPageNumber", &Value::Null);+ let d = &app.session.doc().unwrap().doc;+ assert_eq!(d.story(designcraft_doc::StoryId(story.as_u64().unwrap())).unwrap().text, "Page \u{e000}");+ }+#[test]fn custom_workspaces_save_apply_and_delete() {let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());diff --cc crates/ui-egui/src/panels/layers.rsindex d391e7a59,aa857c5ed..0ce122a0f--- a/crates/ui-egui/src/panels/layers.rs+++ b/crates/ui-egui/src/panels/layers.rs@@@ -105,221 -102,10 +109,250 @@@ fn selection_square} else if resp.hovered() {ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Inside);}+ let tip = if selected && !small { "Select; drag to move the selection to another layer" } else { "Select" };resp.on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(language, "Select"));+ crate::rtl::label(ui, crate::i18n::tr(language, tip));})- .clicked()+}++/// What a drag in the Layers panel carries.+#[derive(Clone, Debug, PartialEq)]+enum LayersDrag {+ Layer(LayerId),+ /// Objects that share one parent: the spread (`group: None`) or a group.+ Objects {+ ids: Vec<ItemId>,+ group: Option<ItemId>,+ },+ /// The selected objects, from a layer's selection square.+ Selection,+}++/// Where a drag would land.+#[derive(Clone, Copy, Debug, PartialEq)]+enum DropAt {+ /// The layer slot at this index of `doc.layers` (0 = top).+ LayerSlot(usize),+ /// Onto a layer: to the top of its stack.+ OntoLayer(LayerId),+ /// In front of (`above`) or behind an object.+ Object { id: ItemId, above: bool },+}++enum RowKind {+ Layer,+ Object { id: ItemId, group: Option<ItemId> },+}++/// A laid-out row, for drop targeting.+struct Row {+ rect: Rect,+ layer: LayerId,+ /// Index of `layer` in `doc.layers`.+ layer_index: usize,+ /// The layer is locked or hidden.+ closed: bool,+ kind: RowKind,+ /// Bottom of the row's block: the last row of an open layer or group, else the row itself.+ end: f32,+}++enum Indicator {+ Line(f32),+ Box(Rect),+}++/// The drop for `drag` with the pointer at `p`, and how to show it. `None` where it can't land.+/// Objects land on a locked or hidden layer only with `force` (Cmd/Ctrl held).+fn drop_target(drag: &LayersDrag, rows: &[Row], p: egui::Pos2, force: bool) -> Option<(DropAt, Indicator)> {+ let r = rows.iter().find(|r| r.rect.contains(p))?;+ let header = rows.iter().find(|h| h.layer == r.layer && matches!(h.kind, RowKind::Layer))?;+ if r.closed && !force && !matches!(drag, LayersDrag::Layer(_)) {+ return None;+ }+ match drag {+ LayersDrag::Layer(src) => {+ let before = p.y < (header.rect.min.y + header.end) / 2.0;+ let slot = if before { r.layer_index } else { r.layer_index + 1 };+ let from = rows.iter().find(|h| h.layer == *src && matches!(h.kind, RowKind::Layer))?.layer_index;+ if slot == from || slot == from + 1 {+ return None;+ }+ Some((DropAt::LayerSlot(slot), Indicator::Line(if before { header.rect.min.y } else { header.end })))+ }+ LayersDrag::Selection => Some((DropAt::OntoLayer(r.layer), Indicator::Box(header.rect))),+ LayersDrag::Objects { ids, group } => match r.kind {+ RowKind::Layer if group.is_none() => Some((DropAt::OntoLayer(r.layer), Indicator::Box(r.rect))),+ RowKind::Object { id, group: g } if g == *group && !ids.contains(&id) => {+ let above = p.y < r.rect.center().y;+ Some((DropAt::Object { id, above }, Indicator::Line(if above { r.rect.min.y } else { r.end })))+ }+ _ => None,+ },+ }+}++/// The command a drop runs.+fn drop_command(drag: &LayersDrag, at: DropAt, doc: &Document, selected: &[ItemId]) -> Option<(&'static str, serde_json::Value)> {+ let ids = |ids: &[ItemId]| ids.iter().map(|i| i.0).collect::<Vec<_>>();+ match (drag, at) {+ (LayersDrag::Layer(id), DropAt::LayerSlot(slot)) => {+ let from = doc.layers.iter().position(|l| l.id == *id)?;+ let to = if slot > from { slot - 1 } else { slot };+ Some(("layer.move", json!({"id": id.0, "to": to})))+ }+ (LayersDrag::Selection, DropAt::OntoLayer(l)) => {+ // Group members move with their group.+ let mut tops: Vec<ItemId> = Vec::new();+ for t in selected.iter().filter_map(|i| doc.top_level_of(*i)) {+ if !tops.contains(&t) {+ tops.push(t);+ }+ }+ let moves = tops.iter().any(|i| doc.item(*i).is_some_and(|it| it.layer != l));+ moves.then(|| ("object.setLayer", json!({"layer": l.0, "ids": ids(&tops)})))+ }+ (LayersDrag::Objects { ids: o, .. }, DropAt::OntoLayer(l)) => Some(("object.reorder", json!({"ids": ids(o), "layer": l.0, "index": 0}))),+ (LayersDrag::Objects { ids: o, .. }, DropAt::Object { id, above }) => {+ Some(("object.reorder", json!({"ids": ids(o), if above { "above" } else { "below" }: id.0})))+ }+ _ => None,+ }+}++/// Nesting limit for listing group members.+const MAX_DEPTH: usize = 32;++/// Per-frame inputs shared by the object rows.+struct Listing<'a> {+ doc: &'a Document,+ language: &'a str,+ selected: &'a [ItemId],++ /// The top-level objects of the selection (see `show`).++ shown: &'a [ItemId],++ /// A new selection: its first row scrolls into view.++ reveal: bool,++ scrolled: &'a std::cell::Cell<bool>,+ layer: LayerId,+ layer_index: usize,+ layer_color: Color32,+ layer_visible: bool,+ layer_closed: bool,+}++/// Rows for `items` (topmost first) under `group` at `depth`; the commands their clicks run go+/// to `cmds`.+fn object_rows(+ ui: &mut Ui,+ ls: &Listing,+ items: &[std::sync::Arc<Item>],+ group: Option<ItemId>,+ depth: usize,+ rows: &mut Vec<Row>,+ cmds: &mut Vec<(&'static str, serde_json::Value)>,+) {+ let t = Tokens::get(ui.ctx());+ for it in items.iter().rev() {+ let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click_and_drag());+ let is_sel = ls.selected.contains(&it.id);- if resp.hovered() {++ if is_sel || ls.shown.contains(&it.id) {++ ui.painter().rect_filled(row, 0.0, t.row_selected);++ if ls.reveal && !ls.scrolled.get() {++ resp.scroll_to_me(Some(egui::Align::Center));++ ls.scrolled.set(true);++ }++ } else if resp.hovered() {+ ui.painter().rect_filled(row, 0.0, t.hover);+ }+ let (eye, lock) = eye_lock(ui, ls.language, row, !it.hidden, it.locked, !ls.layer_visible, ("item", it.id.0));+ let indent = 14.0 * depth as f32;+ let expandable = !it.children().is_empty() && it.states.is_empty() && depth < MAX_DEPTH;+ let open_id = egui::Id::new(("group_open", it.id.0));+ let open = expandable && ui.data(|d| d.get_temp(open_id)).unwrap_or(false);+ let mut tri_clicked = false;+ if expandable {+ let tri = Rect::from_min_size(row.min + vec2(2.0 * COL_W + 14.0 + indent, 0.0), vec2(14.0, ROW_H));+ disclosure(ui, tri, open, t.icon);+ tri_clicked = ui.interact(tri, ui.id().with(("gtri", it.id.0)), Sense::click()).clicked();+ }+ let name = item_label(ls.doc, it);- let clip = Rect::from_min_max(row.min, pos2(row.max.x - 26.0, row.max.y));- ui.painter().with_clip_rect(clip).text(- row.min + vec2(2.0 * COL_W + 30.0 + indent, ROW_H / 2.0),- egui::Align2::LEFT_CENTER,- &name,- egui::FontId::proportional(11.0),- if it.hidden { t.text_dim } else { t.text },- );++ let field = Rect::from_min_max(row.min + vec2(2.0 * COL_W + 28.0 + indent, 3.0), pos2(row.max.x - 28.0, row.max.y - 3.0));++ let renaming = match rename_field(ui, field, it.id.0) {++ // An empty name goes back to the automatic label.++ Some(Some(new)) => {++ if new != it.name {++ cmds.push(("object.rename", json!({"id": it.id.0, "name": new})));++ }++ false++ }++ Some(None) => false,++ None => ui.data(|d| d.get_temp::<RenameState>(egui::Id::new(RENAME))).is_some_and(|(k, ..)| k == it.id.0),++ };++ if !renaming {++ let clip = Rect::from_min_max(row.min, pos2(row.max.x - 26.0, row.max.y));++ ui.painter().with_clip_rect(clip).text(++ row.min + vec2(2.0 * COL_W + 30.0 + indent, ROW_H / 2.0),++ egui::Align2::LEFT_CENTER,++ &name,++ egui::FontId::proportional(11.0),++ if it.hidden { t.text_dim } else { t.text },++ );++ }+ let sq = selection_square(ui, ls.language, row, ls.layer_color, is_sel, true, ("item", it.id.0)).clicked();+ // Dragging a selected row drags the selected objects that share its parent (top-level+ // rows: those on this layer).+ let dragged: Vec<ItemId> = if is_sel {+ let siblings: &[std::sync::Arc<Item>] = items;+ siblings.iter().map(|i| i.id).filter(|i| ls.selected.contains(i)).collect()+ } else {+ vec![it.id]+ };+ resp.dnd_set_drag_payload(LayersDrag::Objects { ids: dragged, group });+ if resp.dragged() {+ super::pages::drag_ghost(ui, &name, &t);+ }+ if eye {+ cmds.push(("object.setFlags", json!({"ids": [it.id.0], "hidden": !it.hidden})));+ } else if lock {+ cmds.push(("object.setFlags", json!({"ids": [it.id.0], "locked": !it.locked})));+ } else if tri_clicked {+ ui.data_mut(|d| d.insert_temp(open_id, !open));++ } else if resp.double_clicked() {++ // Its own name, or the label it shows without the brackets.++ let current = if it.name.is_empty() { name.trim_start_matches('<').trim_end_matches('>').to_string() } else { it.name.clone() };++ start_rename(ui, it.id.0, ¤t);+ } else if sq || resp.clicked() {+ let add = ui.input(|i| i.modifiers.shift || i.modifiers.command);+ cmds.push(("selection.set", json!({"ids": [it.id.0], "add": add})));+ }+ let at = rows.len();+ rows.push(Row {+ rect: row,+ layer: ls.layer,+ layer_index: ls.layer_index,+ closed: ls.layer_closed,+ kind: RowKind::Object { id: it.id, group },+ end: row.max.y,+ });+ if open {+ object_rows(ui, ls, it.children(), Some(it.id), depth + 1, rows, cmds);+ let end = rows.last().map_or(row.max.y, |r| r.end.max(r.rect.max.y));+ if let Some(r) = rows.get_mut(at) {+ r.end = end;+ }+ }+ }+}++/// A disclosure triangle in `r`: pointing down when open.+fn disclosure(ui: &Ui, r: Rect, open: bool, color: Color32) {+ let c = r.center();+ let pts = if open {+ vec![c + vec2(-4.0, -2.0), c + vec2(4.0, -2.0), c + vec2(0.0, 3.0)]+ } else {+ vec![c + vec2(-2.0, -4.0), c + vec2(3.0, 0.0), c + vec2(-2.0, 4.0)]+ };+ ui.painter().add(egui::Shape::convex_polygon(pts, color, Stroke::NONE));}pub fn show(app: &mut DesignApp, ui: &mut Ui) {@@@ -329,21 -115,29 +362,34 @@@let active = st.active_layer;let selected: Vec<ItemId> = st.selection.items.clone();let sel_layers: Vec<_> = selected.iter().filter_map(|i| doc.item(*i).map(|it| it.layer)).collect();- // The rows stand for top-level objects: an object selected inside a group shows as its group.+ let language = app.ui.language.clone();++ // The rows a selection reveals: an object selected inside a closed group shows as its group.+ let shown: Vec<ItemId> = selected.iter().map(|i| doc.top_level_of(*i).unwrap_or(*i)).collect();+ // A new selection (made on the canvas or anywhere else) is revealed: its layer opens and its row+ // scrolls into view, once, so the panel can still be scrolled and closed freely afterwards.+ let last_id = egui::Id::new("layers_revealed_selection");+ let now: Vec<u64> = shown.iter().map(|i| i.0).collect();+ let reveal = !now.is_empty() && ui.data(|d| d.get_temp::<Vec<u64>>(last_id)).as_ref() != Some(&now);+ ui.data_mut(|d| d.insert_temp(last_id, now));- let mut scrolled = false;- // Objects on the current spread, topmost first.++ let scrolled = std::cell::Cell::new(false);+ // Objects on the current spread, back to front.let cur = crate::canvas::current_page(app).unwrap_or(0);let spread_items: Vec<std::sync::Arc<Item>> =- doc.page_loc(cur).and_then(|(si, _)| doc.spreads.get(si)).map(|sp| sp.items.iter().rev().cloned().collect()).unwrap_or_default();+ doc.page_loc(cur).and_then(|(si, _)| doc.spreads.get(si)).map(|sp| sp.items.clone()).unwrap_or_default();+ let mut rows: Vec<Row> = Vec::new();+ let mut cmds: Vec<(&'static str, serde_json::Value)> = Vec::new();ui.spacing_mut().item_spacing.y = 0.0;- for l in doc.layers.iter().rev() {+ // `doc.layers` runs top (frontmost) to bottom, as the panel lists them.+ for (li, l) in doc.layers.iter().enumerate() {let open_id = egui::Id::new(("layer_open", l.id.0));- let open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(l.id == active);+ let mut open: bool = ui.data(|d| d.get_temp(open_id)).unwrap_or(l.id == active);+ if reveal && sel_layers.contains(&l.id) && !open {+ open = true;+ ui.data_mut(|d| d.insert_temp(open_id, true));+ }let lc = c32(l.color);- let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());+ let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click_and_drag());+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &l.name));if l.id == active {ui.painter().rect_filled(row, 0.0, t.row_selected);} else if resp.hovered() {@@@ -431,43 -216,54 +477,46 @@@if !open {continue;}- for it in spread_items.iter().filter(|i| i.layer == l.id) {- let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());- let is_sel = shown.contains(&it.id);- if is_sel {- ui.painter().rect_filled(row, 0.0, t.row_selected);- if reveal && !scrolled {- resp.scroll_to_me(Some(egui::Align::Center));- scrolled = true;- }- } else if resp.hovered() {- ui.painter().rect_filled(row, 0.0, t.hover);+ // The layer's objects keep their spread order; the panel lists them topmost first.+ let on_layer: Vec<std::sync::Arc<Item>> = spread_items.iter().filter(|i| i.layer == l.id).cloned().collect();+ let ls = Listing {+ doc: &doc,+ language: &language,+ selected: &selected,++ shown: &shown,++ reveal,++ scrolled: &scrolled,+ layer: l.id,+ layer_index: li,+ layer_color: lc,+ layer_visible: l.visible,+ layer_closed: l.locked || !l.visible,+ };+ object_rows(ui, &ls, &on_layer, None, 0, &mut rows, &mut cmds);+ let end = rows.last().map_or(row.max.y, |r| r.end.max(r.rect.max.y));+ if let Some(r) = rows.get_mut(at) {+ r.end = end;+ }+ }+ // Drag and drop: an indicator line between rows (a box around a layer row) while dragging;+ // one command on release.+ if let Some(drag) = egui::DragAndDrop::payload::<LayersDrag>(ui.ctx())+ && let Some(p) = ui.ctx().pointer_latest_pos()+ && let Some((at, indicator)) = drop_target(&drag, &rows, p, ui.input(|i| i.modifiers.command))+ {+ let x = ui.max_rect().x_range();+ match indicator {+ Indicator::Line(y) => {+ ui.painter().line_segment([pos2(x.min, y), pos2(x.max, y)], Stroke::new(2.0, t.accent));}- let (eye, lock) = eye_lock(ui, &app.ui.language, row, !it.hidden, it.locked, !l.visible, ("item", it.id.0));- let name = item_label(&doc, it);- let field = Rect::from_min_max(row.min + vec2(2.0 * COL_W + 28.0, 3.0), pos2(row.max.x - 28.0, row.max.y - 3.0));- let renaming = match rename_field(ui, field, it.id.0) {- // An empty name goes back to the automatic label.- Some(Some(new)) => {- if new != it.name {- let _ = app.run("object.rename", json!({"id": it.id.0, "name": new}));- }- false- }- Some(None) => false,- None => ui.data(|d| d.get_temp::<RenameState>(egui::Id::new(RENAME))).is_some_and(|(k, ..)| k == it.id.0),- };- if !renaming {- let clip = Rect::from_min_max(row.min, pos2(row.max.x - 26.0, row.max.y));- ui.painter().with_clip_rect(clip).text(- row.min + vec2(2.0 * COL_W + 30.0, ROW_H / 2.0),- egui::Align2::LEFT_CENTER,- &name,- egui::FontId::proportional(11.0),- if it.hidden { t.text_dim } else { t.text },- );+ Indicator::Box(r) => {+ ui.painter().rect_stroke(r, 0.0, Stroke::new(2.0, t.accent), StrokeKind::Inside);}- let sq = selection_square(ui, &app.ui.language, row, lc, is_sel, true, ("item", it.id.0));- if eye {- let _ = app.run("object.setFlags", json!({"ids": [it.id.0], "hidden": !it.hidden}));- } else if lock {- let _ = app.run("object.setFlags", json!({"ids": [it.id.0], "locked": !it.locked}));- } else if resp.double_clicked() {- // Its own name, or the label it shows without the brackets.- let current = if it.name.is_empty() { name.trim_start_matches('<').trim_end_matches('>').to_string() } else { it.name.clone() };- start_rename(ui, it.id.0, ¤t);- } else if sq || resp.clicked() {- let add = ui.input(|i| i.modifiers.shift || i.modifiers.command);- let _ = app.run("selection.set", json!({"ids": [it.id.0], "add": add}));+ }+ if ui.input(|i| i.pointer.any_released()) {+ egui::DragAndDrop::clear_payload(ui.ctx());+ if let Some(c) = drop_command(&drag, at, &doc, &selected) {+ cmds.push(c);}}}@@@ -516,108 -353,80 +609,185 @@@ mod testsassert_eq!(item_label(doc, rr), "<rectangle>");}+ /// The panel alone, 304 pt wide; rows start at (8, 8).+ fn panel(app: DesignApp) -> egui_kittest::Harness<'static, DesignApp> {+ let mut h = egui_kittest::Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui), app);+ h.run_steps(2);+ h+ }++ /// The point `y` of the way down row `i`, in the name column (or at the selection square).+ fn row(i: usize, y: f32, square: bool) -> egui::Pos2 {+ pos2(if square { 300.0 } else { 150.0 }, 8.0 + ROW_H * (i as f32 + y))+ }++ fn drag(h: &mut egui_kittest::Harness<'static, DesignApp>, from: egui::Pos2, to: egui::Pos2) {+ h.hover_at(from);+ h.run_steps(1);+ h.drag_at(from);+ h.run_steps(1);+ for k in 1..=6 {+ h.hover_at(from.lerp(to, k as f32 / 6.0));+ h.run_steps(1);+ }+ h.drop_at(to);+ h.run_steps(3);+ }++ fn app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app+ }++ fn layers(app: &DesignApp) -> Vec<String> {+ app.session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect()+ }++ #[test]+ fn dragging_a_layer_row_below_another_reorders_the_layers() {+ let mut app = app();+ app.run("layer.new", json!({"name": "Art"})).unwrap();+ assert_eq!(layers(&app), ["Art", "Layer 1"]);+ let mut h = panel(app);+ // Art (open, no objects) is row 0, Layer 1 row 1: drop on Layer 1's lower half.+ drag(&mut h, row(0, 0.5, false), row(1, 0.8, false));+ assert_eq!(layers(h.state()), ["Layer 1", "Art"]);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(layers(h.state()), ["Art", "Layer 1"], "one undo step");+ }++ #[test]+ fn dragging_objects_and_the_selection_square_moves_them_between_layers() {+ let mut app = app();+ let l1 = app.session.active().unwrap().active_layer;+ let a = app.run("frame.create", json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap();+ let art = LayerId(app.run("layer.new", json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap());+ let x = app.run("frame.create", json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": []})).unwrap();+ let mut h = panel(app);+ let layer_of =+ |h: &egui_kittest::Harness<'static, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(ItemId(id)).unwrap().layer;+ // Rows: Art, x, Layer 1 (closed). Open Layer 1: Art, x, Layer 1, a.+ click(&mut h, pos2(8.0 + 2.0 * COL_W + 9.0, row(2, 0.5, false).y));+ // x dropped on the lower half of a goes behind it on Layer 1.+ drag(&mut h, row(1, 0.5, false), row(3, 0.8, false));+ assert_eq!(layer_of(&h, x), l1);+ let order: Vec<u64> = h.state().session.active().unwrap().doc.spreads[0].items.iter().map(|i| i.id.0).collect();+ assert_eq!(order, [x, a], "x is behind a");+ // Rows: Art, Layer 1, a, x. Select x and drag Layer 1's selection square onto Art.+ h.state_mut().run("selection.set", json!({"ids": [x]})).unwrap();+ h.run_steps(2);+ drag(&mut h, row(1, 0.5, true), row(0, 0.5, false));+ assert_eq!(layer_of(&h, x), art);+ assert_eq!(layer_of(&h, a), l1);+ }++ #[test]+ fn locked_layers_take_drops_with_cmd_and_group_members_move_with_their_group() {+ let mut app = app();+ let l1 = app.session.active().unwrap().active_layer;+ let a = app.run("frame.create", json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [0, 0, 10, 10]})).unwrap()["id"].as_u64().unwrap();+ let g = app.run("object.group", json!({"ids": [a, b]})).unwrap()["id"].as_u64().unwrap();+ let art = LayerId(app.run("layer.new", json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap());+ app.run("layer.set", json!({"id": art.0, "locked": true})).unwrap();+ // Select a group member directly.+ app.run("selection.set", json!({"ids": [a]})).unwrap();+ let mut h = panel(app);+ let layer_of =+ |h: &egui_kittest::Harness<'static, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(ItemId(id)).unwrap().layer;+ // Rows: Art (open, empty), Layer 1. Without Cmd the locked layer refuses the drop.+ drag(&mut h, row(1, 0.5, true), row(0, 0.5, false));+ assert_eq!(layer_of(&h, g), l1);+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));+ drag(&mut h, row(1, 0.5, true), row(0, 0.5, false));+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));+ h.run_steps(1);+ assert!([g, a, b].iter().all(|i| layer_of(&h, *i) == art), "the whole group moved");+ }++ fn click(h: &mut egui_kittest::Harness<'static, DesignApp>, p: egui::Pos2) {+ h.hover_at(p);+ h.drag_at(p);+ h.drop_at(p);+ h.run_steps(3);+ }+++ #[test]+ fn selecting_an_object_opens_its_layer_in_the_panel() {+ use egui_kittest::Harness;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let first = app.session.active().unwrap().doc.item(ItemId(id)).unwrap().layer;+ // A new layer becomes the active one: the first layer's row starts closed.+ app.run("layer.new", json!({})).unwrap();+ app.run("selection.set", json!({"ids": []})).unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(260.0, 400.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui), app);+ h.run_steps(2);+ let open = |h: &Harness<'_, DesignApp>| h.ctx.data(|d| d.get_temp::<bool>(egui::Id::new(("layer_open", first.0)))).unwrap_or(false);+ assert!(!open(&h), "closed while nothing on it is selected");+ h.state_mut().run("selection.set", json!({"ids": [id]})).unwrap();+ h.run_steps(2);+ assert!(open(&h), "selecting the object opens its layer");+ // Closed again by hand, it stays closed while the selection stays the same.+ h.ctx.data_mut(|d| d.insert_temp(egui::Id::new(("layer_open", first.0)), false));+ h.run_steps(2);+ assert!(!open(&h));+ }++ #[test]+ fn rows_rename_in_place() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(260.0, 400.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui), app);+ h.run_steps(2);+ let rename = |h: &mut Harness<'_, DesignApp>, key: RenameKey, typed: &str| {+ // As a double-click starts it (with an emptied field here, so the typing is the name).+ h.ctx.data_mut(|d| d.insert_temp(egui::Id::new(RENAME), (key, String::new(), String::new())));+ h.run_steps(2);+ h.get_by_role(egui::accesskit::Role::TextInput).type_text(typed);+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+ };+ rename(&mut h, id, "Hero bottle");+ assert_eq!(h.state().session.active().unwrap().doc.item(ItemId(id)).unwrap().name, "Hero bottle");+ // Esc leaves the name as it was.+ h.ctx.data_mut(|d| d.insert_temp(egui::Id::new(RENAME), (id, String::new(), String::new())));+ h.run_steps(2);+ h.get_by_role(egui::accesskit::Role::TextInput).type_text("Oops");+ h.key_press(egui::Key::Escape);+ h.run_steps(2);+ assert_eq!(h.state().session.active().unwrap().doc.item(ItemId(id)).unwrap().name, "Hero bottle");+ }++ #[test]+ fn confirming_an_unedited_automatic_label_keeps_the_object_unnamed() {+ use egui_kittest::{Harness, kittest::Queryable};+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let mut h = Harness::builder().with_size(egui::vec2(260.0, 400.0)).build_ui_state(|ui, app: &mut DesignApp| show(app, ui), app);+ h.run_steps(2);+ let name = |h: &Harness<'_, DesignApp>| h.state().session.active().unwrap().doc.item(ItemId(id)).unwrap().name.clone();+ // As a double-click on the unnamed row starts it: the field shows the automatic label.+ let start = |h: &mut Harness<'_, DesignApp>| {+ h.ctx.data_mut(|d| d.insert_temp(egui::Id::new(RENAME), (id, "Rectangle".to_string(), "Rectangle".to_string())));+ h.run_steps(2);+ };+ start(&mut h);+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+ assert_eq!(name(&h), "", "Enter without editing keeps following the automatic label");+ start(&mut h);+ h.get_by_role(egui::accesskit::Role::TextInput).type_text("X");+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+ assert!(name(&h).contains('X'), "an edited text becomes the name");+ }}diff --cc crates/ui-egui/src/panels/mod.rsindex 8cc2d2df7,c88ae30a3..3367fda0c--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@@ -15,7 -12,10 +15,11 @@@ pub mod propertiespub mod styles;pub mod swatches;pub mod table;+pub mod tabs;+ pub mod typography;++ #[cfg(test)]+ mod color_panel_tests;use designcraft_doc::{Content, StrokeAlign, WrapMode};use designcraft_geom::Rect;@@@ -47,9 -47,8 +51,11 @@@ pub struct SelInfo/// Uniform corner (shape, size) — the first corner.pub corner: (designcraft_geom::corners::CornerShape, f64),pub wrap_invert: bool,+ /// Text wrap side and contour type ids (`bothSides`, `sameAsClipping`, …).+ pub wrap_side: String,+ pub wrap_contour: String,+ /// Text wrap offsets: top, left, bottom, right.+ pub wrap_offsets: [f64; 4],pub locked: bool,}@@@ -153,9 -155,8 +173,10 @@@ pub fn sel_info(app: &DesignApp) -> Opt.and_then(|v| v.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| v.as_str().map(str::to_string))).unwrap_or_else(|| "solid".into()),corner: (first.corners.corners[0].shape, first.corners.corners[0].size),- wrap_invert: first.wrap.invert,- wrap_offsets: first.wrap.offsets,+ wrap_invert: tw.invert,+ wrap_side: serde_json::to_value(tw.side).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),+ wrap_contour: serde_json::to_value(tw.contour).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(),++ wrap_offsets: tw.offsets,locked: first.locked,})}diff --cc crates/ui-egui/src/panels/properties.rsindex d60bedc23,c45c40c01..5743f7acc--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@@ -1916,64 -1834,65 +1928,110 @@@ pub fn wrap_panel(app: &mut DesignApp,("wrap-jump", "jumpObject", "Jump Object"),("wrap-next", "jumpToNextColumn", "Jump to Next Column"),] {- let on = info.as_ref().is_some_and(|i| i.wrap == mode);- if icons::button(ui, icon, 26.0, on, crate::i18n::tr(&app.ui.language, tip)).clicked() {- let _ = app.run("object.textWrap", json!({"mode": mode}));+ if icons::button(ui, icon, 26.0, mode == m, crate::i18n::tr(&app.ui.language, tip)).clicked() {+ let _ = app.run("object.textWrap", json!({"mode": m}));}}+ ui.add_space(6.0);+ let mut inv = info.as_ref().is_some_and(|i| i.wrap_invert);+ let r = ui.add_enabled_ui(mode != "none", |ui| widgets::checkbox(ui, &mut inv, crate::i18n::tr(&app.ui.language, "Invert"))).inner;+ if r.changed() {+ let _ = app.run("object.textWrap", json!({"mode": mode, "invert": inv}));+ }});let u = units(app);- ui.horizontal(|ui| {- caption(ui, crate::i18n::tr(&app.ui.language, "Offset"));- if let Some(v) = measure(ui, "wo", Some(0.0), u, 60.0) {- let _ = app.run("object.textWrap", json!({"mode": info.as_ref().map(|i| i.wrap).unwrap_or("boundingBox"), "offset": v}));+ let offsets = info.as_ref().map(|i| i.wrap_offsets);+ // Linked while the offsets are all the same, until the link is clicked.+ let linked_id = egui::Id::new("wrap_offsets_linked");+ let linked = ui.data(|d| d.get_temp::<bool>(linked_id)).unwrap_or_else(|| offsets.is_none_or(|o| o.iter().all(|v| (v - o[0]).abs() < 1e-9)));+ let mut set: Option<[f64; 4]> = None;+ ui.add_enabled_ui(mode != "none" && info.is_some(), |ui| {+ // Two rows of fixed-width cells: Top | Left, then Bottom | Right; the link between them.+ let cell = |ui: &mut Ui, w: f32, label: &str| {+ let x0 = ui.cursor().min.x;+ caption(ui, crate::i18n::tr(&app.ui.language, label));+ ui.add_space((w - (ui.cursor().min.x - x0)).max(0.0));+ };+ // The second column starts where the first row's does (after the link button).+ let mut col2_x: Option<f32> = None;+ for (r, row) in [[(0, "Top"), (1, "Left")], [(2, "Bottom"), (3, "Right")]].into_iter().enumerate() {+ ui.horizontal(|ui| {+ for (k, (side, label)) in row.into_iter().enumerate() {+ if k == 1 {+ match col2_x {+ Some(x) => ui.add_space((x - ui.cursor().min.x).max(0.0)),+ None => col2_x = Some(ui.cursor().min.x),+ }+ }+ cell(ui, if k == 0 { 56.0 } else { 40.0 }, label);+ if let Some(v) = measure(ui, &format!("wo{side}"), offsets.map(|o| o[side]), u, 60.0) {+ let mut o = offsets.unwrap_or([0.0; 4]);+ if linked {+ o = [v; 4];+ } else {+ o[side] = v;+ }+ set = Some(o);+ }+ if k == 0 && r == 0 {+ let tip = crate::i18n::tr(&app.ui.language, "Make all settings the same");+ let link = widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, tip, vec2(22.0, 21.0));+ if link.clicked() {+ ui.data_mut(|d| d.insert_temp(linked_id, !linked));+ }+ }+ }+ });}});+ if let Some(o) = set {+ let _ = app.run("object.textWrap", json!({"mode": mode, "offset": o}));+ }+ let Some(i) = info.as_ref().filter(|i| i.wrap == "boundingBox" || i.wrap == "contour") else { return };+ let sides = [+ ("bothSides", "Both Right & Left Sides"),+ ("rightSide", "Right Side"),+ ("leftSide", "Left Side"),+ ("towardsSpine", "Side Towards Spine"),+ ("awayFromSpine", "Side Away from Spine"),+ ("largestArea", "Largest Area"),+ ];+ wrap_combo(app, ui, "wrap_side", "Wrap To", &sides, &[], &i.wrap_side, "side");+ if i.wrap == "contour" && i.is_graphic {+ // Detected edges, alpha channels and image paths aren't offered: composition doesn't read+ // the image. An imported one shows by name and wraps around the frame.+ let types = [("boundingBox", "Bounding Box"), ("graphicFrame", "Graphic Frame"), ("sameAsClipping", "Same as Clipping")];+ let shown_only = [("detectEdges", "Detect Edges"), ("alphaChannel", "Alpha Channel"), ("photoshopPath", "Photoshop Path")];+ wrap_combo(app, ui, "wrap_contour", "Contour Type", &types, &shown_only, &i.wrap_contour, "contour");+ }+}++/// A Text Wrap panel choice: `opts` are offered, `shown_only` only name the current value.+#[allow(clippy::too_many_arguments)]+fn wrap_combo(+ app: &mut DesignApp,+ ui: &mut egui::Ui,+ salt: &str,+ caption_text: &str,+ opts: &[(&str, &str)],+ shown_only: &[(&str, &str)],+ cur: &str,+ key: &str,+) {+ ui.horizontal(|ui| {+ caption(ui, crate::i18n::tr(&app.ui.language, caption_text));+ let shown = opts.iter().chain(shown_only).find(|o| o.0 == cur).map_or(cur, |o| o.1).to_string();+ egui::ComboBox::from_id_salt(salt).selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &shown))).width(170.0).show_ui(+ ui,+ |ui| {+ for (k, l) in opts {+ if ui.selectable_label(*k == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() {+ let _ = app.run("object.textWrap", json!({ key: k }));+ }+ }+ },+ );+ });}/// The Pathfinder operations, in the order of InDesign's Pathfinder buttons.diff --cc crates/ui-egui/src/panels/swatches.rsindex 1c1a0046d,a21ffdb93..fd0086ead--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@@ -73,27 -58,26 +67,37 @@@ pub fn show(app: &mut DesignApp, ui: &m}}ui.add_space(6.0);+ // InDesign's bottom row: New Color Group, New Swatch, Delete Swatch (the one last clicked).+ let picked: Option<String> = ui.data(|d| d.get_temp(egui::Id::new(PICKED))).filter(|n: &String| doc.swatch(n).is_some_and(|w| !w.locked));ui.horizontal(|ui| {- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Right-click: stroke, groups")).size(10.5).color(t.text_disabled),- ));ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let del = ui+ .add_enabled_ui(picked.is_some(), |ui| icons::button(ui, "trash", 20.0, false, crate::i18n::tr(&app.ui.language, "Delete Swatch")))+ .inner;+ if del.clicked()+ && let Some(name) = &picked+ && app.run("swatch.delete", json!({"name": name})).is_ok()+ {+ ui.data_mut(|d| d.remove::<String>(egui::Id::new(PICKED)));+ }+ // The selection's fill or stroke (whichever is in front) becomes a swatch; with nothing+ // selected, a new colour.if icons::button(ui, "plus", 20.0, false, crate::i18n::tr(&app.ui.language, "New Swatch")).clicked() {- let _ = app.run("swatch.create", json!({"color": {"c": 0, "m": 50, "y": 100, "k": 0}}));+ let target = if app.ui.stroke_front { "stroke" } else { "fill" };+ let _ = app.run("swatch.new", json!({"target": target}));}+ if folder_button(ui, crate::i18n::tr(&app.ui.language, "New Color Group")).clicked() {+ let _ = app.run("swatch.newColorGroup", json!({}));+ }crate::menus::menu_button(ui, "☰", |ui| {+ let current = fill_cur.as_deref().filter(|n| doc.swatch(n).is_some_and(|w| !w.hidden));+ if ui+ .add_enabled(current.is_some(), egui::Button::new(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Swatch Options…"))))+ .clicked()+ {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": current}));+ ui.close();+ }crate::menus::menu_button(ui, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Ink Manager")), |ui| {let Ok(l) = app.session.execute("ink.list", &json!({})) else { return };let mut all = l["allToProcess"].as_bool().unwrap_or(false);@@@ -186,18 -249,11 +281,19 @@@ fn swatch_rowicons::paint(ui.painter(), egui::Rect::from_min_size(egui::pos2(row.max.x - 64.0, row.min.y + 4.0), vec2(13.0, 13.0)), "lock", t.text_dim);}ui.painter().text(row.right_center() - vec2(6.0, 0.0), egui::Align2::RIGHT_CENTER, kind, egui::FontId::proportional(10.5), t.text_dim);- if resp.clicked() {+ if resp.clicked() && !resp.double_clicked() {- let _ = super::apply_swatch(app, false, &sw.name, None);+ ui.data_mut(|d| d.insert_temp(egui::Id::new(PICKED), sw.name.clone()));+ let _ = super::apply_swatch(app, app.ui.stroke_front, &sw.name, None);}+ // Double-click: Swatch Options (the first click has applied the swatch).+ if resp.double_clicked() {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": sw.name}));+ }resp.context_menu(|ui| {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Swatch Options…"))).clicked() {+ let _ = app.run("app.swatchOptionsDialog", json!({"name": sw.name}));+ ui.close();+ }if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Apply to Stroke"))).clicked() {let _ = super::apply_swatch(app, true, &sw.name, None);ui.close();@@@ -481,481 -508,277 +590,570 @@@ fn stops_json(g: &designcraft_color::Gr.collect()}-/// Gradient panel: type, angle, reverse, and the ramp with its stops (drag to move, click below-/// the ramp to add, drag off to remove; the selected stop's location and colour are editable).+fn color32(c: &designcraft_color::Color, alpha: f32) -> egui::Color32 {+ let [r, g, b] = c.to_rgb();+ egui::Color32::from_rgba_unmultiplied((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, (alpha * 255.0) as u8)+}++/// The panel's thumbnail: the gradient in a square, linear across or radial from the centre.+fn thumbnail(p: &egui::Painter, r: egui::Rect, g: &designcraft_color::Gradient, border: egui::Color32) {+ let n = 32;+ if g.kind == designcraft_color::GradientKind::Radial {+ // Rings from the outside in.+ for i in (0..n).rev() {+ let t = (i as f32 + 0.5) / n as f32;+ let (c, a) = g.sample(t);+ let rad = r.width() / 2.0 * std::f32::consts::SQRT_2 * (i + 1) as f32 / n as f32;+ p.with_clip_rect(r).circle_filled(r.center(), rad, color32(&c, a));+ }+ } else {+ for i in 0..n {+ let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);+ let (c, al) = g.sample((a + b) / 2.0);+ let x0 = r.left() + r.width() * a;+ p.rect_filled(egui::Rect::from_x_y_ranges(x0..=r.left() + r.width() * b + 0.5, r.y_range()), 0.0, color32(&c, al));+ }+ }+ p.rect_stroke(r, 0.0, egui::Stroke::new(1.0, border), egui::StrokeKind::Outside);+}++/// What's selected on the ramp: a stop, or the midpoint after a stop.+#[derive(Clone, Copy, PartialEq, Debug)]+enum RampSel {+ Stop(usize),+ Mid(usize),+}++/// A marker being dragged: what, where (0–1), off the panel (stops only).+type RampDrag = (RampSel, f32, bool);++/// The drag kept from the last frame, if it still names a marker of a gradient with `n` stops+/// (the selection or its gradient may have changed since).+fn live_drag(d: Option<RampDrag>, n: usize) -> Option<RampDrag> {+ d.filter(|(h, _, _)| match *h {+ RampSel::Stop(i) => i < n,+ RampSel::Mid(i) => i.saturating_add(1) < n,+ })+}++/// Sets `key` of stop `i` in `object.gradient` stops; nothing if there's no such stop.+fn set_stop(stops: &mut [serde_json::Value], i: usize, key: &str, v: serde_json::Value) {+ if let Some(o) = stops.get_mut(i).and_then(serde_json::Value::as_object_mut) {+ o.insert(key.to_string(), v);+ }+}++/// Gradient panel, laid out as InDesign's: thumbnail, Type, Location and Angle, Reverse, and the+/// ramp with midpoint diamonds above it and stops below it. Drag a stop or a diamond to move it,+/// click below the ramp to add a stop, drag a stop off to remove it, and drop a swatch from the+/// Swatches panel on a stop to colour it or elsewhere on the ramp to add a stop (or right-click a+/// stop for its colour). Until the fill is+/// a gradient the ramp shows the default White → Black, and using it gives the fill a gradient.pub fn gradient_panel(app: &mut DesignApp, ui: &mut egui::Ui) {let t = Tokens::get(ui.ctx());+ let lang = app.ui.language.clone();let Some(st) = app.session.active() else { return };- let Some(it) = st.selection.items.first().and_then(|i| st.doc.item(*i)) else {- ui.label(crate::rtl::widget(- ui,- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Select an object to give its fill a gradient.")).color(t.text_dim),- ));- return;+ let item = st.selection.items.first().and_then(|i| st.doc.item(*i));+ let has_item = item.is_some();+ // The fill's gradient, or the stroke's when the toolbox's Stroke box is in front.+ let stroke_front = app.ui.stroke_front;+ let fill = item.map(|it| if stroke_front { it.stroke.as_fill() } else { it.fill.clone() }).unwrap_or_default();+ let cur = designcraft_color::swatch::resolve_gradient(&st.doc.swatches, &fill.swatch).cloned();+ let is_gradient = cur.is_some();+ let g = cur.unwrap_or_default();+ let radial = g.kind == designcraft_color::GradientKind::Radial;+ let sel_id = egui::Id::new("grad_sel");+ let drag_id = egui::Id::new("grad_drag");+ let mut sel: RampSel = ui.data(|d| d.get_temp(sel_id)).unwrap_or(RampSel::Stop(0));+ let last = g.stops.len().saturating_sub(1);+ sel = match sel {+ RampSel::Stop(i) => RampSel::Stop(i.min(last)),+ RampSel::Mid(i) if i < last => RampSel::Mid(i),+ RampSel::Mid(_) => RampSel::Stop(0),};- // The fill's gradient, or the stroke's when the toolbox's Stroke box is in front (as InDesign's- // Gradient panel follows the Fill/Stroke proxy).- let target = if app.ui.stroke_front { "stroke" } else { "fill" };- let fill = if app.ui.stroke_front { it.stroke.as_fill() } else { it.fill.clone() };- let Some(g) = designcraft_color::swatch::resolve_gradient(&st.doc.swatches, &fill.swatch).cloned() else {- crate::rtl::label(- ui,- egui::RichText::new(crate::i18n::tr(- &app.ui.language,- if app.ui.stroke_front { "The stroke isn't a gradient." } else { "The fill isn't a gradient." },- ))- .color(t.text_dim),- );- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Apply Gradient"))).clicked() {- let _ = app.run("object.gradient", json!({"target": target, "target": target}));+ let mut send: Option<serde_json::Value> = None;+ // The ramp spans the panel, however wide the rows above are.+ let full = ui.available_width().max(60.0);+ ui.add_enabled_ui(has_item, |ui| {+ ui.horizontal(|ui| {+ let (r, resp) = ui.allocate_exact_size(vec2(34.0, 34.0), Sense::click());+ thumbnail(ui.painter(), r.shrink(1.0), &g, t.field_border);+ // Clicking the thumbnail applies the gradient shown (InDesign's way to start one).+ if resp.clicked() && !is_gradient {+ send = Some(json!({}));+ }+ ui.add_space(4.0);+ ui.vertical(|ui| {+ ui.spacing_mut().item_spacing.x = 4.0;+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Type:"), 52.0);+ let shown = if is_gradient { crate::i18n::tr(&lang, g.kind.label()) } else { "" };+ egui::ComboBox::from_id_salt("grad_type").selected_text(crate::rtl::widget(ui, shown)).width(104.0).show_ui(ui, |ui| {+ for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {+ if ui.selectable_label(is_gradient && g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(&lang, k))).clicked() {+ send = Some(json!({"kind": v}));+ }+ }+ });+ });+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Location:"), 52.0);+ let loc = match sel {+ RampSel::Stop(i) => g.stops.get(i).map(|s| s.offset as f64 * 100.0),+ RampSel::Mid(i) => g.stops.get(i).map(|s| s.midpoint as f64 * 100.0),+ };+ if let Some(v) = crate::widgets::number(ui, "grad_loc", loc.filter(|_| is_gradient), "", 50.0, 3) {+ let mut stops = stops_json(&g);+ match sel {+ RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(v.clamp(0.0, 100.0))),+ RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(v.clamp(13.0, 87.0))),+ }+ send = Some(json!({"stops": stops}));+ }+ crate::widgets::caption(ui, "%");+ ui.add_space(4.0);+ crate::widgets::caption(ui, crate::i18n::tr(&lang, "Angle:"));+ let angle =+ fill.gradient_vector.map(|[x0, y0, x1, y1]| (-(y1 - y0)).atan2(x1 - x0).to_degrees()).or(fill.gradient_angle).unwrap_or(0.0);+ ui.add_enabled_ui(is_gradient && !radial, |ui| {+ if let Some(v) = crate::widgets::number(ui, "grad_angle", is_gradient.then_some(angle), "°", 44.0, 1) {+ send = Some(json!({"angle": v}));+ }+ });+ });+ ui.horizontal(|ui| {+ crate::widgets::caption_w(ui, crate::i18n::tr(&lang, "Reverse"), 52.0);+ if icons::button(ui, "swap", 20.0, false, crate::i18n::tr(&lang, "Reverse the gradient")).clicked() && is_gradient {+ send = Some(json!({"reverse": true}));+ }+ });+ });+ });+ ui.add_space(6.0);+ // The ramp: midpoint diamonds above, stops below.+ let w = full;+ let (area, resp) = ui.allocate_exact_size(vec2(w, 40.0), Sense::click_and_drag());+ let ramp = egui::Rect::from_min_size(area.min + vec2(6.0, 10.0), vec2(w - 12.0, 14.0));+ let painter = ui.painter();+ let n = 96;+ for i in 0..n {+ let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);+ let (c, alpha) = g.sample((a + b) / 2.0);+ let x0 = ramp.left() + ramp.width() * a;+ let x1 = ramp.left() + ramp.width() * b + 0.5;+ painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, color32(&c, alpha));}- return;- };- let radial = g.kind == designcraft_color::GradientKind::Radial;- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Type:"));- egui::ComboBox::from_id_salt("grad_type")- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, g.kind.label())))- .width(100.0)- .show_ui(ui, |ui| {- for (k, v) in [("Linear", "linear"), ("Radial", "radial")] {- if ui.selectable_label(g.kind.label() == k, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, k))).clicked() {- let _ = app.run("object.gradient", json!({"target": target, "kind": v}));+ painter.rect_stroke(ramp, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);+ let x_of = |o: f32| ramp.left() + ramp.width() * o;+ let o_of = |x: f32| ((x - ramp.left()) / ramp.width()).clamp(0.0, 1.0);+ let mid_x = |i: usize| match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) => Some(x_of(a.offset + (b.offset - a.offset) * a.midpoint)),+ _ => None,+ };+ // The marker under the pointer: a stop below the ramp, a diamond above it.+ let hit = |p: egui::Pos2| -> Option<RampSel> {+ if p.y < ramp.top() {+ (0..last)+ .filter_map(|i| mid_x(i).map(|x| (i, (x - p.x).abs())))+ .filter(|(_, d)| *d < 6.0)+ .min_by(|a, b| a.1.total_cmp(&b.1))+ .map(|(i, _)| RampSel::Mid(i))+ } else {+ g.stops+ .iter()+ .enumerate()+ .map(|(i, s)| (i, (x_of(s.offset) - p.x).abs()))+ .filter(|(_, d)| *d < 7.0)+ .min_by(|a, b| a.1.total_cmp(&b.1))+ .map(|(i, _)| RampSel::Stop(i))+ }+ };+ let mut dragging = live_drag(ui.data(|d| d.get_temp(drag_id)), g.stops.len());+ if resp.drag_started()+ && let Some(p) = resp.interact_pointer_pos()+ && let Some(h) = hit(p)+ && let Some(o) = match h {+ RampSel::Stop(i) => g.stops.get(i).map(|s| s.offset),+ RampSel::Mid(i) => g.stops.get(i).map(|s| s.midpoint),+ }+ {+ sel = h;+ dragging = Some((h, o, false));+ }+ if resp.dragged()+ && let (Some((h, _, _)), Some(p)) = (dragging, resp.interact_pointer_pos())+ {+ dragging = Some(match h {+ RampSel::Stop(_) => (h, o_of(p.x), p.y > area.bottom() + 16.0 && g.stops.len() > 2),+ RampSel::Mid(i) => {+ let m = match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) if b.offset - a.offset > 1e-6 => ((o_of(p.x) - a.offset) / (b.offset - a.offset)).clamp(0.13, 0.87),+ _ => 0.5,+ };+ (h, m, false)+ }+ });+ }+ if resp.drag_stopped()+ && let Some((h, o, off)) = dragging.take()+ {+ let mut stops = stops_json(&g);+ match h {+ RampSel::Stop(i) if off => {+ if i < stops.len() {+ stops.remove(i);}+ sel = RampSel::Stop(0);+ }+ RampSel::Stop(i) => set_stop(&mut stops, i, "location", json!(o as f64 * 100.0)),+ RampSel::Mid(i) => set_stop(&mut stops, i, "midpoint", json!(o as f64 * 100.0)),+ }+ send = Some(json!({"stops": stops}));+ }+ if resp.clicked()+ && let Some(p) = resp.interact_pointer_pos()+ {+ match hit(p) {+ Some(h) => sel = h,+ // Below the ramp, away from the stops: a new stop with the colour there.+ None if p.y > ramp.bottom() => {+ let o = o_of(p.x);+ let (c, a) = g.sample(o);+ let mut stops = stops_json(&g);+ stops.push(json!({"location": o as f64 * 100.0, "color": color_json(&c), "opacity": a as f64 * 100.0, "midpoint": 50.0}));+ send = Some(json!({"stops": stops}));+ sel = RampSel::Stop(g.stops.iter().filter(|s| s.offset <= o).count());}+ None => {}+ }+ }+ // Right-click a stop: its colour (InDesign takes it from the Swatches or Color panel).+ if resp.secondary_clicked()+ && let Some(RampSel::Stop(i)) = resp.interact_pointer_pos().and_then(hit)+ {+ sel = RampSel::Stop(i);+ }+ if let (true, RampSel::Stop(i)) = (is_gradient, sel)+ && let Some(s) = g.stops.get(i)+ {+ resp.context_menu(|ui| {+ ui.horizontal(|ui| {+ crate::widgets::caption(ui, crate::i18n::tr(&lang, "Stop Color:"));+ let [r, gg, bb] = s.color.to_rgb();+ let mut rgb = [(r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8];+ if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {+ let mut stops = stops_json(&g);+ set_stop(&mut stops, i, "color", json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));+ send = Some(json!({"stops": stops}));+ }+ });});- if ui- .button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Reverse")))- .on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Reverse the gradient"));- })- .clicked()+ }+ // A swatch dropped from the Swatches panel: on a stop it colours that stop, elsewhere on+ // the ramp it's a new stop there.+ let drop_at = |p: egui::Pos2| match hit(egui::pos2(p.x, ramp.bottom() + 4.0)) {+ Some(RampSel::Stop(i)) => match g.stops.get(i) {+ Some(s) => (Some(i), s.offset),+ None => (None, o_of(p.x)),+ },+ _ => (None, o_of(p.x)),+ };+ if resp.dnd_hover_payload::<SwatchDrag>().is_some()+ && let Some(p) = ui.ctx().pointer_hover_pos(){- let _ = app.run("object.gradient", json!({"target": target, "reverse": true}));+ let x = x_of(drop_at(p).1);+ painter.line_segment([egui::pos2(x, ramp.top() - 3.0), egui::pos2(x, ramp.bottom() + 14.0)], egui::Stroke::new(2.0, t.accent));}- });- let sel_id = egui::Id::new("grad_sel");- let drag_id = egui::Id::new("grad_drag");- let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0).min(g.stops.len().saturating_sub(1));- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Location:"));- let loc = g.stops.get(sel).map(|s| s.offset as f64 * 100.0);- if let Some(v) = crate::widgets::number(ui, "grad_loc", loc, " %", 54.0, 1) {+ if let Some(sw) = resp.dnd_release_payload::<SwatchDrag>()+ && let Some(p) = ui.ctx().pointer_interact_pos()+ {let mut stops = stops_json(&g);- stops[sel]["location"] = json!(v.clamp(0.0, 100.0));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- }- if !radial {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Angle:"));- let angle = fill.gradient_vector.map(|[x0, y0, x1, y1]| (-(y1 - y0)).atan2(x1 - x0).to_degrees()).or(fill.gradient_angle).unwrap_or(0.0);- if let Some(v) = crate::widgets::number(ui, "grad_angle", Some(angle), "°", 54.0, 1) {- let _ = app.run("object.gradient", json!({"target": target, "angle": v}));+ match drop_at(p) {+ (Some(i), _) => {+ if let Some(o) = stops.get_mut(i).and_then(serde_json::Value::as_object_mut) {+ o.insert("swatch".to_string(), json!(sw.0));+ o.remove("color");+ }+ sel = RampSel::Stop(i);+ }+ (None, o) => {+ stops.push(json!({"location": o as f64 * 100.0, "swatch": sw.0, "midpoint": 50.0}));+ sel = RampSel::Stop(g.stops.iter().filter(|s| s.offset <= o).count());+ }+ }+ send = Some(json!({"stops": stops}));+ }+ // Diamonds.+ for i in 0..last {+ let x = match dragging {+ Some((RampSel::Mid(j), m, _)) if j == i => match (g.stops.get(i), g.stops.get(i + 1)) {+ (Some(a), Some(b)) => x_of(a.offset + (b.offset - a.offset) * m),+ _ => ramp.left(),+ },+ _ => mid_x(i).unwrap_or(ramp.left()),+ };+ let (cy, r) = (ramp.top() - 6.0, 4.0);+ let pts = vec![egui::pos2(x, cy - r), egui::pos2(x + r, cy), egui::pos2(x, cy + r), egui::pos2(x - r, cy)];+ let on = sel == RampSel::Mid(i);+ painter.add(egui::Shape::convex_polygon(pts, if on { t.text } else { egui::Color32::TRANSPARENT }, egui::Stroke::new(1.0, t.text_dim)));+ }+ // Stops: a colour square under a pointer.+ for (i, s) in g.stops.iter().enumerate() {+ let (o, off) = match dragging {+ Some((RampSel::Stop(j), o, off)) if j == i => (o, off),+ _ => (s.offset, false),+ };+ if off {+ continue;}+ let x = x_of(o);+ let top = ramp.bottom() + 2.0;+ let on = sel == RampSel::Stop(i);+ let edge = if on { t.text_strong } else { t.text_dim };+ painter.add(egui::Shape::convex_polygon(+ vec![egui::pos2(x, top), egui::pos2(x + 5.0, top + 5.0), egui::pos2(x - 5.0, top + 5.0)],+ if on { t.text_strong } else { t.panel },+ egui::Stroke::new(1.0, edge),+ ));+ let sq = egui::Rect::from_min_size(egui::pos2(x - 5.0, top + 5.0), vec2(10.0, 9.0));+ painter.rect_filled(sq, 0.0, color32(&s.color, 1.0));+ painter.rect_stroke(sq, 0.0, egui::Stroke::new(if on { 1.5 } else { 1.0 }, edge), egui::StrokeKind::Inside);}+ ui.data_mut(|d| {+ d.insert_temp(sel_id, sel);+ match dragging {+ Some(v) => {+ d.insert_temp(drag_id, v);+ }+ None => d.remove::<RampDrag>(drag_id),+ }+ });});- ui.add_space(4.0);- // The ramp, with stop markers below it.- let w = ui.available_width().min(240.0);- let (area, resp) = ui.allocate_exact_size(vec2(w, 34.0), Sense::click_and_drag());- let ramp = egui::Rect::from_min_size(area.min + vec2(6.0, 0.0), vec2(w - 12.0, 18.0));- let painter = ui.painter();- let n = 64;- for i in 0..n {- let (a, b) = (i as f32 / n as f32, (i + 1) as f32 / n as f32);- let (c, alpha) = g.sample((a + b) / 2.0);- let [r, gg, bb] = c.to_rgb();- let col = egui::Color32::from_rgba_unmultiplied((r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8, (alpha * 255.0) as u8);- let x0 = ramp.left() + ramp.width() * a;- let x1 = ramp.left() + ramp.width() * b + 0.5;- painter.rect_filled(egui::Rect::from_x_y_ranges(x0..=x1, ramp.y_range()), 0.0, col);+ if let Some(mut p) = send {+ if let Some(o) = p.as_object_mut() {+ o.insert("target".to_string(), json!(if stroke_front { "stroke" } else { "fill" }));+ }+ let _ = app.run("object.gradient", p);}- painter.rect_stroke(ramp, 0.0, egui::Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside);- // A stop being dragged: (index, location 0–1, off the ramp).- let mut dragging: Option<(usize, f32, bool)> = ui.data(|d| d.get_temp(drag_id));- let x_of = |o: f32| ramp.left() + ramp.width() * o;- let o_of = |x: f32| ((x - ramp.left()) / ramp.width()).clamp(0.0, 1.0);- let near = |x: f32| {- g.stops.iter().enumerate().map(|(i, s)| (i, (x_of(s.offset) - x).abs())).filter(|(_, d)| *d < 7.0).min_by(|a, b| a.1.total_cmp(&b.1))- };- if resp.drag_started()- && let Some(p) = resp.interact_pointer_pos()- && let Some((i, _)) = near(p.x)- {- sel = i;- dragging = Some((i, g.stops[i].offset, false));+}++#[cfg(test)]+mod gradient_panel_tests {+ use designcraft_color::Color;+ use egui_kittest::{Harness, kittest::Queryable};+ use serde_json::json;++ use super::*;++ fn app_with_frame() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [100, 100, 300, 300], "content": "unassigned"})).unwrap();+ app}- if resp.dragged()- && let (Some((i, _, _)), Some(p)) = (dragging, resp.interact_pointer_pos())- {- dragging = Some((i, o_of(p.x), p.y > area.bottom() + 16.0 && g.stops.len() > 2));++ fn gradient(app: &DesignApp) -> Option<designcraft_color::Gradient> {+ let d = &app.session.doc().unwrap().doc;+ let id = app.session.doc().unwrap().selection.items[0];+ designcraft_color::swatch::resolve_gradient(&d.swatches, &d.item(id).unwrap().fill.swatch).cloned()}- if resp.drag_stopped()- && let Some((i, o, off)) = dragging.take()- {++ #[test]+ fn panel_edits_keep_cmyk_and_grey_stops() {+ let mut app = app_with_frame();+ app.run(+ "object.gradient",+ json!({"stops": [{"location": 0, "swatch": "C=0 M=100 Y=0 K=0"}, {"location": 50, "color": {"gray": 60}}, {"location": 100, "color": {"model": "gray", "k": 0.01}}]}),+ )+ .unwrap();+ let g = gradient(&app).unwrap();+ // What the panel sends when a stop moves: the colours come back exactly.let mut stops = stops_json(&g);- if off {- stops.remove(i);- sel = 0;- } else {- stops[i]["location"] = json!(o as f64 * 100.0);- }- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));+ stops[1]["location"] = json!(80.0);+ app.run("object.gradient", json!({"stops": stops})).unwrap();+ let g = gradient(&app).unwrap();+ assert_eq!(g.stops[0].color, Color::cmyk(0.0, 1.0, 0.0, 0.0));+ assert_eq!(g.stops[1].color, Color::gray(0.6));+ assert!((g.stops[1].offset - 0.8).abs() < 1e-6);+ assert_eq!(g.stops[2].color, Color::gray(0.01), "a 1 % grey stays 1 %");}- if resp.clicked()- && let Some(p) = resp.interact_pointer_pos()- {- match near(p.x) {- Some((i, _)) => sel = i,- // Below the ramp, away from the stops: a new stop with the colour there.- None if p.y > ramp.bottom() => {- let o = o_of(p.x);- let (c, a) = g.sample(o);- let mut stops = stops_json(&g);- stops.push(json!({"location": o as f64 * 100.0, "color": c.to_hex(), "opacity": a as f64 * 100.0, "midpoint": 50.0}));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- sel = g.stops.iter().filter(|s| s.offset <= o).count();- }- None => {}- }++ #[test]+ fn a_drag_kept_from_a_longer_gradient_is_dropped() {+ let d = |h| Some((h, 0.5, false));+ assert_eq!(live_drag(d(RampSel::Stop(1)), 2), d(RampSel::Stop(1)));+ assert_eq!(live_drag(d(RampSel::Stop(2)), 2), None);+ assert_eq!(live_drag(d(RampSel::Mid(0)), 2), d(RampSel::Mid(0)));+ assert_eq!(live_drag(d(RampSel::Mid(1)), 2), None);+ assert_eq!(live_drag(d(RampSel::Mid(usize::MAX)), 2), None);+ let mut stops = vec![json!({"location": 0})];+ set_stop(&mut stops, 3, "location", json!(50));+ assert_eq!(stops, vec![json!({"location": 0})]);}- for (i, s) in g.stops.iter().enumerate() {- let (o, off) = match dragging {- Some((j, o, off)) if j == i => (o, off),- _ => (s.offset, false),- };- if off {- continue;- }- let x = x_of(o);- let top = ramp.bottom() + 2.0;- let [r, gg, bb] = s.color.to_rgb();- let col = egui::Color32::from_rgb((r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8);- let edge = if i == sel { t.accent } else { t.text_dim };- painter.add(egui::Shape::convex_polygon(- vec![- egui::pos2(x, top),- egui::pos2(x + 6.0, top + 7.0),- egui::pos2(x + 6.0, top + 13.0),- egui::pos2(x - 6.0, top + 13.0),- egui::pos2(x - 6.0, top + 7.0),- ],- col,- egui::Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge),- ));++ #[test]+ fn a_swatch_dropped_on_the_ramp_is_a_new_stop() {+ let app = app_with_frame();+ let mut h = Harness::builder().with_size(vec2(280.0, 200.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ gradient_panel(app, ui);+ },+ app,+ );+ h.run_steps(3);+ assert!(gradient(h.state()).is_none(), "no gradient yet");+ // The ramp sits under the Reverse row: drop cyan at its middle.+ let row = h.get_by_label("Reverse the gradient").rect();+ let at = egui::pos2(h.ctx.content_rect().center().x, row.bottom() + 6.0 + 17.0);+ egui::DragAndDrop::set_payload(&h.ctx, SwatchDrag("C=100 M=0 Y=0 K=0".into()));+ h.event(egui::Event::PointerMoved(at));+ h.run_steps(2);+ h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });+ h.run_steps(3);+ let g = gradient(h.state()).expect("the drop gives the fill a gradient");+ assert_eq!(g.stops.len(), 3, "White, cyan, Black");+ assert_eq!(g.stops[1].color, Color::cmyk(1.0, 0.0, 0.0, 0.0));+ assert!((g.stops[1].offset - 0.5).abs() < 0.05, "{}", g.stops[1].offset);}- ui.data_mut(|d| {- d.insert_temp(sel_id, sel);- match dragging {- Some(v) => {- d.insert_temp(drag_id, v);- }- None => d.remove::<(usize, f32, bool)>(drag_id),- }- });- // The selected stop's colour.- if let Some(s) = g.stops.get(sel) {- ui.horizontal(|ui| {- crate::widgets::caption(ui, crate::i18n::tr(&app.ui.language, "Stop Color:"));- let [r, gg, bb] = s.color.to_rgb();- let mut rgb = [(r * 255.0) as u8, (gg * 255.0) as u8, (bb * 255.0) as u8];- if egui::color_picker::color_edit_button_srgb(ui, &mut rgb).changed() {- let mut stops = stops_json(&g);- stops[sel]["color"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));- let _ = app.run("object.gradient", json!({"target": target, "stops": stops}));- }- });+}++#[cfg(test)]+mod color_panel_tests {+ use egui::vec2;+ use egui_kittest::Harness;+ use egui_kittest::kittest::Queryable;+ use serde_json::json;++ use crate::DesignApp;++ fn fill(app: &DesignApp, id: u64) -> designcraft_color::Color {+ let d = &app.session.active().unwrap().doc;+ d.resolve_color(&d.item(designcraft_doc::ItemId(id)).unwrap().fill.swatch, 1.0).unwrap()+ }++ /// A number typed into the M field stays while typing and applies as a percent on Enter:+ /// M 1 is 1 %, not 100 %.+ #[test]+ fn a_typed_channel_value_is_kept_and_applied_as_a_percent() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ app.run("object.color", json!({"color": {"c": 0, "m": 50, "y": 100, "k": 0}})).unwrap();+ let mut h = Harness::builder().with_size(vec2(320.0, 300.0)).build_ui_state(|ui, app: &mut DesignApp| super::color_panel(app, ui), app);+ h.run_steps(3);+ let fields: Vec<egui::Rect> = h.query_all_by(|n| n.role() == egui::accesskit::Role::SpinButton).map(|n| n.rect()).collect();+ assert_eq!(fields.len(), 4, "C, M, Y and K fields");+ let m = fields[1].center();+ h.hover_at(m);+ h.drag_at(m);+ h.drop_at(m);+ h.run_steps(2);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text("1".into()));+ h.run_steps(4);+ let typed = h.query_by(|n| n.role() == egui::accesskit::Role::SpinButton && n.is_focused()).and_then(|n| n.value());+ assert_eq!(typed.as_deref(), Some("1"), "the typed text stays while the field has focus");+ let designcraft_color::Color::Cmyk { m, .. } = fill(h.state(), id) else { panic!("not CMYK") };+ assert!((m - 0.5).abs() < 1e-6, "nothing is applied while typing: {m}");+ h.key_press(egui::Key::Enter);+ h.run_steps(2);+ let designcraft_color::Color::Cmyk { c, m, y, k } = fill(h.state(), id) else { panic!("not CMYK") };+ assert!(c == 0.0 && (m - 0.01).abs() < 1e-6 && (y - 1.0).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");}}++ #[cfg(test)]+ mod swatches_header_tests {+ use egui_kittest::{Harness, kittest::Queryable};+ use serde_json::json;++ use super::*;++ fn harness(app: DesignApp) -> Harness<'static, DesignApp> {+ Harness::builder().with_size(vec2(300.0, 520.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::new("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ )+ }++ fn items(app: &DesignApp) -> Vec<designcraft_doc::Item> {+ let st = app.session.doc().unwrap();+ st.selection.items.iter().map(|id| st.doc.item(*id).unwrap().clone()).collect()+ }++ #[test]+ fn swatches_go_to_the_fill_or_stroke_in_front_and_the_bottom_row_deletes_the_one_clicked() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [36, 36, 200, 200], "content": "unassigned"})).unwrap();+ app.run("swatch.create", json!({"name": "Brand", "color": "#108080"})).unwrap();+ let mut h = harness(app);+ h.run_steps(3);+ // Fill in front: a swatch is the fill.+ h.get_by_label("C=0 M=100 Y=0 K=0").click();+ h.run_steps(2);+ assert_eq!(items(h.state())[0].fill.swatch, "C=0 M=100 Y=0 K=0");+ // The proxy brings the stroke to the front; the next swatch is the stroke.+ h.get_by_label("Fill").click();+ h.run_steps(2);+ assert!(h.state().ui.stroke_front);+ h.get_by_label("C=100 M=0 Y=0 K=0").click();+ h.run_steps(2);+ let it = &items(h.state())[0];+ assert_eq!((it.fill.swatch.as_str(), it.stroke.swatch.as_str()), ("C=0 M=100 Y=0 K=0", "C=100 M=0 Y=0 K=0"));+ // Formatting affects text, from the panel.+ h.get_by_label("Formatting affects text (J)").click();+ h.run_steps(2);+ assert!(h.state().ui.formatting_affects_text);+ h.get_by_label("Formatting affects container (J)").click();+ h.run_steps(2);+ assert!(!h.state().ui.formatting_affects_text);+ // Delete Swatch removes the swatch last clicked.+ h.get_by_label("Brand").click();+ h.run_steps(2);+ h.get_by_label("Delete Swatch").click();+ h.run_steps(2);+ assert!(h.state().session.doc().unwrap().doc.swatch("Brand").is_none());+ }++ #[test]+ fn the_tint_field_keeps_each_objects_own_swatch() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [36, 36, 100, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [136, 36, 200, 100], "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"ids": [a], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();+ app.run("object.fill", json!({"ids": [b], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();+ app.run("object.stroke", json!({"ids": [a, b], "swatch": "[Black]"})).unwrap();+ app.run("selection.set", json!({"ids": [a, b]})).unwrap();+ let mut h = harness(app);+ h.run_steps(3);+ // The field shows the first selected object's fill tint.+ assert!(h.query_all_by_value("100").next().is_some());+ set_tint(h.state_mut(), 40.0).unwrap();+ h.run_steps(2);+ assert!(h.query_all_by_value("40").next().is_some(), "the field follows");+ // The stroke in front: the strokes' tints.+ h.state_mut().ui.stroke_front = true;+ set_tint(h.state_mut(), 70.0).unwrap();+ assert!(items(h.state()).iter().all(|i| i.stroke.tint == 0.7));+ let it = items(h.state());+ assert_eq!((it[0].fill.swatch.as_str(), it[0].fill.tint), ("C=100 M=0 Y=0 K=0", 0.4));+ assert_eq!((it[1].fill.swatch.as_str(), it[1].fill.tint), ("C=0 M=100 Y=0 K=0", 0.4));+ }+ }diff --cc crates/ui-egui/src/toolbar.rsindex 5572924c8,dfd8c4ce4..2f941fa15--- a/crates/ui-egui/src/toolbar.rs+++ b/crates/ui-egui/src/toolbar.rs@@@ -70,14 -74,17 +74,18 @@@ pub fn show(app: &mut DesignApp, ui: &mui.add_space(8.0);ui.spacing_mut().item_spacing.x = 4.0;for _ in 0..cols {- let Some(Some(gi)) = row_items.get(i).copied() else { break };- let g = TOOL_GROUPS[gi];+ let Some(Some((gi, pinned))) = row_items.get(i).copied() else { break };+ let group = TOOL_GROUPS[gi];+ let g = match pinned {+ Some(k) => &group[k..=k],+ None => group,+ };let shown = g.iter().find(|tl| tl.id == current).unwrap_or(&g[0]);let active = g.iter().any(|tl| tl.id == current);+ let name = crate::i18n::tr(&app.ui.language, shown.label);let tip = match shown.shortcut {- Some(s) => format!("{} ({s})", shown.label),- None => shown.label.to_string(),+ Some(s) => format!("{name} ({s})"),+ None => name.to_string(),};let resp = tool_button(ui, shown.icon, active, &tip);if g.len() > 1 {@@@ -438,8 -560,38 +554,39 @@@ pub(crate) fn toggle_fill_stroke(app: &Ok(json!({"strokeFront": app.ui.stroke_front}))}+ /// Apply Color (,): the colour applied last ([Black] at first) to the fill or stroke in front.+ pub(crate) fn apply_color(app: &mut DesignApp) -> Result<Value, String> {+ let sw = app.ui.last_color.clone().filter(|s| app.session.active().is_some_and(|d| d.doc.swatch(s).is_some()));+ crate::panels::apply_swatch(app, app.ui.stroke_front, sw.as_deref().unwrap_or("[Black]"), None)+ }++ /// Apply Gradient (.): the gradient applied last, else the document's first gradient swatch, else+ /// a new white-to-black gradient (InDesign's default), on the fill or stroke in front.+ pub(crate) fn apply_gradient(app: &mut DesignApp) -> Result<Value, String> {+ let st = app.session.active().ok_or("no document")?;+ let known = app+ .ui+ .last_gradient+ .clone()+ .filter(|s| designcraft_color::swatch::resolve_gradient(&st.doc.swatches, s).is_some())+ .or_else(|| st.doc.swatches.iter().find(|w| matches!(w.value, designcraft_color::SwatchValue::Gradient { .. })).map(|w| w.name.clone()));+ let stroke = app.ui.stroke_front;+ if let Some(sw) = known {+ return crate::panels::apply_swatch(app, stroke, &sw, None);+ }+ if crate::panels::colors_affect_text(app) {+ return Err("no gradient to apply yet: make one in the Gradient panel".into());+ }+ let stops = json!([{"location": 0, "color": "#ffffff"}, {"location": 100, "color": "#000000"}]);+ let r = app.run("object.gradient", json!({"stops": stops, "target": if stroke { "stroke" } else { "fill" }}))?;+ if let Some(sw) = r["swatch"].as_str() {+ app.ui.last_gradient = Some(sw.to_string());+ }+ Ok(r)+ }+-/// Apply None (/): to the fill or the stroke, whichever is in front of the proxy.+/// Apply None (/): to the fill or the stroke, whichever is in front of the proxy, of the text or+/// the objects.pub(crate) fn apply_none(app: &mut DesignApp) -> Result<Value, String> {crate::panels::apply_swatch(app, app.ui.stroke_front, "[None]", None)}diff --cc docs/file-format-parity.mdindex d32492602,cc02a7405..356b2d546--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@@ -54,9 -54,9 +54,9 @@@ score below)| Format | Ext | InDesign | DesignCraft | Notes | Weight ||---|---|---|---|---|---|| PDF / AI (PDF-compatible) | `.pdf`, `.ai` | ✓ page boxes, layers, pages | ✓ rendered with hayro, embedded as vector in PDF export, crop to page boxes | layer visibility depth; editable vectors not offered (#227) | 3% |-| JPEG, PNG, GIF, BMP, WebP | | ✓ | ✓ | CMYK JPEG/TIFF keep inks in PDF (#35) | 2% |-| TIFF | `.tif` | ✓ incl. CMYK, alpha, indexed colour, paths | ✓ incl. CMYK | clipping paths from 8BIM resources unverified | 1% |-| PSD | `.psd` | ✓ layers, comps, alpha, paths | ~ composite + Object Layer Options | layer comps partial | 1% |+| JPEG, PNG, GIF, BMP, WebP | | ✓ | ✓ embedded ICC profiles applied on screen; CMYK JPEGs (incl. YCCK) through their own profile or the working CMYK space | CMYK JPEG/TIFF keep inks in PDF (#35) | 2% |- | TIFF | `.tif` | ✓ incl. CMYK, alpha, paths | ✓ incl. CMYK, embedded ICC profiles on screen | clipping paths from 8BIM resources unverified | 1% |++| TIFF | `.tif` | ✓ incl. CMYK, alpha, indexed colour, paths | ✓ incl. CMYK, embedded ICC profiles on screen | clipping paths from 8BIM resources unverified | 1% |+| PSD | `.psd` | ✓ layers, comps, alpha, paths | ~ composite + Object Layer Options; embedded ICC profile and managed CMYK on screen | layer comps partial | 1% || EPS | `.eps` | ✓ (PostScript) | ~ preview only (no interpreter) | | <1% || SVG | `.svg` | ✓ | ✓ (usvg) | | <1% || HEIC | `.heic` | ✓ | ✗ | | <1% |diff --cc docs/gaps.mdindex 93c8b04ef,81503ab9d..601469e13--- a/docs/gaps.md+++ b/docs/gaps.md@@@ -1,6 -1,6 +1,6 @@@# Where DesignCraft falls short of InDesign- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers) · **Target:** Adobe InDesign 2026 (21.6)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (bounded control click/drag input) · **Target:** Adobe InDesign 2026 (21.6)++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (.indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input) · **Target:** Adobe InDesign 2026 (21.6)Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops anInDesign professional from doing real work. This is the work list: agents pick from the top.@@@ -170,10 -164,8 +170,10 @@@ Kind: **F** feature · **U** UI/UX · *Window ▸ Arrange (2-up … 6-up), Trap Presets, Overlays, Edit ▸ Assign Profiles / Convert toProfile / Edit Original, File ▸ File Info / Open PDF / Document and Print Presets / UserSettings, Type ▸ Size presets, Table ▸ Table Options / Cell Options submenus, Paste Before/After,- Convert Rows/Columns, Object ▸ Interactive ▸ Convert to (form fields), Flex Layout (new in 2026),+ Convert Rows/Columns, Object ▸ Interactive ▸ Convert to (form fields),- View ▸ Extras badges and Story Editor options.+ View ▸ Extras badges and Story Editor options. Pages panel ▸ Parent Options (Based on Parent is+ the `layout.parents.options` command only); overriding a base parent's items on a parent spread+ itself (overrides work on document pages only).- **Estimate:** 40–70 h (most are thin wrappers over existing engine features).- **Doc:** [ui-parity.md](ui-parity.md)diff --cc docs/localization-parity.mdindex 88e938e46,b69eec33c..fa75a20d8--- a/docs/localization-parity.md+++ b/docs/localization-parity.md@@@ -1,6 -1,6 +1,6 @@@# Localization parity- > **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (Polish interface; catalog counts remain the 2026-10-10 measurement) · **Target:** Adobe InDesign 2026 (21.6)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (Georgian interface) · **Target:** Adobe InDesign 2026 (21.6)++> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (Polish and Georgian interfaces; catalog counts remain the 2026-10-10 measurement) · **Target:** Adobe InDesign 2026 (21.6)Per-language status of the DesignCraft interface and of document typesetting in each script.Script-specific typesetting detail: [cjk.md](cjk.md), [cjk-typography.md](cjk-typography.md),@@@ -11,7 -11,7 +11,7 @@@## How it was measuredInterface strings live in `crates/ui-egui/src/i18n.rs` (a shared table with German, French,- Spanish, Japanese and Simplified Chinese columns) and `crates/ui-egui/src/i18n/{ar,cs,it,ja,pt_br,uk}.rs`.-Spanish, Japanese and Simplified Chinese columns) and `crates/ui-egui/src/i18n/{ar,it,ja,ka,pt_br,uk}.rs`.++Spanish, Japanese and Simplified Chinese columns) and `crates/ui-egui/src/i18n/{ar,cs,it,ja,ka,pt_br,uk}.rs`.Untranslated strings fall back to English. A script (2026-10-10) built the set of Englishinterface strings as the union of every catalog's keys, every engine command label and everyliteral passed to `tr`/`t` in the UI crate: **1,724 strings**. A further ~145 capitalized literals@@@ -52,12 -47,11 +52,13 @@@ craft-fonts. The language totals above| Language | Code | UI strings translated | Status ||---|---|---|---|+| Czech | cs | 1,722 (99%), plural categories handled | partial || Italian | it | 1,464 (85%) | partial || Ukrainian | uk | 1,432 (83%), plural categories handled | partial |+| Polish | pl | 1,717 (99%), count captions category-first; AI-drafted, awaiting native review | partial |+ | Georgian | ka | 1,724 (~100%: every catalog key plus the command labels the others lack), count captions as `noun: n` | partial (reviewed by a native speaker) |- DesignCraft ships **4** interface languages beyond the twelve; InDesign ships 17 beyond its-DesignCraft ships **3** interface languages beyond the twelve; InDesign ships 17 beyond its++DesignCraft ships **5** interface languages beyond the twelve; InDesign ships 17 beyond itseight of the twelve (cs, da, el, en_GB, fi, hu, it, nb, nl, pl, ro, ru, sq, sv, tr, uk, zh_TW).## Document languages@@@ -84,7 -78,5 +85,8 @@@ locale shaping. See [typography-parity.| Date | Change | Summary ||---|---|---|+| 2026-10-11 | minor | Localized Japanese print, import and table controls; checked Japanese and English renders |+ | 2026-10-14 | minor | Georgian (`ka`) interface added || 2026-10-10 | major | Created: catalogs measured (1,724 strings), the twelve key languages plus Italian and Ukrainian |+| 2026-10-11 | minor | Czech (cs) added: 1,722 strings, plural categories handled |+| 2026-10-13 | minor | Polish interface added (1,717 strings) |diff --cc docs/roadmap.mdindex fa158f7da,331807156..b142088f9--- a/docs/roadmap.md+++ b/docs/roadmap.md@@@ -58,8 -56,8 +58,8 @@@ set exists; depth gaps are in gaps.md| # | Milestone | State ||---|---|---|| M0 | Skeleton + vertical slice | ✅ |-| M1 | Selection, transform, layers, pages, MCP | ✅ core; handle and snapping issues (#186, #188, #337) |+| M1 | Selection, transform, layers, pages, MCP | ✅ core; handle and snapping issues (#188, #337) |- | M2 | Type I (Type tool, threading, Character/Paragraph, composer) | partial: Type tool, composer and threading ✅; Primary Text Frame pages (#165, alpha blocker); caret formatting (#289); no IME (#322) |+ | M2 | Type I (Type tool, threading, Character/Paragraph, composer) | partial: Type tool, composer and threading ✅; Primary Text Frame pages (#165, alpha blocker); caret formatting (#289); IME not checked by hand (#322) || M3 | Styles (nested/GREP, bullets, keeps, span columns) | ✅; style editing reliability (#169) || M4 | Color & effects | ✅ core; colour management depth || M5 | Graphics & links | ✅ core; EPS preview only |diff --cc docs/target-app-parity.mdindex 7446f0a89,d0b65eaee..e2f405fa5--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -60,8 -60,8 +60,8 @@@ they receive, setting type exactly, an|---|---|---|---|---|---|| Features (depth of each area) | 25% | 55% | 250–400 | 275 catalogue rows exist; many lack options (e.g. Books is 258 lines of engine code, Liquid Layout 329); see the area table | this file || Typography and composition fidelity | 15% | 45% | 120–200 | Knuth–Plass composer, keeps, grids, CJK, Arabic all exist; no comparison with InDesign's line breaks; optical kerning falls back to metrics (#181); overset rule differs (#180); hyphenation patterns for English, Spanish, Portuguese and Norwegian only | [typography-parity.md](typography-parity.md) |-| File formats | 20% | 40% | 150–250 (+20–60 for INDD integration) | INDD cannot be opened (#21); IDML both ways and verified in InDesign 2026, but real-file bugs open (#193, #338, #339, #340); PDF export strong; PDF/X-4 only | [file-format-parity.md](file-format-parity.md) |+| File formats | 20% | 40% | 150–250 (+10–30 for an INDD corpus) | INDD and INDT open through indd-utils, measured on synthetic bytes only (#21); IDML both ways and verified in InDesign 2026, but real-file bugs open (#193, #338, #339, #340); PDF export strong; PDF/X-4 only | [file-format-parity.md](file-format-parity.md) |- | UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165), canvas IME (#322) failing | [ui-parity.md](ui-parity.md) |+ | UI/UX fidelity | 15% | 45% | 120–180 | Measured InDesign 2026 look; but users report object copy/paste (#351, #348, #185, #164), right-click menus (#238, #187, #160), out-port threading (#352, #194, #165) failing | [ui-parity.md](ui-parity.md) || Stability | 10% | 45% | 60–100 | Never-crash rules and last-resort guards; startup failures on some GPUs and machines (#334, #273, #220, #192, #167, #166); no CI runs the tests on pull requests | [gaps.md](gaps.md) || Performance | 5% | 65% | 40–80 | 300k characters compose in ~38 ms warm; typing repaints in < 1 ms (damage regions); no incremental composition; nothing benchmarked against InDesign; no large real documents | [gaps.md](gaps.md) || Localization | 3% | 45% | 120–180 | 9 translations beyond English; Japanese 95%, most others 83–85%, pt-BR 61%; Hindi, Indonesian, Korean, Vietnamese none | [localization-parity.md](localization-parity.md) |@@@ -268,12 -268,12 +268,12 @@@ It is evidence of breadth: each item ex- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together — at start/end of paragraph by default, as in InDesign — widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.- FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.- - UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.-- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches (InDesign's header: Fill/Stroke proxy, Formatting Affects Container/Text, Tint; a swatch goes to the fill or stroke in front; New Color Group / New Swatch / Delete Swatch row), Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.-- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.-- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.++- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts and the Fill/Stroke proxy (D, X, Shift+X, / as `color.*` commands), document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), document grid (View ▸ Grids & Guides, ⌘', on the snap positions, behind or in front of items), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches (InDesign's header: Fill/Stroke proxy, Formatting Affects Container/Text, Tint; a swatch goes to the fill or stroke in front; New Color Group / New Swatch / Delete Swatch row), Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.+- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows, expandable groups and drag-and-drop reorder of layers and objects (the selection square moves the selection to another layer).+- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type; Option/Alt+Left/Right kerns at the caret or tracks a selection by the Kerning/Tracking increment, ×5 with Cmd/Ctrl; words move with Cmd+Left/Right on macOS and Ctrl+Left/Right elsewhere), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own; frames take the fill, stroke, corners and Text Frame Options they don't write from their object style chain, then [None]) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).-- Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.+- Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; Type tool drags of row and column borders (Shift keeps the table size, or scales every row/column on the outer edge; `table.resizeBorder`); `table.*` commands.- Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).- Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid, with a previewing dialog), snippets, object styles, Numbering & Section Options.@@@ -403,9 -400,10 +404,9 @@@- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.- View › Overprint Preview (⌥⇧⌘Y): overprinting fills, strokes and 100% [Black] text mix with what's beneath on screen.- Type on a Path (⇧T tool, `type.onPath`): a story along any line, curve or shape on screen and in PDF; Type on a Path Options (start, flip, baseline/ascender/descender/centre) and Delete Type from Path. Round-trips through IDML as TextPath; on-path caret drawing is still to come.- - Preferences › Appearance of Black: 100% K on screen accurately (dark grey) or as rich black (`window.richBlack`); the printing/export side is still to come.+ - Preferences › Appearance of Black: 100% K on screen as rich black (InDesign's default) or accurately as dark grey (`window.richBlack`); the printing/export side is still to come.- Spreads of up to 10 pages: Add to Previous Spread and Allow Spread to Shuffle (Pages panel; `layout.pages.toSpread`, `layout.spreadShuffle`); inserted pages go around kept spreads.- - Page tool (⇧P) and `layout.pageSize`: pages of their own size (or a preset); the spine stays put and objects keep their place on their page. A click selects a page (handles, its liquid page rule tagged above it); dragging a handle previews the liquid rule and springs back, Alt-drag resizes, Shift keeps proportions, with a W/H readout; `anchor` keeps a reference point in place; double-click for exact sizes. With the Page tool the Control panel shows the page (reference point, W/H, preset, orientation, Liquid Page Rule, Show Parent Page Overlay); X/Y are shown, but pages don't move within their spread yet. On an object-based page it selects objects and shows their pins and width/height locks on the canvas (click to toggle, with tooltips).+ - Page tool (⇧P) and `layout.pageSize`: pages of their own size (or a preset); the spine stays put and objects keep their place on their page. A click selects a page (handles, its liquid page rule tagged above it); dragging a handle previews the liquid rule and springs back, Alt-drag resizes, Shift keeps proportions, with a W/H readout; `anchor` keeps a reference point in place; double-click for exact sizes. With the Page tool the Control panel shows the page (reference point, W/H, preset, orientation, Liquid Page Rule including Controlled by Parent, Show Parent Page Overlay); X/Y and Objects Move with Page are shown, but pages don't move within their spread yet. On an object-based page it selects objects and shows their pins and width/height locks on the canvas (click to toggle, with tooltips).-- Page tool (⇧P) and `layout.pageSize`: pages of their own size (or a preset); the spine stays put and objects keep their place on their page. A click selects a page (handles, its liquid page rule tagged above it); dragging a handle previews the liquid rule and springs back, Alt-drag resizes, Shift keeps proportions, with a W/H readout; `anchor` keeps a reference point in place; double-click for exact sizes. With the Page tool the Control panel shows the page (reference point, W/H, preset, orientation, Liquid Page Rule, Show Parent Page Overlay); X/Y are shown, but pages don't move within their spread yet.- File › Print (⌘P): printer, copies, page range, spreads, marks, bleed; printed as PDF through the system spooler (`file.print`, `file.printers`, `dryRun` for agents). Shortcuts now act like choosing the menu item (dialogs open), and UI commands win shortcut ties (⌘N opens New Document).- Nested styles (through/up to N sentences, words, characters, letters, digits, tabs, breaks, spaces or given characters) and GREP styles (regex → character style), edited in Paragraph Style Options and composed under local formatting; `ui.dialog.open` for agents. Nested line styles are still to come; nested and GREP styles round-trip through IDML.- Table and cell styles (round-trip through IDML): cell styles (fill, insets, vertical justification, strokes, paragraph style) and table styles (region cell styles, border, alternating rows, spacing); apply from the Table panel, edits re-apply to every user; `style.cell.*`, `style.table.*`.@@@ -424,8 -420,9 +425,9 @@@- File › Package (⌥⇧⌘P): the document relinked to a Links folder, the placed files, the font files that draw its text in a Document Fonts folder (the fonts it names and any fallback fonts that draw characters those lack; except fonts whose licence restricts it, OS/2 `fsType`), an IDML copy, an optional PDF and a report (fonts, fallback fonts, links, preflight, instructions); Copy Links To (`links.copyTo`).- Document fonts: opening a `.designcraft` or `.idml` file loads the fonts in the `Document Fonts` folder beside it (as Package writes it), ahead of installed fonts with the same name, so a packaged document opens with its fonts on another machine. Damaged, oversized (over 256 MB per file, 512 MB in all) and surplus (over 200) font files are skipped and listed in `file.open`'s `warnings`; `font.list` gives each font's `source`. Document fonts belong to their document, as in InDesign: other open documents don't see them (each document with a same-named font draws with its own), and closing the document (or reverting it, or a book chapter's export ending) makes them unavailable. Their files stay in memory until DesignCraft quits, so reopening a document doesn't read or load them again; on the web there is no folder to read.- Load Swatches / Save Swatches for Exchange (.ase: CMYK, RGB, Lab, Gray; spot or process) from the Swatches panel menu; `swatch.load` / `swatch.save`.+- Load Paragraph Styles / Load Character Styles / Load All Text Styles from the styles panels' menus: the styles of another `.designcraft` or `.idml` document, chosen in a dialog, with the styles, swatches and lists they name; a style the document defines differently is redefined, kept or loaded under a new name; `style.load` / `style.load.list`.- - Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); `object.pathfinder`.+ - Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); the result keeps the frontmost object's look and content, so a photo intersected with shapes behind it shows through them (Subtract keeps the backmost); `object.pathfinder`.-- Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); `object.pathfinder`.+ - Pathfinder panel as InDesign's: Paths (Join Path `path.join`, Open/Close Path, Reverse Path), Pathfinder, Convert Shape, Convert Point (`path.convertPoints`: plain, corner, smooth, symmetrical).- Make / Release Compound Path (⌘8; nested paths become holes), Create Outlines (⇧⌘O; one path per text colour), Scissors tool (C) with `path.split`.- Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character).- Floating panels: tear a panel off the dock (its float button, or drag its header away) into a movable, resizable window; Dock puts it back; positions persist; `window.floatPanel` / `window.dockPanel`.diff --cc docs/ui-parity.mdindex 33429949f,a66d3b64b..7454e1369--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@@ -40,8 -40,8 +40,8 @@@ basics of editing fail for too many use| Threading: click out port, load text cursor, click frame | ✓ | ✗ ports drawn only; no thread/unthread command; Primary Text Frame and autoflow on Place | ✗ | **alpha blocker** (#352, #194, #165, #140) || Copy / cut / paste objects and text, Paste Into / in Place | ✓ | ✓ on macOS | ~ | **failing on Windows/Linux** (#351, #348, #312, #185, #164, #201, #212) || Context menus (canvas, panels, rulers) | ✓ everywhere | 9 context-menu sites, ruler units by right-click | ~ | **not opening for several users** (#238, #187, #160) |- | IME text input on the canvas | ✓ | ✗ | ✗ | #322 |+ | IME text input on the canvas | ✓ | ✓ | ~ | not checked by hand with a system IME (#322) |-| Font menu: search, preview, favourites, type-ahead | ✓ | ✓ | ~ | search field focus on macOS (#335, #86) |+| Font menu: search, preview, favourites, type-ahead, filters (class, recently added), styles per family, sample text and size, recently used, similar fonts | ✓ | ✓ | ~ | search field focus on macOS (#335, #86); Adobe Fonts (Find More, activated) out of scope || Keyboard shortcuts: InDesign defaults, editor, sets | ✓ | ✓ editor; defaults from 09-shortcuts.md | ✓ | || Quick Apply | ✓ | ✓ | ✓ | || Numeric fields: units, arithmetic, scrubbing | ✓ | 21 pt spinner fields with arithmetic | ✓ | |@@@ -72,9 -64,9 +72,9 @@@ history (DC-1)| Work | Opus 5.5 h ||---|---|| Copy/paste, context menus, threading clicks, caret formatting on every platform, with control-channel regression tests | 30–50 |- | Canvas IME (port from VectorCraft) | 10–20 |+ | Canvas IME: checks by hand with system IMEs, and fixes | 10–20 || Missing menu items (~150) and panels (Tabs, Navigator, Trap Presets) | 40–70 |-| Handle/tool feel fixes (#186, #188, #337), font search focus | 10–20 |+| Handle/tool feel fixes (#188, #337), font search focus | 10–20 || Dialog depth pass against 07-dialogs.md | 30–40 || **Total** | **120–180** (overlaps gaps 1, 8, 16) |