Merge main into fix/2880-bottom-aligned-resize

This commit is contained in:
AlPaka1234 committed 2026-11-19 09:46:46 +00:00
commit a77656acad
88 files changed
+4239 -285

No files matched your search

Generated
+59 -26
View File
@@ -1120,6 +1120,14 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"rayon",
]
[[package]]
name = "craft-designcraft-format"
version = "0.1.0"
@@ -1214,6 +1222,11 @@ dependencies = [
"serde",
]
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac#5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac"
[[package]]
name = "craft-eps"
version = "0.1.0"
@@ -1303,13 +1316,17 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"craft-dds",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
@@ -1326,10 +1343,10 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"exr",
"flate2",
"half",
@@ -1398,6 +1415,14 @@ dependencies = [
"indd",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
@@ -1409,7 +1434,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
dependencies = [
"thiserror 2.0.21",
]
@@ -1417,7 +1442,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f#cc23ffd4d26f3074808e2187d332564817624f8f"
source = "git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33#e7873217287876f76a045550369c90a541693c33"
dependencies = [
"thiserror 2.0.21",
]
@@ -1454,11 +1479,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"quick-xml 0.41.0",
"serde",
]
@@ -1466,11 +1491,11 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
dependencies = [
"brotli-decompressor 6.3.1",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813)",
"quick-xml 0.41.0",
"serde",
]
@@ -1603,6 +1628,19 @@ dependencies = [
"winsafe",
]
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac#5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac"
dependencies = [
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac)",
"kurbo",
"miniz_oxide 0.8.9",
"pdf-writer",
"skrifa 0.47.0",
"weezl",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
@@ -1675,7 +1713,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1684,7 +1722,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701#bfea7d9800a9f14e496209f9df30e9ef45655701"
source = "git+https://github.com/storytold/craft-libs?rev=a5ac3aa05cf3ec013961a85599ddd9e0b5c03813#a5ac3aa05cf3ec013961a85599ddd9e0b5c03813"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -2118,7 +2156,7 @@ name = "designcraft-cli"
version = "0.21.0"
dependencies = [
"craft-file-formats",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"designcraft-color",
"designcraft-compose",
"designcraft-doc",
@@ -2295,14 +2333,15 @@ dependencies = [
"craft-cms",
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba24fe2435adb3c81ad6057faf36365fbba736cf)",
"craft-file-formats",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7873217287876f76a045550369c90a541693c33)",
"craft-ps",
"craft-psd",
"craft-svg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cc23ffd4d26f3074808e2187d332564817624f8f)",
"designcraft-color",
"designcraft-fonts",
"flate2",
"image",
"jpeg-decoder",
"log",
"quick-xml 0.41.0",
"skrifa 0.47.0",
@@ -2329,7 +2368,7 @@ version = "0.21.0"
dependencies = [
"chrono",
"craft-cms",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-pdf",
"craft-prepress",
"designcraft-color",
@@ -2354,7 +2393,7 @@ name = "designcraft-pptx"
version = "0.21.0"
dependencies = [
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-opc 0.1.0 (git+https://github.com/storytold/craft-libs?rev=8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551)",
"craft-pptx",
"designcraft-color",
@@ -2375,7 +2414,7 @@ name = "designcraft-render"
version = "0.21.0"
dependencies = [
"bytemuck",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfea7d9800a9f14e496209f9df30e9ef45655701)",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)",
"craft-pdf",
"designcraft-color",
"designcraft-compose",
@@ -4188,12 +4227,6 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-decoder"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
[[package]]
name = "jpeg-encoder"
version = "0.6.1"
+3 -1
View File
@@ -17,6 +17,7 @@ craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5ac3aa05cf3ec013961a85599ddd9e0b5c03813", version = "=0.1.0", default-features = false }
craft-designcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b1b4602a71d19e09ad33f7752a10d6598cf39b2b", version = "=0.1.0" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "5bd7eb9e88e8574a9cd011accaa9b4beaf4118ac", version = "=0.1.0", features = ["read"] }
craft-epub = { git = "https://github.com/storytold/craft-libs", rev = "ba24fe2435adb3c81ad6057faf36365fbba736cf", version = "=0.1.0" }
craft-idml = { git = "https://github.com/storytold/craft-libs", rev = "899e396b9e2710fcdf1ad9b6249d6c456b7ca9a2", version = "=0.1.0" }
craft-indd = { git = "https://github.com/storytold/craft-libs", rev = "47bf5650b0d503b97bfb5e841746c4957897d11f", version = "=0.1.0" }
@@ -28,7 +29,8 @@ craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "2b9a325f5
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "7ad4765ee55496d0ccdb7659ad7a6375c7bbb484", version = "=0.1.0" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "387c64892b30fdad491b263cc3d9eac660d88dcc", version = "=0.1.0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bfea7d9800a9f14e496209f9df30e9ef45655701", version = "=0.1.0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "=0.1.0" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e7873217287876f76a045550369c90a541693c33", version = "=0.1.0" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d15bf1f35b17b759870f9e5111b9a5d243f64888", version = "=0.1.0" }
craft-file-formats = { git = "https://github.com/storytold/craft-libs", rev = "eed3c28cf016723d004d6f2c79c61424c15d4558", version = "=0.1.0" }
craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8abfa9d0f14bafbfc3449fc552ffeafb9ca6a551", version = "=0.1.0" }
+5
View File
@@ -395,6 +395,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
## Progress log
- **2026-11-16** · Fitting a bottom-aligned text frame from its top handle keeps its bottom edge and text in place (#2880): double-clicking any selection handle passes the opposite local reference point (`ref` 0..=8) to `object.fit`, menu/panel/scripting fits without `ref` anchor to vertical justification (`Bottom`/`Center`/`Top`/`Justify`), and `transform.resize` keeps unchanged edges pinned across its `1e-3` scale clamp and flips. No readiness percentage change.
- **2026-11-13** · A placed Photoshop file comes in at its own resolution (ResolutionInfo), as other rasters do since #1991: a 300 ppi PSD was placed four times too large at 72 ppi. No readiness percentage change.
- **2026-11-15** · Removed the obsolete gap saying pull requests have no test workflow: [CI](.github/workflows/ci.yml) runs the shared quality gate on every pull request and push to main (#1352). No readiness percentage change.
- **2026-11-15** · Accepting tracked deletions or rejecting insertions follows body-text selections through the removed text, including resolving all changes, and preserves independent cell and footnote insertion points. No readiness percentage change.
- **2026-11-15** · Format follow-ups to the craft-libs cutover (craft-libs#778; ported from #2734 by Dylan M. Taylor): IDML export keeps CDATA image contents and table spans such as `inf` reach the table edge; DOCX plain-text import leaves out deleted tracked changes and expands inline objects; an XLSX number cell that isn't a number shows as written; unmarked CMYK JPEGs keep the shared decoder's ink polarity; PPTX export writes exact opacity; PDF export repins craft-pdf and craft-prepress to craft-libs main. No readiness percentage change.
@@ -415,6 +416,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
- **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change.
- **2026-11-12** · Object › Text Frame Options… (Cmd+B) opens with the Type tool in a frame, so inset spacing and vertical justification can be changed while typing; it changes the frame that shows the insertion point, or every frame that holds part of the selected text (#2396). No readiness percentage change.
- **2026-11-05** · Document tabs that overflow the bar scroll (trackpad, wheel, arrows), keep the active tab in view and list every open document in a menu. No readiness percentage change.
- **2026-11-04** · Striped strokes retain out-and-back cubic segments whose second control point is away from the coincident endpoints and first control point. A geometry regression checks the offset extent and both stripe bands. No readiness percentage change.
- **2026-11-04** · Esperanto is a text language (Character › Language, `type.char {language: "Esperanto"}`, IDML `$ID/Esperanto`): tag `eo`, English-style quotes; not hyphenated yet (#1201). No readiness percentage change.
@@ -451,10 +453,12 @@ Newest first.
- **2026-10-28** · Discretionary hyphens (U+00AD) break in the single-line composer with automatic hyphenation on or off, matching the paragraph composer. Unbroken soft hyphens remain invisible and zero-width, and words containing them keep only their discretionary break points (#1955). No readiness percentage change.
- **2026-10-28** · Autoflow no longer sizes the rest of a story by a frame that a Start Paragraph option (next column, frame, page, or odd or even page) ends early (#1209). With a title before a chapter that starts on the next odd page, it estimated a page per few characters, added up to 2000 pages (the autoflow limit) and removed them again: placing 2000 words took 36 s in the app, now 0.4 s, with the same pages. It looks past tracked-deleted paragraphs for the option, as composing does, and asks for every frame that start options and breaks force in one round: 200 one-line chapters on their own pages take 9 ms (58 ms before). A break and the start option it meets count once, and breaks that tracked changes delete or a hidden condition hides don't count. No readiness percentage change.
- **2026-10-28** · IDML export writes the document's default `StoryPreference` in `Resources/Preferences.xml`, as InDesign does. Only each story carried one, and IDML readers that take the spread reading order from the document's (Okapi's IDML filter) failed on DesignCraft's files. No readiness percentage change.
- **2026-10-28** · The text caret's blink restarts on typing, caret keys and canvas clicks, for story text and table cell or footnote text alike, so it never disappears under the user's hand; it repaints at each phase boundary instead of every 330 ms. No readiness percentage change.
- **2026-10-27** · An iconic panel's flyout stays open while you work in the canvas or a text field: Auto-Collapse Iconic Panels is off by default, and preferences saved with it on start with it off. Preferences › Interface › Panels holds the setting next to the column bar's menu item. No readiness percentage change.
- **2026-10-26** · Inner Shadow, Inner Glow (from the edges) and Bevel and Emboss on a frame holding an image follow what the image paints: a transparent part is outside the object, so the effect lines the image's opaque edge, not the frame (#1622). Satin and a centred Inner Glow still follow the frame. No readiness percentage change.
- **2026-10-25** · Duplicate Layer (`layer.duplicate`; the layer's context menu in the Layers panel, or a layer dropped on Create New Layer) adds a copy named after the layer with " copy" added ("Art copy" for Art) above the layer, with its settings, a copy of every object on it and copies of its ruler guides, on document and parent pages, in one undo step. Copied frames stay threaded to the copies of frames on the same layer and are not threaded to frames on other layers. A copied override of a parent item overrides that item's copy, and pages hide the copy where they hide the parent item. Hyperlinks on copied objects and text get copies that go to the same destinations. No readiness percentage change.
- **2026-10-24** · Column rules run from the top line's ascent to the bottom line's descent, as InDesign draws them, instead of from the top to the bottom of the columns, on screen, in PDF and in PowerPoint export. The top and bottom insets shorten the rule from those lines. Existing documents draw their column rules at the new length. No readiness percentage change.
- **2026-10-24** · Table › Cell Options › Diagonal Lines… (`table.setCell` `diagonal`, `table.getCellDiagonal`): as in InDesign, a cell can carry a diagonal line from the top left corner to the bottom right, from the top right to the bottom left, or both, with the weight, type, color, tint, gap color and gap tint that cell edges take, drawn in front of the cell's contents or behind them. The lines draw on screen and in PDF and are saved in the native format. No readiness percentage change.
- **2026-10-20** · Edit › Keyboard Shortcuts is craft-keymap's shared dialog: commands grouped by menu with Show and Filter, recording that asks before taking a key from another command, undo and redo, named shortcut sets (edits of Default become Custom; an imported set becomes a set of its own), an on-screen US keyboard, InDesign Show Set files reviewed before they apply, JSON export and an HTML summary. ui.json keeps the `shortcuts` map earlier versions read, for the active set. No readiness percentage change.
- **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 366 of 1,629 items (was 233) and changes 23 commands. No readiness percentage change.
- **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change.
@@ -481,6 +485,7 @@ Newest first.
- **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change.
- **2026-10-23** · Layout › Go Back and Go Forward (Cmd+Page Up / Cmd+Page Down, Ctrl on Windows and Linux) retrace the jumps between pages (Go to Page, the page and spread commands, the Pages panel) as InDesign's do, returning to where the view was on each page at the current zoom; a new jump after going back drops the pages ahead, scrolling adds no entry, and pages deleted since are skipped. No readiness percentage change.
- **2026-10-24** · The Story Editor has InDesign's vertical depth ruler between the style column and the text, and View › Story Editor › Show/Hide Depth Ruler (`view.storyEditorDepthRuler`) shows or hides it in the Story Editor, remembered with the preferences. The ruler is marked in the document's vertical ruler units with how deep the story's text fills its frames, counted through its columns and threaded frames (lines set side by side, in the sub-columns of a split paragraph or on both sides of a wrap object, count once), and is shaded down to the overset point, where a red line now crosses the editor. No readiness percentage change.
- **2026-10-24** · View › Story Editor › Show/Hide Style Name Column (`view.storyEditorStyleColumn`) shows or hides the Story Editor's column of paragraph style names, as in InDesign, and dragging the bar between the column and the text makes the column wider or narrower (40 to 400 points; the command's `width` sets it too). Both settings are remembered with the preferences, so the editor opens with the same column the next time. No readiness percentage change.
- **2026-10-24** · Split Note (`note.split {story, id, at}`, the Notes panel's Split Note button): as in InDesign, a note splits in two at the insertion point in its text. DesignCraft moves the text after it into a new note by the same author, anchored right after the first. No readiness percentage change.
- **2026-10-24** · Type › Notes › Previous Note and Next Note (`note.previous`, `note.next`): as in InDesign, they move the insertion point from note to note in the story, putting the caret after the note's anchor. Each item is unavailable when no note lies in its direction in the story, or when the insertion point is in a table cell or a footnote. No readiness percentage change.
- **2026-10-24** · Type › Notes › Convert to Note (`note.convertFromText {author?}`): as in InDesign, the selected text leaves the story and becomes the text of a new note, whose anchor takes its place; Convert Note to Text puts it back. DesignCraft refuses a selection in a table cell, or one that holds a note, footnote, endnote, anchored object, index marker, text anchor, cross-reference or table. No readiness percentage change.
+3
View File
@@ -92,5 +92,8 @@ display_name = "Jonathan Cardoso"
real_name = "Adithya Shankaran"
sync_github_name = true
[people.alejo-c]
sync_github_name = true
[people.gmrmad1]
real_name = "Madhav Agarwal"
+260
View File
@@ -224,6 +224,135 @@ pub fn word_breaks_in(word: &str, lang: Lang) -> (Vec<usize>, Source) {
(out, src)
}
/// Whether a whitespace-delimited token is one no language's hyphenation should break.
///
/// Korean attaches particles straight onto Latin words ("News와", "PDF로"), and notices are full
/// of addresses. With the paragraph language left at the default English -- which is what an
/// ordinary Korean document has -- a word run inside such a token was hyphenated as English,
/// giving `New-` / `s와` and `library.exam-` / `ple.kr` (#1688).
///
/// A token is kept whole when it carries Hangul, kana or Han, or when it reads as an address: a
/// URL with a scheme, an e-mail address, a dotted domain, a `/`-rooted path or a Windows drive
/// path. Breaking at a hyphen the author typed is still allowed; this only stops hyphens being
/// invented inside the token.
pub fn keep_whole(token: &str) -> bool {
let cjk = |c: char| {
matches!(c as u32,
0xAC00..=0xD7A3 // Hangul syllables
| 0x1100..=0x11FF // Hangul Jamo
| 0x3130..=0x318F // Hangul compatibility Jamo
| 0xA960..=0xA97F // Hangul Jamo Extended-A
| 0xD7B0..=0xD7FF // Hangul Jamo Extended-B
| 0x3040..=0x30FF // kana
| 0xFF66..=0xFF9F // halfwidth katakana
| 0x4E00..=0x9FFF // CJK unified ideographs
| 0x3400..=0x4DBF
| 0xF900..=0xFAFF
| 0x20000..=0x3FFFF) // supplementary ideographs
};
if token.chars().any(cjk) {
return true;
}
// Prose punctuation around a token is not part of the address inside it: `(https://...)` was
// not recognised because the bracket came first, and `library.example.kr,` because the comma
// ended the last label. Only this classification ignores it; the text keeps
// every character it had.
let wrapper = |c: char| {
matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\'' | ',' | ';' | ':' | '!' | '?' | '\u{201C}' | '\u{201D}' | '\u{2018}' | '\u{2019}')
};
// Full stops count with the wrapper characters at the end, so `(library.example.kr).` loses
// both its closing bracket and the sentence's full stop.
let token = token.trim_start_matches(wrapper).trim_end_matches(|c: char| wrapper(c) || c == '.');
let lower = token.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("ftp://") || lower.starts_with("www.") {
return true;
}
// An e-mail address: one `@` with something either side, no space (tokens have none).
if let Some((user, host)) = token.split_once('@') {
return !user.is_empty() && host.contains('.');
}
// A path, rooted or with a drive letter.
if token.starts_with('/') || token.starts_with('\\') {
return true;
}
let mut cs = token.chars();
if let (Some(a), Some(b), Some(c)) = (cs.next(), cs.next(), cs.next())
&& a.is_ascii_alphabetic()
&& b == ':'
&& (c == '/' || c == '\\')
{
return true;
}
// A domain: dot-separated labels up to the first `/`, whose last label is a short run of
// letters -- "example.kr", "library.example.kr". Ordinary prose ("end. Next") never reaches
// here, because a token holds no space.
// Judged as written, not lower-cased: a domain's last label is lower-case letters, so `Mr.Smith`
// is not one and stays a word to hyphenate.
let host = token.split('/').next().unwrap_or("");
let labels: Vec<&str> = host.trim_end_matches('.').split('.').collect();
labels.len() >= 2
&& labels.iter().all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
&& labels.last().is_some_and(|tld| tld.len() <= 6 && tld.chars().all(|c| c.is_ascii_lowercase()))
}
/// Whether a paragraph is set in Korean, so automatic hyphenation does not apply to it.
///
/// Korean is set word by word and is not hyphenated (KLREQ). A paragraph with at least as many
/// Hangul syllables as Latin letters is treated as Korean however its language is set, since an
/// ordinary Korean document leaves the paragraph language at the default English (#1688).
pub fn mostly_hangul(text: &str) -> bool {
mostly_hangul_chars(text.chars())
}
/// [`mostly_hangul`] over characters, for judging the text that is actually set: hidden text has
/// no glyphs, and counting it let hidden Korean turn hyphenation off for the visible English
/// around it, and hidden Latin keep it on for visible Korean.
pub fn mostly_hangul_chars(chars: impl Iterator<Item = char>) -> bool {
let (mut hangul, mut latin) = (0usize, 0usize);
for c in chars {
match c as u32 {
_ if crate::breaker::is_hangul(c) => hangul += 1,
_ if c.is_ascii_alphabetic() => latin += 1,
_ => {}
}
}
hangul > 0 && hangul >= latin
}
/// [`mostly_hangul`] over a paragraph's set glyphs, given as `(source byte, character,
/// generated)` so it can be tested without a font.
///
/// One vote per set character, not per glyph. Shaping makes a cluster several glyphs over one
/// character and each repeats that character, so a syllable shaped into three glyphs voted three
/// times -- and since the test is `hangul >= latin`, that can turn hyphenation off for a
/// paragraph that is mostly Latin. Consecutive glyphs on one source byte are one character.
///
/// Generated glyphs do not vote: a list bullet or number, or a footnote label, is not the
/// paragraph's own text, and `prepend_label` gives it the paragraph's *first* byte -- so counting
/// it would also swallow the real first character in the deduplication.
///
/// **Approximation.** A ligature is one glyph over several characters, so those characters vote
/// once between them and Latin is under-counted. That can change the answer: 16 Hangul with
/// `office hyphenation` is 17 Latin letters, and a font that shapes `fi` counts at most 16, so
/// the paragraph classifies as Korean and loses its hyphens. Fixing it needs
/// the visible source characters each cluster stands for; `byte..byte + len` is not that, because
/// the glyph after a hidden run spans it -- measured, every byte of the paragraph came out
/// covered -- which would revive the hidden-text bug this function was changed to avoid.
pub fn korean_paragraph(glyphs: impl Iterator<Item = (usize, char, bool)>) -> bool {
let mut chars: Vec<char> = Vec::new();
let mut last: Option<usize> = None;
for (byte, ch, generated) in glyphs {
if generated {
continue;
}
if last != Some(byte) {
chars.push(ch);
}
last = Some(byte);
}
mostly_hangul_chars(chars.into_iter())
}
/// Allowed hyphenation points in `word` as char indices (a hyphen goes before that char), with
/// the paragraph limits applied to each letter run.
pub fn hyphen_points(word: &str, lim: &Limits) -> Vec<usize> {
@@ -359,6 +488,65 @@ fn heuristic_points(c: &[char]) -> Vec<usize> {
#[cfg(test)]
mod tests {
/// A token no language's hyphenation should break: Korean particles on Latin words, and the
/// addresses a notice is full of (#1688).
#[test]
fn a_token_with_hangul_or_an_address_is_kept_whole() {
for t in [
"News\u{C640}", // News와
"PDF\u{B85C}", // PDF로
"\u{C77C}\u{BCF8}\u{C5B4}", // 일본어
"https://example.kr/page",
"www.example.kr",
"library.example.kr",
"mail@example.kr",
"/usr/share/fonts",
"C:\\Users\\Hong",
"example.kr",
] {
assert!(keep_whole(t), "{t} should be kept whole");
}
// Ordinary words, including ones with a hyphen or a full stop, are still hyphenated.
for t in ["hyphenation", "well-known", "sentence.", "Mr.", "re-examine", "3.5"] {
assert!(!keep_whole(t), "{t} should not be protected");
}
// An address wrapped in prose punctuation is the same address.
for t in [
"library.example.kr,",
"(https://example.kr/page)",
"\u{201C}www.example.kr\u{201D}",
"mail@example.kr;",
"example.kr.",
// A bracket and then the sentence's full stop.
"(library.example.kr).",
"[https://example.kr]",
] {
assert!(keep_whole(t), "{t} should be kept whole");
}
// Halfwidth katakana and a supplementary ideograph are CJK too.
for t in ["News\u{FF76}", "\u{20B9F}\u{C640}", "x\u{FF9F}"] {
assert!(keep_whole(t), "{t:?} should be kept whole");
}
// A domain's last label is lower-case letters as written: a name run into the next word
// after a full stop is not one, and its words still hyphenate.
for t in ["Mr.Smith", "Section.Introduction", "End.Next"] {
assert!(!keep_whole(t), "{t} is not an address");
}
}
/// A Korean paragraph gets no automatic hyphens whatever its language is set to (#1688).
#[test]
fn a_paragraph_that_is_mostly_hangul_is_not_hyphenated() {
assert!(mostly_hangul("\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}"));
assert!(!mostly_hangul("An English paragraph about hyphenation and composition"));
// A Latin paragraph with a Korean word in it is still hyphenated as Latin.
assert!(!mostly_hangul("The Korean word \u{D55C}\u{AD6D} appears once in this English sentence"));
assert!(!mostly_hangul(""));
}
use super::*;
fn h(w: &str) -> String {
@@ -720,3 +908,75 @@ mod tests {
assert!(t.elapsed().as_secs() < 5, "{:?}", t.elapsed());
}
}
#[cfg(test)]
mod korean_paragraph_tests {
use super::korean_paragraph;
/// `(byte, ch, generated)` per glyph, which is all the classification reads -- so these cases
/// need no font and state the counting rules directly.
fn k(glyphs: &[(usize, char, bool)]) -> bool {
korean_paragraph(glyphs.iter().copied())
}
/// One character per source byte, however many glyphs shaping made of it. A syllable shaped
/// into three glyphs voted three times, which could classify a mostly-Latin paragraph as
/// Korean.
#[test]
fn glyphs_of_one_cluster_vote_once() {
// Two Hangul characters, the first shaped into three glyphs, against three Latin letters.
let clustered = [
(0, '\u{AC00}', false),
(0, '\u{AC00}', false),
(0, '\u{AC00}', false),
(3, '\u{B098}', false),
(6, 'a', false),
(7, 'b', false),
(8, 'c', false),
];
assert!(!k(&clustered), "two Hangul against three Latin is not Korean");
// Counting each glyph instead gives four Hangul against three, which flips it -- so the
// deduplication is what decides this case.
let per_glyph: Vec<char> = clustered.iter().map(|(_, c, _)| *c).collect();
assert!(super::mostly_hangul_chars(per_glyph.into_iter()), "per-glyph counting would call it Korean");
}
/// A generated label is not the paragraph's own text, and `prepend_label` gives it the
/// paragraph's *first* byte -- so counting it also swallowed the real first character in the
/// deduplication.
#[test]
fn a_generated_label_neither_votes_nor_hides_the_first_character() {
// A footnote label at byte 0, then two Hangul characters (the first also at byte 0) and
// two Latin letters. Two against two is Korean, since the test is `hangul >= latin` --
// and losing one Hangul character to the label makes it one against two, which is not.
let labelled = [(0, '1', true), (0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'a', false), (7, 'b', false)];
assert!(k(&labelled), "two Hangul against two Latin is Korean");
// Without the exclusion the label takes byte 0, the Hangul character there is deduplicated
// away, and one Hangul against two Latin is no longer Korean.
let counted: Vec<char> = {
let mut out = Vec::new();
let mut last = None;
for (b, c, _) in labelled {
if last != Some(b) {
out.push(c);
}
last = Some(b);
}
out
};
assert!(!super::mostly_hangul_chars(counted.into_iter()), "counting the label loses the first character");
}
/// The remaining approximation, pinned so it is visible rather than surprising: a ligature is
/// one glyph over several characters, so Latin is under-counted and this paragraph classifies
/// as Korean although it has more Latin letters.
#[test]
fn a_ligature_under_counts_latin_which_is_a_known_approximation() {
// Two Hangul characters against three Latin letters shaped as one `ffi` glyph.
let ligated = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, '\u{FB03}', false)];
assert!(k(&ligated), "the ligature counts as one character, so this reads as Korean");
// Spelled out, the same text is not Korean -- which is the error the approximation makes.
let spelled = [(0, '\u{AC00}', false), (3, '\u{B098}', false), (6, 'f', false), (7, 'f', false), (8, 'i', false)];
assert!(!k(&spelled), "the same characters unligated are not Korean");
}
}
+1
View File
@@ -123,6 +123,7 @@ fn shape_mark(face: FaceRef, text: &str, m: &KentenMark, b: &PlacedGlyph) -> Vec
let ch = text.get(sg.cluster..).and_then(|t| t.chars().next()).unwrap_or(' ');
let adv = f64::from(sg.x_advance) * sx;
out.push(PlacedGlyph {
list_label: false,
rendered_char: ch,
face,
gid: sg.gid,
+51 -2
View File
@@ -165,6 +165,10 @@ pub struct PlacedGlyph {
/// How far after its pen position the glyph is drawn (CJK aki, ruby parent spacing): its
/// advance starts at `x - dx`.
pub dx: f64,
/// Part of the bullet or number the paragraph's list adds (see [`shape::Glyph::list_label`]).
/// It carries the first character's offset and no length, so anything selecting glyphs by
/// byte range has to leave it out or it reaches text outside the range.
pub list_label: bool,
}
impl PlacedGlyph {
@@ -1695,6 +1699,9 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) {
for _ in 0..3 {
// The same drop cap, spacing, hyphenation and breaker as the layout below.
let mut gl = sp.glyphs.clone();
// Classified before the drop cap is split off: `split_drop_cap` takes those glyphs out
// of the vector, and the drop cap's character still votes (#1688).
let korean = hyphen::korean_paragraph(gl.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some())));
let dc = split_drop_cap(db, &mut gl, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align, drop_tabs);
let width = |j: usize| {
let ind = match &dc {
@@ -1706,7 +1713,7 @@ fn apply_nested_line_styles(input: NestedLineStyleInput<'_, '_, '_>) {
};
apply_desired_spacing(&mut gl, pp);
mojikumi::apply(&mut gl, &doc.styles, &pp.mojikumi);
let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars));
let mut hy = hyphenation_points(&story.text, &gl, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean);
suppress_hyphens(&mut hy, &gl, suppressed_hyphens);
let breaks = if pp.composer.single_line() || gl.iter().any(|g| g.ch == '\t') || gl.len() > 4000 {
let tab = |j: usize, x: f64, i: usize| {
@@ -2857,6 +2864,8 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
g.and_then(|g| table.styles.get(g.style as usize)).map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint))
};
let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0)));
// Classified before the drop cap is split off (see the same call in the measuring loop above).
let korean = hyphen::korean_paragraph(sp.glyphs.iter().map(|g| (g.byte, g.ch, g.list_label || g.generated_text.is_some())));
let drop_cap = split_drop_cap(
db,
&mut sp.glyphs,
@@ -2946,7 +2955,8 @@ fn shape_paragraph(input: ParagraphShapeInput<'_, '_>) -> ShapedParagraph {
);
apply_desired_spacing(&mut glyphs, pp);
mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi);
let mut hyph_after = hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars));
let mut hyph_after =
hyphenation_points(&story.text, &glyphs, pp, hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), base_chars), korean);
suppress_hyphens(&mut hyph_after, &glyphs, suppressed_hyphens);
let base_size = base_chars.size;
let spacing = spacing_for(pp, base_size, story, cjk);
@@ -5474,6 +5484,12 @@ fn tab_leader(tab: &Glyph, leader: &str, x: f64, w: f64, origin: f64, out: &mut
while at + pw <= end + 0.01 && n < 2000 {
for &(gid, adv) in &glyphs {
out.push(PlacedGlyph {
// The leader fills a tab, so it belongs to whatever that tab belongs to. Saying
// `false` for the tab of a list label made the leader claim to be the
// paragraph's own text while carrying the paragraph-start byte, so a PDF link
// starting at the first text character swept the leader positions into its
// rectangle (noted in review).
list_label: tab.list_label,
rendered_char: '\t',
face: tab.face,
gid,
@@ -5638,6 +5654,7 @@ fn place(g: &Glyph, x: f64) -> PlacedGlyph {
len: g.len,
generated_text: g.generated_text.clone(),
visible,
list_label: g.list_label,
upright: g.upright,
tcy: g.tcy,
rtl: false,
@@ -5965,17 +5982,31 @@ fn hyphenation_points(
pp: &ParaProps,
exceptions: &HashMap<String, Vec<usize>>,
foreign: &[(Range<usize>, Option<hyphen::Lang>)],
korean: bool,
) -> Vec<bool> {
let mut out = vec![false; glyphs.len()];
if !pp.hyphenate {
return out;
}
// Korean is set word by word and is not hyphenated (KLREQ). An ordinary Korean document
// leaves the paragraph language at the default English, so the paragraph's own text decides
// rather than its language setting (#1688).
//
// Decided by the caller, from the paragraph's glyphs *before* its drop cap is split off:
// `split_drop_cap` takes those glyphs out of the vector, so classifying here lost the drop
// cap's character -- 15 Hangul against 15 Latin became 14 against 15, and the paragraph
// hyphenated its English. See `hyphen::korean_paragraph`.
if korean {
return out;
}
let lim = hyphen::Limits {
min_word: pp.hyph_min_word as usize,
after_first: pp.hyph_after_first as usize,
before_last: pp.hyph_before_last as usize,
capitalized: pp.hyph_capitalized,
};
// The token the last word run sat in, and whether it is kept whole (see below).
let mut token: Option<(usize, usize, bool)> = None;
let mut i = 0;
while i < glyphs.len() {
if !glyphs[i].is_letter() || glyphs[i].len == 0 {
@@ -5996,6 +6027,24 @@ fn hyphenation_points(
let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len);
if !discretionary && b > a && b <= text.len() && text.is_char_boundary(a) && text.is_char_boundary(b) {
let word = &text[a..b];
// The whitespace-delimited token the word sits in: a Latin run with a Korean particle
// on it ("News와") or inside an address is not a word to hyphenate (#1688). Found once
// per token and reused for the word runs inside it: unspaced CJK text is one token
// however many Latin words it holds, and scanning it again for each was quadratic.
let keep = match token {
Some((start, end, keep)) if start <= a && b <= end => keep,
_ => {
let start = text[..a].rfind(char::is_whitespace).map_or(0, |i| i + text[i..].chars().next().map_or(1, char::len_utf8));
let end = text[b..].find(char::is_whitespace).map_or(text.len(), |i| b + i);
let keep = hyphen::keep_whole(&text[start..end]);
token = Some((start, end, keep));
keep
}
};
if keep {
i = j.max(i + 1);
continue;
}
// Do not hyphenate the paragraph's last word unless allowed.
let is_last_word = !pp.hyph_last_word && glyphs[j..].iter().all(|g| !g.is_letter());
let lang = foreign.iter().find(|(r, _)| r.contains(&a)).map_or(Some(hyphen::Lang::English), |(_, l)| *l);
+1
View File
@@ -648,6 +648,7 @@ pub(crate) fn annotate(
let style = ruby_style(styles, &st, &spec, shaped.size, missing);
for (r, off) in shaped.glyphs.iter().zip(offsets) {
extra.push(PlacedGlyph {
list_label: false,
rendered_char: r.ch,
face: shaped.face,
gid: r.gid,
+16
View File
@@ -34,6 +34,10 @@ pub struct PlacedCell {
pub repeated: bool,
/// Graphic cell content (drawn at `clip`'s top left, clipped to it).
pub graphic: Option<designcraft_doc::Graphic>,
/// The cell's diagonal lines (Cell Options › Diagonal Lines), corner to corner of `rect`.
pub diagonals: Vec<StrokeSeg>,
/// Whether the diagonals are drawn over the cell's contents (otherwise under them).
pub diagonals_in_front: bool,
}
/// One cell edge (or the table border) to stroke.
@@ -91,6 +95,10 @@ impl TableFrag {
c.rect = c.rect + v;
c.clip = c.clip + v;
c.origin += v;
for s in &mut c.diagonals {
s.a += v;
s.b += v;
}
}
for r in &mut self.rows {
r.1 += dy;
@@ -474,6 +482,14 @@ fn emit(
overset,
repeated,
graphic: cell.graphic.clone(),
diagonals: cell
.diagonal
.segments(rect)
.into_iter()
.filter(|_| cell.diagonal.stroke.is_visible())
.map(|(a, b)| StrokeSeg { a, b, stroke: cell.diagonal.stroke.clone() })
.collect(),
diagonals_in_front: cell.diagonal.in_front,
});
}
}
+36
View File
@@ -31,6 +31,42 @@ fn explicit_cell_edges_override_table_border_without_changing_native_defaults()
assert_eq!(right.stroke.weight, 2.0, "unoverridden right edge keeps the table border");
}
#[test]
fn diagonal_lines_cross_the_placed_cell_corner_to_corner() {
let mut table = Table::new(77, 2, 2, 0, 0, 100.0);
let stroke = CellStroke { weight: 3.0, ..Default::default() };
let cell = table.cell_mut(0, 0).unwrap();
cell.col_span = 2;
cell.diagonal = designcraft_doc::CellDiagonal { lines: designcraft_doc::DiagonalLines::Crossed, stroke: stroke.clone(), in_front: false };
table.cell_mut(1, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft;
table.cell_mut(1, 0).unwrap().diagonal.stroke.color = designcraft_color::swatch::NONE.into();
let composed = compose_table(table);
let fragment = &composed.frames[0].tables[0];
let merged = fragment.cells.iter().find(|c| (c.row, c.col) == (0, 0)).unwrap();
let r = merged.rect;
let ends: Vec<_> = merged.diagonals.iter().map(|s| (s.a, s.b)).collect();
assert_eq!(ends, [(Point::new(r.x0, r.y0), Point::new(r.x1, r.y1)), (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1))], "across the merged cell");
assert!(merged.diagonals.iter().all(|s| s.stroke == stroke) && !merged.diagonals_in_front);
assert!(fragment.cells.iter().filter(|c| c.row == 1).all(|c| c.diagonals.is_empty()), "none, or an invisible stroke, draws nothing");
assert!(fragment.strokes.iter().all(|s| s.a.x == s.b.x || s.a.y == s.b.y), "the edges stay edges");
}
#[test]
fn diagonal_lines_move_with_their_cell_in_a_bottom_justified_frame() {
let mut table = Table::new(77, 1, 1, 0, 0, 100.0);
table.cell_mut(0, 0).unwrap().diagonal.lines = designcraft_doc::DiagonalLines::TopLeft;
let mut doc = Document::new(&NewDocument::default());
let layer = doc.default_layer();
let (fid, sid) = doc.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 200.0, 300.0), layer, "", ParaFormat::default()).unwrap();
doc.item_mut(fid).unwrap().text_frame_mut().unwrap().options.vertical_justification = VerticalJustification::Bottom;
doc.story_mut(sid).unwrap().insert_table(0, table);
let composed = crate::compose_story(&doc, sid, &ComposeOptions::default());
let cell = &composed.frames[0].tables[0].cells[0];
assert!(cell.rect.y0 > 100.0, "the table sits at the bottom: {:?}", cell.rect);
let s = &cell.diagonals[0];
assert_eq!((s.a, s.b), (Point::new(cell.rect.x0, cell.rect.y0), Point::new(cell.rect.x1, cell.rect.y1)));
}
#[test]
fn merged_cell_keeps_explicit_border_suppression() {
let mut table = Table::new(77, 2, 2, 0, 0, 100.0);
+131
View File
@@ -1499,6 +1499,137 @@ fn hyphen_limit_is_a_hard_constraint() {
}
}
/// Each paragraph's own text decides, not the story's: a Korean document's English paragraphs
/// still hyphenate, and a mostly-English story's Korean paragraphs still do not (noted in review
/// of #1688).
#[test]
fn hyphenation_follows_each_paragraph_not_the_story() {
let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0);
let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() };
// 이번 통지문은 아래와 같습니다 / an English paragraph that wants hyphenation
let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4}";
let english = "This notice about hyphenation and composition continues for a while in English";
let hyphens = |text: &str| {
let (d, sid, _) = doc_with(text, rect, para.clone());
let cs = compose_story(&d, sid, &ComposeOptions::default());
let lines = all_lines(&cs);
// Which paragraph each hyphenated line belongs to: the Korean one is first.
lines.iter().filter(|l| l.hyphenated).count()
};
// The English paragraph in a Korean document still hyphenates: the story is mostly Hangul,
// but that paragraph is not.
let mixed = format!("{korean}\n{english}");
assert!(hyphens(&mixed) > 0, "the English paragraph of a Korean document still hyphenates");
// And the Korean paragraph alone invents none.
assert_eq!(hyphens(korean), 0, "a Korean paragraph invents no hyphens");
}
/// The paragraph's *glyphs* decide, not its source text: hidden conditional text is not set, so
/// it does not get a vote. Reading the source let hidden Korean turn hyphenation off for the
/// visible English around it (noted in review of #1688).
#[test]
fn hidden_text_does_not_decide_whether_a_paragraph_hyphenates() {
let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0);
let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() };
// 이번 통지문은 아래와 같습니다 — repeated, so the Hangul outweighs the English after it
// (`mostly_hangul` wants at least as many Hangul characters as ASCII letters).
let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} \u{C544}\u{B798}\u{C640} \u{AC19}\u{C2B5}\u{B2C8}\u{B2E4} ".repeat(6);
let english = "This notice about hyphenation and composition continues for a while in English";
let text = format!("{korean}{english}");
let hyphens = |hide: bool| {
let (mut d, sid, _) = doc_with(&text, rect, para.clone());
d.conditions.push(designcraft_doc::Condition { name: "Draft".into(), color: [255, 0, 0], visible: !hide });
let story = d.story_mut(sid).expect("the story is there");
let chars = designcraft_doc::CharAttrs { conditions: Some(vec!["Draft".into()]), ..Default::default() };
story.chars = vec![
designcraft_doc::CharRun { len: korean.len(), format: designcraft_doc::CharFormat { over: chars, ..Default::default() } },
designcraft_doc::CharRun { len: english.len(), format: designcraft_doc::CharFormat::default() },
];
let cs = compose_story(&d, sid, &ComposeOptions::default());
all_lines(&cs).iter().filter(|l| l.hyphenated).count()
};
// Shown, the Hangul outweighs the English and the paragraph is not hyphenated.
assert_eq!(hyphens(false), 0, "a visibly Korean paragraph invents no hyphens");
// Hidden, the only text set is English, and it hyphenates like any English paragraph.
assert!(hyphens(true) > 0, "hidden Korean does not turn hyphenation off for the visible English");
}
/// `split_drop_cap` takes the drop cap's glyphs out of the vector, so classifying the paragraph
/// after it ran lost that character's vote: with the Hangul and Latin counts level, dropping one
/// Hangul character made the paragraph read as Latin and its English words took automatic hyphens
/// (noted in review). The classification is made before the split.
#[test]
fn a_drop_cap_still_counts_when_a_paragraph_is_judged_korean() {
let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0);
// English long enough that it really does hyphenate in a 90 pt column -- the run
// `hidden_text_does_not_decide_whether_a_paragraph_hyphenates` uses for the same reason. A
// short run leaves no hyphens whichever way the paragraph is classified, so the test would
// pass without testing anything (measured: it did).
let english = "This notice about hyphenation and composition continues for a while in English";
let letters = english.chars().filter(char::is_ascii_alphabetic).count();
// One Hangul syllable per Latin letter, so the counts are level -- which `hangul >= latin`
// calls Korean, and one character either way decides it.
let korean: String = "\u{AC00}\u{B098}\u{B2E4}\u{B77C}\u{B9C8}".chars().cycle().take(letters).collect();
assert_eq!(korean.chars().count(), letters, "the two counts are level at {letters}");
let text = format!("{korean} {english}");
let hyphens = |para: ParaAttrs| {
let (d, sid, _) = doc_with(&text, rect, para);
let cs = compose_story(&d, sid, &ComposeOptions::default());
all_lines(&cs).iter().filter(|l| l.hyphenated).count()
};
let base = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() };
// Level counts read as Korean, so nothing hyphenates.
assert_eq!(hyphens(base.clone()), 0, "level counts read as Korean");
// The paragraph opens on a Hangul character, so that character is the drop cap. It is still
// set, just larger, so the answer must not change.
let with_cap = ParaAttrs { drop_cap_lines: Some(2), drop_cap_chars: Some(1), ..base.clone() };
assert_eq!(hyphens(with_cap), 0, "a drop cap does not turn the paragraph Latin");
// And the fixture really is poised on the boundary: one Latin letter more and the English
// hyphenates, so the assertions above are not passing for want of any hyphen at all.
let tipped = format!("{korean} {english}x");
let (d, sid, _) = doc_with(&tipped, rect, base);
let cs = compose_story(&d, sid, &ComposeOptions::default());
assert!(all_lines(&cs).iter().any(|l| l.hyphenated), "one more Latin letter tips it and hyphens appear");
}
/// A Korean notice leaves its paragraphs at the default English language, so English
/// hyphenation broke the Latin words Korean particles attach to and the addresses such a document
/// is full of: `New-` / `s와`, `library.exam-` / `ple.kr` (#1688). The lines may now be looser --
/// that is the cost of not hyphenating, and what #1691 is about -- but no hyphen is invented
/// inside those tokens.
#[test]
fn korean_text_and_addresses_are_not_hyphenated() {
// Narrow enough that every line has to break somewhere.
let rect = Rect::new(0.0, 0.0, 90.0, 100_000.0);
let para = ParaAttrs { align: Some(Align::LeftJustified), hyphenate: Some(true), ..Default::default() };
let hyphens_in = |text: &str| {
let (d, sid, _) = doc_with(text, rect, para.clone());
let cs = compose_story(&d, sid, &ComposeOptions::default());
all_lines(&cs).iter().filter(|l| l.hyphenated).count()
};
// 이번 통지문은 News와 관련된 library.example.kr 주소를 포함합니다
let korean = "\u{C774}\u{BC88} \u{D1B5}\u{C9C0}\u{BB38}\u{C740} News\u{C640} \u{AD00}\u{B828}\u{B41C} library.example.kr \u{C8FC}\u{C18C}\u{B97C} \u{D3EC}\u{D568}\u{D569}\u{B2C8}\u{B2E4}";
assert_eq!(hyphens_in(korean), 0, "a Korean paragraph invents no hyphens");
// An English paragraph holding the same address: the prose still hyphenates, the address does
// not, so the protection is about the token and not about turning hyphenation off.
let english = "This notice about hyphenation and composition mentions library.example.kr somewhere inside a long sentence";
assert!(hyphens_in(english) > 0, "English prose is still hyphenated");
let (d, sid, _) = doc_with(english, rect, para.clone());
let cs = compose_story(&d, sid, &ComposeOptions::default());
for l in all_lines(&cs).iter().filter(|l| l.hyphenated) {
let upto = &english[..l.range.end.min(english.len())];
let token = upto.rsplit(char::is_whitespace).next().unwrap_or("");
assert!(!"library.example.kr".starts_with(token) || token.is_empty(), "a hyphen was invented inside the address: {token:?}");
}
}
#[test]
fn hyphenation_zone_limits_ragged_hyphens() {
let text = CORPUS.join(" ");
+3 -2
View File
@@ -174,6 +174,7 @@ impl Names<'_> {
for s in &mut c.strokes {
self.cell_stroke(s);
}
self.cell_stroke(&mut c.diagonal.stroke);
}
}
/// One story's own text, objects and tables (cell and note text are visited separately).
@@ -239,8 +240,8 @@ impl Document {
/// Point every reference to swatch `from` at `to`: tints based on it, colour groups, inks,
/// styles, page items (fills, strokes, gaps, effects, column rules, the swatch an image is
/// coloured with), text, kenten and ruby colours, rules, shading, borders and border gaps,
/// tables (with stroke gaps and cell images), footnotes, gradient stops, endnotes and the
/// footnote rule. The swatch itself is renamed by the caller.
/// tables (with stroke gaps, diagonal lines and cell images), footnotes, gradient stops,
/// endnotes and the footnote rule. The swatch itself is renamed by the caller.
pub fn rename_swatch_refs(&mut self, from: &str, to: &str) {
if from == to {
return;
+24 -1
View File
@@ -22,7 +22,7 @@ mod grid;
mod merge;
mod story;
pub use cell::{AltFills, AltStrokes, Cell, CellStroke, Column, Row, RowHeightMode, RowKind, TableOptions};
pub use cell::{AltFills, AltStrokes, Cell, CellDiagonal, CellStroke, Column, DiagonalLines, Row, RowHeightMode, RowKind, TableOptions};
pub use grid::CellRange;
/// Most rows a table holds, as InDesign allows.
@@ -366,4 +366,27 @@ mod tests {
assert_eq!(back, explicit);
assert_eq!(back.blank_like().border_overrides, explicit.border_overrides);
}
#[test]
fn cell_diagonal_lines_roundtrip_and_run_corner_to_corner() {
let plain = serde_json::to_value(Cell::default()).unwrap();
assert!(plain.get("diagonal").is_none(), "a cell without diagonal lines saves none");
let diagonal = CellDiagonal { lines: DiagonalLines::Crossed, stroke: CellStroke { weight: 2.0, ..Default::default() }, in_front: false };
let cell = Cell { diagonal: diagonal.clone(), ..Cell::default() };
let back: Cell = serde_json::from_str(&serde_json::to_string(&cell).unwrap()).unwrap();
assert_eq!(back.diagonal, diagonal);
assert_eq!(back.blank_like().diagonal, diagonal, "new cells take the cell's formatting");
let r = designcraft_geom::Rect::new(10.0, 20.0, 110.0, 70.0);
let p = designcraft_geom::Point::new;
let down = (p(10.0, 20.0), p(110.0, 70.0));
let up = (p(110.0, 20.0), p(10.0, 70.0));
for (lines, want) in [
(DiagonalLines::None, vec![]),
(DiagonalLines::TopLeft, vec![down]),
(DiagonalLines::TopRight, vec![up]),
(DiagonalLines::Crossed, vec![down, up]),
] {
assert_eq!(CellDiagonal { lines, ..Default::default() }.segments(r), want, "{lines:?}");
}
}
}
+53
View File
@@ -74,6 +74,55 @@ impl Default for CellStroke {
}
}
/// Cell Options › Diagonal Lines: the diagonals drawn across a cell.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DiagonalLines {
#[default]
None,
/// From the top left corner to the bottom right corner.
TopLeft,
/// From the top right corner to the bottom left corner.
TopRight,
/// Both diagonals.
Crossed,
}
/// A cell's diagonal lines, their stroke, and whether they are drawn in front of the cell's
/// contents (Draw › Diagonal In Front) or behind them (Content In Front).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct CellDiagonal {
pub lines: DiagonalLines,
pub stroke: CellStroke,
pub in_front: bool,
}
impl Default for CellDiagonal {
fn default() -> Self {
CellDiagonal { lines: DiagonalLines::None, stroke: CellStroke::default(), in_front: true }
}
}
impl CellDiagonal {
pub fn is_default(&self) -> bool {
*self == CellDiagonal::default()
}
/// The diagonals' ends in the cell rectangle `r`, as (start, end) pairs.
pub fn segments(&self, r: designcraft_geom::Rect) -> Vec<(designcraft_geom::Point, designcraft_geom::Point)> {
use designcraft_geom::Point;
let down = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y1));
let up = (Point::new(r.x1, r.y0), Point::new(r.x0, r.y1));
match self.lines {
DiagonalLines::None => vec![],
DiagonalLines::TopLeft => vec![down],
DiagonalLines::TopRight => vec![up],
DiagonalLines::Crossed => vec![down, up],
}
}
}
impl CellStroke {
pub fn none() -> Self {
CellStroke { weight: 0.0, ..Default::default() }
@@ -207,6 +256,9 @@ pub struct Cell {
/// content box, origin at the box's top left).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graphic: Option<crate::Graphic>,
/// Cell Options › Diagonal Lines.
#[serde(default, skip_serializing_if = "CellDiagonal::is_default")]
pub diagonal: CellDiagonal,
}
impl Default for Cell {
@@ -228,6 +280,7 @@ impl Default for Cell {
stroke_defined: [false; 4],
style: String::new(),
graphic: None,
diagonal: CellDiagonal::default(),
}
}
}
+21 -2
View File
@@ -147,8 +147,27 @@ fn fields_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let Some(src) = st.doc.data_merge.sources.first() else {
return Ok(json!([]));
};
let placeholders = st.doc.data_merge.placeholders.clone();
Ok(fields_json(&src.fields, |name| placeholders.iter().filter(|ph| ph.field == name).count()))
let doc = st.preview_stash.as_deref().unwrap_or(st.doc.as_ref());
let placeholders = &doc.data_merge.placeholders;
let mut marker_counts = std::collections::HashMap::<String, usize>::new();
for (story_id, story) in &doc.stories {
// The generated endnote frame repeats note text already counted in its owning story.
if Some(*story_id) == doc.endnote_story {
continue;
}
for (start, end, name) in fill::find_markers(&story.text) {
// A bound placeholder already accounts for its marker in the usage count.
let covered = placeholders.iter().any(|ph| {
matches!((&ph.role, &ph.anchor), (PlaceholderRole::Text | PlaceholderRole::Image, PlaceholderAnchor::Text { story, start: a, end: b })
if story == story_id && start < *b && end > *a)
});
if !covered {
*marker_counts.entry(name).or_default() += 1;
}
}
fill::count_nested_markers(story, &mut marker_counts, 0);
}
Ok(fields_json(&src.fields, |name| placeholders.iter().filter(|ph| ph.field == name).count() + marker_counts.get(name).copied().unwrap_or(0)))
}
fn placeholder_add(s: &mut Session, p: &Value) -> Result<Value> {
+21 -1
View File
@@ -417,6 +417,26 @@ fn fill_inner(st: &mut Story, fields: &[DataField], row: &[String], depth: usize
}
}
/// Count markers in nested text to match the merge's depth limit.
pub(super) fn count_nested_markers(st: &Story, counts: &mut HashMap<String, usize>, depth: usize) {
if depth >= MAX_NESTED_DEPTH {
return;
}
let mut count = |inner: &Story| {
for (_, _, name) in find_markers(&inner.text) {
*counts.entry(name).or_default() += 1;
}
count_nested_markers(inner, counts, depth + 1);
};
for table in st.tables.values() {
for cell in &table.cells {
count(&cell.text);
}
}
for note in st.notes.iter().chain(st.endnotes.iter()) {
count(&note.text);
}
}
/// Replace the markers of known fields in `st`'s own text with the record's values.
fn fill_own(st: &mut Story, fields: &[DataField], row: &[String]) {
let found: Vec<(usize, usize, String)> =
@@ -426,7 +446,7 @@ fn fill_own(st: &mut Story, fields: &[DataField], row: &[String]) {
}
}
fn find_markers(text: &str) -> Vec<(usize, usize, String)> {
pub(super) fn find_markers(text: &str) -> Vec<(usize, usize, String)> {
let mut out = Vec::new();
let mut i = 0;
// The next `>>` at or after the `<<` being looked at: found once, kept until passed, so the
+50
View File
@@ -1654,8 +1654,10 @@ fn a_field_converted_into_a_table_is_filled_in_its_cell() {
exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 13}));
exec(&mut s, "table.convertFromText", json!({"columnSeparator": "tab"}));
assert_eq!(cell_texts(&s), ["Name", "<<Name>>"]);
assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1);
exec(&mut s, "data.preview", json!({"record": 1}));
assert_eq!(cell_texts(&s), ["Name", "Ada"], "the field is filled in its cell");
assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1, "the count reads the unfilled template while previewing");
}
/// A table `Who⇥Where` with the caret in its second cell, and a source with `Name` and `City`.
@@ -1745,6 +1747,7 @@ fn a_field_in_an_endnote_is_filled() {
s.documents()[s.active_index().unwrap()].doc.stories.values().flat_map(|st| st.endnotes.iter().map(|e| e.text.text.clone())).collect()
};
assert_eq!(endnotes(&s), ["From <<City>>"]);
assert_eq!(exec(&mut s, "data.fields", json!({}))[1]["uses"], 1);
exec(&mut s, "data.preview", json!({"record": 1}));
assert_eq!(endnotes(&s), ["From London"]);
}
@@ -1799,3 +1802,50 @@ fn select_records_stops_expanding_once_the_limit_is_met_but_still_checks_every_r
assert!(parse::select_records(10, "range", 1, "1-10,5-11", Some(2)).is_err());
assert!(parse::select_records(10, "range", 1, "1-2,0", Some(2)).is_err());
}
#[test]
fn idml_reopen_relink_counts_existing_text_field() {
let dir = scratch("idml-field-count");
let csv = dir.join("people.csv");
let idml = dir.join("template.idml");
write(&csv, "Name\nAda\n");
let mut s = Session::new();
new_doc(&mut s, 1);
text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "", None);
exec(&mut s, "data.source.select", json!({"path": csv}));
exec(&mut s, "data.placeholder.add", json!({"field": "Name"}));
assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 1);
exec(&mut s, "file.exportIdml", json!({"path": idml}));
let mut reopened = Session::new();
exec(&mut reopened, "file.openIdml", json!({"path": idml}));
exec(&mut reopened, "data.source.select", json!({"path": csv}));
let uses = exec(&mut reopened, "data.fields", json!({}))[0]["uses"].clone();
exec(&mut reopened, "data.merge", json!({}));
assert!(texts(&reopened).contains(&"Ada".to_string()));
assert_eq!(uses, 1);
}
#[test]
fn fields_count_unbound_markers_without_double_counting_bound_placeholders() {
let mut s = Session::new();
new_doc(&mut s, 1);
select_csv(&mut s, "Name\nAda\n");
text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "<<Name>> <<Name>>", None);
text_frame(&mut s, [36.0, 100.0, 240.0, 150.0], "", None);
exec(&mut s, "data.placeholder.add", json!({"field": "Name"}));
assert_eq!(exec(&mut s, "data.fields", json!({}))[0]["uses"], 3);
assert_eq!(exec(&mut s, "data.fields", json!({"csv": "Name\nAda\n"}))[0]["uses"], 0);
}
#[test]
fn hyperlink_over_marker_does_not_hide_its_field_usage() {
let mut s = Session::new();
new_doc(&mut s, 1);
select_csv(&mut s, "Name,Link\nAda,https://example.com\n");
let made = text_frame(&mut s, [36.0, 36.0, 240.0, 80.0], "<<Name>>", None);
exec(&mut s, "text.select", json!({"story": made["story"], "anchor": 0, "focus": 8}));
exec(&mut s, "data.placeholder.add", json!({"field": "Link", "role": "hyperlink"}));
let fields = exec(&mut s, "data.fields", json!({}));
assert_eq!(fields[0]["uses"], 1);
assert_eq!(fields[1]["uses"], 1);
}
+30
View File
@@ -438,6 +438,36 @@ mod pptx_tests {
assert!(s.execute("file.exportPptx", &json!({"pages": [9]})).is_err());
}
#[test]
fn cell_diagonal_lines_export_as_cell_diagonal_borders() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
for (row, col, lines) in [(0, 0, "topLeft"), (0, 1, "topRight"), (1, 0, "crossed")] {
s.execute("table.setCell", &json!({"row": row, "col": col, "diagonal": {"lines": lines, "weight": 3}})).unwrap();
}
let r = s.execute("file.exportPptx", &json!({})).unwrap();
let x = read(&mut unzip(r["base64"].as_str().unwrap()), "ppt/slides/slide1.xml");
let cells: Vec<&str> = x.split("</a:tc>").filter(|c| c.contains("<a:tcPr")).collect();
assert_eq!(cells.len(), 4, "{x}");
let has = |c: &str| (c.contains("<a:lnTlToBr w=\"38100\""), c.contains("<a:lnBlToTr w=\"38100\""));
let got: Vec<(bool, bool)> = cells.iter().map(|c| has(c)).collect();
assert_eq!(got, [(true, false), (false, true), (true, true), (false, false)], "{x}");
// The diagonals follow the four edges and come before the cell's fill, in the schema's order.
let c = cells[2];
let at = |tag: &str| c.find(tag).unwrap_or(usize::MAX);
assert!(at("<a:lnB ") < at("<a:lnTlToBr") && at("<a:lnTlToBr") < at("<a:lnBlToTr"), "{c}");
assert!(c.rfind("Fill").is_some_and(|f| f > at("<a:lnBlToTr")), "{c}");
// The slide has no drawing order for them, so diagonals behind the contents are reported.
let behind = |r: &serde_json::Value| r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("diagonal lines"));
assert!(!behind(&r), "{}", r["warnings"]);
s.execute("table.setCell", &json!({"row": 1, "col": 0, "diagonal": {"inFront": false}})).unwrap();
let r = s.execute("file.exportPptx", &json!({})).unwrap();
assert!(behind(&r), "{}", r["warnings"]);
}
#[test]
fn rasterize_option_places_a_picture() {
let mut s = Session::new();
+58 -2
View File
@@ -279,7 +279,14 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
}
let skew = if st.skew != 0.0 { Affine::new([1.0, 0.0, -st.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
let shatai = st.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
let a = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
let mut a = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
// Upright in vertical text, as the canvas and the PDF export draw it (#2895):
// without the turn, CJK glyphs lay on their sides along the column.
if ft.vertical
&& let Some(turn) = g.vertical_xf(l.baseline)
{
a = turn * a;
}
let key = (li, st.fill.clone(), st.fill_tint, st.stroke.clone(), st.stroke_tint, st.stroke_weight, st.stroke_behind_fill);
let k = match runs.iter().position(|r| r.0 == key) {
Some(k) => k,
@@ -298,6 +305,8 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
let (sr, _) = spread_xf(d, *id).ok_or(designcraft_doc::DocError::NoItem(*id))?;
let at = d.spread(sr).and_then(|sp| sp.items.iter().position(|i| i.id == *id));
let text_xf = d.text_xf(&it);
// Text space → the item's inner space: a vertical frame's quarter turn (#2895).
let text_local = d.text_local(&it);
let make = |d: &mut Document, ((_, fill, ft, stroke, stt, sw, behind), bp): ((usize, String, f32, String, f32, f64, bool), BezPath)| {
let mut o = Item::new(ItemId(d.alloc()), it.layer, Shape::Path, PathData::from_bezpath(&bp));
o.xf = text_xf;
@@ -319,8 +328,10 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
one
} else {
let mut g = Item::new(ItemId(d.alloc()), it.layer, Shape::Group, PathData::default());
// Each line is in text space: in the group (which has the frame's transform) it
// takes the frame's text turn, so the columns of vertical text stay columns.
for p in &mut parts {
p.xf = Affine::IDENTITY;
p.xf = text_local;
}
g.xf = it.xf;
g.content = Content::Group { items: parts.into_iter().map(Arc::new).collect() };
@@ -689,4 +700,49 @@ mod tests {
assert!(!it.path.is_closed());
assert_eq!(it.path.anchor_count(), 6);
}
/// #2895: Create Outlines on vertical text draws the glyphs where the canvas does. Upright
/// glyphs take their own quarter turn, and a frame of several columns (a group of lines) keeps
/// the frame's turn: the columns stay columns, read top to bottom.
#[test]
fn outlines_of_vertical_text_stay_where_the_text_was_drawn() {
let family = "DC Test Outline Vertical";
designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::font_with(family, &['一', '日']).unwrap());
for (text, columns) in [("日一", 1), ("日一\n一日", 2)] {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id =
s.execute("frame.create", &json!({"rect": [100, 100, 300, 500], "content": "text", "text": text})).unwrap()["id"].as_u64().unwrap();
s.execute("selection.set", &json!({"ids": [id]})).unwrap();
s.execute("type.char", &json!({"fontFamily": family, "fontStyle": "Regular"})).unwrap();
s.execute("type.storyDirection", &json!({"vertical": true})).unwrap();
// Where the canvas draws each glyph (render/src/text.rs): the frame's text transform,
// then each upright glyph's turn, then its place on the line.
let d = s.doc().unwrap().doc.clone();
let it = d.item(ItemId(id)).unwrap().clone();
let story = it.text_frame().unwrap().story;
let cs = designcraft_compose::compose_story(&d, story, &Default::default());
let ft = cs.frame(ItemId(id)).unwrap();
assert!(ft.vertical);
assert_eq!(ft.lines.len(), columns, "{text}");
let db = designcraft_fonts::FontDb::global();
let text_xf = d.text_xf(&it);
let mut drawn: Option<kurbo::Rect> = None;
for l in &ft.lines {
for g in l.glyphs.iter().filter(|g| g.visible) {
assert!(g.upright, "{text}: CJK is set upright");
let turn = g.vertical_xf(l.baseline).unwrap();
let a = text_xf * turn * Affine::translate((g.x, l.baseline + g.y)) * Affine::scale_non_uniform(g.sx, g.sy);
let b = (a * db.outline(&g.face, g.gid).as_ref().clone()).bounding_box();
drawn = Some(drawn.map_or(b, |r| r.union(b)));
}
}
let drawn = drawn.unwrap();
let out = ItemId(s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap());
let b = s.doc().unwrap().doc.item(out).unwrap().bounds();
for (got, want) in [(b.x0, drawn.x0), (b.y0, drawn.y0), (b.x1, drawn.x1), (b.y1, drawn.y1)] {
assert!((got - want).abs() < 0.01, "{text}: outlines {b:?}, drawn {drawn:?}");
}
}
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ const ID: &str = "ink.separations";
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(query "ink.separations", "Separations Preview", [], None,
"{page?: 1-based page position (default 1; its spread is separated), dpi?: 9–300 (default 72), inkLimit?: percent, standard?: none|x4|a2b, compressImages?: bool, flatten?: high|medium|low|ppi (as file.exportPdf)} — the spread exported as Export PDF prints it and separated → {spread, dpi, width, height, conversion, inks: [{name, spot, max, mean, area} (percent)], unseparated: [spot names past 32], maxTotal, maxTotalAt?: [x, y] (pt, spread), overLimit?: {limit, pixels, regions: [{x, y, width, height}] (pt, spread)}, warnings}",
"{page?: 1-based page position (default 1; its spread is separated), dpi?: 9–300 (default 72; lowered to fit 4 megapixels per plate, as for an A5 page or larger at 300, which `dpi` and a warning then say), inkLimit?: percent, standard?: none|x4|a2b, compressImages?: bool, flatten?: high|medium|low|ppi (as file.exportPdf)} — the spread exported as Export PDF prints it and separated → {spread, dpi, width, height, conversion, inks: [{name, spot, max, mean, area} (percent)], unseparated: [spot names past 32], maxTotal, maxTotalAt?: [x, y] (pt, spread), overLimit?: {limit, pixels, regions: [{x, y, width, height}] (pt, spread)}, warnings}",
has_doc, separations)]
}
+6 -4
View File
@@ -495,6 +495,7 @@ mod swatch_options_tests {
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
s.execute("table.select", &json!({"what": "table"})).unwrap();
s.execute("table.setCell", &json!({"stroke": {"weight": 2, "type": "dashed", "gapColor": "Brand", "edges": ["all"]}})).unwrap();
s.execute("table.setCell", &json!({"diagonal": {"lines": "crossed", "type": "dashed", "color": "Brand", "gapColor": "Brand"}})).unwrap();
s.execute("swatch.newColorGroup", &json!({"name": "Brand Colors", "swatches": ["Brand"]})).unwrap();
s.execute("style.character.create", &json!({"name": "Accent"})).unwrap();
let image = s.execute("frame.create", &json!({"rect": [72, 300, 200, 400], "content": "graphic"})).unwrap()["id"].as_u64().unwrap();
@@ -557,6 +558,7 @@ mod swatch_options_tests {
basic.chars.ruby_stroke.as_deref() == Some(name),
d.styles.char_style("Accent").unwrap().chars.kenten_fill.as_deref() == Some(name),
story.tables.values().any(|t| t.cells.iter().all(|c| c.strokes.iter().all(|e| e.gap_color == name))),
story.tables.values().any(|t| t.cells.iter().all(|c| c.diagonal.stroke.color == name && c.diagonal.stroke.gap_color == name)),
d.spreads.iter().flat_map(|sp| &sp.items).any(|it| it.graphic().is_some_and(|g| g.fill.swatch == name)),
story.tables.values().any(|t| t.cells.iter().any(|c| c.graphic.as_ref().is_some_and(|g| g.fill.swatch == name))),
]
@@ -571,10 +573,10 @@ mod swatch_options_tests {
let d = &s.doc().unwrap().doc;
assert!(d.swatch("Brand").is_none());
assert!(matches!(d.swatch("Signal Orange").unwrap().value, SwatchValue::Color { color_type: designcraft_color::ColorType::Spot, .. }));
assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 14]);
assert_eq!(uses(&s, id, sid, "Signal Orange"), vec![true; 15]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Brand").is_some());
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 14]);
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 15]);
}
#[test]
@@ -595,7 +597,7 @@ mod swatch_options_tests {
assert!(s.execute("swatch.options", &p).is_err(), "{p}");
}
assert_eq!(s.doc().unwrap().doc.swatches, before.swatches);
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 14]);
assert_eq!(uses(&s, id, sid, "Brand"), vec![true; 15]);
// [Paper]'s colour can change; its name can't.
s.execute("swatch.options", &json!({"name": "[Paper]", "to": "[Paper]", "color": "#fff8e0"})).unwrap();
}
@@ -605,7 +607,7 @@ mod swatch_options_tests {
let (mut s, id, sid) = brand_doc();
let r = s.execute("swatch.options", &json!({"name": "Brand", "nameWithValue": true, "color": {"c": 10, "m": 20, "y": 30, "k": 40}})).unwrap();
assert_eq!(r["name"], "C=10 M=20 Y=30 K=40");
assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 14]);
assert_eq!(uses(&s, id, sid, "C=10 M=20 Y=30 K=40"), vec![true; 15]);
// Later colour edits keep the name in step until the swatch is named by hand.
let r = s.execute("swatch.options", &json!({"name": "C=10 M=20 Y=30 K=40", "color": {"c": 0, "m": 0, "y": 0, "k": 50}})).unwrap();
assert_eq!(r["name"], "C=0 M=0 Y=0 K=50");
+2 -2
View File
@@ -9,8 +9,8 @@
use designcraft_compose as compose;
use designcraft_doc::story::floor_char_boundary;
use designcraft_doc::{
AltFills, CellAddr, CellRange, CellStroke, Document, RowHeightMode, RowKind, Selection, StoryId, StrokeType, Table, TableSel, TextSel,
VerticalJustification,
AltFills, CellAddr, CellRange, CellStroke, DiagonalLines, Document, RowHeightMode, RowKind, Selection, StoryId, StrokeType, Table, TableSel,
TextSel, VerticalJustification,
};
use serde_json::{Value, json};
+87 -1
View File
@@ -1,5 +1,8 @@
use super::target::{clamp_selection, target};
use super::{CellRange, CellStroke, Document, Result, Session, StrokeType, Table, Value, VerticalJustification, bad, compose, json, ok, str_param};
use super::{
CellRange, CellStroke, DiagonalLines, Document, Result, Session, StrokeType, Table, Value, VerticalJustification, bad, compose, json, ok,
str_param,
};
/// Cell edges chosen for a stroke edit: the target range's four outer sides (physical left and
/// right) and the lines between its rows and columns.
@@ -146,6 +149,48 @@ impl StrokeEdit {
}
}
/// A `diagonal` edit of `table.setCell`: the lines, their stroke attributes and Draw.
struct DiagonalEdit {
lines: Option<DiagonalLines>,
stroke: StrokeEdit,
in_front: Option<bool>,
}
impl DiagonalEdit {
fn parse(doc: &Document, v: &Value, cmd: &str) -> Result<DiagonalEdit> {
if !v.is_object() {
return Err(bad(cmd, "diagonal must be an object"));
}
let lines = match v.get("lines").filter(|l| !l.is_null()) {
Some(Value::String(name)) => match name.as_str() {
"none" => Some(DiagonalLines::None),
"topLeft" => Some(DiagonalLines::TopLeft),
"topRight" => Some(DiagonalLines::TopRight),
"crossed" => Some(DiagonalLines::Crossed),
other => return Err(bad(cmd, format!("unknown diagonal lines `{other}`: none, topLeft, topRight or crossed"))),
},
Some(other) => return Err(bad(cmd, format!("diagonal lines must be a string, not {other}"))),
None => None,
};
let in_front = match v.get("inFront").filter(|f| !f.is_null()) {
Some(Value::Bool(b)) => Some(*b),
Some(other) => return Err(bad(cmd, format!("inFront must be true or false, not {other}"))),
None => None,
};
Ok(DiagonalEdit { lines, stroke: StrokeEdit::parse(doc, v, cmd)?, in_front })
}
fn apply(&self, d: &mut designcraft_doc::CellDiagonal) {
if let Some(l) = self.lines {
d.lines = l;
}
d.stroke = self.stroke.apply(d.stroke.clone());
if let Some(f) = self.in_front {
d.in_front = f;
}
}
}
/// The stroke drawn on side `side` of the owner cell at `(r, c)` (where that side meets its
/// first neighbour), as rendering resolves it; the cell's own copy if the side has no stretch.
fn drawn_side(t: &Table, owners: &[(usize, usize)], (r, c): (usize, usize), side: usize) -> Option<CellStroke> {
@@ -247,6 +292,10 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
Some(sv) => Some((StrokeEdit::parse(doc, sv, ID)?, EdgeSel::parse(sv.get("edges"), ID)?)),
None => None,
};
let diagonal = match p.get("diagonal").filter(|v| !v.is_null()) {
Some(dv) => Some(DiagonalEdit::parse(doc, dv, ID)?),
None => None,
};
let apply = |t: &mut Table| {
let owners = t.owners();
let nc = t.ncols();
@@ -323,6 +372,9 @@ pub(super) fn set_cell(s: &mut Session, p: &Value) -> Result<Value> {
let len = cell.text.len();
cell.text.replace(0..len, tx);
}
if let Some(edit) = &diagonal {
edit.apply(&mut cell.diagonal);
}
if let Some((edit, _)) = &stroke {
for i in 0..4 {
if let Some(base) = bases.remove(&(r, c, i)) {
@@ -412,6 +464,40 @@ pub(super) fn get_cell_stroke(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Object(out))
}
/// The diagonal lines of the target cells and their stroke; values that differ are null. The
/// result also names the target cells (`story`, `table`, `rows`, `cols`).
pub(super) fn get_cell_diagonal(s: &mut Session, p: &Value) -> Result<Value> {
const ID: &str = "table.getCellDiagonal";
let g = target(s, p, ID)?;
let st = s.doc()?;
let t = st.doc.story(g.story).and_then(|x| x.tables.get(&g.table)).ok_or_else(|| bad(ID, "no table"))?;
let keys = ["lines", "weight", "color", "tint", "type", "gapColor", "gapTint", "inFront"];
let mut slots: [Option<Value>; 8] = Default::default();
for (r, c) in t.selected_owners(g.range) {
let Some(cell) = t.cell(r, c) else { continue };
let d = &cell.diagonal;
let e = &d.stroke;
let values =
[json!(d.lines), json!(e.weight), json!(e.color), json!(e.tint), json!(e.kind), json!(e.gap_color), json!(e.gap_tint), json!(d.in_front)];
for (slot, v) in slots.iter_mut().zip(values) {
match slot {
None => *slot = Some(v),
Some(cur) if *cur != v => *cur = Value::Null,
_ => {}
}
}
}
let mut out = serde_json::Map::new();
for (k, v) in keys.iter().zip(slots) {
out.insert((*k).into(), v.unwrap_or(Value::Null));
}
out.insert("story".into(), json!(g.story.0));
out.insert("table".into(), json!(g.table));
out.insert("rows".into(), json!([g.range.r0, g.range.r1]));
out.insert("cols".into(), json!([g.range.c0, g.range.c1]));
Ok(Value::Object(out))
}
/// Only saturation needs rebasing. Preserve every distinct priority's order and keep
/// zero/negative priorities untouched; the work is bounded by the table's edges.
fn next_cell_stroke_priority(t: &mut Table) -> i32 {
+1 -1
View File
@@ -83,7 +83,7 @@ pub(super) fn get(s: &mut Session, p: &Value) -> Result<Value> {
.filter_map(|(r, c)| {
let cell = t.cell(r, c)?;
Some(json!({"row": r, "col": c, "rowSpan": cell.row_span, "colSpan": cell.col_span, "text": cell.text.text, "fill": cell.fill,
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style}))
"insets": cell.insets, "vj": cell.vj, "firstBaseline": cell.first_baseline, "firstBaselineMin": cell.first_baseline_min, "rotation": cell.rotation, "style": cell.style, "diagonal": cell.diagonal}))
})
.collect();
out["cells"] = json!(cells);
+11 -2
View File
@@ -1,4 +1,4 @@
use super::cell::{get_cell_stroke, set_cell};
use super::cell::{get_cell_diagonal, get_cell_stroke, set_cell};
use super::content::{drop_cells, place_graphic, sort_rows};
use super::options::{get, options};
use super::selection::{go_to_row, move_rc, select, step_cell, toggle_selection};
@@ -292,7 +292,7 @@ fn table_specs() -> Vec<CommandSpec> {
"Cell Options",
[],
None,
"{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",
"{fill?: swatch, tint?: 0..1, insets?: n | [t,l,b,r], vj? | verticalJustification?: top|center|bottom|justify, firstBaseline?: ascent|capHeight|leading|xHeight|fixed|emboxHeight, firstBaselineMin?: pt, rotation?: 0|90|180|270 (Cell Options › Text › Rotation; kept and written back to IDML, composed horizontally for now), text?, stroke?: {weight?, color?: swatch, tint?: 0..1, type?: solid|dashed|dotted|thickThin|thinThick|thinThin|thickThick|thinThickThin|thickThinThick|wavy|hashed | {kind:…}, gapColor?: swatch, gapTint?: 0..1, edges?: name | [names] (all|outer|inner|top|left|bottom|right|innerHorizontal|innerVertical; default all)}, diagonal?: {lines?: none|topLeft|topRight|crossed (Cell Options › Diagonal Lines: top left to bottom right, top right to bottom left, or both), weight?, color?, tint?, type?, gapColor?, gapTint? (as stroke), inFront?: bool (true: Diagonal In Front, false: Content In Front)}, story?, table?, rows?: [a, b] | row?, cols?: [a, b] | col? (the target cells; default: the selection)} — top/left/bottom/right are the target range's outer sides, innerHorizontal/innerVertical the lines between its rows/columns",
in_table,
set_cell
),
@@ -305,6 +305,15 @@ fn table_specs() -> Vec<CommandSpec> {
in_table_or_ids,
get_cell_stroke
),
cmd!(
query "table.getCellDiagonal",
"Get Cell Diagonal Lines",
[],
None,
"{story?, table?, rows?, cols?} → {lines, weight, color, tint, type, gapColor, gapTint, inFront} of the target cells' diagonal lines (a value that differs between them is null), with story, table, rows: [a, b] and cols: [a, b] naming the target cells",
in_table_or_ids,
get_cell_diagonal
),
cmd!(
"table.setRowHeight",
"Row Height",
+48
View File
@@ -300,6 +300,54 @@ mod style_tests {
assert_eq!(t.cell(1, 0).unwrap().first_baseline, designcraft_doc::FirstBaseline::Ascent);
}
#[test]
fn diagonal_lines_are_a_cell_option_of_the_target_cells() {
use designcraft_doc::DiagonalLines;
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 400], "content": "text", "text": ""})).unwrap();
let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 0})).unwrap();
s.execute("table.insert", &json!({"rows": 2, "cols": 2})).unwrap();
let fresh = s.execute("table.getCellDiagonal", &json!({})).unwrap();
assert_eq!((&fresh["lines"], &fresh["weight"], &fresh["inFront"]), (&json!("none"), &json!(1.0), &json!(true)));
let p = json!({"rows": [0, 0], "cols": [0, 1], "diagonal": {"lines": "crossed", "weight": 2, "color": "[Paper]", "type": "dotted", "inFront": false}});
s.execute("table.setCell", &p).unwrap();
let cell = |s: &Session, r: usize, c: usize| {
s.doc().unwrap().doc.story(sid).unwrap().tables.values().next().unwrap().cell(r, c).unwrap().diagonal.clone()
};
let d = cell(&s, 0, 1);
assert_eq!(
(d.lines, d.stroke.weight, d.stroke.color.as_str(), &d.stroke.kind, d.in_front),
(DiagonalLines::Crossed, 2.0, "[Paper]", &designcraft_doc::StrokeType::Dotted, false)
);
assert!(cell(&s, 1, 0).is_default(), "other cells keep none");
// Only the attributes given change.
s.execute("table.setCell", &json!({"row": 0, "col": 0, "diagonal": {"lines": "topRight"}})).unwrap();
let d = cell(&s, 0, 0);
assert_eq!((d.lines, d.stroke.weight, d.in_front), (DiagonalLines::TopRight, 2.0, false));
let got = s.execute("table.getCellDiagonal", &json!({"rows": [0, 0], "cols": [0, 1]})).unwrap();
assert_eq!(
(&got["lines"], &got["weight"], &got["color"], &got["inFront"]),
(&serde_json::Value::Null, &json!(2.0), &json!("[Paper]"), &json!(false)),
"{got}"
);
let tid = s.doc().unwrap().doc.story(sid).unwrap().tables.keys().next().copied().unwrap();
assert_eq!(
(&got["story"], &got["table"], &got["rows"], &got["cols"]),
(&json!(sid.0), &json!(tid), &json!([0, 0]), &json!([0, 1])),
"the result names the target cells"
);
let shown = s.execute("table.get", &json!({})).unwrap()["cells"][1]["diagonal"].clone();
assert_eq!((&shown["lines"], &shown["inFront"]), (&json!("crossed"), &json!(false)));
for bad in [json!({"lines": "x"}), json!({"lines": 1}), json!({"inFront": "yes"}), json!({"weight": -1}), json!("crossed")] {
assert!(s.execute("table.setCell", &json!({"row": 0, "col": 0, "diagonal": bad})).is_err(), "{bad}");
}
assert_eq!(cell(&s, 0, 0).lines, DiagonalLines::TopRight, "a refused edit changes nothing");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(cell(&s, 0, 0).lines, DiagonalLines::Crossed, "one undo step per edit");
}
#[test]
fn cell_and_table_styles_apply_and_follow_edits() {
let mut s = Session::new();
+154
View File
@@ -296,4 +296,158 @@ mod tests {
let glyphs: usize = cs.frames[0].lines.iter().map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum();
assert_eq!(glyphs, "SeeChapter".len());
}
/// Every `/Rect` in an exported PDF, as `[x0, y0, x1, y1]`: the link annotations of a
/// document with nothing else annotated.
fn link_rects(s: &mut Session) -> Vec<[f64; 4]> {
let r = s.execute("file.exportPdf", &json!({})).unwrap();
let bytes = super::super::file::base64_decode(r["base64"].as_str().unwrap());
let text = String::from_utf8_lossy(&bytes).into_owned();
let mut out = Vec::new();
for part in text.split("/Rect[").skip(1) {
let Some(end) = part.find(']') else { continue };
let v: Vec<f64> = part[..end].split_whitespace().filter_map(|n| n.parse().ok()).collect();
if let [x0, y0, x1, y1] = v[..] {
out.push([x0, y0, x1, y1]);
}
}
out
}
/// A cross-reference's link covered its first letter only: the source range is the one marker
/// character, and the glyphs of the text it generates all point at that character while only
/// the first of them owns it, so measuring the glyphs that own their bytes measured one glyph
/// — a ~7 pt link under ~40 pt of text (#1446).
#[test]
fn a_cross_references_link_covers_the_text_it_generated() {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let sp = s.doc().unwrap().doc.page_loc(1).unwrap().0;
s.execute("frame.create", &json!({"spread": sp, "rect": [72, 72, 400, 200], "content": "text", "text": "Photo 1"})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "See for details."})).unwrap();
let src = r["story"].clone();
s.execute("text.select", &json!({"story": src, "anchor": 4, "focus": 4})).unwrap();
s.execute("xref.defineFormat", &json!({"name": "Bare", "definition": "<paraText />"})).unwrap();
s.execute("xref.insert", &json!({"paragraph": "Photo 1", "format": "Bare"})).unwrap();
let generated = s.execute("xref.list", &json!({})).unwrap()[0]["text"].as_str().unwrap().to_string();
assert_eq!(generated, "Photo 1");
let xref_rects = link_rects(&mut s);
assert_eq!(xref_rects.len(), 1, "one link, for the cross-reference: {xref_rects:?}");
let xref_width = xref_rects[0][2] - xref_rects[0][0];
// The same text, written out and linked as text: the same letters in the same font at the
// same size, so the two links cover the same width.
let mut t = Session::new();
t.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let r = t
.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": format!("See {generated} for details.")}))
.unwrap();
let story = r["story"].clone();
let (start, end) = (4, 4 + generated.len());
t.execute("text.select", &json!({"story": story, "anchor": start, "focus": end})).unwrap();
t.execute("hyperlink.create", &json!({"page": 2})).unwrap();
let plain = link_rects(&mut t);
assert_eq!(plain.len(), 1, "{plain:?}");
let plain_width = plain[0][2] - plain[0][0];
assert!(plain_width > 20.0, "the text is wider than one glyph: {plain_width}");
assert!((xref_width - plain_width).abs() < 1.0, "the cross-reference covers its text: {xref_width} vs {plain_width}");
// And it starts where the text starts.
assert!((xref_rects[0][0] - plain[0][0]).abs() < 1.0, "{:?} vs {:?}", xref_rects[0], plain[0]);
}
/// A link starting at the first character of a numbered paragraph took the number in: the
/// composer gives the list label that character's offset and no length, so the rectangle
/// reached over text outside the link (noted in review of #1446).
#[test]
fn a_links_rectangle_leaves_out_the_number_a_list_adds() {
// The same linked words twice: once in a plain paragraph, once in a numbered one.
let width = |numbered: bool| {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Linked words here"})).unwrap();
let story = r["story"].clone();
if numbered {
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 0})).unwrap();
s.execute("type.para", &json!({"attrs": {"listType": "numbers"}})).unwrap();
}
// The link starts at the paragraph's first character, where the label also sits.
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": "Linked words".len()})).unwrap();
s.execute("hyperlink.create", &json!({"page": 2})).unwrap();
let rects = link_rects(&mut s);
assert_eq!(rects.len(), 1, "one link (numbered: {numbered}): {rects:?}");
(rects[0][2] - rects[0][0], rects[0][0])
};
let (plain, plain_x0) = width(false);
let (listed, listed_x0) = width(true);
assert!(plain > 20.0, "the linked words are wider than one glyph: {plain}");
// The same letters at the same size, so the link is the same width either way. The label
// sits before the text and the paragraph is indented for it, so the rectangle starts
// further right -- but it covers the words and nothing else.
assert!((listed - plain).abs() < 1.0, "the number is not inside the link: {listed} vs {plain}");
assert!(listed_x0 >= plain_x0, "the numbered paragraph's text starts no earlier: {listed_x0} vs {plain_x0}");
}
/// A list label's tab can carry a leader: the paragraph defines a stop at the Tab Position
/// with one, so the composer does not add its own stop there and the label's tab takes that
/// leader. Those leader glyphs carry the paragraph's first byte, as the label does, but were
/// not flagged as part of it -- so a link starting at the first text character swept them into
/// its rectangle and it reached back across the label (#1495 review).
#[test]
fn a_links_rectangle_leaves_out_the_leader_of_a_list_labels_tab() {
let left_edge = |leader: bool| {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 460, 200], "content": "text", "text": "Chapter one here"})).unwrap();
let story = r["story"].clone();
s.execute("text.select", &json!({"story": story.clone(), "anchor": 0, "focus": 1})).unwrap();
s.execute("type.para", &json!({"listType": "numbers", "listTab": 72})).unwrap();
if leader {
s.execute("type.tabs.add", &json!({"position": 72, "leader": "."})).unwrap();
}
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": "Chapter one".len()})).unwrap();
s.execute("hyperlink.create", &json!({"page": 2})).unwrap();
let rects = link_rects(&mut s);
assert_eq!(rects.len(), 1, "one link (leader: {leader}): {rects:?}");
rects[0][0]
};
// The same link, with and without a leader on the label's tab: the leader sits between the
// label and the text, so taking it in would move the rectangle's left edge leftwards.
let plain = left_edge(false);
let dotted = left_edge(true);
assert!((dotted - plain).abs() < 0.5, "the leader is left out of the link: {dotted} vs {plain}");
}
/// The rectangle is the extent of the selected glyphs, not the first and the last of them.
/// Kenten marks and ruby are appended after a line's base glyphs, so with only the first
/// character marked the last glyph in the range was that mark, sitting over the first
/// character -- and the link ended there, leaving the rest of it unclickable (noted in
/// review of #1446).
#[test]
fn a_links_rectangle_spans_its_glyphs_whatever_order_they_are_in() {
let width = |marked: bool| {
let mut s = Session::new();
s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Linked words here"})).unwrap();
let story = r["story"].clone();
if marked {
// The first character only, so its mark is the line's last glyph.
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": 1})).unwrap();
s.execute("type.char", &json!({"attrs": {"kenten": true}})).unwrap();
}
s.execute("text.select", &json!({"story": story, "anchor": 0, "focus": "Linked words".len()})).unwrap();
s.execute("hyperlink.create", &json!({"page": 2})).unwrap();
let rects = link_rects(&mut s);
assert_eq!(rects.len(), 1, "one link (marked: {marked}): {rects:?}");
rects[0][2] - rects[0][0]
};
let plain = width(false);
assert!(plain > 20.0, "the linked words are wider than one glyph: {plain}");
// A mark over the first character does not shorten the link to that character.
let marked = width(true);
assert!((marked - plain).abs() < 1.0, "the link still covers its words: {marked} vs {plain}");
}
}
+472 -3
View File
@@ -13,6 +13,11 @@
//! (`/work2` isn't inside `/work`), in the case the file system stores (so a case-variant name
//! reaches the same folder on an ordinary Windows volume, and a distinct sibling in a
//! case-sensitive one stays outside). Two roots don't make their common parent one.
//! - On Windows a network path (`\\server\share`, `\\?\UNC\...`, WebDAV's `\\host@SSL\share`), a
//! device path (`\\.\...`) or a verbatim path that isn't a disk (a volume by its `\\?\Volume{…}` name is local) is refused by its name before
//! the file system is asked about it, unless a root is on that same server and share (or that
//! same verbatim prefix). Looking such a path up would contact a host the agent chose. A link
//! whose text leads to one is refused before it is followed.
//! - Read and write access are separate: a root given alone grants only its own kind of access.
//!
//! Roots are in force on a thread inside [`confine`], and in the whole process after
@@ -24,7 +29,7 @@
//! guard against other programs on the computer.
use std::cell::RefCell;
use std::ffi::OsString;
use std::ffi::{OsStr, OsString};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, OnceLock};
@@ -110,7 +115,8 @@ impl AutomationRoots {
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {}", path.display())),
};
}
let resolved = resolve(path)?;
let folders: Vec<&Path> = roots.iter().map(|r| r.resolved.as_path()).collect();
let resolved = resolve(path, &folders)?;
if roots.iter().any(|r| inside(&resolved, &r.resolved)) {
return Ok(());
}
@@ -210,7 +216,10 @@ pub fn check_write(path: impl AsRef<Path>) -> Result<(), String> {
/// `path` made absolute with its links followed; for a path that doesn't exist (yet), its nearest
/// existing folder's links followed and the rest appended.
fn resolve(path: &Path) -> Result<PathBuf, String> {
///
/// A Windows network, device or non-disk verbatim prefix is refused before any of that, unless one
/// of `roots` (resolved folders) already stands on the same server and share or the same verbatim prefix.
fn resolve(path: &Path, roots: &[&Path]) -> Result<PathBuf, String> {
if path.as_os_str().is_empty() {
return Err("automation path rejected: path is empty".into());
}
@@ -218,7 +227,26 @@ fn resolve(path: &Path) -> Result<PathBuf, String> {
if cfg!(windows) && path.components().any(|c| matches!(c, Component::Normal(n) if is_device_name(&n.to_string_lossy()))) {
return Err(format!("automation path rejected: reserved device names are not allowed: {}", path.display()));
}
// Win32 trims a trailing period or space from a name where it looks one up, but not always from a name in the middle: refused as given.
if cfg!(windows) && has_trimmed_name(path) {
return Err(format!("automation path rejected: a name Windows trims: {}", path.display()));
}
// Before `absolute` too: on Windows that call asks the system about the path.
if let Some(why) = refused_prefix(path, roots) {
return Err(format!("automation path rejected: {why}: {}", path.display()));
}
let absolute = std::path::absolute(path).map_err(|e| format!("automation path rejected: cannot resolve {}: {e}", path.display()))?;
if let Some(why) = refused_prefix(&absolute, roots) {
return Err(format!("automation path rejected: {why}: {}", path.display()));
}
// A link is judged by its own text: canonicalizing one that leads to a network path would
// contact that host. Only Windows has such prefixes. One walk of the whole path covers every
// shorter one the loop below tries.
if cfg!(windows)
&& let Some(why) = link_leads_to_refused_prefix(&absolute, roots)
{
return Err(format!("automation path rejected: {why}: {}", path.display()));
}
// The names below the nearest existing folder, last first.
let mut missing: Vec<OsString> = vec![];
let mut at = absolute.as_path();
@@ -273,6 +301,213 @@ pub(crate) fn is_device_name(component: &str) -> bool {
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$") || numbered("COM") || numbered("LPT")
}
/// A Windows path prefix that isn't a local disk: opening or even resolving a path that starts
/// with one can reach another computer.
#[derive(Debug)]
enum OffDisk {
/// `\\server\share` or `\\?\UNC\server\share`; WebDAV's `\\host@SSL\share` is a server name too.
Unc(OsString, OsString),
/// `\\.\device`, which no root stands on: a configured one is canonicalized to a disk path.
Device,
/// `\\?\` followed by anything but a drive or `UNC`.
Verbatim(OsString),
}
impl OffDisk {
/// The prefix of `path` when it isn't a local disk. A drive letter, a path without a prefix
/// and every path off Windows give `None`.
fn of(path: &Path) -> Option<Self> {
use std::path::Prefix;
let Some(Component::Prefix(prefix)) = path.components().next() else { return Self::unparsed(path) };
match prefix.kind() {
Prefix::Disk(_) | Prefix::VerbatimDisk(_) => None,
Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => Some(Self::Unc(server.to_os_string(), share.to_os_string())),
Prefix::DeviceNS(_) => Some(Self::Device),
// A volume named by its GUID (a folder a volume is mounted in) is on this computer.
Prefix::Verbatim(rest) if is_volume_name(rest) => None,
Prefix::Verbatim(rest) => Some(Self::Verbatim(rest.to_os_string())),
}
}
/// A Windows path `std` finds no prefix in, though Windows reads one: two separators that aren't a whole
/// `\\server\share` (`\\server`, `\\\x`) name a computer, so that is a UNC path with no share; `\??\` is
/// the NT form of `\\?\` (`\??\UNC\server\share`), so that is a device path.
fn unparsed(path: &Path) -> Option<Self> {
let bytes = path.as_os_str().as_encoded_bytes();
let separator = |b: Option<&u8>| matches!(b, Some(b'\\' | b'/'));
if !cfg!(windows) {
None
} else if separator(bytes.first()) && separator(bytes.get(1)) {
Some(Self::Unc(OsString::new(), OsString::new()))
} else if bytes.get(..4).is_some_and(|b| b.eq_ignore_ascii_case(br"\??\")) {
Some(Self::Device)
} else {
None
}
}
/// The refusal for a path with this prefix, which names the prefix.
fn refusal(&self) -> &'static str {
match self {
Self::Unc(..) => "UNC paths are refused unless a root is on the same server and share",
Self::Device => "device paths are refused",
Self::Verbatim(_) => "verbatim paths are refused unless a root uses the same prefix",
}
}
/// Whether `other` is the same server and share, or the same verbatim prefix, the ASCII case aside. This
/// decides only whether that host may be contacted; [`inside`] still decides the folder.
fn same_as(&self, other: &Self) -> bool {
let same = |a: &OsString, b: &OsString| a.eq_ignore_ascii_case(b);
match (self, other) {
(Self::Unc(server, share), Self::Unc(other_server, other_share)) => same(server, other_server) && same(share, other_share),
(Self::Verbatim(rest), Self::Verbatim(other)) => same(rest, other),
_ => false,
}
}
}
/// Why `path` must not be looked up: it starts with a Windows network, device or non-disk
/// verbatim prefix and none of `roots` stands on that same server and share or verbatim prefix. A local path gives `None`.
fn refused_prefix(path: &Path, roots: &[&Path]) -> Option<&'static str> {
let prefix = OffDisk::of(path)?;
if roots.iter().filter_map(|root| OffDisk::of(root)).any(|root| root.same_as(&prefix)) { None } else { Some(prefix.refusal()) }
}
/// How many links in a row [`link_leads_to_refused_prefix`] follows before it gives up and refuses.
const MAX_LINK_HOPS: usize = 40;
/// How many spellings of a path one walk scans in all, so a hostile set of links can't make it
/// scan without end.
const MAX_SPELLINGS: usize = 1024;
/// The refusal for a link in `path`, taken from the link's own text.
///
/// Folders are inspected from the top down with [`std::fs::symlink_metadata`], which doesn't follow
/// a link, and a link's target is read with [`std::fs::read_link`]. A link to a network path is
/// therefore refused before [`std::fs::canonicalize`] could open that host, also when the link is
/// only an ancestor of the name. A link whose target can't be read, the one after
/// [`MAX_LINK_HOPS`] in a row, or a walk past [`MAX_SPELLINGS`] spellings, is refused rather than
/// opened.
fn link_leads_to_refused_prefix(path: &Path, roots: &[&Path]) -> Option<&'static str> {
follow_links(path, roots, &mut std::collections::HashSet::new(), MAX_LINK_HOPS)
}
/// [`link_leads_to_refused_prefix`] for one spelling of the path. `judged` holds every spelling the
/// walk has scanned (so none is scanned twice, nor in a cycle forever) and `hops_left` the links
/// still allowed in this chain, which the other spelling of a target does not use up.
fn follow_links(path: &Path, roots: &[&Path], judged: &mut std::collections::HashSet<PathBuf>, hops_left: usize) -> Option<&'static str> {
// A \\?\ path is opened as written, so a link before its `..` is followed; rebuilding the path below would pop that link unseen.
if matches!(path.components().next(), Some(Component::Prefix(p)) if p.kind().is_verbatim())
&& path.components().any(|c| c == Component::ParentDir)
{
return Some("parent traversal in a verbatim path");
}
// Without a trailing separator: Windows reads `remote\` as a folder to go into, so a link named `remote` would be followed by the
// probe itself, to wherever it leads, instead of being seen as a link.
let normalized: PathBuf = path.components().collect();
let path = normalized.as_path();
if !judged.insert(path.to_path_buf()) {
return None;
}
if judged.len() > MAX_SPELLINGS {
return Some("too many links");
}
let mut ancestors: Vec<&Path> = path.ancestors().collect();
ancestors.reverse();
for prefix in ancestors {
if prefix.as_os_str().is_empty() {
continue;
}
if let Some(why) = refused_prefix(prefix, roots) {
return Some(why);
}
let meta = match std::fs::symlink_metadata(prefix) {
Ok(meta) => meta,
// Nothing is there, so no link is below it.
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => return None,
// Anything else (no permission to look): a link below it can't be seen, so don't go on.
Err(_) => return Some("a folder that can't be looked at"),
};
if !meta.file_type().is_symlink() {
continue;
}
if hops_left == 0 {
return Some("too many links");
}
let Ok(target) = std::fs::read_link(prefix) else { return Some("a link that leads nowhere") };
if cfg!(windows) && is_native_name(&target) {
return Some("device paths are refused");
}
// Win32 lookups trim a trailing period or space, the kernel follows a link target as written: the two could name different things.
if cfg!(windows) && has_trimmed_name(&target) {
return Some("a link to a name Windows trims");
}
// Judged as written: joined onto the link's folder, a bare `\\server` would keep that folder's drive.
if let Some(why) = refused_prefix(&target, roots) {
return Some(why);
}
let joined = match prefix.parent() {
Some(parent) if !target.is_absolute() && !parent.as_os_str().is_empty() => parent.join(target),
_ => target,
};
let next = match path.strip_prefix(prefix) {
Ok(rest) if !rest.as_os_str().is_empty() => joined.join(rest),
_ => joined,
};
if let Some(why) = refused_prefix(&next, roots) {
return Some(why);
}
// Windows takes the `..` of a relative target by name, so `missing\..\remote` is `remote`
// though `missing` isn't there: judge that spelling as well as the one written.
let by_name = lexical(&next);
if by_name != next
&& let Some(why) = follow_links(&by_name, roots, judged, hops_left - 1)
{
return Some(why);
}
return follow_links(&next, roots, judged, hops_left - 1);
}
None
}
/// Whether `rest` (the part after `\\?\`) names a volume by its GUID, `Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}`: a local volume, such as the one
/// a folder is a mount point of.
fn is_volume_name(rest: &OsStr) -> bool {
let bytes = rest.as_encoded_bytes();
bytes.len() == 44
&& bytes.get(..7).is_some_and(|b| b.eq_ignore_ascii_case(b"Volume{"))
&& bytes.ends_with(b"}")
&& bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() })
}
/// Whether `path` is a name that starts with one separator and no drive (`\Device\Mup\server\share`, `\RPC Control\x`,
/// `\??\UNC\x`, `\work`), as a link may hold one: `std` sees no prefix in it, yet the system reads it in its own object
/// namespace or on the link's drive, and may follow it to wherever it names. Joined onto the link's folder it would look local.
fn is_native_name(path: &Path) -> bool {
matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\'))
}
/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up.
fn has_trimmed_name(path: &Path) -> bool {
path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' '))))
}
/// `path` with its `.` and `..` taken by name, never above its root.
fn lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
other => out.push(other),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
@@ -545,6 +780,240 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// A path with no Windows prefix, a drive letter, and every path off Windows have no off-disk prefix to refuse.
#[test]
fn a_local_path_has_no_off_disk_prefix() {
for p in ["/home/me/a.designcraft", "a.designcraft", r"C:\Projects\a.designcraft", r"\\?\C:\Projects\a.designcraft"] {
assert!(OffDisk::of(Path::new(p)).is_none(), "{p}");
assert_eq!(refused_prefix(Path::new(p), &[]), None, "{p}");
}
}
/// A network, device or non-disk verbatim path is refused by its name before the file system is
/// asked, so no host the agent names is contacted. The error names the prefix; it is not the
/// error that opening the path would give. Nothing here touches the network.
#[cfg(windows)]
#[test]
fn a_network_path_is_refused_before_it_is_opened() {
let (base, roots) = folders("unc");
let paths = [
(r"\\203.0.113.5\s\x.designcraft", "UNC"),
(r"\\?\UNC\203.0.113.5\s\x.designcraft", "UNC"),
("//203.0.113.5/s/x.designcraft", "UNC"),
(r"\\host@SSL\share\x.designcraft", "UNC"),
(r"\\host@SSL@443\share\x.designcraft", "UNC"),
(r"\\203.0.113.5", "UNC"),
(r"\\\203.0.113.5\s\x.designcraft", "UNC"),
("//203.0.113.5", "UNC"),
(r"\\.\PhysicalDrive0", "device path"),
(r"\\?\GLOBALROOT\Device\Mup\203.0.113.5\s\x.designcraft", "verbatim path"),
(r"\??\UNC\203.0.113.5\s\x.designcraft", "device path"),
];
for (p, kind) in paths {
for access in [Access::Read, Access::Write] {
let e = roots.check(p, access).unwrap_err();
assert!(e.starts_with("automation path rejected:"), "{p}: {e}");
assert!(e.contains(kind), "{p}: {e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{p}: {e}");
}
}
let e = roots.check(s(base.join("outside/secret.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("outside the read root"), "a local path is still judged by its folder: {e}");
let verbatim = format!(r"\\?\{}", s(base.join("in").join("a.designcraft")));
assert_eq!(roots.check(&verbatim, Access::Read), Ok(()), "a verbatim disk path is a local path: {verbatim}");
let _ = std::fs::remove_dir_all(base);
}
/// A root on a share lets that server and share through (either spelling, any ASCII case) and nothing else.
#[cfg(windows)]
#[test]
fn a_root_on_a_share_lets_only_that_share_through() {
assert!(OffDisk::of(Path::new(r"\\?\Volume{00000000-0000-0000-0000-000000000000}\x")).is_none(), "a volume by GUID is local");
assert!(OffDisk::of(Path::new(r"\\?\Volume{remote}\x")).is_some(), "a name that is not a GUID is not a volume");
let share = [Path::new(r"\\?\UNC\FileServer\Projects\work")];
assert_eq!(refused_prefix(Path::new(r"\\fileserver\projects\a.designcraft"), &share), None);
assert_eq!(refused_prefix(Path::new(r"\\?\UNC\FILESERVER\PROJECTS\a.designcraft"), &share), None);
assert!(refused_prefix(Path::new(r"\\fileserver\secret\a.designcraft"), &share).is_some(), "another share");
assert!(refused_prefix(Path::new(r"\\203.0.113.5\Projects\a.designcraft"), &share).is_some(), "another server");
let work = [Path::new(r"\\?\UNC\work\Projects\w")];
assert!(refused_prefix(Path::new("\\\\wor\u{212a}\\Projects\\a.designcraft"), &work).is_some(), "U+212A is not k");
assert!(refused_prefix(Path::new(r"\\.\PhysicalDrive0"), &share).is_some(), "a share is not a device");
let device = [Path::new(r"\\.\PhysicalDrive0")];
assert!(refused_prefix(Path::new(r"\\.\PhysicalDrive0"), &device).is_some(), "a device is refused even when a root names it");
}
/// A link whose text is a bare `\\server` (no share) is refused as written: joined onto the link's folder
/// it would read as a local path and pass.
#[cfg(windows)]
#[test]
fn a_link_to_a_bare_server_name_is_refused() {
let (base, roots) = folders("unc-link-bare");
let link = base.join("in").join("bare");
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5", &link).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("UNC"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// Nine links that each go through `sub\..\` to the next are nine links, not a reason to give up: both
/// spellings of each target are judged once.
#[cfg(windows)]
#[test]
fn a_chain_of_links_with_parent_names_is_followed_in_few_steps() {
let (base, roots) = folders("link-chain");
let folder = base.join("in");
std::fs::create_dir_all(folder.join("sub")).unwrap();
for n in 1..=9 {
let target = if n == 9 { "sub".to_string() } else { format!(r"sub\..\l{}", n + 1) };
if std::os::windows::fs::symlink_dir(&target, folder.join(format!("l{n}"))).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
}
assert_eq!(roots.check(s(folder.join("l1").join("x.designcraft")), Access::Read), Ok(()));
let _ = std::fs::remove_dir_all(base);
}
/// A name that starts with one separator and no drive is a native or rooted name, whichever object directory it
/// names (`\Device`, `\RPC Control`, `\BaseNamedObjects`, `\??`): a link to it is refused, and it is the same
/// with the rest of the path after it.
#[test]
fn rooted_names_without_a_drive_are_native_names() {
for p in
[r"\Device", r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\GLOBAL??", r"\work", r"\"]
{
assert!(is_native_name(Path::new(p)), "{p}");
}
for p in [r"Device", r"work\x", r"C:\x", r"C:\Device", r"\\server\share", r"\\?\C:\x", ""] {
assert!(!is_native_name(Path::new(p)), "{p}");
}
}
/// A link whose text is a native NT name (`\Device\Mup\server\share`) isn't a local path just because
/// `std` sees no prefix in it: it is refused as written, before it is joined onto the link's folder.
#[cfg(windows)]
#[test]
fn a_link_to_a_native_device_name_is_refused() {
let (base, roots) = folders("native-link");
let link = base.join("in").join("native");
if std::os::windows::fs::symlink_dir(r"\Device\Mup\203.0.113.5\s", &link).is_err()
|| std::fs::read_link(&link).ok().as_deref() != Some(std::path::Path::new(r"\Device\Mup\203.0.113.5\s"))
{
eprintln!("skipped: this system can't make that link, or stores its text differently");
let _ = std::fs::remove_dir_all(base);
return;
}
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("device path"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// A link whose target ends in a period or a space (`remote.`) is refused as written: Win32 lookups trim
/// that ending but the kernel follows the text as it is, so the two could name different things.
#[cfg(windows)]
#[test]
fn a_link_to_a_name_windows_trims_is_refused() {
let (base, roots) = folders("trimmed-link");
let link = base.join("in").join("trimmed");
if std::os::windows::fs::symlink_dir(r"remote.", &link).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let e = roots.check(s(link.join("x.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("name Windows trims"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// A path that names a link with a trailing separator (`remote\`) is judged as the link: Windows reads that as a
/// folder to go into, and would follow the link to a network path to find out what it is.
#[cfg(windows)]
#[test]
fn a_link_with_a_trailing_separator_is_judged_as_the_link() {
let (base, roots) = folders("slashed-link");
let link = base.join("in").join("slashed");
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &link).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let e = roots.check(format!(r"{}\", link.display()), Access::Read).unwrap_err();
assert!(e.contains("UNC"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// A path with a name that ends in a space (`remote \x`) is refused as given: Windows keeps that space in the
/// middle of a path but trims it when it looks the folder up by itself, so the two could name different things.
#[cfg(windows)]
#[test]
fn a_path_with_a_name_windows_trims_is_refused() {
let (base, roots) = folders("trimmed-path");
let e = roots.check(s(base.join("in").join("remote ").join("x.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("name Windows trims"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
#[cfg(windows)]
#[test]
fn a_verbatim_path_with_a_parent_name_is_refused() {
let (base, roots) = folders("verbatim-dotdot");
let p = format!(r"\\?\{}\..\a.designcraft", s(base.join("in").join("sub")));
let e = roots.check(&p, Access::Read).unwrap_err();
assert!(e.contains("parent traversal in a verbatim path"), "{p}: {e}");
let _ = std::fs::remove_dir_all(base);
}
/// A link whose relative target goes through a missing folder and back (`missing\..\remote`) is
/// judged with the `..` taken by name too, as Windows takes it: `remote` is a link to a network path.
#[cfg(windows)]
#[test]
fn a_relative_link_through_a_missing_folder_still_reaches_the_network_check() {
let (base, roots) = folders("unc-link-dotdot");
let (remote, alias) = (base.join("in").join("remote"), base.join("in").join("alias"));
if std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &remote).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
assert!(std::os::windows::fs::symlink_dir(r"missing\..\remote", &alias).is_ok());
let e = roots.check(s(alias.join("x.designcraft")), Access::Read).unwrap_err();
assert!(e.contains("UNC"), "{e}");
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// A link whose text names a network path, or that has one as a folder on the way, is refused
/// from that text before the link is followed: following it would contact the host.
#[cfg(windows)]
#[test]
fn a_link_to_a_network_path_is_refused_before_it_is_followed() {
let (base, roots) = folders("unc-link");
let file_link = base.join("in/leak.designcraft");
if std::os::windows::fs::symlink_file(r"\\203.0.113.5\s\x.designcraft", &file_link).is_err() {
eprintln!("skipped: symbolic links can't be made here");
let _ = std::fs::remove_dir_all(base);
return;
}
let folder_link = base.join("in/folder-leak");
assert!(std::os::windows::fs::symlink_dir(r"\\203.0.113.5\s", &folder_link).is_ok());
for path in [file_link, folder_link.join("x.designcraft")] {
let e = roots.check(s(path.clone()), Access::Read).unwrap_err();
assert!(e.contains("UNC"), "{}: {e}", path.display());
assert!(!e.contains("cannot resolve") && !e.to_ascii_lowercase().contains("os error"), "{}: {e}", path.display());
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn scopes_nest_and_stay_on_their_thread() {
let (base, roots) = folders("scopes");
+40 -3
View File
@@ -33,7 +33,7 @@ pub struct Sheet {
pub plates: Plates,
/// The printing condition the composite converts process plates through.
cms: CmsConversion,
/// Export warnings.
/// Export warnings, and one when the resolution was lowered to fit the plate size.
pub warnings: Vec<String>,
}
@@ -77,7 +77,9 @@ pub struct Print {
/// Exports spread `si` as Export PDF prints it with `print` (one page for the spread, with
/// the document bleed, without printer's marks) and separates it at `dpi`, clamped to
/// [`MIN_DPI`]–[`MAX_DPI`].
/// [`MIN_DPI`]–[`MAX_DPI`]. A spread larger than [`craft_prepress::MAX_PLATE_PIXELS`] at that
/// resolution is separated at a lower one; `plates.dpi` says which, and a warning says it was
/// lowered (#2945).
pub fn separate(doc: &Document, cache: &Cache, si: usize, dpi: f32, print: &Print) -> Result<Sheet> {
let sp = doc.spreads.get(si).ok_or_else(|| EngineError::Other(format!("spread {si} does not exist")))?;
let first = doc.first_page_of_spread(si);
@@ -96,7 +98,18 @@ pub fn separate(doc: &Document, cache: &Cache, si: usize, dpi: f32, print: &Prin
let (fallback, cms) = printing_condition();
let plates = craft_prepress::plates(&report.bytes, 0, dpi, &Options { overprint: true, fallback })
.map_err(|e| EngineError::Other(format!("separations: {e}")))?;
Ok(Sheet { spread: si, area, plates, cms, warnings: report.warnings })
let mut warnings = report.warnings;
// Total-ink checks depend on resolution (a thin rich-black rule averages under the limit at a
// low one), so a resolution lowered to fit the plate size is said, not only reported.
if plates.dpi < dpi - 0.5 {
warnings.push(format!(
"separated at {:.0} dpi, not the {:.0} dpi asked for: at that resolution the spread would be more than {:.0} megapixels per plate or 8192 pixels a side",
plates.dpi,
dpi,
craft_prepress::MAX_PLATE_PIXELS / 1.0e6
));
}
Ok(Sheet { spread: si, area, plates, cms, warnings })
}
impl Sheet {
@@ -199,6 +212,30 @@ mod tests {
assert!((inked as f64 - square).abs() < square * 0.1, "{inked} dark pixels, the square has {square}");
}
/// #2945: a page too large for 4 megapixels a plate at the dpi asked for is separated at a
/// lower one, and the result says so; one that fits says nothing.
#[test]
fn a_lowered_resolution_is_a_warning() {
let run = |preset: &str, dpi: u32| {
let mut s = Session::new();
s.execute("file.new", &json!({"preset": preset, "facingPages": false, "pages": 1})).unwrap();
s.execute("ink.separations", &json!({"dpi": dpi})).unwrap()
};
let lowered = |r: &serde_json::Value| {
r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().is_some_and(|w| w.contains("dpi asked for"))).count()
};
let a3 = run("A3", 300);
let used = a3["dpi"].as_f64().unwrap();
assert!(used < 150.0, "{a3}");
assert_eq!(lowered(&a3), 1, "{a3}");
let text =
a3["warnings"].as_array().and_then(|ws| ws.iter().filter_map(|w| w.as_str()).find(|w| w.contains("dpi asked for"))).unwrap_or_default();
assert!(text.contains(&format!("{used:.0} dpi")) && text.contains("300 dpi"), "{text}");
let a5 = run("A5", 72);
assert_eq!(a5["dpi"].as_f64(), Some(72.0));
assert_eq!(lowered(&a5), 0, "{a5}");
}
#[test]
fn ink_limit_flags_the_400_percent_area() {
let mut s = document();
+13
View File
@@ -278,6 +278,19 @@ impl FontFace {
.get_or_init(|| if self.is_variable() { None } else { self.skrifa().and_then(|f| name(&f, &[StringId::POSTSCRIPT_NAME])) })
.as_deref()
}
/// The PostScript name of this face as an instance of its variable font (Adobe TN #5902): a
/// named instance's name, or one built from the axis values for a point between them. `None`
/// for a static face; the default point gets the file's `name` ID 6.
///
/// [`Self::postscript_name`] is the file's own `name` ID 6, which names the font's default
/// instance: embedding by it put every weight of a variable font into a PDF under one name
/// (#1690).
pub fn instance_postscript_name(&self) -> Option<String> {
if !self.is_variable() {
return None;
}
crate::psname::instance_postscript_name(&self.skrifa()?, &self.coords)
}
/// Glyph id for `c` (0 = .notdef).
pub fn glyph_for(&self, c: char) -> u32 {
+1
View File
@@ -13,6 +13,7 @@ mod group;
mod kind;
#[cfg(target_os = "macos")]
mod mac_fonts;
pub mod psname;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod vertical;
+499
View File
@@ -0,0 +1,499 @@
//! The PostScript name of a variable font's named instance (Adobe TN #5902).
//!
//! `name` ID 6 names the font's **default** instance, so every instance of a variable font embeds
//! under the same name: all the weights of Noto Sans KR went into a PDF as `NotoSansKR-Thin`, and
//! Acrobat's font list, preflight and a print shop's checks then report Thin for every weight
//! (#1690). The outlines were right; only the name was wrong.
use skrifa::raw::TableProvider;
use skrifa::{FontRef, MetadataProvider, raw::types::NameId};
/// Longest PostScript name `name` ID 6 may carry (OpenType), which is where this name goes.
///
/// TN #5902 works to 127 characters and prescribes a "last resort" name past that; the shorter
/// limit here is the one that matters for a name written into the font's own `name` table.
const MAX_LEN: usize = 63;
/// Axis values count as the same instance within this much (user units).
const AXIS_EPSILON: f32 = 1e-4;
/// The PostScript name for the instance of `font` at `coords`, or `None` for a static font; the
/// default point gets the file's `name` ID 6.
///
/// TN #5902: a named instance's own `postScriptNameID` wins; otherwise the name is the family
/// prefix (`name` ID 25, else the typographic family, else the family -- OpenType reads a missing
/// ID 16 as ID 1) joined to the instance's subfamily with a hyphen, keeping only ASCII letters and
/// digits. A point no named instance covers is named by its axis values
/// ([`arbitrary_instance_name`]). No more than 63 characters either way, the limit of the `name`
/// ID 6 this goes into, where the note allows 127.
pub fn instance_postscript_name(font: &FontRef<'_>, coords: &[([u8; 4], f32)]) -> Option<String> {
let axes = font.axes();
// `fvar` coordinates are 16.16, so two instances can sit 1/65536 apart -- closer than
// AXIS_EPSILON. Asking for an exact instance would then match whichever of them came first
// and give the one asked for the other's name, so an exact match is looked for first and the
// tolerance is only a fallback for a point that is not exactly on any instance (noted in
// review).
let at = |tolerance: f32| {
let axes = &axes;
move |ni: &skrifa::NamedInstance<'_>| {
axes.iter().zip(ni.user_coords()).all(|(axis, value)| (effective(&axis, coords) - value).abs() <= tolerance)
}
};
let exact = at(0.0);
let near = at(AXIS_EPSILON);
let Some(instance) = font.named_instances().iter().find(|ni| exact(ni)).or_else(|| font.named_instances().iter().find(|ni| near(ni))) else {
return arbitrary_instance_name(font, coords);
};
if let Some(id) = instance.postscript_name_id()
&& let Some(name) = string(font, id)
{
// The font names this instance itself, so the name is used as it stands -- a hyphen is
// legal in a PostScript name, and `Pretendard-Heavy` is the name, not a family and a
// subfamily to join (noted in review). Only characters a PostScript name cannot hold are
// dropped.
let kept = legal(&name);
if !kept.is_empty() {
return Some(truncate(kept));
}
}
let prefix = family_prefix(font)?;
let subfamily = string(font, instance.subfamily_name_id()).map(|s| keep(&s)).filter(|s| !s.is_empty())?;
Some(join(&prefix, &subfamily))
}
/// TN #5902's family prefix: `name` ID 25, else the typographic family (ID 16), else the family
/// (ID 1, which OpenType says stands in for a missing ID 16), keeping ASCII letters and digits.
fn family_prefix(font: &FontRef<'_>) -> Option<String> {
[NameId::VARIATIONS_POSTSCRIPT_NAME_PREFIX, NameId::TYPOGRAPHIC_FAMILY_NAME, NameId::FAMILY_NAME]
.into_iter()
.find_map(|id| string(font, id).map(|s| keep(&s)).filter(|s| !s.is_empty()))
}
/// The value of `axis` at `coords` (its default when absent), inside the axis. Compared, not
/// `clamp`ed -- `fvar` is font data, and `f32::clamp` panics on a range whose minimum is past
/// its maximum.
fn effective(axis: &skrifa::Axis, coords: &[([u8; 4], f32)]) -> f32 {
let tag = axis.tag().to_be_bytes();
let asked = coords.iter().find(|(t, _)| *t == tag).map_or(axis.default_value(), |(_, v)| *v);
if asked < axis.min_value() {
axis.min_value()
} else if asked > axis.max_value() {
axis.max_value()
} else {
asked
}
}
/// TN #5902's name for a point no named instance covers: the family prefix, then `_<value><tag>`
/// for each axis away from its default, in `fvar` order -- `AndreVar_900wght_5.5wdth`. Axes at
/// their default are left out, as the note allows, so the default point itself has no
/// descriptors and gets the file's `name` ID 6.
///
/// Returning `None` for every such point, which this did first, left all of them embedding under
/// the default instance's name -- the bug this module is for, at any weight that is not a named
/// one (noted in review).
fn arbitrary_instance_name(font: &FontRef<'_>, coords: &[([u8; 4], f32)]) -> Option<String> {
let axes = font.axes();
if axes.is_empty() {
return None;
}
let prefix = family_prefix(font)?;
let mut name = prefix.clone();
for axis in axes.iter() {
let tag = axis.tag().to_be_bytes();
let value = effective(&axis, coords);
let fixed = to_fixed(value);
if fixed == to_fixed(axis.default_value()) {
continue;
}
name.push('_');
name.push_str(&fixed_decimal(fixed));
// Trailing spaces are dropped from a tag (`ital`, `wd `); anything else not a letter or
// digit cannot be in the name either.
name.push_str(&keep(&String::from_utf8_lossy(&tag)));
}
if name == prefix {
return string(font, NameId::POSTSCRIPT_NAME).map(|s| truncate(legal(&s))).filter(|s| !s.is_empty());
}
if name.chars().count() <= MAX_LEN {
return Some(name);
}
// TN #5902's last resort: the prefix, `-`, an identifier for this instance, and `...`.
let id = format!("{:08X}", digest(&name));
let room = MAX_LEN - 1 - id.len() - 3;
Some(format!("{}-{id}...", prefix.chars().take(room).collect::<String>()))
}
/// A user coordinate as `fvar`'s 16.16 fixed point. A value past `i32` saturates and NaN is 0, as
/// `as` does; neither reaches here from a font that parsed.
fn to_fixed(v: f32) -> i32 {
(f64::from(v) * 65536.0).round() as i32
}
/// The shortest decimal that reads back as the 16.16 value `v` (TN #5902 and its appendix): no
/// trailing zeroes, no decimal point for a whole number, `0` for zero and no `+`. A value under
/// one keeps the `0` before its point (`0.5`), the zero the integer part needs, not padding.
fn fixed_decimal(v: i32) -> String {
let x = f64::from(v) / 65536.0;
// Sixteen fractional bits need at most six decimal places to come back exactly.
for places in 0..=6 {
let s = format!("{x:.places$}");
let back = s.parse::<f64>().map(|b| (b * 65536.0).round() as i64);
if back == Ok(i64::from(v)) {
let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s };
return if s == "-0" { "0".into() } else { s };
}
}
format!("{x}")
}
/// `prefix-subfamily`, or, when that is past [`MAX_LEN`], both halves shortened with a digest of
/// the whole after them.
///
/// Both halves matter. The subfamily is what tells two instances of one family apart, so cutting
/// its end lets `Thin` and `Thin Italic` meet; the prefix is what tells two families apart, so
/// cutting *its* end lets `FamilyOne` and `FamilyTwo` meet. Neither can be shortened on its own
/// and stay unique, so a name that does not fit keeps a readable piece of each and ends in a
/// digest of `prefix-subfamily` entire -- the shape TN #5902 prescribes as a "last resort" name
/// for an instance that cannot be named inside the limit. A PDF embedding two instances under one
/// name is the thing this function exists to stop.
///
/// Shortening only one half -- what this did before -- collided two ways, both noted in review: a
/// 62-character subfamily took a digest of the subfamily alone, so every family reached the same
/// head and the same digest, and a 60-character one left room for two prefix characters, so
/// `FamilyOne` and `FamilyTwo` both shortened to `Fa`.
fn join(prefix: &str, subfamily: &str) -> String {
let whole = format!("{prefix}-{subfamily}");
if whole.chars().count() <= MAX_LEN {
return whole;
}
// The subfamily is usually the short half, so it is served first, down to the floor the
// prefix keeps for itself; the prefix takes what is left. The digest, not either piece, is
// what actually keeps this name off another one.
let sub_room = (VISIBLE - PREFIX_MIN - 1).min(subfamily.chars().count());
let short_prefix: String = prefix.chars().take(VISIBLE - 1 - sub_room).collect();
let short_subfamily: String = subfamily.chars().take(sub_room).collect();
format!("{short_prefix}-{short_subfamily}-{:08x}", digest(&whole))
}
/// Characters a shortened name's readable `prefix-subfamily` gets, the rest going to the digest
/// and the hyphen before it.
const VISIBLE: usize = MAX_LEN - DIGEST_LEN - 1;
/// A shortened name keeps at least this much of the prefix, so it still says which family it is.
const PREFIX_MIN: usize = 8;
/// Hex characters the last-resort digest takes.
const DIGEST_LEN: usize = 8;
/// FNV-1a over the whole `prefix-subfamily`, so two names that agree as far as the limit still
/// differ. Not a security property -- only that two different strings rarely collide.
fn digest(s: &str) -> u32 {
s.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ u32::from(b)).wrapping_mul(0x0100_0193))
}
/// The characters a PostScript name may hold: printable ASCII except the delimiters `[](){}<>/%`
/// and space (OpenType `name` ID 6). Used for a name the font supplies itself.
fn legal(s: &str) -> String {
s.chars().filter(|c| c.is_ascii_graphic() && !matches!(c, '[' | ']' | '(' | ')' | '{' | '}' | '<' | '>' | '/' | '%')).collect()
}
/// A `name` table string, preferring the US English Windows record a PDF reader looks at.
///
/// Picking the first record of the right platform took whichever language came first, so a font
/// whose subfamily is listed in another language before English generated its name from that
/// one -- or from a string whose characters all drop out, leaving no name at all (noted in
/// review). US English (0x0409 on Windows, 0 on Macintosh) is tried first.
fn string(font: &FontRef<'_>, id: NameId) -> Option<String> {
let name = font.name().ok()?;
let records = name.name_record();
let pick = |platform: u16, language: Option<u16>| {
records.iter().find(|r| r.name_id() == id && r.platform_id() == platform && language.is_none_or(|want| r.language_id() == want))
};
let record = pick(3, Some(0x0409))
.or_else(|| pick(1, Some(0)))
.or_else(|| pick(3, None))
.or_else(|| pick(1, None))
.or_else(|| records.iter().find(|r| r.name_id() == id))?;
let text = record.string(name.string_data()).ok()?.chars().collect::<String>();
(!text.trim().is_empty()).then_some(text)
}
/// ASCII letters and digits of `s`, which is what a PostScript name may hold.
fn keep(s: &str) -> String {
s.chars().filter(char::is_ascii_alphanumeric).collect()
}
/// `s` at most [`MAX_LEN`] characters, cut on a character boundary (the name is ASCII here, so
/// this is a byte cut, but the font's own string need not have been).
fn truncate(s: String) -> String {
match s.char_indices().nth(MAX_LEN) {
Some((at, _)) => s[..at].to_string(),
None => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A variable font named like Noto Sans KR: a `wght` axis and four named instances, with the
/// family prefix in name ID 25.
fn variable(entries: &[(u16, &str)], instances: &[(u16, Option<u16>, Vec<f32>)]) -> Vec<u8> {
let base = crate::testing::font_with_names(entries, &['A']).expect("a font with these names");
crate::testing::with_fvar(&base, &[(*b"wght", 100.0, 100.0, 900.0, 256)], instances).expect("an fvar")
}
fn at(font: &[u8], weight: f32) -> Option<String> {
let f = skrifa::FontRef::new(font).expect("the fixture parses");
instance_postscript_name(&f, &[(*b"wght", weight)])
}
/// `name` ID 6 names the default instance, so every weight embedded under it: the four
/// weights of Noto Sans KR all went into the PDF as `NotoSansKR-Thin` (#1690).
#[test]
fn each_named_instance_has_its_own_postscript_name() {
// 1 family, 6 the default instance's PostScript name, 25 the variations prefix,
// 257.. the instances' subfamily names.
let font = variable(
&[(1, "Noto Sans KR"), (6, "NotoSansKR-Thin"), (25, "NotoSansKR"), (257, "Thin"), (258, "Regular"), (259, "Bold"), (260, "Black")],
&[(257, None, vec![100.0]), (258, None, vec![400.0]), (259, None, vec![700.0]), (260, None, vec![900.0])],
);
assert_eq!(at(&font, 100.0).as_deref(), Some("NotoSansKR-Thin"));
assert_eq!(at(&font, 400.0).as_deref(), Some("NotoSansKR-Regular"));
assert_eq!(at(&font, 700.0).as_deref(), Some("NotoSansKR-Bold"));
assert_eq!(at(&font, 900.0).as_deref(), Some("NotoSansKR-Black"));
// A point between the named instances is not one of them, and is named by its value
// (TN #5902, arbitrary instances).
assert_eq!(at(&font, 550.0).as_deref(), Some("NotoSansKR_550wght"));
}
/// An instance that names its own PostScript name uses it **as it stands**: the font is
/// naming the instance, not handing over a family and a subfamily to join, and a hyphen is
/// legal in a PostScript name (noted in review).
#[test]
fn an_instances_own_postscript_name_is_used_as_it_stands() {
let font = variable(
&[(1, "Pretendard Variable"), (6, "PretendardVariable-Regular"), (25, "PretendardVariable"), (257, "Bold"), (300, "Pretendard-Heavy")],
&[(257, Some(300), vec![700.0])],
);
assert_eq!(at(&font, 700.0).as_deref(), Some("Pretendard-Heavy"), "the hyphen the font wrote is kept");
// Only the characters a PostScript name cannot hold are dropped: the delimiters and
// spaces, not punctuation a name may carry.
let odd = variable(&[(1, "Fixture"), (25, "Fixture"), (257, "Bold"), (300, "Fix (ture)/Bold+2_x")], &[(257, Some(300), vec![700.0])]);
assert_eq!(at(&odd, 700.0).as_deref(), Some("FixtureBold+2_x"));
}
/// Two instances must not arrive at the same name. Cutting the end of a long name would do
/// exactly that, so the family prefix gives way and the subfamily -- the part that tells the
/// instances apart -- is kept whole where there is room (noted in review; TN #5902 keeps the
/// identifier for the same reason). The digest after it is what keeps the name off another
/// family's, which shortening the prefix alone did not.
#[test]
fn a_long_name_keeps_the_subfamily_that_tells_instances_apart() {
let long_prefix = "P".repeat(70);
let font = variable(
&[(1, "Fixture"), (25, &long_prefix), (257, "CondensedExtraBoldItalic"), (258, "CondensedExtraBoldOblique")],
&[(257, None, vec![700.0]), (258, None, vec![800.0])],
);
let (a, b) = (at(&font, 700.0).expect("a name"), at(&font, 800.0).expect("a name"));
assert!(a.len() <= MAX_LEN && b.len() <= MAX_LEN, "within the limit: {} and {}", a.len(), b.len());
assert!(a.contains("-CondensedExtraBoldItalic-"), "the subfamily survives: {a}");
assert!(b.contains("-CondensedExtraBoldOblique-"), "the subfamily survives: {b}");
assert!(a.starts_with(&long_prefix[..8]) && b.starts_with(&long_prefix[..8]), "and so does enough of the family: {a}");
assert_ne!(a, b, "two instances never share a name");
}
/// A name listed in another language before English must not be the one the name is built
/// from (noted in review).
#[test]
fn the_english_record_is_preferred() {
// `with_names` writes the whole table, so every record this needs is in the one call:
// the subfamily is listed in Japanese *before* US English for the same id.
let base = crate::testing::font_with("Fixture", &['A']).unwrap();
let named = crate::testing::with_names(
&base,
&[
(3, 1, 0x0411, 1, "Fixture"),
(3, 1, 0x0409, 1, "Fixture"),
(3, 1, 0x0409, 25, "Fixture"),
(3, 1, 0x0411, 257, "\u{592A}\u{5B57}"),
(3, 1, 0x0409, 257, "Bold"),
],
)
.expect("a name table with both languages");
let font = crate::testing::with_fvar(&named, &[(*b"wght", 100.0, 100.0, 900.0, 256)], &[(257, None, vec![700.0])]).unwrap();
let f = skrifa::FontRef::new(&font).unwrap();
assert_eq!(instance_postscript_name(&f, &[(*b"wght", 700.0)]).as_deref(), Some("Fixture-Bold"));
}
/// An instance with no PostScript name of its own, beside one that has one: `fvar` writes
/// 0xFFFF for "none", and 0 would be the copyright notice's id (noted in review).
#[test]
fn an_instance_without_its_own_name_falls_back_to_the_generated_one() {
let font = variable(
&[(0, "Copyright 2026 Nobody"), (1, "Fixture"), (25, "Fixture"), (257, "Bold"), (258, "Black"), (300, "Fixture-TheBold")],
&[(257, Some(300), vec![700.0]), (258, None, vec![900.0])],
);
assert_eq!(at(&font, 700.0).as_deref(), Some("Fixture-TheBold"), "the instance that names itself");
assert_eq!(at(&font, 900.0).as_deref(), Some("Fixture-Black"), "and the one that does not is generated");
}
/// Without ID 25 the typographic family is the prefix, then the family; and a name a
/// PostScript name cannot hold keeps only its letters and digits.
#[test]
fn the_prefix_falls_back_and_the_name_is_sanitised() {
let typographic = variable(&[(1, "Fixture"), (16, "Fixture Display"), (257, "Semi Bold")], &[(257, None, vec![600.0])]);
assert_eq!(at(&typographic, 600.0).as_deref(), Some("FixtureDisplay-SemiBold"));
let family_only = variable(&[(1, "Fixture (Beta)"), (257, "Extra Light")], &[(257, None, vec![200.0])]);
assert_eq!(at(&family_only, 200.0).as_deref(), Some("FixtureBeta-ExtraLight"));
}
/// `name` ID 6 carries at most 63 characters.
#[test]
fn a_name_stays_within_the_limit() {
let long = "L".repeat(80);
let font = variable(&[(1, "Fixture"), (25, &long), (257, "Regular")], &[(257, None, vec![400.0])]);
let name = at(&font, 400.0).expect("a name");
assert!(name.len() <= MAX_LEN, "within the limit: {name}");
// Both halves are kept, the subfamily whole here because it is short, and the digest
// after them is what tells this name from another family's (noted in review).
assert!(name.contains("-Regular-"), "and the subfamily is kept: {name}");
assert!(name.starts_with(&long[..8]), "with enough of the family to name it: {name}");
}
/// A static font has no named instances, so it keeps its own `name` ID 6.
#[test]
fn a_static_font_has_no_instance_name() {
let base = crate::testing::font_with_names(&[(1, "Fixture"), (6, "Fixture-Regular")], &['A']).unwrap();
let f = skrifa::FontRef::new(&base).unwrap();
assert_eq!(instance_postscript_name(&f, &[]), None);
}
/// `fvar` coordinates are 16.16, so two instances can sit 1/65536 apart -- inside
/// AXIS_EPSILON. Asking for one of them matched whichever came first and returned the
/// other's name (noted in review).
#[test]
fn two_instances_closer_than_the_tolerance_keep_their_own_names() {
// 1.0 and 1.0 + 1/65536, one 16.16 step apart: distinct in the file and 1.5e-5 apart,
// which is inside AXIS_EPSILON (1e-4). The axis has to be a small-numbered one for the
// two to be different f32s at all -- at a weight of 400 a step of 1/65536 is below half
// an ulp, so the file cannot hold two such instances there in the first place.
let step = 1.0 / 65536.0;
let base = crate::testing::font_with_names(&[(1, "Test"), (6, "Test-Regular"), (25, "Test"), (257, "Regular"), (258, "RegularPlus")], &['A'])
.expect("a font with these names");
let font = crate::testing::with_fvar(&base, &[(*b"slnt", 0.0, 1.0, 2.0, 256)], &[(257, None, vec![1.0]), (258, None, vec![1.0 + step])])
.expect("an fvar");
let slnt = |font: &[u8], v: f32| {
let f = skrifa::FontRef::new(font).expect("the fixture parses");
instance_postscript_name(&f, &[(*b"slnt", v)])
};
assert_ne!(1.0f32, 1.0 + step, "the two coordinates really are different numbers");
assert_eq!(slnt(&font, 1.0).as_deref(), Some("Test-Regular"), "the exact instance wins");
assert_eq!(slnt(&font, 1.0 + step).as_deref(), Some("Test-RegularPlus"), "and so does the one next to it");
// A point on neither still falls back to the tolerance, which is what it is for.
assert_eq!(slnt(&font, 1.0 + step / 2.0).as_deref(), Some("Test-Regular"), "a point in between takes the nearest match");
}
/// Two instances must never arrive at one name: a PDF would then embed two different ones
/// under it. Both halves of the name can be what tells them apart, and shortening either in
/// isolation collided -- the subfamily's tail for two instances of a family, the prefix's for
/// two families (both noted in review).
#[test]
fn two_names_that_agree_as_far_as_the_limit_still_differ() {
// Same family, subfamilies differing only past the limit.
let head = "A".repeat(61);
let (a, b) = (join("Family", &format!("{head}B")), join("Family", &format!("{head}C")));
assert_ne!(a, b, "{a} and {b} name different instances of one family");
// Different families, one subfamily. 62 characters took the digest path, which digested
// the subfamily alone, so every family reached the same head and the same digest; 60 left
// room for two prefix characters, so `FamilyOne` and `FamilyTwo` both became `Fa`.
for len in [60, 62] {
let sub = "A".repeat(len);
let (one, two) = (join("FamilyOne", &sub), join("FamilyTwo", &sub));
assert_ne!(one, two, "subfamily of {len}: {one} and {two} name different families");
}
// A one-character difference anywhere in the prefix is enough, however far past the cut.
let long = "P".repeat(80);
let (p, q) = (join(&format!("{long}A"), "Thin"), join(&format!("{long}B"), "Thin"));
assert_ne!(p, q, "{p} and {q} name different families");
// Every shortened name is inside the limit, and is a name a PDF can hold.
for name in [a, b, p, q, join("FamilyOne", &"A".repeat(62))] {
assert!(name.chars().count() <= MAX_LEN, "{} characters: {name}", name.chars().count());
assert_eq!(legal(&name), name, "{name} has a character a PostScript name may not hold");
}
// An ordinary name is untouched, and so is one that fits exactly.
assert_eq!(join("NotoSansKR", "Thin"), "NotoSansKR-Thin");
let exact = join("Family", &"A".repeat(MAX_LEN - "Family-".len()));
assert_eq!(exact.chars().count(), MAX_LEN);
assert!(exact.starts_with("Family-") && exact.ends_with('A'), "kept whole: {exact}");
}
/// TN #5902's own examples for arbitrary instances, and the rules beside them: axes at their
/// default are left out, the default point itself keeps `name` ID 6, and values are the
/// shortest decimal that reads back as the same 16.16 number (noted in review).
#[test]
fn a_point_no_instance_names_is_named_by_its_axis_values() {
// 16 "Andre Var" and no prefix of its own; `wght` and `wdth`, no named instances.
let base = crate::testing::font_with_names(&[(1, "Andre Var"), (16, "Andre Var")], &['A']).expect("a font with these names");
let font =
crate::testing::with_fvar(&base, &[(*b"wght", -10.0, 400.0, 1000.0, 256), (*b"wdth", -10.0, 100.0, 200.0, 257)], &[]).expect("an fvar");
let f = skrifa::FontRef::new(&font).expect("the fixture parses");
let name = |wght: f32, wdth: f32| instance_postscript_name(&f, &[(*b"wght", wght), (*b"wdth", wdth)]);
assert_eq!(name(900.0, 5.5).as_deref(), Some("AndreVar_900wght_5.5wdth"), "the note's example");
assert_eq!(name(-2.9, -1.4).as_deref(), Some("AndreVar_-2.9wght_-1.4wdth"), "and its negative one");
assert_eq!(name(900.0, 100.0).as_deref(), Some("AndreVar_900wght"), "an axis at its default is left out");
assert_eq!(name(400.0, 100.0), None, "the default point is the one name ID 6 names");
assert_eq!(name(5000.0, 100.0).as_deref(), Some("AndreVar_1000wght"), "a value past the axis is where the font draws it");
// An axis the caller does not mention is at its default.
assert_eq!(instance_postscript_name(&f, &[(*b"wdth", 150.0)]).as_deref(), Some("AndreVar_150wdth"));
// The shortest decimal that comes back as the same fixed value.
assert_eq!(fixed_decimal(0), "0");
assert_eq!(fixed_decimal(to_fixed(0.5)), "0.5");
assert_eq!(fixed_decimal(to_fixed(-2.9)), "-2.9");
assert_eq!(fixed_decimal(1), "0.00002", "one 65536th");
assert_eq!(fixed_decimal(to_fixed(100.0)), "100");
for v in [1, -1, 3, 32768, 65535, 65537, -190054, 0x7fff_ffff, -0x7fff_ffff] {
let s = fixed_decimal(v);
assert_eq!((s.parse::<f64>().unwrap() * 65536.0).round() as i64, i64::from(v), "{v} came back from {s}");
assert!(!s.ends_with('0') || !s.contains('.'), "no trailing zero: {s}");
}
}
/// Too many axes for the limit: TN #5902's last resort, the prefix, an identifier and `...`,
/// still one name per point.
#[test]
fn a_point_too_long_to_describe_gets_the_last_resort_name() {
let tags: Vec<[u8; 4]> = (0..12u8).map(|i| [b'a', b'x', b'0' + i / 10, b'0' + i % 10]).collect();
let axes: Vec<_> = tags.iter().map(|t| (*t, 0.0, 0.0, 1000.0, 256)).collect();
let base = crate::testing::font_with_names(&[(16, "Andre Var"), (25, "AndreVar")], &['A']).expect("names");
let font = crate::testing::with_fvar(&base, &axes, &[]).expect("an fvar");
let f = skrifa::FontRef::new(&font).expect("the fixture parses");
let point = |v: f32| instance_postscript_name(&f, &tags.iter().map(|t| (*t, v)).collect::<Vec<_>>()).expect("a name");
let (a, b) = (point(123.25), point(456.5));
for n in [&a, &b] {
assert!(n.starts_with("AndreVar-") && n.ends_with("..."), "the last resort's shape: {n}");
assert!(n.chars().count() <= MAX_LEN, "within the limit: {n}");
assert_eq!(legal(n), *n, "only characters a PostScript name may hold: {n}");
}
assert_ne!(a, b, "two points, two names");
}
/// `fvar` is font data: an axis whose minimum is past its maximum names a point without a
/// panic (`f32::clamp` would have panicked).
#[test]
fn a_malformed_axis_range_does_not_panic() {
let base = crate::testing::font_with_names(&[(16, "Odd")], &['A']).expect("names");
let font = crate::testing::with_fvar(&base, &[(*b"wght", 900.0, 400.0, 100.0, 256)], &[]).expect("an fvar");
let Ok(f) = skrifa::FontRef::new(&font) else { return };
let _ = instance_postscript_name(&f, &[(*b"wght", 550.0)]);
let _ = instance_postscript_name(&f, &[(*b"wght", f32::NAN)]);
}
}
+61
View File
@@ -95,6 +95,42 @@ pub fn font_with_names(entries: &[(u16, &str)], chars: &[char]) -> Option<Vec<u8
with_tables(&base, vec![(*b"name", name)])
}
/// `font` with an `fvar` table: `axes` are (tag, min, default, max, axis name id) and `instances`
/// are (subfamily name id, PostScript name id, one user coordinate per axis). Version 1.0, with
/// the optional `postScriptNameID` present only when some instance names one.
pub fn with_fvar(font: &[u8], axes: &[([u8; 4], f32, f32, f32, u16)], instances: &[(u16, Option<u16>, Vec<f32>)]) -> Option<Vec<u8>> {
let fixed = |v: f32| ((v * 65536.0).round() as i32).to_be_bytes();
let any_ps = instances.iter().any(|(_, ps, _)| ps.is_some());
let axis_count = u16::try_from(axes.len()).ok()?;
let instance_size = axis_count.checked_mul(4)?.checked_add(if any_ps { 6 } else { 4 })?;
let mut t = Vec::new();
for v in [1u16, 0, 16, 2, axis_count, 20, u16::try_from(instances.len()).ok()?, instance_size] {
t.extend_from_slice(&v.to_be_bytes());
}
for (tag, min, def, max, name_id) in axes {
t.extend_from_slice(tag);
t.extend_from_slice(&fixed(*min));
t.extend_from_slice(&fixed(*def));
t.extend_from_slice(&fixed(*max));
t.extend_from_slice(&0u16.to_be_bytes());
t.extend_from_slice(&name_id.to_be_bytes());
}
for (subfamily, ps, coords) in instances {
if coords.len() != axes.len() {
return None;
}
t.extend_from_slice(&subfamily.to_be_bytes());
t.extend_from_slice(&0u16.to_be_bytes());
coords.iter().for_each(|v| t.extend_from_slice(&fixed(*v)));
if any_ps {
// 0xFFFF is "no PostScript name" in `fvar`; 0 is the copyright notice's name id, so
// writing 0 made an instance look as though it named itself (noted in review).
t.extend_from_slice(&ps.unwrap_or(0xFFFF).to_be_bytes());
}
}
with_tables(font, vec![(*b"fvar", t)])
}
/// Every table of the font file `font`: (tag, bytes).
fn tables_of(font: &[u8]) -> Option<Vec<([u8; 4], Vec<u8>)>> {
let be16 = |b: &[u8], at: usize| b.get(at..at + 2).and_then(|s| s.try_into().ok()).map(u16::from_be_bytes);
@@ -326,3 +362,28 @@ pub fn with_meta(font: &[u8], dlng: Option<&str>, slng: Option<&str>) -> Option<
pub fn installed_face(bytes: Vec<u8>, path: std::path::PathBuf) -> Option<crate::FontFace> {
crate::FontDb::with_font_dirs(vec![]).new_faces(bytes, crate::FontSource::Installed(path)).into_iter().next()
}
/// A synthetic weight-variable font with Regular and SemiBold named instances, using bundled outlines.
/// Only discovery is variable; the outlines do not change with weight.
pub fn variable_font(family: &str) -> Option<Vec<u8>> {
let base =
font_with_names(&[(1, family), (2, "Regular"), (6, "SyntheticVF-Regular"), (256, "Weight"), (257, "Regular"), (258, "SemiBold")], &['X'])?;
// fvar 1.0: one weight axis and two named instances, without PostScript name IDs.
let mut fvar = Vec::new();
for v in [1u16, 0, 16, 2, 1, 20, 2, 8] {
fvar.extend_from_slice(&v.to_be_bytes());
}
fvar.extend_from_slice(b"wght");
for v in [100i32 << 16, 400 << 16, 900 << 16] {
fvar.extend_from_slice(&v.to_be_bytes());
}
for v in [0u16, 256] {
fvar.extend_from_slice(&v.to_be_bytes());
}
for (id, weight) in [(257u16, 400i32), (258, 600)] {
fvar.extend_from_slice(&id.to_be_bytes());
fvar.extend_from_slice(&0u16.to_be_bytes());
fvar.extend_from_slice(&(weight << 16).to_be_bytes());
}
with_tables(&base, vec![(*b"fvar", fvar)])
}
+2 -2
View File
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
craft-eps = { workspace = true }
craft-ps = { workspace = true }
craft-svg = { workspace = true }
designcraft-color = { workspace = true }
designcraft-fonts = { workspace = true }
@@ -21,8 +22,7 @@ quick-xml = { workspace = true }
craft-image-codecs = { workspace = true }
craft-psd = { workspace = true }
craft-file-formats = { workspace = true }
# Reduced-size JPEG decoding (1/2, 1/4, 1/8 through the DCT) for screen proxies.
jpeg-decoder = { version = "0.3", default-features = false }
craft-jpeg = { workspace = true }
[dev-dependencies]
image = { workspace = true, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp"] }
+1 -2
View File
@@ -10,8 +10,7 @@ fn sections(bytes: &[u8]) -> (&[u8], Option<&[u8]>) {
/// The bounding box in points: (x0, y0, x1, y1), the high-resolution one when given.
pub fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> {
let parts = craft_eps::sections(bytes).ok()?;
craft_eps::Comments::read(parts.postscript).page_box()
craft_ps::read::bounding_box(craft_ps::read::postscript_section(bytes))
}
/// Natural EPS dimensions in points. Bound sizes before fitting or allocating a proxy:
+16 -62
View File
@@ -1,7 +1,5 @@
//! Reduced-size JPEG decoding (1/2, 1/4, 1/8 through the DCT) for screen proxies.
use jpeg_decoder::{CodingProcess, PixelFormat};
/// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8.
pub(crate) const MAX_SHRINK: u8 = 3;
@@ -32,39 +30,19 @@ pub(crate) fn progressive_coefficient_bytes(bytes: &[u8]) -> usize {
0
}
fn limits() -> craft_jpeg::Limits {
let mut limits = craft_jpeg::Limits::default();
limits.max_alloc = MAX_BYTES as u64;
limits
}
/// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder
/// cannot handle the JPEG, including its full-size resource limits.
pub(crate) fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> {
if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK {
return None;
}
let mut d = jpeg_decoder::Decoder::new(bytes);
d.set_max_decoding_buffer_size(MAX_BYTES);
d.read_info().ok()?;
let info = d.info()?;
let colour = match info.pixel_format {
PixelFormat::RGB24 => true,
PixelFormat::L8 => false,
PixelFormat::L16 | PixelFormat::CMYK32 => return None,
};
if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) {
return None;
}
let progressive_bytes = if info.coding_process == CodingProcess::DctProgressive {
let side = |n: u16| u64::from(n).next_multiple_of(32);
let components: u64 = if colour { 3 } else { 1 };
let bytes = side(info.width) * side(info.height) * components * 2;
if bytes > MAX_BYTES as u64 {
return None;
}
usize::try_from(bytes).ok()?
} else {
0
};
let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink);
let (width, height) = (reduced(info.width), reduced(info.height));
let output_bytes = width as usize * height as usize * 8;
Some((width, height, progressive_bytes.saturating_add(output_bytes)))
craft_jpeg::reduced_estimate(bytes, &limits(), shrink).ok()
}
/// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for
@@ -77,40 +55,16 @@ pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaIma
if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK {
return None;
}
let mut d = jpeg_decoder::Decoder::new(bytes);
// This limits the output only, which is the reduced size.
d.set_max_decoding_buffer_size(MAX_BYTES);
d.read_info().ok()?;
let info = d.info()?;
if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) {
return None;
}
let colour = match info.pixel_format {
PixelFormat::RGB24 => true,
PixelFormat::L8 => false,
PixelFormat::L16 | PixelFormat::CMYK32 => return None,
let decoded = craft_jpeg::decode_reduced(bytes, &limits(), None, shrink).ok()?;
let colour = match decoded.components {
3 => true,
1 => false,
_ => return None,
};
if info.coding_process == CodingProcess::DctProgressive {
// A progressive JPEG holds every coefficient of the full-size image (two bytes each) until
// its last scan, whatever the output size. Each component is counted at the full size and
// each side is rounded up to the largest MCU (32 pixels): an upper bound.
let side = |n: u16| u64::from(n).next_multiple_of(32);
let components: u64 = if colour { 3 } else { 1 };
if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 {
return None;
}
}
let reduced = |n: u16| u16::try_from(u32::from(n).div_ceil(1 << shrink)).ok();
let expected = (reduced(info.width)?, reduced(info.height)?);
// The decoder takes the smallest scale that meets either requested side, and a short side
// rounds up to the same size at several scales, so only the long side is requested.
let request = if info.width >= info.height { (expected.0, u16::MAX) } else { (u16::MAX, expected.1) };
let (w, h) = d.scale(request.0, request.1).ok()?;
if (w, h) != expected {
let craft_jpeg::Samples::U8(px) = decoded.samples else {
return None;
}
let px = d.decode().ok()?;
let pixels = usize::from(w).checked_mul(usize::from(h))?;
};
let pixels = usize::try_from(decoded.width).ok()?.checked_mul(usize::try_from(decoded.height).ok()?)?;
let rgba: Vec<u8> = if colour {
if px.len() != pixels.checked_mul(3)? {
return None;
@@ -122,5 +76,5 @@ pub(crate) fn decode_reduced(bytes: &[u8], shrink: u8) -> Option<(image::RgbaIma
}
px.iter().flat_map(|&v| [v, v, v, 255]).collect()
};
Some((image::RgbaImage::from_raw(u32::from(w), u32::from(h), rgba)?, colour))
Some((image::RgbaImage::from_raw(decoded.width, decoded.height, rgba)?, colour))
}
+1 -1
View File
@@ -13,7 +13,7 @@ mod jpeg;
mod psd;
mod resolution;
mod tone;
pub use craft_eps::is_eps;
pub use craft_ps::read::is_eps;
pub use eps::{bounding_box as eps_bounding_box, eps_pixel_size, eps_png, eps_proxy, eps_size};
pub use tone::{Tone, tone};
+16
View File
@@ -81,3 +81,19 @@ fn cmyk(file: &craft_psd::PsdFile, pixels: usize) -> Option<CmykRaster> {
let alpha = alpha.iter().any(|&a| a < 255).then_some(alpha);
Some(CmykRaster { width: header.width, height: header.height, cmyk: inks, alpha })
}
/// ResolutionInfo stores pixels per inch regardless of its display units. Read only the
/// borrowed head within the declared resource section, without allocating or decoding pixels.
/// Preserve the placement policy from #2550: reject incomplete or out-of-range values.
pub(crate) fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
let head = craft_psd::HeadView::from_bytes(bytes).ok()?;
for resource in head.resources() {
let resource = resource.ok()?;
if resource.id == craft_psd::resources::ids::RESOLUTION_INFO {
let info = craft_psd::ResolutionInfo::from_bytes(resource.data).ok()?;
let (h, v) = (info.h_res(), info.v_res());
return ((1.0..=10_000.0).contains(&h) && (1.0..=10_000.0).contains(&v)).then_some((h, v));
}
}
None
}
+5 -2
View File
@@ -1,8 +1,8 @@
//! Embedded raster resolution: the density a placed graphic was saved with, so placing honors
//! it instead of assuming 72 ppi (#1991: a 600 px photo saved at 600 dpi places one inch wide).
//! Reads JFIF/EXIF from JPEG (and EXIF from WebP), pHYs from PNG, the resolution
//! tags from TIFF, and the header density from BMP. GIF, PSD and files without (usable) metadata
//! report nothing and keep the pixel-is-a-point size.
//! tags from TIFF, the header density from BMP, and ResolutionInfo from PSD. GIF and files
//! without (usable) metadata report nothing and keep the pixel-is-a-point size.
/// Dots per inch in x and y, when the file carries usable resolution metadata.
pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> {
@@ -24,6 +24,9 @@ pub fn raster_resolution(bytes: &[u8]) -> Option<(f64, f64)> {
if is_classic_tiff(bytes) {
return tiff_resolution(bytes);
}
if crate::is_psd(bytes) {
return crate::psd::resolution(bytes);
}
None
}
+68 -3
View File
@@ -309,6 +309,53 @@ fn tiny_psd() -> Vec<u8> {
b
}
/// `tiny_psd` with a ResolutionInfo resource of `ppi` horizontally and vertically.
fn tiny_psd_at(ppi: u32) -> Vec<u8> {
tiny_psd_with_resolution(ppi, 16)
}
/// `tiny_psd` with a ResolutionInfo resource of `ppi`, its data cut to `len` bytes (16 in full).
fn tiny_psd_with_resolution(ppi: u32, len: usize) -> Vec<u8> {
let mut b = tiny_psd();
let mut data = Vec::new();
for v in [ppi << 16, 0x0001_0002, ppi << 16, 0x0001_0002] {
data.extend(v.to_be_bytes());
}
data.truncate(len);
let mut res = Vec::new();
res.extend(b"8BIM");
res.extend(1005u16.to_be_bytes());
res.extend([0, 0]); // empty name, padded
res.extend((data.len() as u32).to_be_bytes());
res.extend(data);
let at = 26 + 4; // header and empty colour mode data; then the image resources length
b.splice(at..at + 4, (res.len() as u32).to_be_bytes());
b.splice(at + 4..at + 4, res);
b
}
/// A 300 ppi PSD places at its resolution (2 px = 0.48 pt), as in the reference app; without
/// ResolutionInfo, or with a nonsense or incomplete one, at 72 ppi.
#[test]
fn psd_natural_size_follows_its_resolution() {
assert_eq!(natural_size(&tiny_psd()), Some((2.0, 1.0)));
let b = tiny_psd_at(300);
let (w, h) = natural_size(&b).unwrap();
assert!((w - 0.48).abs() < 1e-9 && (h - 0.24).abs() < 1e-9, "{w} {h}");
assert_eq!(raster_resolution(&b), Some((300.0, 300.0)));
assert_eq!(pixel_size(&b), Some((2, 1)));
assert!(decode_rgba(&b).is_some(), "the resource does not disturb decoding");
assert_eq!(natural_size(&tiny_psd_at(0)), Some((2.0, 1.0)));
assert_eq!(natural_size(&tiny_psd_at(20_000)), Some((2.0, 1.0)));
// ResolutionInfo is 16 bytes; a shorter one holding both resolutions is still not trusted.
assert!(psd::resolution(&tiny_psd_with_resolution(300, 16)).is_some());
assert_eq!(natural_size(&tiny_psd_with_resolution(300, 12)), Some((2.0, 1.0)));
// A resource length past the end of the file is ignored, not trusted.
let mut cut = tiny_psd_at(300);
cut.truncate(40);
assert!(psd::resolution(&cut).is_none());
}
#[test]
fn psd_composite_decodes() {
let b = tiny_psd();
@@ -1049,9 +1096,9 @@ fn reduced_decoding_refuses_progressive_jpegs_whose_full_size_coefficients_are_o
assert_eq!(pixel_size(&large), Some((10_240, 8_800)));
assert!(!too_large_to_decode(&large));
assert!(decode_rgba_reduced(&large, 3).is_none());
// One component of the same size stays under the limit.
let gray = decode_rgba_reduced(&progressive_jpeg(10_240, 8_800, 1), 3).unwrap();
assert_eq!(gray.dimensions(), (1_280, 1_100));
// A 1-component progressive JPEG that stays within the 512 MiB decoder buffer budget succeeds.
let gray = decode_rgba_reduced(&progressive_jpeg(10_240, 4_400, 1), 3).unwrap();
assert_eq!(gray.dimensions(), (1_280, 550));
}
/// Planar CMYK TIFFs and CMYK TIFFs with associated (premultiplied) alpha keep their inks through
@@ -1104,3 +1151,21 @@ fn planar_and_premultiplied_cmyk_tiffs_keep_their_inks() {
let straight = &r.cmyk[4..];
assert!(straight[0] <= 1 && straight[1] >= 254 && straight[2] >= 254 && straight[3] <= 1, "made straight: {straight:?}");
}
#[test]
fn psd_resolution_preserves_axes_display_units_and_section_bounds() {
let mut bytes = tiny_psd_at(300);
// Resource payload begins after header, two section lengths and the resource framing.
let payload = 46;
bytes[payload + 8..payload + 12].copy_from_slice(&(150u32 << 16).to_be_bytes());
bytes[payload + 4..payload + 6].copy_from_slice(&2u16.to_be_bytes());
bytes[payload + 12..payload + 14].copy_from_slice(&2u16.to_be_bytes());
assert_eq!(raster_resolution(&bytes), Some((300.0, 150.0)));
assert_eq!(natural_size(&bytes), Some((0.48, 0.48)));
// The same resource framing is used in PSB; display units do not rescale the values.
bytes[4..6].copy_from_slice(&2u16.to_be_bytes());
assert_eq!(raster_resolution(&bytes), Some((300.0, 150.0)));
// Bytes beyond the declared resource section must never complete a short payload.
bytes[30..34].copy_from_slice(&24u32.to_be_bytes());
assert_eq!(raster_resolution(&bytes), None);
}
+101 -4
View File
@@ -45,10 +45,29 @@ fn source_rects(doc: &Document, cache: &designcraft_compose::Cache, src: &Hyperl
if l.range.end <= *start || l.range.start >= *end {
continue;
}
let gs: Vec<_> = l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= *start && g.byte < *end).collect();
let (Some(a), Some(b)) = (gs.first(), gs.last()) else { continue };
let r = Rect::new(a.x, l.baseline - l.ascent, b.x + b.adv, l.baseline + l.descent);
out.push(m.transform_rect_bbox(r));
// Every glyph the source's characters produced, not only the ones that own
// their bytes: the glyphs of generated text — a cross-reference's — all point
// at the one marker character, and only the first of them owns it, so asking
// for owned bytes measured the first letter and nothing else (#1446).
//
// The bullet or number a paragraph's list adds is not the paragraph's text,
// but the composer gives it the first character's offset and no length, so a
// link starting at that character took the label in and the rectangle
// covered text outside the link. So `list_label` glyphs are left out, and so are the zero-length glyphs that are not
// generated text (kenten marks, ruby, kashidas, tab leaders, a cluster's later glyphs): they
// sit over or inside text that is counted already (noted in review).
for (x0, x1) in visual_link_spans(l.glyphs.iter().filter_map(|g| {
// Decorative marks do not partition a text row. Generated cross-reference
// glyphs do count even when only their first glyph owns the source byte.
if g.list_label || (g.len == 0 && g.generated_text.is_none()) {
return None;
}
let stacked = cs.styles.get(g.style as usize).is_some_and(|style| style.warichu);
Some((link_row(stacked, g.y), g.x, g.x + g.adv, g.byte >= *start && g.byte < *end))
})) {
let r = Rect::new(x0, l.baseline - l.ascent, x1, l.baseline + l.descent);
out.push(m.transform_rect_bbox(r));
}
}
}
out
@@ -56,6 +75,84 @@ fn source_rects(doc: &Document, cache: &designcraft_compose::Cache, src: &Hyperl
}
}
/// Selected horizontal spans, split by intervening unselected text, not by empty
/// letter spacing. The composer retains logical glyph order after bidi positioning;
/// sort the positioned text by row and x instead. Separate rows (warichu, for example)
/// must not act as separators for one another. Non-finite or zero-width glyphs cannot
/// define clickable coverage or a visible separator.
fn link_row(stacked: bool, y: f64) -> f64 {
if stacked { y } else { 0.0 }
}
fn visual_link_spans(glyphs: impl Iterator<Item = (f64, f64, f64, bool)>) -> Vec<(f64, f64)> {
let mut glyphs: Vec<_> = glyphs.filter(|(y, x0, x1, _)| y.is_finite() && x0.is_finite() && x1.is_finite() && x1 > x0).collect();
glyphs.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1)));
let mut out = Vec::new();
let mut first = 0;
while first < glyphs.len() {
let row = glyphs[first].0;
let end = first + glyphs[first..].iter().take_while(|g| g.0 == row).count();
let items = &glyphs[first..end];
let selected = items.iter().filter(|g| g.3);
let left = selected.clone().map(|g| g.1).fold(f64::INFINITY, f64::min);
let right = selected.map(|g| g.2).fold(f64::NEG_INFINITY, f64::max);
let mut cursor = left;
// Subtract unselected advances even when they overlap selected glyphs. Prefer
// a smaller clickable region over assigning another text cluster this link.
for (_, x0, x1, _) in items.iter().filter(|g| !g.3) {
if *x1 <= cursor || *x0 >= right {
continue;
}
if *x0 > cursor {
out.push((cursor, *x0));
}
cursor = cursor.max(*x1);
}
if cursor < right {
out.push((cursor, right));
}
first = end;
}
out
}
#[cfg(test)]
mod visual_link_tests {
use super::{link_row, visual_link_spans};
#[test]
fn bidi_selection_does_not_cover_intervening_unselected_text() {
// Logical order differs from visual order: selected Hebrew at the right,
// then a selected digit at the left, with unselected digits between them.
let glyphs = [(0.0, 30.0, 40.0, true), (0.0, 0.0, 10.0, true), (0.0, 10.0, 20.0, false), (0.0, 20.0, 30.0, false)];
assert_eq!(visual_link_spans(glyphs.into_iter()), [(0.0, 10.0), (30.0, 40.0)]);
}
#[test]
fn letter_spacing_and_zero_width_marks_do_not_split_selected_text() {
let glyphs = [(0.0, 0.0, 10.0, true), (0.0, 12.0, 22.0, true), (0.0, 11.0, 11.0, false)];
assert_eq!(visual_link_spans(glyphs.into_iter()), [(0.0, 22.0)]);
}
#[test]
fn baseline_shifted_unselected_text_is_still_a_separator() {
let glyphs = [(link_row(false, 0.0), 0.0, 10.0, true), (link_row(false, -5.0), 10.0, 20.0, false), (link_row(false, 0.0), 20.0, 30.0, true)];
assert_eq!(visual_link_spans(glyphs.into_iter()), [(0.0, 10.0), (20.0, 30.0)]);
}
#[test]
fn overlapping_unselected_advance_is_not_clickable() {
let glyphs = [(0.0, 0.0, 20.0, true), (0.0, 10.0, 15.0, false), (0.0, 15.0, 25.0, true)];
assert_eq!(visual_link_spans(glyphs.into_iter()), [(0.0, 10.0), (15.0, 25.0)]);
}
#[test]
fn another_text_row_is_not_a_separator() {
let glyphs = [(0.0, 0.0, 10.0, true), (0.0, 20.0, 30.0, true), (link_row(true, 5.0), 10.0, 20.0, false)];
assert_eq!(visual_link_spans(glyphs.into_iter()), [(0.0, 30.0)]);
}
}
/// Link annotations for the sheet at `idx`.
pub(crate) fn annotations(doc: &Document, cache: &designcraft_compose::Cache, sheets: &[Sheet], idx: usize) -> Vec<Annotation> {
let sh = &sheets[idx];
+23
View File
@@ -267,6 +267,29 @@ fn tables_export_cell_text() {
}
}
#[test]
fn cell_diagonal_lines_export_in_front_of_or_behind_the_cell_text() {
let export = |lines, in_front| {
let mut d = Document::new(&NewDocument::default());
let lid = d.default_layer();
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();
let mut t = designcraft_doc::Table::new(9, 1, 1, 0, 0, 200.0);
let cell = t.cell_mut(0, 0).unwrap();
cell.text.insert(0, "Ink");
let stroke = designcraft_doc::CellStroke { weight: 3.0, ..Default::default() };
cell.diagonal = designcraft_doc::CellDiagonal { lines, stroke, in_front };
d.story_mut(sid).unwrap().insert_table(0, t);
let bytes = export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap();
// The table's edges are 1 pt; the diagonals are the 3 pt strokes.
paint_order(&bytes).into_iter().filter(|(op, w)| op.ends_with("text") || *w == 3.0).map(|(op, _)| op).collect::<Vec<_>>()
};
use designcraft_doc::DiagonalLines;
let (text, line) = ("fill text".to_string(), "stroke path".to_string());
assert_eq!(export(DiagonalLines::None, true), [text.clone(), text.clone(), text.clone()]);
assert_eq!(export(DiagonalLines::Crossed, true), [text.clone(), text.clone(), text.clone(), line.clone(), line.clone()], "Diagonal In Front");
assert_eq!(export(DiagonalLines::TopLeft, false), [line.clone(), text.clone(), text.clone(), text.clone()], "Content In Front");
}
#[test]
fn drop_cap_text_extracts_in_order() {
let mut d = Document::new(&NewDocument::default());
+75 -59
View File
@@ -370,72 +370,88 @@ impl Exporter<'_> {
}
}
for c in &t.cells {
if !c.diagonals_in_front {
self.cell_diagonals(s, c);
}
self.table_cell(s, c);
if c.diagonals_in_front {
self.cell_diagonals(s, c);
}
}
for seg in &t.strokes {
let st = &seg.stroke;
let Some(col) = self.swatch_color(&st.color, st.tint) else { continue };
let kind = self.doc.stroke_kind(&st.kind);
let mut bp = BezPath::new();
bp.move_to(seg.a);
bp.line_to(seg.b);
let Some(p) = to_path(&bp) else { continue };
// Butt-ended fills close the table's corners the way square caps do.
let (ca, cb) = t.corner_capped(seg);
let mut capped = BezPath::new();
capped.move_to(ca);
capped.line_to(cb);
let Some(cp) = to_path(&capped) else { continue };
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& st.gap_color != designcraft_color::swatch::NONE
&& let Some(gap) = self.swatch_color(&st.gap_color, st.gap_tint)
{
s.set_fill(None);
s.set_stroke(Some(Stroke {
paint: gap.into(),
width: st.weight as f32,
line_cap: krilla::paint::LineCap::Butt,
..Default::default()
}));
s.draw_path(&cp);
s.set_stroke(None);
}
// Stripes, wavy and hash types are fills along the edge.
if let Some(o) = kind.outline(&capped, st.weight, 0.05)
&& let Some(op) = to_path(&o)
{
s.set_stroke(None);
s.set_fill(Some(solid_fill(col, 1.0)));
s.draw_path(&op);
s.set_fill(None);
continue;
}
let (cap, dash) = match &kind {
designcraft_doc::StrokeType::Dashed { pattern }
if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) =>
{
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
if pat.len() % 2 == 1 {
pat.extend(pat.clone());
}
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
}
designcraft_doc::StrokeType::Dotted
if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) =>
{
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
}
_ => (krilla::paint::LineCap::Square, None),
};
s.set_fill(None);
s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));
s.draw_path(&p);
s.set_stroke(None);
self.cell_stroke(s, seg, t.corner_capped(seg));
}
}
}
/// A cell's diagonal lines, clipped to the cell so their caps stay inside it.
fn cell_diagonals(&mut self, s: &mut Surface, c: &designcraft_compose::PlacedCell) {
if c.diagonals.is_empty() {
return;
}
let Some(clip) = to_path(&c.rect.to_path(0.1)) else { return };
s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero);
for seg in &c.diagonals {
self.cell_stroke(s, seg, (seg.a, seg.b));
}
s.pop();
}
/// One cell edge or diagonal: the gap color, then the stroke type. `capped` holds the ends the
/// butt-ended fills (stripes, wavy, hash, the gap color) run between.
fn cell_stroke(&mut self, s: &mut Surface, seg: &designcraft_compose::StrokeSeg, capped: (designcraft_geom::Point, designcraft_geom::Point)) {
let st = &seg.stroke;
let Some(col) = self.swatch_color(&st.color, st.tint) else { return };
let kind = self.doc.stroke_kind(&st.kind);
let mut bp = BezPath::new();
bp.move_to(seg.a);
bp.line_to(seg.b);
let Some(p) = to_path(&bp) else { return };
// Butt-ended fills close the table's corners the way square caps do.
let (ca, cb) = capped;
let mut capped = BezPath::new();
capped.move_to(ca);
capped.line_to(cb);
let Some(cp) = to_path(&capped) else { return };
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& st.gap_color != designcraft_color::swatch::NONE
&& let Some(gap) = self.swatch_color(&st.gap_color, st.gap_tint)
{
s.set_fill(None);
s.set_stroke(Some(Stroke { paint: gap.into(), width: st.weight as f32, line_cap: krilla::paint::LineCap::Butt, ..Default::default() }));
s.draw_path(&cp);
s.set_stroke(None);
}
// Stripes, wavy and hash types are fills along the edge.
if let Some(o) = kind.outline(&capped, st.weight, 0.05)
&& let Some(op) = to_path(&o)
{
s.set_stroke(None);
s.set_fill(Some(solid_fill(col, 1.0)));
s.draw_path(&op);
s.set_fill(None);
return;
}
let (cap, dash) = match &kind {
designcraft_doc::StrokeType::Dashed { pattern } if designcraft_doc::StrokeType::expandable_dashes(pattern, seg.a.distance(seg.b)) => {
let mut pat: Vec<f32> = pattern.iter().map(|v| v.max(0.0) as f32).collect();
if pat.len() % 2 == 1 {
pat.extend(pat.clone());
}
(krilla::paint::LineCap::Butt, Some(krilla::paint::StrokeDash { array: pat, offset: 0.0 }))
}
designcraft_doc::StrokeType::Dotted if designcraft_doc::StrokeType::expandable_dashes(&[0.0, st.weight * 2.0], seg.a.distance(seg.b)) => {
(krilla::paint::LineCap::Round, Some(krilla::paint::StrokeDash { array: vec![0.0, (st.weight * 2.0) as f32], offset: 0.0 }))
}
_ => (krilla::paint::LineCap::Square, None),
};
s.set_fill(None);
s.set_stroke(Some(Stroke { paint: col.into(), width: st.weight as f32, line_cap: cap, dash, ..Default::default() }));
s.draw_path(&p);
s.set_stroke(None);
}
fn fill_rect(&self, s: &mut Surface, r: Rect, c: krilla::color::Color) {
self.fill_path(s, &r.to_path(0.1), c);
}
+7
View File
@@ -167,6 +167,9 @@ fn table(ex: &mut Exporter, t: &TableFrag, m: Affine, k: f64, opacity: f32) {
if t.cells.iter().any(|c| c.graphic.is_some()) {
ex.warn("graphic cells are exported empty");
}
if t.cells.iter().any(|c| !c.diagonals.is_empty() && !c.diagonals_in_front) {
ex.warn("diagonal lines drawn behind cell contents are exported without that drawing order");
}
let edges_of = EdgeIndex::new(&t.strokes);
let id = ex.id();
let mut model = craft_pptx::table::Table {
@@ -223,6 +226,10 @@ fn table(ex: &mut Exporter, t: &TableFrag, m: Affine, k: f64, opacity: f32) {
edges_of.stroke(a, b)
};
cell.borders = ['L', 'R', 'T', 'B'].map(|side| Some(model_border(ex, edge(side), k, opacity)));
// Cell Options › Diagonal Lines.
let diagonal = |down: bool| placed.diagonals.iter().find(|s| ((s.a.x < s.b.x) == (s.a.y < s.b.y)) == down);
cell.diag_down = diagonal(true).map(|seg| model_border(ex, Some(seg), k, opacity));
cell.diag_up = diagonal(false).map(|seg| model_border(ex, Some(seg), k, opacity));
}
}
ex.native_shapes.push(craft_pptx::Shape {
+1 -1
View File
@@ -1515,7 +1515,7 @@ pub(crate) mod tests {
let want = Want { bytes: bytes.clone(), page: 0, width_pt: 1024.0, on_screen: 0.1 };
let (cached, peak) = reduced_estimates(&[want]).unwrap();
assert_eq!(cached, 128 * 96 * 4, "only the selected eighth-size mip is cached");
assert_eq!(peak, 128 * 96 * 8, "only the selected eighth-size mip is decoded");
assert_eq!(peak, 128 * 96 * 16, "only the selected eighth-size mip is decoded");
let full = decode_sizes(&bytes.load().unwrap(), 0);
assert!(cached < full.0 && peak < full.1, "reduced estimates {cached}/{peak}, full {full:?}");
}
+49
View File
@@ -547,6 +547,55 @@ fn table_edges_paint_gap_colour_between_dashes_and_stripes() {
assert!(column.iter().any(|p| ink(*p)) && column.iter().any(|p| cyan(*p)), "stripes and gap: {column:?}");
}
#[test]
fn cell_diagonal_lines_draw_in_front_of_or_behind_the_cell_text() {
let render = |lines, in_front| {
let mut d = Document::new(&NewDocument::default());
let lid = d.default_layer();
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 400.0), lid, "", ParaFormat::default()).unwrap();
let mut t = designcraft_doc::Table::new(1, 1, 1, 0, 0, 200.0);
t.rows[0].height = 60.0;
t.rows[0].mode = designcraft_doc::RowHeightMode::Exactly;
let cell = t.cell_mut(0, 0).unwrap();
cell.text.insert(0, "WWWWWWWWWWWWWWWWWWWW");
cell.text.format_chars(0..20, |f| f.over.size = Some(30.0));
let stroke = designcraft_doc::CellStroke { weight: 6.0, color: "C=100 M=0 Y=0 K=0".into(), ..Default::default() };
cell.diagonal = designcraft_doc::CellDiagonal { lines, stroke, in_front };
d.story_mut(sid).unwrap().insert_table(0, t);
let cache = Cache::new();
let rect = cache.get(&d, sid, None).frames[0].tables[0].cell(0, 0).unwrap().rect;
let mut r = Renderer::new();
r.threads = 0;
let img = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();
let cyan = |p: [u8; 4]| p[0] < 80 && p[2] > 150;
let inside = |x: f64, y: f64| x > rect.x0 + 4.0 && x < rect.x1 - 4.0 && y > rect.y0 + 4.0 && y < rect.y1 - 4.0;
let count = |a: (f64, f64), b: (f64, f64)| {
(0..=200)
.map(|i| (a.0 + (b.0 - a.0) * i as f64 / 200.0, a.1 + (b.1 - a.1) * i as f64 / 200.0))
.filter(|&(x, y)| inside(x, y) && cyan(img.pixel(x as u32, y as u32)))
.count()
};
let down = count((rect.x0, rect.y0), (rect.x1, rect.y1));
let up = count((rect.x1, rect.y0), (rect.x0, rect.y1));
// Just past the corner, outside the cell.
let outside = img.pixel((rect.x1 + 2.0) as u32, (rect.y1 + 2.0) as u32);
(down, up, cyan(outside))
};
use designcraft_doc::DiagonalLines;
assert_eq!(render(DiagonalLines::None, true), (0, 0, false));
let (down, up, outside) = render(DiagonalLines::Crossed, true);
assert!(down > 150 && up > 150 && !outside, "crossed: {down} {up} {outside}");
let (down, up, _) = render(DiagonalLines::TopLeft, true);
// The other diagonal meets this one only where they cross, near the middle.
assert!(down > 150 && up < 40, "top left to bottom right: {down} {up}");
let (down, up, _) = render(DiagonalLines::TopRight, true);
assert!(down < 40 && up > 150, "top right to bottom left: {down} {up}");
// The text covers part of the line drawn behind it.
let (behind, _, _) = render(DiagonalLines::TopLeft, false);
let (front, _, _) = render(DiagonalLines::TopLeft, true);
assert!(behind + 10 < front, "content in front: {behind} vs {front}");
}
#[test]
fn degenerate_dash_patterns_draw_solid_and_fill_types_close_table_corners() {
let fine = designcraft_doc::StrokeType::Dashed { pattern: vec![1e-6, 1e-6] };
+47 -22
View File
@@ -498,6 +498,9 @@ impl Renderer {
}
}
for c in &t.cells {
if !c.diagonals_in_front {
draw_cell_diagonals(ctx, f, xf, c);
}
if let Some(g) = &c.graphic {
ctx.set_transform(f.view * xf);
ctx.push_clip_layer(&c.clip.to_path(0.1));
@@ -507,36 +510,58 @@ impl Renderer {
} else if let Some(cft) = c.text.frames.first() {
self.draw_text(ctx, f, &c.text, cft, xf * Affine::translate(c.origin.to_vec2()));
}
if c.diagonals_in_front {
draw_cell_diagonals(ctx, f, xf, c);
}
}
ctx.set_transform(f.view * xf);
for s in &t.strokes {
let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { continue };
let kind = doc.stroke_kind(&s.stroke.kind);
let line = kurbo::Line::new(s.a, s.b).to_path(0.1);
// Butt-ended fills close the table's corners the way square caps do.
let (ca, cb) = t.corner_capped(s);
let capped = kurbo::Line::new(ca, cb).to_path(0.1);
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& let Some(gap) = doc.resolve_color(&s.stroke.gap_color, s.stroke.gap_tint)
{
ctx.set_paint(color_of(&gap, 1.0));
ctx.set_stroke(kurbo::Stroke::new(s.stroke.weight).with_caps(kurbo::Cap::Butt));
ctx.stroke_path(&capped);
}
ctx.set_paint(color_of(&col, 1.0));
// Stripes, wavy and hash types are fills along the edge.
if let Some(o) = kind.outline(&capped, s.stroke.weight, 0.05 * f.px) {
ctx.fill_path(&o);
continue;
}
ctx.set_stroke(cell_stroke(&kind, s.stroke.weight, s.a.distance(s.b)));
ctx.stroke_path(&line);
draw_cell_stroke(ctx, f, s, t.corner_capped(s));
}
}
}
}
/// A cell's diagonal lines, clipped to the cell so their caps stay inside it.
fn draw_cell_diagonals(ctx: &mut RenderContext, f: &Frame, xf: Affine, c: &designcraft_compose::PlacedCell) {
if c.diagonals.is_empty() {
return;
}
ctx.set_transform(f.view * xf);
ctx.push_clip_layer(&c.rect.to_path(0.1));
for s in &c.diagonals {
draw_cell_stroke(ctx, f, s, (s.a, s.b));
}
ctx.pop_layer();
}
/// One cell edge or diagonal: the gap color, then the stroke type. `capped` holds the ends the
/// butt-ended fills (stripes, wavy, hash, the gap color) run between.
fn draw_cell_stroke(ctx: &mut RenderContext, f: &Frame, s: &designcraft_compose::StrokeSeg, capped: (kurbo::Point, kurbo::Point)) {
let doc = f.doc;
let Some(col) = doc.resolve_color(&s.stroke.color, s.stroke.tint) else { return };
let kind = doc.stroke_kind(&s.stroke.kind);
let line = kurbo::Line::new(s.a, s.b).to_path(0.1);
// Butt-ended fills close the table's corners the way square caps do.
let capped = kurbo::Line::new(capped.0, capped.1).to_path(0.1);
// Gap colour under dashes, dots and stripes: the whole edge, solid.
if !matches!(kind, designcraft_doc::StrokeType::Solid)
&& let Some(gap) = doc.resolve_color(&s.stroke.gap_color, s.stroke.gap_tint)
{
ctx.set_paint(color_of(&gap, 1.0));
ctx.set_stroke(kurbo::Stroke::new(s.stroke.weight).with_caps(kurbo::Cap::Butt));
ctx.stroke_path(&capped);
}
ctx.set_paint(color_of(&col, 1.0));
// Stripes, wavy and hash types are fills along the edge.
if let Some(o) = kind.outline(&capped, s.stroke.weight, 0.05 * f.px) {
ctx.fill_path(&o);
return;
}
ctx.set_stroke(cell_stroke(&kind, s.stroke.weight, s.a.distance(s.b)));
ctx.stroke_path(&line);
}
/// A run's stroke colour, if it has one.
fn stroke_of(doc: &designcraft_doc::Document, st: &designcraft_compose::RunStyle) -> Option<TextPaint> {
if st.stroke == designcraft_color::swatch::NONE {
+1
View File
@@ -14,6 +14,7 @@ use serde_json::{Value, json};
use crate::{DesignApp, ScreenMode, View, theme::Tokens};
mod caret;
mod column_guides;
mod frames;
mod guides;
+42
View File
@@ -0,0 +1,42 @@
//! One blink phase for the text caret: the story, table cell and footnote carets share it.
use designcraft_doc::TextSel;
const BLINK_HZ: f64 = 1.6;
fn start_id() -> egui::Id {
egui::Id::unique("canvas_caret_blink_start")
}
fn caret_id() -> egui::Id {
egui::Id::unique("canvas_caret_blink_caret")
}
pub(super) fn reset(ctx: &egui::Context) {
let now = ctx.input(|i| i.time);
ctx.data_mut(|d| d.insert_temp(start_id(), now));
}
pub(super) fn visible(ctx: &egui::Context, caret: TextSel) -> bool {
let now = ctx.input(|i| i.time);
let start = ctx.data_mut(|d| match (d.get_temp::<f64>(start_id()), d.get_temp::<TextSel>(caret_id())) {
(Some(start), Some(last)) if last == caret => start,
_ => {
d.insert_temp(start_id(), now);
d.insert_temp(caret_id(), caret);
now
}
});
let phase = (now - start) * BLINK_HZ;
let wait = until_flip(phase);
if wait.is_finite() {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
}
phase as i64 % 2 == 0
}
pub(super) fn until_flip(phase: f64) -> f64 {
(1.0 - phase.rem_euclid(1.0)) / BLINK_HZ
}
+10
View File
@@ -1,3 +1,4 @@
use super::caret;
use super::column_guides::{COLUMN_DRAG, ColumnDrag, column_guide_drag};
use super::guides::guide_drag;
use super::ime::{finish_pending_ime_delete, ime_event};
@@ -298,6 +299,13 @@ fn note_release(ui: &egui::Ui, clicks_id: egui::Id, latest: Option<Pos2>, now: f
}
}
/// Typing, IME input, a paste or a key press restarts the caret's blink.
fn restart_caret_blink(ctx: &egui::Context, e: &egui::Event) {
if matches!(e, egui::Event::Text(_) | egui::Event::Ime(_) | egui::Event::Paste(_) | egui::Event::Key { pressed: true, .. }) {
caret::reset(ctx);
}
}
/// Give an open menu priority, then handle wheel/zoom/pan, spring Zoom, guide drags and primary pointer routing.
pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rect: Rect) {
// While a context menu is open (in either pane), the click that closes it and the keys go to the menu.
@@ -348,6 +356,7 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
let (delay, dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
let n = press_count(ui.data(|d| d.get_temp(clicks_id)), o, now, delay, dist);
ui.data_mut(|d| d.insert_temp(clicks_id, Clicks { at: f64::NEG_INFINITY, pos: o, n }));
caret::reset(ui.ctx());
events.push(PointerEvent { kind: PointerKind::Down, pos: pos(o), mods: m, clicks: n });
down = true;
}
@@ -420,6 +429,7 @@ pub(super) fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::
let mut held =
ui.data(|d| d.get_temp::<(egui::Modifiers, egui::Modifiers)>(modifiers_id())).map_or_else(|| ui.input(|i| i.modifiers), |(start, _)| start);
for e in evs {
restart_caret_blink(ui.ctx(), &e);
#[cfg(not(target_arch = "wasm32"))]
let chord = {
if let egui::Event::ModifiersChanged(m) = &e {
+31
View File
@@ -3441,6 +3441,37 @@ fn table_cells_show_their_hidden_characters() {
assert_eq!((last.0, last.1), (designcraft_geom::Point::new(frag.rect.x1 + 1.0, frag.rect.y1), ""));
}
#[test]
fn the_caret_blink_restarts_on_input_and_caret_changes() {
let ctx = egui::Context::default();
let caret = designcraft_doc::TextSel::caret(designcraft_doc::StoryId(1), 7);
let shown = |t: f64, caret: designcraft_doc::TextSel, reset: bool| {
let mut visible = false;
let mut out = ctx.run_ui(egui::RawInput { time: Some(t), ..Default::default() }, |ui| {
if reset {
caret::reset(ui.ctx());
}
visible = caret::visible(ui.ctx(), caret);
});
out.textures_delta.clear();
visible
};
assert!(shown(10.0, caret, true), "a reset shows the caret");
assert!(shown(10.5, caret, false), "the first half is on");
assert!(!shown(10.7, caret, false), "the second half is off");
assert!(shown(11.3, caret, false), "the next cycle is on");
assert!(shown(10.7, caret, true), "typing shows it again");
assert!(!shown(11.4, caret, false), "and its phase follows the reset");
let moved = designcraft_doc::TextSel::caret(designcraft_doc::StoryId(1), 8);
assert!(shown(11.4, moved, false), "a caret that moved shows at once");
assert!((caret::until_flip(0.0) - 0.625).abs() < 1e-9);
assert!((caret::until_flip(0.96) - 0.025).abs() < 1e-9);
assert!((caret::until_flip(1.0) - 0.625).abs() < 1e-9);
}
#[test]
fn leaving_parent_editing_for_the_left_page_of_a_spread_keeps_that_page_selected() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+9 -7
View File
@@ -1,3 +1,4 @@
use super::caret;
use super::frames::{item_canvas_xf, layer_color, path_screen};
use super::{Affine, CanvasLayout, Color32, DesignApp, Document, Point, Pos2, Rect, Stroke, Xf, compose, pos2};
@@ -113,11 +114,9 @@ pub(super) fn draw_text_selection(
let on = |p: Point| compose::PathTextMap::new(it, ft).map_or(p, |map| map.to_path(p));
let p0 = xf.to_screen(m * on(Point::new(x, bl - asc)));
let p1 = xf.to_screen(m * on(Point::new(x, bl + desc)));
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
if caret::visible(painter.ctx(), ts) {
painter.line_segment([p0, p1], Stroke::new(1.0, Color32::BLACK));
}
painter.ctx().request_repaint_after(std::time::Duration::from_millis(330));
}
}
@@ -167,11 +166,9 @@ fn draw_cell_selection(
{
let m = a * doc.text_xf(it);
let (p0, p1) = (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc)));
let blink = (painter.ctx().input(|i| i.time) * 1.6) as i64 % 2 == 0;
if blink {
if caret::visible(painter.ctx(), ts) {
painter.line_segment([p0, p1], Stroke::new(1.0, Color32::BLACK));
}
painter.ctx().request_repaint_after(std::time::Duration::from_millis(330));
}
}
@@ -247,7 +244,12 @@ fn draw_inverse_highlight(
let skew =
if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
let shatai = style.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
let ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
let mut ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
if ft.vertical
&& let Some(turn) = g.vertical_xf(l.baseline)
{
ga = turn * ga;
}
rc.set_transform(view * *m * ga);
rc.fill_path(&outline);
}
+88 -9
View File
@@ -4,6 +4,9 @@ use super::{Color32, DesignApp, Sense, Stroke, Tokens, icons, json, panels, semi
/// tabs after it stay in view.
pub(super) const DOC_TAB_MAX_W: f32 = 260.0;
/// Width of the scroll arrows and the document list button at the ends of an overflowing tab bar.
const DOC_TAB_BUTTON_W: f32 = 22.0;
/// Close button and padding around a tab's title.
const DOC_TAB_PAD: f32 = 44.0;
@@ -15,13 +18,28 @@ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
let close_label = crate::i18n::tr(&app.ui.language, "Close");
ui.painter().rect_filled(bar, 0.0, t.tab_strip);
ui.painter().line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.border));
let mut x = bar.min.x;
// Tabs past the bar scroll sideways: trackpad, shift or a plain wheel, and the active tab is kept in view.
let scroll_id = ui.scope_id().with("doctabs_scroll");
let (mut offset, total_w, seen_active, seen_w): (f32, f32, Option<u64>, f32) = ui.data(|d| d.get_temp(scroll_id)).unwrap_or_default();
if ui.rect_contains_pointer(bar) {
let d = ui.input(|i| i.smooth_scroll_delta);
offset -= if d.x.abs() > d.y.abs() { d.x } else { d.y };
}
// Arrows and the document list take the bar's ends once the tabs overflow.
let overflow = total_w > bar.width();
let tabs =
if overflow { egui::Rect::from_min_max(bar.min + vec2(DOC_TAB_BUTTON_W, 0.0), bar.max - vec2(2.0 * DOC_TAB_BUTTON_W, 0.0)) } else { bar };
offset = offset.clamp(0.0, (total_w - tabs.width()).max(0.0));
let painter = ui.painter().with_clip_rect(tabs);
let origin = tabs.min.x - offset;
let mut x = origin;
let active = app.session.active_index();
let zoom = app.view().map(|v| v.zoom).unwrap_or(1.0);
let mut activate = None;
let mut close = None;
let titles: Vec<(String, bool)> = app.session.documents().iter().map(|d| (d.title(), d.is_dirty())).collect();
for (i, (title, dirty)) in titles.iter().enumerate() {
let mut edges = Vec::new();
let titles: Vec<(String, bool, u64)> = app.session.documents().iter().map(|d| (d.title(), d.is_dirty(), d.uid)).collect();
for (i, (title, dirty, uid)) in titles.iter().enumerate() {
let is_active = Some(i) == active;
// `*` = unsaved; the view-mode suffix only in Preview (InDesign shows its GPU mode there).
let suffix = if is_active && app.ui.screen_mode == crate::ScreenMode::Preview { " [Preview]" } else { "" };
@@ -34,7 +52,11 @@ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
let elided = galley.elided;
let w = (galley.size().x + zoom_label.size().x + DOC_TAB_PAD).max(if is_active { 210.0 } else { 150.0 }).min(max_w);
let r = egui::Rect::from_min_size(egui::pos2(x, bar.min.y), vec2(w, 28.0));
let resp = ui.interact(r, ui.scope_id().with(("doctab", i)), Sense::click());
if is_active && (Some(*uid) != seen_active || (tabs.width() - seen_w).abs() > 0.5) {
offset += (r.max.x - tabs.max.x).max(0.0) + (r.min.x - tabs.min.x).min(0.0);
ui.request_repaint();
}
let resp = ui.interact(r.intersect(tabs), ui.scope_id().with(("doctab", i)), Sense::click());
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title));
let resp = if elided {
resp.on_hover_ui(|ui| {
@@ -43,11 +65,11 @@ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
} else {
resp
};
ui.painter().rect_filled(r, 0.0, if is_active { t.panel } else { t.tab_strip });
painter.rect_filled(r, 0.0, if is_active { t.panel } else { t.tab_strip });
let cr = egui::Rect::from_center_size(egui::pos2(r.min.x + 18.0, r.center().y), vec2(14.0, 14.0));
let cresp = ui.interact(cr, ui.scope_id().with(("docclose", i)), Sense::click());
let cresp = ui.interact(cr.intersect(tabs), ui.scope_id().with(("docclose", i)), Sense::click());
cresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{close_label} {title}")));
ui.painter().text(
painter.text(
cr.center(),
egui::Align2::CENTER_CENTER,
"×",
@@ -56,17 +78,74 @@ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {
);
let name_w = galley.size().x;
// Clipped too, for a window narrower than the zoom label.
let text = ui.painter().with_clip_rect(r);
let text = painter.with_clip_rect(r.intersect(tabs));
text.galley(egui::pos2(r.min.x + 32.0, r.center().y - galley.size().y / 2.0), galley, Color32::WHITE);
text.galley(egui::pos2(r.min.x + 32.0 + name_w, r.center().y - zoom_label.size().y / 2.0), zoom_label, Color32::WHITE);
ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.border));
painter.line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.border));
if cresp.clicked() {
close = Some(i);
} else if resp.clicked() {
activate = Some(i);
}
edges.push((r.min.x, r.max.x));
x += w;
}
if overflow {
let button = |i: f32| {
egui::Rect::from_min_size(
egui::pos2(if i < 0.0 { bar.min.x } else { bar.max.x - (i + 1.0) * DOC_TAB_BUTTON_W }, bar.min.y),
vec2(DOC_TAB_BUTTON_W, 28.0),
)
};
let max_offset = (x - origin - tabs.width()).max(0.0);
for (rect, glyph, label, dir, enabled) in
[(button(-1.0), "‹", "Scroll Tabs Left", -1.0, offset > 0.0), (button(1.0), "›", "Scroll Tabs Right", 1.0, offset < max_offset)]
{
let label = crate::i18n::tr(&app.ui.language, label);
let resp = ui.interact(rect, ui.scope_id().with(("doctab_scroll", glyph)), Sense::click()).on_hover_text(label);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
let color = if !enabled {
t.text_dim.gamma_multiply(0.4)
} else if resp.hovered() {
t.text_strong
} else {
t.text_dim
};
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(16.0), color);
if enabled && resp.clicked() {
// One tab at a time: the next one hidden on that side comes fully into view.
offset += if dir > 0.0 {
edges.iter().find(|e| e.1 > tabs.max.x + 0.5).map(|e| e.1 - tabs.max.x)
} else {
edges.iter().rev().find(|e| e.0 < tabs.min.x - 0.5).map(|e| e.0 - tabs.min.x)
}
.unwrap_or(0.0);
ui.request_repaint();
}
}
let mut list =
ui.new_child(egui::UiBuilder::new().max_rect(button(0.0)).layout(egui::Layout::centered_and_justified(egui::Direction::LeftToRight)));
let widgets = &mut list.visuals_mut().widgets;
for state in [&mut widgets.inactive, &mut widgets.hovered, &mut widgets.active, &mut widgets.open] {
state.weak_bg_fill = Color32::TRANSPARENT;
state.bg_stroke = Stroke::NONE;
}
crate::menus::menu_button(&mut list, egui::RichText::new("▾").size(14.0).color(t.text_dim), |ui| {
for (i, (title, ..)) in titles.iter().enumerate() {
if ui.selectable_label(Some(i) == active, crate::rtl::isolate(title)).clicked() {
activate = Some(i);
ui.close();
}
}
});
}
// The arrows come or go once this frame's width is known: the active tab is brought into view again in the new layout.
let overflows = x - origin > bar.width();
if overflows != overflow {
ui.request_repaint();
}
let seen = if overflows == overflow { active.and_then(|i| titles.get(i)).map(|t| t.2) } else { seen_active };
ui.data_mut(|d| d.insert_temp(scroll_id, (offset, x - origin, seen, tabs.width())));
if let Some(i) = close {
crate::menus::close_document(app, Some(i));
} else if let Some(i) = activate {
+92
View File
@@ -280,6 +280,98 @@ fn long_document_names_keep_tabs_short_and_close_buttons_visible() {
assert!(short.min.x - first.min.x <= 2.0 * super::DOC_TAB_MAX_W, "the last tab {short:?} starts too far right");
}
/// Tabs past the bar are reached with the arrows (one tab per click) and the document list.
#[test]
fn overflowing_document_tabs_scroll_with_arrows_and_list_every_document() {
let mut app = app();
for n in 1..=12 {
app.run("file.new", serde_json::json!({ "title": format!("Doc {n}") })).unwrap();
}
app.run("file.activate", serde_json::json!({"index": 0})).unwrap();
let mut h = test_window::open(app, vec2(1200.0, 600.0));
h.run_steps(4);
let window = h.ctx.content_rect();
let last = |h: &egui_kittest::Harness<'static, test_window::Window>| h.query_by_label("Doc 12").map(|n| n.rect());
assert!(last(&h).is_none_or(|r| r.max.x > window.max.x), "the last tab starts off screen");
// A tab clipped by the bar is narrower than its 150 pt minimum.
let whole = |h: &egui_kittest::Harness<'static, test_window::Window>, n: usize| {
h.query_by_label(&format!("Doc {n}")).is_some_and(|tab| tab.rect().width() > 149.0)
};
let shown = (1..=12).take_while(|n| whole(&h, *n)).count();
let arrow = h.get_by_label("Scroll Tabs Right").rect().center();
test_window::click_at(&mut h, arrow);
assert!(whole(&h, shown + 1), "one click brings the next tab fully into view");
assert!(!whole(&h, shown + 2), "and no more than that one");
for _ in 0..12 {
let arrow = h.get_by_label("Scroll Tabs Right").rect().center();
test_window::click_at(&mut h, arrow);
}
let tab = last(&h).expect("the last tab scrolled into view");
assert!(window.contains_rect(tab), "{tab:?} outside {window:?}");
test_window::click_at(&mut h, tab.right_center() - vec2(10.0, 0.0));
assert_eq!(h.state().app.session.active_index(), Some(11));
for _ in 0..12 {
let arrow = h.get_by_label("Scroll Tabs Left").rect().center();
test_window::click_at(&mut h, arrow);
}
let (first, left) = (h.get_by_label("Doc 1").rect(), h.get_by_label("Scroll Tabs Left").rect());
assert!((first.min.x - left.max.x).abs() < 1.0, "{first:?} is not the first tab, next to {left:?}");
let list = h.query_all_by_label("▾").map(|n| n.rect()).find(|r| first.y_range().contains(r.center().y)).expect("the document list").center();
test_window::click_at(&mut h, list);
h.run_steps(3);
h.query_all_by_label("Doc 7").find(|n| !first.y_range().contains(n.rect().center().y)).expect("the list's entry").click();
h.run_steps(3);
assert_eq!(h.state().app.session.active_index(), Some(6));
assert!(window.contains_rect(h.get_by_label("Doc 7").rect()), "the chosen document's tab is scrolled into view");
}
/// A narrower window must not leave the active tab hidden.
#[test]
fn the_active_document_tab_stays_in_view_when_the_window_shrinks() {
let mut app = app();
for n in 1..=12 {
app.run("file.new", serde_json::json!({ "title": format!("Doc {n}") })).unwrap();
}
let mut h = test_window::open(app, vec2(1800.0, 600.0));
h.run_steps(4);
let full_width = h.get_by_label("Doc 12").rect().width();
h.set_size(vec2(900.0, 600.0));
h.run_steps(6);
let window = h.ctx.content_rect();
// The reported rect is clipped to the bar, so a half-hidden tab would be narrower.
let tab = h.get_by_label("Doc 12").rect();
assert!(window.contains_rect(tab) && (tab.width() - full_width).abs() < 1.0, "{tab:?} (was {full_width} wide) outside {window:?}");
}
/// The successor of a closed active tab takes its index, so identity decides what to reveal.
#[test]
fn closing_an_active_tab_scrolled_out_of_view_reveals_its_successor() {
let mut app = app();
for n in 1..=12 {
app.run("file.new", serde_json::json!({ "title": format!("Doc {n}") })).unwrap();
}
app.run("file.activate", serde_json::json!({"index": 2})).unwrap();
let mut h = test_window::open(app, vec2(1200.0, 600.0));
h.run_steps(4);
for _ in 0..12 {
let arrow = h.get_by_label("Scroll Tabs Right").rect().center();
test_window::click_at(&mut h, arrow);
}
let left_edge = h.get_by_label("Scroll Tabs Left").rect().max.x;
assert!(h.get_by_label("Doc 3").rect().max.x <= left_edge + 1.0, "the active tab is scrolled out of view");
crate::menus::close_document(&mut h.state_mut().app, Some(2));
h.run_steps(6);
// The next document takes the closed one's index, so only its identity tells them apart.
assert_eq!(h.state().app.session.active_index(), Some(2));
let window = h.ctx.content_rect();
let tab = h.get_by_label("Doc 4").rect();
assert!(window.contains_rect(tab) && tab.width() > 149.0, "{tab:?} not fully in view in {window:?}");
}
/// Zero2Graphic's page layout video (0:48): with the Type tool, the Control panel's font size
/// has a list of sizes; the instructor picks 72 pt from it. Leading has the same list.
#[test]
+24
View File
@@ -408,6 +408,11 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest
let fields = p.get("fields").cloned().unwrap_or(Value::Null);
let d = match id {
"frameSize" => crate::dialogs::frame_size_dialog(app, fields),
// Bound to the target cells and document, as Table › Cell Options › Diagonal Lines… opens it.
"diagonalLines" => match crate::dialogs::diagonal_lines_dialog(app, fields) {
Ok(d) => d,
Err(e) => return err(e),
},
"contactSheet" => crate::dialogs::contact_sheet_dialog(app, fields),
"fittingOptions" => {
let mut d = crate::dialogs::Dialog::new(id, fields);
@@ -543,6 +548,25 @@ mod automation_contract_tests {
app.run("style.paragraph.edit", json!({"name":designcraft_doc::BASIC_PARAGRAPH,"chars":{"size":18}})).unwrap();
assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1);
}
#[test]
fn diagonal_lines_opened_through_the_control_channel_applies_to_its_target_cells() {
let mut app = app();
let ctx = egui::Context::default();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
let response = call(&mut app, &ctx, "ui.dialog.open", json!({"id": "diagonalLines", "fields": {"lines": "crossed"}}));
assert_eq!(response["ok"], true, "{response}");
app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();
let response = call(&mut app, &ctx, "ui.dialog.confirm", json!({}));
assert_eq!(response["ok"], true, "{response}");
let st = app.session.active().unwrap();
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
let lines: Vec<_> = t.cells.iter().map(|c| c.diagonal.lines).collect();
use designcraft_doc::DiagonalLines::{Crossed, None as No};
assert_eq!(lines, [Crossed, No, No, No]);
}
/// `ui.dialog.open` opens Place Contact Sheet as the menu does: bare numbers are in the
/// document's ruler unit, so `1` on an inch document is an inch, not a pica.
#[test]
+492 -30
View File
@@ -26,6 +26,10 @@ pub struct Dialog {
/// from when it opened, so a bare `50` means what it did then. `None` falls back to `unit`.
#[serde(skip)]
pub vertical_unit: Option<Unit>,
/// The document contents the dialog opened with (Diagonal Lines), held while it is open: an
/// edit replaces them, so a dialog whose document holds other contents knows it was edited.
#[serde(skip)]
pub contents: Option<std::sync::Arc<designcraft_doc::Document>>,
}
impl Dialog {
@@ -86,7 +90,7 @@ impl Dialog {
if id == "ruby" {
fields.entry("section".to_string()).or_insert(json!("cjk.rubyPlacement"));
}
Dialog { id: id.into(), fields, unit: Unit::Picas, vertical_unit: None }
Dialog { id: id.into(), fields, unit: Unit::Picas, vertical_unit: None, contents: None }
}
/// 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 {
@@ -3272,7 +3276,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
// The menu items' translations (every language has them), without the ellipsis.
"convertTextToTable" => crate::i18n::tr(&app.ui.language, "Convert Text to Table…").trim_end_matches('…').trim_end(),
"convertTableToText" => crate::i18n::tr(&app.ui.language, "Convert Table to Text…").trim_end_matches('…').trim_end(),
"cellOptions" => crate::i18n::tr(&app.ui.language, "Cell Options"),
"cellOptions" | "diagonalLines" => 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"),
@@ -4161,6 +4165,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
"insertTable" => insert_table_dialog(app, ui, &mut d),
"convertTextToTable" | "convertTableToText" => convert_table_dialog(app, ui, &mut d),
"cellOptions" => cell_options(app, ui, &mut d),
"diagonalLines" => diagonal_lines(app, ui, &mut d),
"createGuides" => create_guides_dialog(app, ui, &mut d),
"marginsAndColumns" => margins_and_columns_dialog(app, ui, &mut d),
"textFrameOptions" => {
@@ -4362,7 +4367,7 @@ fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate
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) {
if field.is_none_or(|f| same_cell_value(seed.get(k), k, f)) {
d.fields.insert(k.into(), v.clone());
}
seed.insert(k.into(), v);
@@ -4370,13 +4375,19 @@ fn cell_options_edges_changed(app: &mut DesignApp, d: &mut Dialog, edges: &crate
d.fields.insert("seed".into(), Value::Object(seed));
}
/// Whether the dialog field `k` holds the cells' value `seed`. The Type list picks a stroke type
/// by name (`"solid"`), and the cells' value is the type itself (`{"kind": "solid"}`).
fn same_cell_value(seed: Option<&Value>, k: &str, v: &Value) -> bool {
seed == Some(v) || (k == "type" && v.as_str().is_some_and(|name| seed == Some(&json!({"kind": name}))))
}
/// 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 };
let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && !same_cell_value(seed.get(k), k, v)) else { continue };
match (is_stroke, k) {
(true, _) => {
stroke.insert(k.into(), v.clone());
@@ -4399,6 +4410,170 @@ fn confirm_cell_options(app: &mut DesignApp, d: &Dialog) -> Result<Value, String
app.run("table.setCell", Value::Object(params))
}
/// The line buttons of Cell Options › Diagonal Lines: the `diagonal.lines` name and its label.
const DIAGONAL_LINES: [(&str, &str); 4] = [
("none", "No Diagonal Lines"),
("topLeft", "Diagonal Line from Top Left to Bottom Right"),
("topRight", "Diagonal Line from Top Right to Bottom Left"),
("crossed", "Crossed Diagonal Lines"),
];
/// Cell Options › Diagonal Lines keys (`table.getCellDiagonal` names).
const DIAGONAL_KEYS: [&str; 8] = ["lines", "weight", "type", "color", "tint", "gapColor", "gapTint", "inFront"];
/// Table › Cell Options › Diagonal Lines… for the target cells. The fields start from the
/// cells' values (`seed`); OK applies the fields that differ from it. The dialog keeps the
/// document it opened in (`document`: uid and identity epoch, and `Dialog::contents`) and its
/// target cells (`cells`).
pub fn open_diagonal_lines(app: &mut DesignApp) -> Result<Value, String> {
app.ui.dialog = Some(diagonal_lines_dialog(app, Value::Null)?);
Ok(Value::Null)
}
/// The Diagonal Lines dialog for the target cells, with the `DIAGONAL_KEYS` values in `params`
/// (from `ui.dialog.open`) entered in place of the cells' values.
pub fn diagonal_lines_dialog(app: &mut DesignApp, params: Value) -> Result<Dialog, String> {
let cur = app.session.execute("table.getCellDiagonal", &json!({})).map_err(|e| e.to_string())?;
let st = app.session.active().ok_or("no document open")?;
let document = json!({"uid": st.uid, "epoch": st.identity_epoch});
let contents = st.doc.clone();
let mut fields = Map::new();
for k in DIAGONAL_KEYS {
fields.insert(k.into(), cur[k].clone());
}
fields.insert("seed".into(), Value::Object(fields.clone()));
for k in DIAGONAL_KEYS {
if let Some(v) = params.get(k) {
fields.insert(k.into(), v.clone());
}
}
fields.insert("document".into(), document);
fields.insert("cells".into(), json!({"story": cur["story"], "table": cur["table"], "rows": cur["rows"], "cols": cur["cols"]}));
let mut d = Dialog::new("diagonalLines", Value::Object(fields));
d.contents = Some(contents);
Ok(d)
}
/// Where the document a Diagonal Lines dialog opened in is now.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DiagonalLinesDocument {
/// Active and unchanged since the dialog opened.
Ready,
/// Open, but another document is active.
Inactive,
/// Active, but edited since the dialog opened: the saved cell range may name other cells.
Changed,
/// Closed or reverted.
Gone,
}
/// An edit gives the document new contents, and a selection change keeps them. The dialog holds
/// the contents it opened with, so no new contents can take their address while it is open.
fn diagonal_lines_document(app: &DesignApp, d: &Dialog) -> DiagonalLinesDocument {
let saved = d.fields.get("document");
let get = |k: &str| saved.and_then(|s| s.get(k)).and_then(Value::as_u64);
let (Some(uid), Some(epoch), Some(contents)) = (get("uid"), get("epoch"), d.contents.as_ref()) else {
return DiagonalLinesDocument::Gone;
};
let Some(i) = app.session.documents().iter().position(|st| st.uid == uid && st.identity_epoch == epoch) else {
return DiagonalLinesDocument::Gone;
};
if app.session.active_index() != Some(i) {
DiagonalLinesDocument::Inactive
} else if !std::sync::Arc::ptr_eq(&app.session.documents()[i].doc, contents) {
DiagonalLinesDocument::Changed
} else {
DiagonalLinesDocument::Ready
}
}
/// Cell Options › Diagonal Lines: the four line buttons, the Line Stroke fields and Draw.
fn diagonal_lines(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
let lang = app.ui.language.clone();
let t = crate::theme::Tokens::get(ui.ctx());
ui.horizontal(|ui| {
for (name, label) in DIAGONAL_LINES {
let on = d.fields.get("lines").and_then(Value::as_str) == Some(name);
let text = crate::i18n::tr(&lang, label).to_string();
let (r, resp) = ui.allocate_exact_size(egui::vec2(32.0, 32.0), egui::Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, &text));
let resp = resp.on_hover_text(&text);
if resp.clicked() {
d.fields.insert("lines".into(), json!(name));
}
// Enter on a focused line button picks that line and leaves the dialog open.
if resp.has_focus() {
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
let p = ui.painter();
p.rect_filled(r, 2.0, if resp.hovered() { t.hover } else { t.input });
let cell = r.shrink(7.0);
p.rect_stroke(cell, 0.0, egui::Stroke::new(1.0, t.text_dim), egui::StrokeKind::Inside);
let ink = egui::Stroke::new(1.5, if on { t.accent } else { t.icon });
if matches!(name, "topLeft" | "crossed") {
p.line_segment([cell.left_top(), cell.right_bottom()], ink);
}
if matches!(name, "topRight" | "crossed") {
p.line_segment([cell.right_top(), cell.left_bottom()], ink);
}
let rim = if on { egui::Stroke::new(2.0, t.accent) } else { egui::Stroke::new(1.0, t.field_border) };
p.rect_stroke(r, 2.0, rim, egui::StrokeKind::Inside);
}
});
ui.add_space(10.0);
crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Line Stroke")).font(semibold(12.0)));
let values = Value::Object(d.fields.clone());
if let Some((k, v)) = crate::panels::cell_stroke::stroke_fields(app, ui, "diagonal_lines", &values) {
d.fields.insert(k.into(), v);
}
ui.add_space(10.0);
egui::Grid::new("diagonal_draw").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
crate::rtl::label(ui, crate::i18n::tr(&lang, "Draw:"));
let shown = match d.fields.get("inFront").and_then(Value::as_bool) {
Some(true) => crate::i18n::tr(&lang, "Diagonal In Front"),
Some(false) => crate::i18n::tr(&lang, "Content In Front"),
None => "",
}
.to_string();
craft_ui::ComboBox::from_id_salt("diagonal_draw_order").selected_text(crate::rtl::widget(ui, &shown)).width(140.0).show_ui(ui, |ui| {
for (front, label) in [(true, "Diagonal In Front"), (false, "Content In Front")] {
let text = crate::i18n::tr(&lang, label);
if ui.selectable_label(shown == text, crate::rtl::widget(ui, text)).clicked() {
d.fields.insert("inFront".into(), json!(front));
}
}
});
ui.end_row();
});
}
/// Apply the Diagonal Lines fields that differ from the cells' values, as one `table.setCell`
/// on the cells the dialog opened for, in the document it opened in.
fn confirm_diagonal_lines(app: &mut DesignApp, d: &Dialog) -> Result<Value, String> {
match diagonal_lines_document(app, d) {
DiagonalLinesDocument::Ready => {}
DiagonalLinesDocument::Inactive => return Err("Diagonal Lines: the document the dialog opened in is not the active document".into()),
DiagonalLinesDocument::Changed => return Err("Diagonal Lines: the document changed while the dialog was open".into()),
DiagonalLinesDocument::Gone => return Err("Diagonal Lines: the document the dialog opened in was closed or reverted".into()),
}
let Some(Value::Object(cells)) = d.fields.get("cells") else {
return Err("Diagonal Lines: the dialog has no target cells".into());
};
let seed = d.fields.get("seed").cloned().unwrap_or(Value::Null);
let mut diagonal = Map::new();
for k in DIAGONAL_KEYS {
if let Some(v) = d.fields.get(k).filter(|v| !v.is_null() && !same_cell_value(seed.get(k), k, v)) {
diagonal.insert(k.into(), v.clone());
}
}
if diagonal.is_empty() {
return Ok(Value::Null);
}
let mut params = cells.clone();
params.insert("diagonal".into(), Value::Object(diagonal));
app.run("table.setCell", Value::Object(params))
}
/// Delete absolute pages `pages` as the Pages panel and Layout › Pages › Delete Page do: when
/// they hold objects, InDesign's warning asks first, unless it was told not to.
pub fn delete_pages(app: &mut DesignApp, pages: Vec<usize>) -> Result<Value, String> {
@@ -4578,6 +4753,7 @@ fn format_settings(app: &mut DesignApp, ctx: &egui::Context, d: &mut Dialog) {
fields: d.fields.get(FORMAT_EDIT).and_then(Value::as_object).cloned().unwrap_or_default(),
unit: d.unit,
vertical_unit: None,
contents: None,
};
let base = json!({});
let cf = CharFields { base: &base, sparse: true };
@@ -4865,6 +5041,18 @@ fn confirm_part1(app: &mut DesignApp, d: Dialog) -> Result<Value, String> {
}
r
}
"diagonalLines" => {
// On an error the dialog stays open to be corrected, unless the document it opened
// in was closed, reverted or edited.
let r = confirm_diagonal_lines(app, &d);
if let Err(e) = &r {
app.status(e.clone());
if matches!(diagonal_lines_document(app, &d), DiagonalLinesDocument::Ready | DiagonalLinesDocument::Inactive) {
app.ui.dialog = Some(d);
}
}
r
}
"textFrameOptions" => {
// On an error the dialog stays open to be corrected.
let mut d = d;
@@ -7693,16 +7881,21 @@ fn char_number(ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, su
fn char_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, key: &str, opts: &[(Value, &str)]) {
let cur = cf.get(d, key);
let shown = opts.iter().find(|o| o.0 == cur).map_or("", |o| crate::i18n::tr(lang, o.1));
craft_ui::ComboBox::from_id_salt(("cs", key)).selected_text(crate::rtl::widget(ui, shown)).width(140.0).show_ui(ui, |ui| {
if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {
cf.set(d, key, Value::Null);
}
for (v, label) in opts {
if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
cf.set(d, key, v.clone());
craft_ui::ComboBox::from_id_salt(("cs", key))
.selected_text(crate::rtl::widget(ui, shown))
.width(140.0)
.show_ui(ui, |ui| {
if cf.sparse && ui.selectable_label(cur.is_null(), " ").clicked() {
cf.set(d, key, Value::Null);
}
}
});
for (v, label) in opts {
if ui.selectable_label(*v == cur, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
cf.set(d, key, v.clone());
}
}
})
.response
.accessible_name(setting_label(lang, key));
}
/// An on/off attribute; for a character style a third, mixed state leaves it unset (clicks go
@@ -7729,6 +7922,42 @@ fn char_swatch(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields, d
char_choice(lang, ui, d, cf, key, &opts);
}
/// Load styles once per popup opening, including when the selected family is missing.
fn font_style_combo(
ui: &mut egui::Ui,
fonts: &designcraft_fonts::ScopedFonts<'_>,
scope: u32,
family: &str,
style: &str,
d: &mut Dialog,
cf: &CharFields,
) -> egui::Response {
let key = ui.make_persistent_id(("pssty_styles", scope));
let frame = ui.ctx().cumulative_frame_nr();
let shown = craft_ui::ComboBox::from_id_salt("pssty").selected_text(style).width(200.0).show_ui(ui, |ui| {
let cached = ui.data(|data| data.get_temp::<(String, u64, Vec<String>)>(key));
let styles = if let Some((_, _, styles)) = cached.filter(|(f, last, _)| f == family && last.saturating_add(1) >= frame) {
styles
} else {
let _ = fonts.face(family, style);
fonts.styles(family)
};
ui.data_mut(|data| data.insert_temp(key, (family.to_string(), frame, styles.clone())));
if cf.sparse && ui.selectable_label(style.is_empty(), " ").clicked() {
cf.set(d, "fontStyle", Value::Null);
}
for s in styles {
if ui.selectable_label(s == style, &s).clicked() {
cf.set(d, "fontStyle", json!(s));
}
}
});
if shown.inner.is_none() {
ui.data_mut(|data| data.remove::<(String, u64, Vec<String>)>(key));
}
shown.response
}
/// Basic Character Formats: font, size, leading, kerning, tracking, case, position and the
/// underline, strikethrough, ligatures and no-break switches.
fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog, cf: &CharFields) {
@@ -7738,7 +7967,7 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo
let menu = crate::panels::font_menu(app);
// Two columns, as InDesign's: the font, then Size | Leading, Kerning | Tracking, Case | Position.
egui::Grid::new("psc").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
let name = crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
let fam = cf.get(d, "fontFamily").as_str().unwrap_or("").to_string();
let shown = if fam.is_empty() { "—".to_string() } else { crate::panels::font_label(app, &menu, &fam) };
let picked = craft_ui::ComboBox::from_id_salt("psfam")
@@ -7755,35 +7984,25 @@ fn basic_character_formats(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialo
crate::panels::font_menu_header(app, ui, &menu, &fam, 200.0)
},
crate::panels::font_menu_list,
)
.inner
.flatten();
if let Some(f) = picked {
);
picked.response.labelled_by(name.id);
if let Some(f) = picked.inner.flatten() {
cf.set(d, "fontFamily", json!(f.family));
if let Some(style) = f.style {
cf.set(d, "fontStyle", json!(style));
}
}
ui.end_row();
crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
let name = crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
let sty = cf.get(d, "fontStyle").as_str().unwrap_or("").to_string();
if cf.sparse && fam.is_empty() {
// No family to list styles of: type the style ("Italic" in whatever font the text has).
let mut s = sty.clone();
if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).changed() {
if ui.add(egui::TextEdit::singleline(&mut s).desired_width(200.0)).labelled_by(name.id).changed() {
cf.set(d, "fontStyle", if s.trim().is_empty() { Value::Null } else { json!(s) });
}
} else {
craft_ui::ComboBox::from_id_salt("pssty").selected_text(&sty).width(200.0).show_ui(ui, |ui| {
if cf.sparse && ui.selectable_label(sty.is_empty(), " ").clicked() {
cf.set(d, "fontStyle", Value::Null);
}
for s in fonts.styles(&fam) {
if ui.selectable_label(s == sty, &s).clicked() {
cf.set(d, "fontStyle", json!(s));
}
}
});
font_style_combo(ui, &fonts, crate::panels::font_scope(app), &fam, &sty, d, cf).labelled_by(name.id);
}
ui.end_row();
});
@@ -10317,3 +10536,246 @@ fn picker_field(ui: &mut egui::Ui, d: &mut Dialog, r: egui::Rect, key: &str, nam
d.fields.insert(edit_key, json!(text));
out
}
#[cfg(test)]
mod variable_style_regression {
use super::*;
#[test]
#[ignore = "requires the pinned Bricolage fixture; see docs/testing-variable-fonts.md"]
fn named_instance_style_widget_and_api_agree() {
use egui_kittest::{Harness, kittest::Queryable};
let path = std::env::var_os("DESIGNCRAFT_TEST_VARIABLE_FONT").expect("set DESIGNCRAFT_TEST_VARIABLE_FONT");
let db = designcraft_fonts::FontDb::global();
db.add_font(std::fs::read(path).unwrap());
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("style.paragraph.create", json!({"name":"Base VF", "chars":{"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"}})).unwrap();
app.run("style.paragraph.create", json!({"name":"UI VF", "basedOn":"Base VF"})).unwrap();
app.run("style.paragraph.create", json!({"name":"API VF", "basedOn":"Base VF"})).unwrap();
let base = json!({"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"});
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.with_size(egui::vec2(1000.0, 800.0))
.build_ui_state(
move |ui, state: &mut (DesignApp, Dialog)| {
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
},
(app, Dialog::new("paragraphStyleOptions", json!({"name":"UI VF"}))),
);
h.run_steps(3);
{
let (app, d) = h.state_mut();
let before = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
d.fields.insert("preview".into(), json!(true));
d.fields.insert("c.fontStyle".into(), json!("SemiBold"));
style_options_preview(app, d);
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, "SemiBold");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
d.fields.insert("preview".into(), json!(false));
style_options_preview(app, d);
assert_eq!(app.session.doc().unwrap().doc, before);
d.fields.insert("preview".into(), json!(true));
style_options_preview(app, d);
app.ui.dialog = Some(d.clone());
cancel(app);
assert_eq!(app.session.doc().unwrap().doc, before);
d.fields.remove(PREVIEWED);
d.fields.insert("preview".into(), json!(true));
style_options_preview(app, d);
app.ui.dialog = Some(d.clone());
confirm(app).unwrap();
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, before);
app.run("edit.redo", json!({})).unwrap();
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, "SemiBold");
app.run("edit.undo", json!({})).unwrap();
d.fields.remove(PREVIEWED);
d.fields.remove("c.fontStyle");
d.fields.insert("preview".into(), json!(false));
}
h.run_steps(3);
let mut current = "Regular";
for selected in ["SemiBold", "Bold", "Regular"] {
h.get_by_value(current).click();
h.run_steps(3);
h.get_by_label(selected).click();
h.run_steps(3);
let (app, d) = h.state_mut();
assert_eq!(d.fields["c.fontStyle"], selected);
assert!(!d.fields.contains_key("c.fontFamily"), "inherited family remains inherited");
confirm_paragraph_style_options(app, d).unwrap();
app.run("style.paragraph.edit", json!({"name":"API VF","chars":{"fontStyle":selected}})).unwrap();
let styles = &app.session.doc().unwrap().doc.styles;
assert_eq!(styles.para("UI VF").unwrap().chars, styles.para("API VF").unwrap().chars);
assert_eq!(styles.resolve_para_style("UI VF").1.font_style, selected);
assert_eq!(styles.para("UI VF").unwrap().based_on.as_deref(), Some("Base VF"));
current = selected;
let native = app.run("file.serialize", json!({})).unwrap();
app.run("file.openBytes", json!({"name":"vf.designcraft","base64":native["base64"]})).unwrap();
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("UI VF").1.font_style, selected);
}
}
}
#[cfg(test)]
mod variable_cold_style_regression {
use super::*;
#[test]
#[ignore = "requires a fresh process with the pinned Bricolage fixture catalogued; see docs/testing-variable-fonts.md"]
fn cold_style_combo_contains_named_instances() {
use egui_kittest::{Harness, kittest::Queryable};
let fonts = designcraft_fonts::FontDb::global();
assert!(
!fonts.styles("Bricolage Grotesque").contains(&"SemiBold".into()),
"run in a fresh process with the test font catalogued but not loaded"
);
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
let base = json!({"fontFamily":"Bricolage Grotesque", "fontStyle":"Regular"});
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.with_size(egui::vec2(1000.0, 800.0))
.build_ui_state(
move |ui, state: &mut (DesignApp, Dialog)| {
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
},
(app, Dialog::new("paragraphStyleOptions", json!({}))),
);
h.run_steps(3);
h.get_by_value("Regular").click();
h.run_steps(3);
assert!(h.query_by_label("SemiBold").is_some(), "the cold Style combo must offer named instances");
h.get_by_label("SemiBold").click();
h.run_steps(3);
assert_eq!(h.state().1.fields["c.fontStyle"], "SemiBold");
}
}
#[cfg(test)]
mod synthetic_variable_style_regression {
use super::*;
use egui_kittest::{Harness, kittest::Queryable};
#[test]
fn paragraph_style_formats_select_a_synthetic_named_instance() {
let family = "Synthetic Paragraph Wiring";
designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::variable_font(family).unwrap());
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("style.paragraph.create", json!({"name":"Synthetic UI", "chars":{"fontFamily":family,"fontStyle":"Regular"}})).unwrap();
let base = json!({"fontFamily":family,"fontStyle":"Regular"});
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.with_size(egui::vec2(1000.0, 800.0))
.build_ui_state(
|ui, state: &mut (DesignApp, Dialog)| {
basic_character_formats(&mut state.0, ui, &mut state.1, &CharFields { base: &base, sparse: false });
},
(app, Dialog::new("paragraphStyleOptions", json!({"name":"Synthetic UI"}))),
);
h.run_steps(3);
h.get_by_value("Regular").click();
h.run_steps(3);
h.get_by_label("SemiBold").click();
h.run_steps(3);
let (app, d) = h.state_mut();
confirm_paragraph_style_options(app, d).unwrap();
assert_eq!(app.session.doc().unwrap().doc.styles.resolve_para_style("Synthetic UI").1.font_style, "SemiBold");
}
#[test]
fn cold_style_popup_discovers_instances_and_selects_them() {
let dir = tempfile::tempdir().unwrap();
let family = "Synthetic Cold Style";
std::fs::write(dir.path().join("variable.ttf"), designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
assert_eq!(db.styles(family), ["Regular"]);
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.build_ui_state(
|ui, d: &mut Dialog| {
let style = d.fields.get("c.fontStyle").and_then(Value::as_str).unwrap_or("Regular").to_string();
font_style_combo(ui, &db.scoped(0), 0, family, &style, d, &CharFields { base: &Value::Null, sparse: false })
.accessible_name("Font Style".to_owned());
},
Dialog::new("paragraphStyleOptions", json!({})),
);
h.run_steps(3);
assert_eq!(db.styles(family), ["Regular"], "closed popup must not preload the font");
h.get_by_value("Regular").click();
h.run_steps(3);
assert_eq!(db.styles(family), ["Regular", "SemiBold"]);
h.get_by_label("SemiBold").click();
h.run_steps(3);
assert_eq!(h.state().fields["c.fontStyle"], "SemiBold");
}
#[test]
fn missing_family_styles_are_cached_until_the_popup_reopens() {
for retry in ["reopen", "hidden", "scope"] {
let dir = tempfile::tempdir().unwrap();
let family = "Synthetic Missing Style";
let path = dir.path().join("variable.ttf");
std::fs::write(&path, designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
assert_eq!(db.styles(family), ["Regular"]);
std::fs::remove_file(&path).unwrap();
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.build_ui_state(
|ui, state: &mut (Dialog, bool, u32)| {
if state.1 {
font_style_combo(
ui,
&db.scoped(state.2),
state.2,
family,
"Regular",
&mut state.0,
&CharFields { base: &Value::Null, sparse: false },
)
.accessible_name("Font Style".to_owned());
}
},
(Dialog::new("paragraphStyleOptions", json!({})), true, 0),
);
h.run_steps(3);
h.get_by_value("Regular").click();
h.run_steps(3);
assert!(h.query_by_label("SemiBold").is_none());
std::fs::write(&path, designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
h.run_steps(3);
assert_eq!(db.styles(family), ["Regular"], "an open popup must not retry the missing font every frame");
match retry {
"hidden" => {
h.state_mut().1 = false;
h.run_steps(3);
h.state_mut().1 = true;
}
"scope" => h.state_mut().2 = 1,
_ => {
egui::Popup::close_all(&h.ctx);
h.run_steps(3);
h.get_by_value("Regular").click();
}
}
h.run_steps(3);
if h.query_by_label("SemiBold").is_none() {
h.get_by_value("Regular").click();
h.run_steps(3);
}
assert!(h.query_by_label("SemiBold").is_some(), "{retry} retries the now-readable font");
}
}
}
+256
View File
@@ -413,6 +413,46 @@ fn cell_options_dialog_draws_and_applies_only_changed_values_to_the_chosen_edges
assert!(t.cells.iter().all(|c| c.strokes.iter().all(|e| e.weight == 1.0)), "unchanged values are not applied");
}
#[test]
fn cell_options_ok_edits_nothing_when_the_picked_stroke_type_is_the_cells() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
app.run("table.select", json!({"what": "table"})).unwrap();
app.run("app.cellOptionsDialog", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
// The Type list picks a stroke type by name.
d.fields.insert("type".into(), json!("solid"));
let (undo, revision) = {
let st = app.session.active().unwrap();
(st.history.undo.len(), st.revision)
};
confirm(&mut app).unwrap();
let st = app.session.active().unwrap();
assert_eq!((st.history.undo.len(), st.revision), (undo, revision), "no edit and no undo step");
}
#[test]
fn cell_options_edge_change_reseeds_a_picked_stroke_type_that_was_the_cells() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
app.run("table.select", json!({"what": "table"})).unwrap();
app.run("table.setCell", json!({"stroke": {"type": "dotted", "edges": "innerHorizontal"}})).unwrap();
app.run("app.cellOptionsDialog", json!({})).unwrap();
let mut d = app.ui.dialog.take().unwrap();
cell_options_edges_changed(&mut app, &mut d, &[true, true, true, true, false, false]);
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
// Solid picked by name for the outer edges is what they show; the inner horizontal edges
// chosen next show their own type.
d.fields.insert("type".into(), json!("solid"));
cell_options_edges_changed(&mut app, &mut d, &[false, false, false, false, true, false]);
assert_eq!(d.fields["type"], json!({"kind": "dotted"}));
}
#[test]
fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
@@ -440,6 +480,222 @@ fn cell_options_edge_changes_reseed_every_stroke_field_and_survive_a_bad_seed()
assert_eq!([t.cell(0, 0).unwrap().strokes[2].weight, t.cell(1, 1).unwrap().strokes[0].weight], [1.0; 2]);
}
#[test]
fn diagonal_lines_dialog_draws_and_applies_its_values_but_not_a_mixed_one() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
app.run("table.setCell", json!({"row": 0, "col": 0, "diagonal": {"color": "[Paper]"}})).unwrap();
app.run("table.select", json!({"what": "table"})).unwrap();
app.run("app.diagonalLinesDialog", json!({})).unwrap();
let ctx = dialog_context("");
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0));
// The first frame sizes the window without painting it.
dialog_frame(&mut app, &ctx, screen, vec![]);
let labels = dialog_frame(&mut app, &ctx, screen, vec![]);
for shown in ["Line Stroke", "Weight:", "Draw:", "Diagonal In Front"] {
visible_label(&labels, screen, shown);
}
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!(d.id, "diagonalLines");
assert_eq!((&d.fields["lines"], &d.fields["color"], &d.fields["inFront"]), (&json!("none"), &Value::Null, &json!(true)));
// The fourth line button, in the row above Line Stroke, is Crossed Diagonal Lines.
let caption = visible_label(&labels, screen, "Line Stroke");
let gap = ctx.global_style().spacing.item_spacing;
let crossed = egui::pos2(caption.left() + 3.0 * (32.0 + gap.x) + 16.0, caption.top() - 10.0 - gap.y - 16.0);
click_dialog(&mut app, &ctx, screen, crossed);
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["lines"], json!("crossed"));
d.fields.insert("inFront".into(), json!(false));
d.fields.insert("weight".into(), json!(0.5));
confirm(&mut app).unwrap();
let st = app.session.active().unwrap();
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
assert!(
t.cells
.iter()
.all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::Crossed && !c.diagonal.in_front && c.diagonal.stroke.weight == 0.5)
);
let colors: Vec<_> = t.cells.iter().map(|c| c.diagonal.stroke.color.as_str()).collect();
assert_eq!(colors, ["[Paper]", "[Black]", "[Black]", "[Black]"], "a mixed value is left as it is");
}
#[test]
fn cell_options_menu_items_need_a_table_target() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
let items = ["app.cellOptionsDialog", "app.diagonalLinesDialog"];
for id in items {
assert!(!crate::menus::menu_enabled(&app, id), "{id} without a table");
}
app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap();
for id in items {
assert!(crate::menus::menu_enabled(&app, id), "{id} in a table");
}
}
#[test]
fn enter_on_a_diagonal_line_button_picks_it_and_leaves_the_dialog_open() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
app.run("table.select", json!({"what": "table"})).unwrap();
app.run("app.diagonalLinesDialog", json!({})).unwrap();
let ctx = dialog_context("");
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0));
dialog_frame(&mut app, &ctx, screen, vec![]);
dialog_frame(&mut app, &ctx, screen, vec![]);
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
// Tab past the title bar and the first line button to Diagonal Line from Top Left to Bottom
// Right, then press Enter.
for _ in 0..3 {
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Tab)]);
dialog_frame(&mut app, &ctx, screen, vec![]);
}
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Enter)]);
dialog_frame(&mut app, &ctx, screen, vec![]);
let d = app.ui.dialog.as_ref().expect("Enter on a line button leaves the dialog open");
assert_eq!(d.fields["lines"], json!("topLeft"));
let st = app.session.active().unwrap();
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
assert!(t.cells.iter().all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::None), "nothing is applied yet");
// Enter with no line button focused still confirms.
ctx.memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
dialog_frame(&mut app, &ctx, screen, vec![key(egui::Key::Enter)]);
assert!(app.ui.dialog.is_none());
let st = app.session.active().unwrap();
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
assert!(t.cells.iter().all(|c| c.diagonal.lines == designcraft_doc::DiagonalLines::TopLeft));
}
/// A document holding a 2×2 table with cell (0, 0) selected; returns the table id.
fn table_document_for_diagonals(app: &mut DesignApp) -> u64 {
app.run("file.new", json!({})).unwrap();
app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();
let tid = app.run("table.insert", json!({"rows": 2, "cols": 2})).unwrap()["table"].as_u64().unwrap();
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
tid
}
/// The diagonal lines of the cells of table `tid` in document `doc`, row by row.
fn diagonal_lines_of(app: &DesignApp, doc: usize, tid: u64) -> Vec<designcraft_doc::DiagonalLines> {
let st = &app.session.documents()[doc];
let t = st.doc.stories.values().find_map(|s| s.tables.get(&tid)).unwrap();
t.cells.iter().map(|c| c.diagonal.lines).collect()
}
#[test]
fn diagonal_lines_dialog_applies_to_the_cells_and_document_it_opened_for() {
use designcraft_doc::DiagonalLines::{Crossed, None as No, TopRight};
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let a = table_document_for_diagonals(&mut app);
// The selection moves to another cell while the dialog is open: OK still edits cell (0, 0).
app.run("app.diagonalLinesDialog", json!({})).unwrap();
app.run("table.select", json!({"rows": [1, 1], "cols": [1, 1]})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(diagonal_lines_of(&app, 0, a), [Crossed, No, No, No]);
// Another document with a table selection becomes active: OK is refused and changes neither
// document, and the dialog stays open.
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
app.run("app.diagonalLinesDialog", json!({})).unwrap();
let b = table_document_for_diagonals(&mut app);
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("topRight"));
assert!(confirm(&mut app).is_err());
assert!(app.ui.dialog.is_some(), "the dialog stays open while its document is open");
assert_eq!(diagonal_lines_of(&app, 1, b), [No; 4]);
assert_eq!(diagonal_lines_of(&app, 0, a), [Crossed, No, No, No]);
// Back in the first document, OK applies there.
app.run("file.activate", json!({"index": 0})).unwrap();
confirm(&mut app).unwrap();
assert_eq!(diagonal_lines_of(&app, 0, a), [TopRight, No, No, No]);
// A row is added above the target cell while the dialog is open: the document changed and the
// saved range would name another cell, so OK is refused, nothing changes and the dialog closes.
app.run("app.diagonalLinesDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
app.run("table.insertRowAbove", json!({})).unwrap();
assert!(confirm(&mut app).is_err());
assert!(app.ui.dialog.is_none(), "a dialog whose table changed closes");
// The new row takes the formatting of the row below it.
assert_eq!(diagonal_lines_of(&app, 0, a), [TopRight, No, TopRight, No, No, No]);
// The first document is closed while the dialog is open: OK is refused and the dialog closes.
app.run("app.diagonalLinesDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
app.run("file.close", json!({"index": 0})).unwrap();
assert!(confirm(&mut app).is_err());
assert!(app.ui.dialog.is_none(), "a dialog whose document was closed closes");
assert_eq!(diagonal_lines_of(&app, 0, b), [No; 4]);
}
#[test]
fn diagonal_lines_dialog_is_refused_when_new_contents_reuse_the_old_address() {
use designcraft_doc::DiagonalLines::None as No;
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let tid = table_document_for_diagonals(&mut app);
app.run("app.diagonalLinesDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
// A row is added above the target cell, and the edit is undone: the contents the dialog
// opened with are back, and the undo stack no longer holds them.
app.run("table.insertRowAbove", json!({})).unwrap();
let edited = (*app.session.active().unwrap().doc).clone();
app.session.execute("edit.undo", &json!({})).unwrap();
// The edited contents are written in place when nothing else holds the old contents, at the
// address an allocation that reuses freed memory would give them. The saved cell range now
// names the new row.
let st = app.session.active_mut().unwrap();
*std::sync::Arc::make_mut(&mut st.doc) = edited;
assert!(confirm(&mut app).is_err());
assert!(app.ui.dialog.is_none(), "a dialog whose table changed closes");
assert_eq!(diagonal_lines_of(&app, 0, tid), [No; 6]);
}
#[test]
fn diagonal_lines_dialog_ok_edits_nothing_when_the_picked_stroke_type_is_the_cells() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
table_document_for_diagonals(&mut app);
app.run("app.diagonalLinesDialog", json!({})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["seed"]["type"], json!({"kind": "solid"}));
// The Type list picks a stroke type by name.
d.fields.insert("type".into(), json!("solid"));
let (undo, revision) = {
let st = app.session.active().unwrap();
(st.history.undo.len(), st.revision)
};
confirm(&mut app).unwrap();
let st = app.session.active().unwrap();
assert_eq!((st.history.undo.len(), st.revision), (undo, revision), "no edit and no undo step");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn diagonal_lines_dialog_is_refused_after_its_document_is_reverted() {
use designcraft_doc::DiagonalLines::None as No;
let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let tid = table_document_for_diagonals(&mut app);
let dir = tempfile::tempdir().unwrap();
app.run("file.saveAs", json!({"path": dir.path().join("diagonal.designcraft")})).unwrap();
app.run("table.setCell", json!({"row": 1, "col": 1, "text": "unsaved"})).unwrap();
app.run("app.diagonalLinesDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("lines".into(), json!("crossed"));
app.session.execute("file.revert", &json!({})).unwrap();
// The reverted document holds the same table; a selection in it does not let OK through.
let story = app.session.active().unwrap().doc.stories.iter().find(|(_, s)| s.tables.contains_key(&tid)).map(|(k, _)| k.0).unwrap();
app.run("text.select", json!({"story": story, "anchor": 0, "focus": 0})).unwrap();
app.run("table.select", json!({"rows": [0, 0], "cols": [0, 0]})).unwrap();
assert!(confirm(&mut app).is_err());
assert!(app.ui.dialog.is_none(), "a dialog whose document was reverted closes");
assert_eq!(diagonal_lines_of(&app, 0, tid), [No; 4]);
}
#[test]
fn preferences_ok_saves_a_story_editor_size_that_loads_back() {
// `ui.dialog.set` takes any value; a size that isn't finite is saved as `null`.
+10
View File
@@ -1687,6 +1687,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "إظهار/إخفاء اللوحات"),
("Show/Hide Panels Except Tools", "إظهار/إخفاء اللوحات باستثناء الأدوات"),
("Show/Hide Rulers", "إظهار/إخفاء المساطر"),
("Show/Hide Style Name Column", "إظهار/إخفاء عمود أسماء الأنماط"),
("Show/Hide Tagged Frames", "إظهار/إخفاء الإطارات الموسومة"),
("Show/Hide Text Threads", "إظهار/إخفاء روابط الإطارات النصية"),
("Smooth", "تنعيم"),
@@ -1948,6 +1949,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Continue from Previous Number", "المتابعة من الرقم السابق"),
("Start At", "البدء عند"),
("Strokes and Fills…", "الحدود والتعبئة…"),
("Diagonal Lines…", "الخطوط القطرية…"),
("No Diagonal Lines", "بلا خطوط قطرية"),
("Diagonal Line from Top Left to Bottom Right", "خط قطري من أعلى اليسار إلى أسفل اليمين"),
("Diagonal Line from Top Right to Bottom Left", "خط قطري من أعلى اليمين إلى أسفل اليسار"),
("Crossed Diagonal Lines", "خطوط قطرية متقاطعة"),
("Line Stroke", "حد الخط"),
("Draw:", "الرسم:"),
("Diagonal In Front", "القطري في الأمام"),
("Content In Front", "المحتوى في الأمام"),
("Cell Stroke", "حد الخلية"),
("Cell Fill", "تعبئة الخلية"),
("Cell edges", "حواف الخلية"),
+1
View File
@@ -837,6 +837,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Zobrazit/skrýt panely"),
("Show/Hide Panels Except Tools", "Zobrazit/skrýt panely kromě nástrojů"),
("Show/Hide Rulers", "Zobrazit/skrýt pravítka"),
("Show/Hide Style Name Column", "Zobrazit/skrýt sloupec názvů stylů"),
("Show/Hide Tagged Frames", "Zobrazit/skrýt otagované rámečky"),
("Show/Hide Text Threads", "Zobrazit/skrýt zřetězení textu"),
("Smooth", "Vyhladit"),
+10
View File
@@ -784,6 +784,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Bedienfelder ein-/ausblenden"),
("Show/Hide Panels Except Tools", "Bedienfelder außer Werkzeugen ein-/ausblenden"),
("Show/Hide Rulers", "Lineale ein-/ausblenden"),
("Show/Hide Style Name Column", "Spalte mit Formatnamen ein-/ausblenden"),
("Show/Hide Tagged Frames", "Getaggte Rahmen ein-/ausblenden"),
("Show/Hide Text Threads", "Textverkettungen ein-/ausblenden"),
("Smooth", "Glätten"),
@@ -1962,6 +1963,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Fancy", "Verziert"),
("Gap Tint:", "Lückenfarbton:"),
("Strokes and Fills…", "Konturen und Flächen …"),
("Diagonal Lines…", "Diagonale Linien …"),
("No Diagonal Lines", "Keine diagonalen Linien"),
("Diagonal Line from Top Left to Bottom Right", "Diagonale Linie von links oben nach rechts unten"),
("Diagonal Line from Top Right to Bottom Left", "Diagonale Linie von rechts oben nach links unten"),
("Crossed Diagonal Lines", "Gekreuzte diagonale Linien"),
("Line Stroke", "Linienkontur"),
("Draw:", "Zeichnen:"),
("Diagonal In Front", "Diagonale im Vordergrund"),
("Content In Front", "Inhalt im Vordergrund"),
("Cell Stroke", "Zellkontur"),
("Cell Fill", "Zellfläche"),
("Cell edges", "Zellkanten"),
+1
View File
@@ -142,6 +142,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Generate Index", "Générer l'index"),
("Generate Live Caption", "Générer une légende dynamique"),
("Get Cell Stroke", "Obtenir le contour de cellule"),
("Get Cell Diagonal Lines", "Obtenir les lignes diagonales de cellule"),
("Get Tabs", "Obtenir les tabulations"),
("Global Light", "Lumière globale"),
("Grab bag", "Liste"),
+1
View File
@@ -1528,6 +1528,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Panelek megjelenítése/elrejtése"),
("Show/Hide Panels Except Tools", "Panelek megjelenítése/elrejtése az eszközök kivételével"),
("Show/Hide Rulers", "Vonalzók megjelenítése/elrejtése"),
("Show/Hide Style Name Column", "Stílusnevek oszlopának megjelenítése/elrejtése"),
("Show/Hide Tagged Frames", "Címkézett keretek megjelenítése/elrejtése"),
("Show/Hide Text Threads", "Szövegláncok megjelenítése/elrejtése"),
("Signature", "Aláírás"),
+10
View File
@@ -969,6 +969,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Mostra/nascondi pannelli"),
("Show/Hide Panels Except Tools", "Mostra/nascondi pannelli tranne Strumenti"),
("Show/Hide Rulers", "Mostra/nascondi righelli"),
("Show/Hide Style Name Column", "Mostra/nascondi colonna nomi stili"),
("Show/Hide Tagged Frames", "Mostra/nascondi cornici con tag"),
("Show/Hide Text Threads", "Mostra/nascondi concatenamenti testo"),
("Smooth", "Arrotonda"),
@@ -2008,6 +2009,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Continue from Previous Number", "Continua dal numero precedente"),
("Start At", "Inizia da"),
("Strokes and Fills…", "Tracce e riempimenti…"),
("Diagonal Lines…", "Linee diagonali…"),
("No Diagonal Lines", "Nessuna linea diagonale"),
("Diagonal Line from Top Left to Bottom Right", "Linea diagonale dall'angolo superiore sinistro a quello inferiore destro"),
("Diagonal Line from Top Right to Bottom Left", "Linea diagonale dall'angolo superiore destro a quello inferiore sinistro"),
("Crossed Diagonal Lines", "Linee diagonali incrociate"),
("Line Stroke", "Traccia linea"),
("Draw:", "Disegna:"),
("Diagonal In Front", "Diagonale in primo piano"),
("Content In Front", "Contenuto in primo piano"),
("Cell Stroke", "Traccia cella"),
("Cell Fill", "Riempimento cella"),
("Cell edges", "Bordi cella"),
+10
View File
@@ -975,6 +975,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "パネルを表示・非表示"),
("Show/Hide Panels Except Tools", "ツール以外のパネルを表示・非表示"),
("Show/Hide Rulers", "定規を表示・非表示"),
("Show/Hide Style Name Column", "スタイル名の列を表示・非表示"),
("Show/Hide Tagged Frames", "タグ付きフレームを表示・非表示"),
("Show/Hide Text Threads", "テキストフレームの連結を表示・非表示"),
("Smooth", "平滑化"),
@@ -2171,6 +2172,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Bounding Box (Visible Layers Only)", "バウンディングボックス(表示レイヤーのみ)"),
("Bounding Box (All Layers)", "バウンディングボックス(すべてのレイヤー)"),
("Strokes and Fills…", "線と塗り…"),
("Diagonal Lines…", "斜線…"),
("No Diagonal Lines", "斜線なし"),
("Diagonal Line from Top Left to Bottom Right", "左上から右下への斜線"),
("Diagonal Line from Top Right to Bottom Left", "右上から左下への斜線"),
("Crossed Diagonal Lines", "交差する斜線"),
("Line Stroke", "斜線の線"),
("Draw:", "描画:"),
("Diagonal In Front", "斜線を前面へ"),
("Content In Front", "内容を前面へ"),
("Cell Stroke", "セルの線"),
("Cell Fill", "セルの塗り"),
("Cell edges", "セルの境界線"),
+2
View File
@@ -887,6 +887,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "პანელების ჩვენება/დამალვა"),
("Show/Hide Panels Except Tools", "პანელების ჩვენება/დამალვა, ხელსაწყოების გარდა"),
("Show/Hide Rulers", "სახაზავების ჩვენება/დამალვა"),
("Show/Hide Style Name Column", "სტილების სახელების სვეტის ჩვენება/დამალვა"),
("Show/Hide Tagged Frames", "ტეგირებული ჩარჩოების ჩვენება/დამალვა"),
("Show/Hide Text Threads", "ტექსტის კავშირების ჩვენება/დამალვა"),
("Smooth", "გლუვი"),
@@ -2066,6 +2067,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Clear Recent Files", "ბოლო ფაილების სიის გასუფთავება"),
("Transparency…", "გამჭვირვალობა…"),
("Strokes and Fills…", "კონტურები და შევსებები…"),
("Diagonal Lines…", "დიაგონალური ხაზები…"),
("Show/Hide Document Grid", "დოკუმენტის ბადის ჩვენება/დამალვა"),
("% of all commits", "ყველა კომიტის %"),
("(Paragraph Font)", "(აბზაცის შრიფტი)"),
+1
View File
@@ -847,6 +847,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Pokaż/ukryj panele"),
("Show/Hide Panels Except Tools", "Pokaż/ukryj panele oprócz narzędzi"),
("Show/Hide Rulers", "Pokaż/ukryj linijki"),
("Show/Hide Style Name Column", "Pokaż/ukryj kolumnę nazw stylów"),
("Show/Hide Tagged Frames", "Pokaż/ukryj ramki z tagami"),
("Show/Hide Text Threads", "Pokaż/ukryj powiązania tekstu"),
("Smooth", "Wygładź"),
+10
View File
@@ -1554,6 +1554,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Continue from Previous Number", "Continuar do número anterior"),
("Start At", "Iniciar em"),
("Strokes and Fills…", "Traçados e preenchimentos…"),
("Diagonal Lines…", "Linhas diagonais…"),
("No Diagonal Lines", "Sem linhas diagonais"),
("Diagonal Line from Top Left to Bottom Right", "Linha diagonal do canto superior esquerdo ao inferior direito"),
("Diagonal Line from Top Right to Bottom Left", "Linha diagonal do canto superior direito ao inferior esquerdo"),
("Crossed Diagonal Lines", "Linhas diagonais cruzadas"),
("Line Stroke", "Traçado da linha"),
("Draw:", "Desenhar:"),
("Diagonal In Front", "Diagonal à frente"),
("Content In Front", "Conteúdo à frente"),
("Cell Stroke", "Traçado da célula"),
("Cell Fill", "Preenchimento da célula"),
("Cell edges", "Bordas da célula"),
@@ -1841,6 +1850,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Mostrar/ocultar painéis"),
("Show/Hide Panels Except Tools", "Mostrar/ocultar painéis, exceto ferramentas"),
("Show/Hide Rulers", "Mostrar/ocultar réguas"),
("Show/Hide Style Name Column", "Mostrar/ocultar coluna de nomes de estilo"),
("Show/Hide Tagged Frames", "Mostrar/ocultar quadros marcados"),
("Show/Hide Text Threads", "Mostrar/ocultar encadeamentos de texto"),
("Sort", "Ordenar"),
+1
View File
@@ -827,6 +827,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Показать/скрыть панели"),
("Show/Hide Panels Except Tools", "Показать/скрыть панели, кроме инструментов"),
("Show/Hide Rulers", "Показать/скрыть линейки"),
("Show/Hide Style Name Column", "Показать/скрыть столбец имен стилей"),
("Show/Hide Tagged Frames", "Показать/скрыть рамки с тегами"),
("Show/Hide Text Threads", "Показать/скрыть связи текстовых рамок"),
("Smooth", "Сгладить"),
+10
View File
@@ -2050,6 +2050,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Fancy", "Dekorativ"),
("Gap Tint:", "Färgton för mellanrum:"),
("Strokes and Fills…", "Konturer och fyllningar…"),
("Diagonal Lines…", "Diagonala linjer…"),
("No Diagonal Lines", "Inga diagonala linjer"),
("Diagonal Line from Top Left to Bottom Right", "Diagonal linje från övre vänstra till nedre högra hörnet"),
("Diagonal Line from Top Right to Bottom Left", "Diagonal linje från övre högra till nedre vänstra hörnet"),
("Crossed Diagonal Lines", "Korsade diagonala linjer"),
("Line Stroke", "Linjekontur"),
("Draw:", "Rita:"),
("Diagonal In Front", "Diagonal i förgrunden"),
("Content In Front", "Innehåll i förgrunden"),
("Cell Stroke", "Cellkontur"),
("Cell Fill", "Cellfyllning"),
("Cell edges", "Cellkanter"),
@@ -2523,6 +2532,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Optical Margin Size", "Storlek för optisk marginal"),
("Dismiss", "Stäng"),
("Show/Hide Depth Ruler", "Visa/dölj djuplinjal"),
("Show/Hide Style Name Column", "Visa/dölj kolumnen med stilnamn"),
("Split Note", "Dela anteckning"),
("Arrangement", "Arrangemang"),
("All Inks", "Alla tryckfärger"),
+40
View File
@@ -2655,6 +2655,16 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[
],
),
("Show/Hide Rulers", ["Show/Hide Rulers", "Afficher/Masquer les règles", "Show/Hide Rulers", "Show/Hide Rulers", "显示/隐藏标尺"]),
(
"Show/Hide Style Name Column",
[
"Show/Hide Style Name Column",
"Afficher/Masquer la colonne des noms de style",
"Mostrar/ocultar columna de nombres de estilo",
"Show/Hide Style Name Column",
"显示/隐藏样式名称栏",
],
),
(
"Show/Hide Tagged Frames",
[
@@ -4843,6 +4853,36 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[
("Start At", ["Beginnen bei", "Commencer à", "Empezar en", "開始番号", "起始编号"]),
// Cell strokes.
("Strokes and Fills…", ["Konturen und Flächen …", "Contours et fonds…", "Trazos y rellenos…", "線と塗り…", "描边和填色…"]),
("Diagonal Lines…", ["Diagonale Linien …", "Lignes diagonales…", "Líneas diagonales…", "斜線…", "对角线…"]),
("No Diagonal Lines", ["Keine diagonalen Linien", "Aucune ligne diagonale", "Sin líneas diagonales", "斜線なし", "无对角线"]),
(
"Diagonal Line from Top Left to Bottom Right",
[
"Diagonale Linie von links oben nach rechts unten",
"Ligne diagonale du coin supérieur gauche au coin inférieur droit",
"Línea diagonal de la esquina superior izquierda a la inferior derecha",
"左上から右下への斜線",
"从左上到右下的对角线",
],
),
(
"Diagonal Line from Top Right to Bottom Left",
[
"Diagonale Linie von rechts oben nach links unten",
"Ligne diagonale du coin supérieur droit au coin inférieur gauche",
"Línea diagonal de la esquina superior derecha a la inferior izquierda",
"右上から左下への斜線",
"从右上到左下的对角线",
],
),
(
"Crossed Diagonal Lines",
["Gekreuzte diagonale Linien", "Lignes diagonales croisées", "Líneas diagonales cruzadas", "交差する斜線", "交叉对角线"],
),
("Line Stroke", ["Linienkontur", "Contour de ligne", "Trazo de línea", "斜線の線", "线条描边"]),
("Draw:", ["Zeichnen:", "Dessin :", "Dibujar:", "描画:", "绘制:"]),
("Diagonal In Front", ["Diagonale im Vordergrund", "Diagonale au premier plan", "Diagonal delante", "斜線を前面へ", "对角线置前"]),
("Content In Front", ["Inhalt im Vordergrund", "Contenu au premier plan", "Contenido delante", "内容を前面へ", "内容置前"]),
("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", "セルの境界線", "单元格边缘"]),
+10
View File
@@ -972,6 +972,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Show/Hide Panels", "Показати/приховати панелі"),
("Show/Hide Panels Except Tools", "Показати/приховати панелі, крім інструментів"),
("Show/Hide Rulers", "Показати/приховати лінійки"),
("Show/Hide Style Name Column", "Показати/приховати стовпець назв стилів"),
("Show/Hide Tagged Frames", "Показати/приховати фрейми з тегами"),
("Show/Hide Text Threads", "Показати/приховати зв’язки текстових фреймів"),
("Smooth", "Згладити"),
@@ -1976,6 +1977,15 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Continue from Previous Number", "Продовжити з попереднього номера"),
("Start At", "Почати з"),
("Strokes and Fills…", "Обведення та заливки…"),
("Diagonal Lines…", "Діагональні лінії…"),
("No Diagonal Lines", "Без діагональних ліній"),
("Diagonal Line from Top Left to Bottom Right", "Діагональна лінія з верхнього лівого кута в нижній правий"),
("Diagonal Line from Top Right to Bottom Left", "Діагональна лінія з верхнього правого кута в нижній лівий"),
("Crossed Diagonal Lines", "Перехресні діагональні лінії"),
("Line Stroke", "Обведення лінії"),
("Draw:", "Малювати:"),
("Diagonal In Front", "Діагональ попереду"),
("Content In Front", "Вміст попереду"),
("Cell Stroke", "Обведення клітинки"),
("Cell Fill", "Заливка клітинки"),
("Cell edges", "Краї клітинки"),
+19
View File
@@ -244,6 +244,7 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
Ok(Value::Null)
}
"app.cellOptionsDialog" => crate::dialogs::open_cell_options(app),
"app.diagonalLinesDialog" => crate::dialogs::open_diagonal_lines(app),
"window.hideMenuItem" => {
let Some(item) = p.get("item").and_then(Value::as_str) else { return Some(Err("missing item".into())) };
let hide = p.get("hidden").and_then(Value::as_bool).unwrap_or(true);
@@ -767,6 +768,24 @@ fn run_ui_part3(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value
"view.textThreads" => flag(&mut app.ui.text_threads),
"view.hiddenCharacters" => flag(&mut app.ui.hidden_characters),
"view.taggedFrames" => flag(&mut app.ui.tagged_frames),
"view.storyEditorStyleColumn" => {
let on = p.get("on");
let width = p.get("width");
if on.is_some_and(|v| !v.is_boolean()) || width.is_some_and(|v| !v.is_number()) {
return Some(Err(format!("{id}: `on` is a bool and `width` a number")));
}
match (on.and_then(Value::as_bool), width.and_then(Value::as_f64)) {
(None, None) => app.ui.story_editor_style_column = !app.ui.story_editor_style_column,
(on, width) => {
app.ui.story_editor_style_column = on.unwrap_or(app.ui.story_editor_style_column);
if let Some(w) = width {
app.ui.story_editor_style_width =
crate::story_editor::style_column_width(w.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32);
}
}
}
Ok(json!({"on": app.ui.story_editor_style_column, "width": app.ui.story_editor_style_width}))
}
"view.storyEditorDepthRuler" => flag(&mut app.ui.story_editor_depth_ruler),
"window.hidePanels" | "window.hidePanelsExceptTools" => {
let mode = if id == "window.hidePanels" { 1 } else { 2 };
+4
View File
@@ -118,6 +118,7 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option<bool> {
"view.textThreads" => app.ui.text_threads,
"view.hiddenCharacters" => app.ui.hidden_characters,
"view.taggedFrames" => app.ui.tagged_frames,
"view.storyEditorStyleColumn" => app.ui.story_editor_style_column,
"view.storyEditorDepthRuler" => app.ui.story_editor_depth_ruler,
"changes.track" => app.session.active().is_some_and(|d| d.doc.settings.track_changes),
// Pressed, as the Bulleted and Numbered List buttons: every paragraph the command applies
@@ -184,6 +185,9 @@ pub fn menu_enabled(app: &DesignApp, id: &str) -> bool {
if matches!(id, "app.justificationDialog" | "app.hyphenationDialog") {
return enabled(app, "type.para");
}
if matches!(id, "app.cellOptionsDialog" | "app.diagonalLinesDialog") {
return enabled(app, "table.setCell");
}
if id == "app.graphicCell" {
return enabled(app, "table.placeGraphic");
}
+2
View File
@@ -437,6 +437,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
"-",
">Cell Options",
"ui:app.cellOptionsDialog",
"ui:app.diagonalLinesDialog",
"<",
"-",
">Insert",
@@ -552,6 +553,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
"ui:view.tagMarkers",
"<",
">Story Editor",
"ui:view.storyEditorStyleColumn",
"ui:view.storyEditorDepthRuler",
"<",
],
+1
View File
@@ -92,6 +92,7 @@ fn view_items_are_in_the_view_menu_as_in_indesign() {
"view.separations",
"view.taggedFrames",
"view.tagMarkers",
"view.storyEditorStyleColumn",
"view.storyEditorDepthRuler",
] {
assert!(view.contains(&id), "{id} is in View");
+12
View File
@@ -146,6 +146,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
None,
"{} — Cell Options › Strokes and Fills of the target cells: edge proxy, stroke weight, type, colour, tint, gap colour, gap tint, and cell fill (table.setCell)",
),
(
"app.diagonalLinesDialog",
"Diagonal Lines…",
None,
"{} — Cell Options › Diagonal Lines of the target cells: the line type, its weight, type, color, tint, gap color and gap tint, and Draw (table.setCell {diagonal})",
),
("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),
("app.rubyDialog", "Ruby…", None, "{} — the reading set over the selected text"),
(
@@ -271,6 +277,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("view.textThreads", "Show/Hide Text Threads", Some("Cmd+Alt+Y"), "{}"),
("view.hiddenCharacters", "Show Hidden Characters", Some("Cmd+Alt+I"), "{}"),
("view.taggedFrames", "Show/Hide Tagged Frames", None, "{} — XML-tagged frames outlined in their tag colour"),
(
"view.storyEditorStyleColumn",
"Show/Hide Style Name Column",
None,
"{on?: bool, width?: 40–400 (points)} — the Story Editor's column of paragraph style names; toggles without either → {on, width}",
),
(
"view.storyEditorDepthRuler",
"Show/Hide Depth Ruler",
+116 -1
View File
@@ -63,13 +63,15 @@ fn regular(styles: &[String]) -> String {
styles.iter().find(|s| *s == "Regular").or(styles.first()).cloned().unwrap_or_else(|| "Regular".into())
}
fn meta(ui: &Ui, fonts: &designcraft_fonts::ScopedFonts<'static>, scope: u32, family: &str) -> FamilyMeta {
fn meta(ui: &Ui, fonts: &designcraft_fonts::ScopedFonts<'_>, scope: u32, family: &str) -> FamilyMeta {
let key = egui::Id::unique(("font_meta", family, scope));
if let Some(m) = ui.data(|d| d.get_temp::<FamilyMeta>(key)) {
return m;
}
let styles = fonts.styles(family);
let kind = fonts.face(family, &regular(&styles)).kind();
// Loading a catalogued variable font discovers its named instances.
let styles = fonts.styles(family);
let m = FamilyMeta { styles, kind };
ui.data_mut(|d| d.insert_temp(key, m.clone()));
m
@@ -730,3 +732,116 @@ mod preview_cache_tests {
assert!(c.get(key(Previews::CAP + 39)).is_some());
}
}
#[cfg(test)]
mod variable_catalog_regression {
#[test]
#[ignore = "requires the pinned Bricolage fixture; see docs/testing-variable-fonts.md"]
fn cold_family_menu_contains_named_instances() {
let path = std::env::var_os("DESIGNCRAFT_TEST_VARIABLE_FONT").expect("set DESIGNCRAFT_TEST_VARIABLE_FONT");
let path = std::path::PathBuf::from(path);
let db = Box::leak(Box::new(designcraft_fonts::FontDb::with_font_dirs(vec![path.parent().unwrap().to_owned()])));
let fonts = db.scoped(0);
assert!(!fonts.styles("Bricolage Grotesque").contains(&"SemiBold".into()), "the fixture must be catalogued but not loaded");
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |root| {
egui::CentralPanel::default().show(root, |ui| {
let first = super::meta(ui, &fonts, 0, "Bricolage Grotesque");
assert!(
first.styles.contains(&"SemiBold".into()),
"cold menu cached {:?}, live styles {:?}",
first.styles,
fonts.styles("Bricolage Grotesque")
);
let second = super::meta(ui, &fonts, 0, "Bricolage Grotesque");
assert_eq!(first.styles, second.styles);
});
});
output.textures_delta.clear();
// Exercise the family menu's actual style-row selection too.
use egui_kittest::{Harness, kittest::Queryable};
designcraft_fonts::FontDb::global().add_font(std::fs::read(&path).unwrap());
let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let menu: Vec<_> =
designcraft_fonts::FontDb::global().scoped(0).family_infos().into_iter().filter(|f| f.family == "Bricolage Grotesque").collect();
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.with_size(egui::vec2(1000.0, 800.0))
.build_ui_state(
move |ui, state: &mut (crate::DesignApp, Option<super::FontPick>)| {
let key = egui::Id::unique("font_menu_state");
let mut st: super::MenuState = ui.data(|d| d.get_temp(key)).unwrap_or_default();
st.expanded.insert("Bricolage Grotesque".into());
ui.data_mut(|d| d.insert_temp(key, st));
let m = super::font_menu_header(&mut state.0, ui, &menu, "Bricolage Grotesque", 560.0);
if let Some(pick) = super::font_menu_list(ui, m) {
state.1 = Some(pick);
}
},
(app, None),
);
h.run_steps(3);
h.get_by_label("SemiBold").click();
h.run_steps(3);
let pick = h.state().1.as_ref().expect("a style row was picked");
assert_eq!(pick.family, "Bricolage Grotesque");
assert_eq!(pick.style.as_deref(), Some("SemiBold"));
}
}
#[cfg(test)]
mod synthetic_variable_catalog_regression {
#[test]
fn family_menu_selects_a_synthetic_named_instance() {
use egui_kittest::{Harness, kittest::Queryable};
let family = "Synthetic Menu Wiring";
let db = designcraft_fonts::FontDb::global();
db.add_font(designcraft_fonts::testing::variable_font(family).unwrap());
let app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
let menu: Vec<_> = db.scoped(0).family_infos().into_iter().filter(|f| f.family == family).collect();
let mut h = Harness::builder()
.with_context_setup(|ctx| {
crate::theme::install_fonts(ctx, "");
})
.with_size(egui::vec2(1000.0, 800.0))
.build_ui_state(
|ui, state: &mut (crate::DesignApp, Option<super::FontPick>)| {
let key = egui::Id::unique("font_menu_state");
let mut st: super::MenuState = ui.data(|d| d.get_temp(key)).unwrap_or_default();
st.expanded.insert(family.into());
ui.data_mut(|d| d.insert_temp(key, st));
let m = super::font_menu_header(&mut state.0, ui, &menu, family, 560.0);
if let Some(pick) = super::font_menu_list(ui, m) {
state.1 = Some(pick);
}
},
(app, None),
);
h.run_steps(3);
h.get_by_label("SemiBold").click();
h.run_steps(3);
let pick = h.state().1.as_ref().expect("the real Family menu selected a style");
assert_eq!(pick.family, family);
assert_eq!(pick.style.as_deref(), Some("SemiBold"));
}
#[test]
fn cold_family_menu_discovers_and_caches_named_instances() {
let dir = tempfile::tempdir().unwrap();
let family = "Synthetic Cold Menu";
std::fs::write(dir.path().join("variable.ttf"), designcraft_fonts::testing::variable_font(family).unwrap()).unwrap();
let db = designcraft_fonts::FontDb::with_font_dirs(vec![dir.path().to_owned()]);
let fonts = db.scoped(0);
assert_eq!(fonts.styles(family), ["Regular"]);
let ctx = egui::Context::default();
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
let first = super::meta(ui, &fonts, 0, family);
assert_eq!(first.styles, ["Regular", "SemiBold"]);
let second = super::meta(ui, &fonts, 0, family);
assert_eq!(first.styles, second.styles);
});
output.textures_delta.clear();
}
}
+1
View File
@@ -34,6 +34,7 @@ impl UiState {
}
}
let mut ui: UiState = serde_json::from_value(saved)?;
ui.story_editor_style_width = crate::story_editor::style_column_width(ui.story_editor_style_width);
clear_stale_open_panels(&mut ui);
intact &= migrate(&mut ui.docking, &mut ui.floating, &ui.docking_hidden, ui.dock_expanded, ui.icon_groups.as_deref());
for workspace in &mut ui.custom_workspaces {
+8 -1
View File
@@ -1,6 +1,6 @@
#[cfg(not(target_arch = "wasm32"))]
use super::render_worker;
use super::{Deserialize, Point, Serialize, SnapView, Unit, canvas, dialogs, page_history, panels, prefs, separations, theme};
use super::{Deserialize, Point, Serialize, SnapView, Unit, canvas, dialogs, page_history, panels, prefs, separations, story_editor, theme};
/// Context captured before any host file-picker or read await.
#[derive(Clone, Debug)]
@@ -233,6 +233,11 @@ pub struct UiState {
pub story_editor_size: f32,
/// View › Story Editor › Show/Hide Depth Ruler.
pub story_editor_depth_ruler: bool,
/// View › Story Editor › Show/Hide Style Name Column.
pub story_editor_style_column: bool,
/// Width of the Story Editor's style name column, in screen points (set by dragging its bar or by
/// `view.storyEditorStyleColumn` `width`).
pub story_editor_style_width: f32,
/// The Color Picker's component (its radio button, as `PickComp::key`: `h`, `s`, `b`, `l`,
/// `la`, `lb`, `r`, `g`, `bl`), kept between openings and sessions, as Photoshop's picker is.
pub color_picker_component: String,
@@ -411,6 +416,8 @@ impl Default for UiState {
show_full_menus: false,
story_editor_size: 14.0,
story_editor_depth_ruler: true,
story_editor_style_column: true,
story_editor_style_width: story_editor::STYLE_COLUMN_WIDTH,
color_picker_component: "r".into(),
scripts: vec![
("Number the pages".into(), "# A page-number frame at the bottom of the current page.\nframe.create {\"rect\": [288, 740, 324, 760], \"content\": \"text\", \"text\": \"\"}\ntext.select {\"story\": \"$0.story\", \"anchor\": 0, \"focus\": 0}\ntext.insert {\"text\": \"\\ue000\", \"raw\": true}".into()),
+219 -14
View File
@@ -11,6 +11,12 @@ use designcraft_doc::StoryId;
use crate::DesignApp;
use crate::theme::Tokens;
/// Width of the style name column before its bar is dragged, in screen points.
pub const STYLE_COLUMN_WIDTH: f32 = 130.0;
/// Narrowest and widest the style name column can be dragged, in screen points.
const STYLE_COLUMN_RANGE: (f32, f32) = (40.0, 400.0);
/// Width of the bar between the style name column and the text, in screen points.
const STYLE_BAR_WIDTH: f32 = 6.0;
/// Width of the depth ruler, in screen points.
const RULER_WIDTH: f32 = 34.0;
/// Least distance between two of the depth ruler's labels, in screen points.
@@ -51,8 +57,10 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
let overset = cs.overset_at;
let depths = app.ui.story_editor_depth_ruler.then(|| line_depths(&cs));
let unit = st.doc.settings.vertical_units;
let style_width = app.ui.story_editor_style_column.then(|| style_column_width(app.ui.story_editor_style_width));
let mut open = true;
let mut edit: Option<(usize, usize, String)> = None;
let mut dragged_width: Option<f32> = None;
let words = story.text.split_whitespace().count().to_string();
egui::Window::new(crate::i18n::tr(&app.ui.language, "Story Editor — {count} words").replace("{count}", &words))
.id(egui::Id::unique("story_editor"))
@@ -61,16 +69,20 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
.show(ctx, |ui| {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.horizontal_top(|ui| {
// Style column: the labels are painted after the text, at the rows the text really wraps to.
let (column, _) = ui.allocate_exact_size(vec2(130.0, 0.0), egui::Sense::hover());
ui.separator();
// Style column: the labels are painted after the text, at the rows the text really wraps to,
// and so is the bar that resizes it.
let column = style_width.map(|w| {
let column = ui.allocate_exact_size(vec2(w, 0.0), egui::Sense::hover()).0;
let bar = ui.allocate_exact_size(vec2(STYLE_BAR_WIDTH, 0.0), egui::Sense::hover()).0;
(column, bar)
});
// Depth ruler: painted after the text too, beside the rows the lines start on.
let ruler = depths.as_ref().map(|_| ui.allocate_exact_size(vec2(RULER_WIDTH, 0.0), egui::Sense::hover()).0);
let mut text = story.text.clone();
// (a fixed id: the ruler's allocation above would otherwise move the editor's auto id,
// and its focus and caret with it, whenever the ruler is shown or hidden)
// The text field has a fixed id, so it keeps its focus and caret when the columns before it
// are shown or hidden.
let out = egui::TextEdit::multiline(&mut text)
.id_salt("story_text")
.id(egui::Id::unique("story_editor_text"))
.font(egui::FontId::proportional(app.ui.story_editor_size.clamp(8.0, 36.0)))
.desired_width(f32::INFINITY)
.desired_rows(20)
@@ -78,14 +90,40 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
.show(ui);
let r = out.response;
let changed = r.changed();
let starts = paragraph_start_offsets(out.galley.rows.iter().map(|row| (row.pos.y, row.ends_with_newline)));
for (i, y) in starts.into_iter().enumerate() {
let Some(para) = story.paras.get(i) else { break };
let rect = egui::Rect::from_min_size(egui::pos2(column.min.x, out.galley_pos.y + y), vec2(130.0, 14.0));
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
let name = crate::i18n::style_name(&app.ui.language, &para.style);
crate::rtl::label(ui, egui::RichText::new(name).size(11.0).color(t.text_dim));
});
if let Some((column, bar)) = column {
let starts = paragraph_start_offsets(out.galley.rows.iter().map(|row| (row.pos.y, row.ends_with_newline)));
for (i, y) in starts.into_iter().enumerate() {
let Some(para) = story.paras.get(i) else { break };
let rect = egui::Rect::from_min_size(egui::pos2(column.min.x, out.galley_pos.y + y), vec2(column.width(), 14.0));
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
let name = crate::i18n::style_name(&app.ui.language, &para.style);
crate::rtl::label(ui, egui::RichText::new(name).size(11.0).color(t.text_dim));
});
}
// The bar between the column and the text: drag it to make the column wider or narrower.
let bar = egui::Rect::from_x_y_ranges(bar.x_range(), r.rect.y_range());
let drag = ui.interact(bar, egui::Id::unique("story_editor_style_bar"), egui::Sense::drag());
let line = egui::Rect::from_center_size(bar.center(), vec2(1.0, bar.height()));
ui.painter().rect_filled(line, 0.0, if drag.hovered() || drag.dragged() { t.text_dim } else { t.section_divider });
let drag = drag.on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
// The width follows the pointer from where the drag started, so the bar comes back
// with the pointer after the drag passes the narrowest or widest width.
if drag.drag_started() {
let origin = ui.input(|i| i.pointer.press_origin()).or(drag.interact_pointer_pos());
if let Some(origin) = origin {
ui.data_mut(|d| d.insert_temp(drag.id, (column.width(), origin.x)));
}
}
if drag.dragged() {
let start = ui.data(|d| d.get_temp::<(f32, f32)>(drag.id));
let width = match (start, drag.interact_pointer_pos()) {
(Some((width, origin)), Some(pos)) => width + pos.x - origin,
_ => column.width() + drag.drag_delta().x,
};
dragged_width = Some(style_column_width(width));
}
drag.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Style name column divider"));
}
let overset_y = overset.filter(|_| !changed).map(|o| {
let ci = char_offsets(&story.text, std::iter::once(o));
@@ -145,6 +183,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
}
});
});
if let Some(w) = dragged_width {
let _ = app.run("view.storyEditorStyleColumn", json!({"width": w}));
}
if let Some((a, b, text)) = edit {
let _ = app.run("story.replaceRange", json!({"story": sid.0, "start": a, "end": b, "text": text}));
}
@@ -153,6 +194,12 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {
}
}
/// The style name column's width for a saved or dragged `width`: kept between the narrowest and
/// widest the bar allows, and the starting width when `width` is not a number.
pub(crate) fn style_column_width(width: f32) -> f32 {
if width.is_finite() { width.clamp(STYLE_COLUMN_RANGE.0, STYLE_COLUMN_RANGE.1) } else { STYLE_COLUMN_WIDTH }
}
/// Vertical offset of the first laid-out row of each paragraph, from `(row y, row ends with a newline)`
/// in layout order. A paragraph that wraps spans several rows, so counting characters per line
/// drifts from what the editor draws; the rows themselves are the truth.
@@ -471,6 +518,156 @@ mod tests {
assert!(!crate::UiState::from_preferences_json(&saved).unwrap().story_editor_depth_ruler);
}
fn story_editor_harness(text: &str) -> egui_kittest::Harness<'static, crate::test_window::Window> {
let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": text, "caret": false})).unwrap();
app.run("app.storyEditor", json!({"story": r["story"].as_u64().unwrap()})).unwrap();
let mut h = crate::test_window::open(app, egui::vec2(1440.0, 900.0));
h.run_steps(2);
h
}
fn text_left(h: &egui_kittest::Harness<'_, crate::test_window::Window>, text: &str) -> f32 {
h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some(text)).rect().min.x
}
/// View › Story Editor › Show/Hide Style Name Column: hiding the column takes away the style
/// names and the bar beside them, and the text moves left by their width; the setting is
/// remembered.
#[test]
fn style_name_column_shows_and_hides_from_the_view_menu() {
let mut h = story_editor_harness("Column story");
assert!(h.state().app.ui.story_editor_style_column, "shown by default");
let app = &h.state().app;
let para_style = &app.session.active().unwrap().doc.stories.values().next().unwrap().paras[0].style;
let style = crate::i18n::style_name(&app.ui.language, para_style).to_string();
assert!(h.query_by_label(&style).is_some(), "the column names the paragraph's style {style:?}");
assert!(h.query_by_label("Style name column divider").is_some());
let with = text_left(&h, "Column story");
h.state_mut().app.run("view.storyEditorStyleColumn", json!({})).unwrap();
h.run_steps(2);
let without = text_left(&h, "Column story");
assert!(h.query_by_label(&style).is_none(), "no style names while the column is hidden");
assert!(h.query_by_label("Style name column divider").is_none());
assert!(
(with - without - super::STYLE_COLUMN_WIDTH - super::STYLE_BAR_WIDTH).abs() < 20.0,
"the text moves by the column: {with} vs {without}"
);
let app = &h.state().app;
assert_eq!(crate::menus::checked(app, "view.storyEditorStyleColumn", &json!({})), Some(false));
let saved = serde_json::to_vec(&app.ui).unwrap();
assert!(!crate::UiState::from_preferences_json(&saved).unwrap().story_editor_style_column);
}
/// A style name wider than the column is cut short at the column's edge, so it does not run
/// into the story text.
#[test]
fn a_long_style_name_stays_in_the_column() {
let mut h = story_editor_harness("Narrow story");
h.state_mut().app.run("view.storyEditorStyleColumn", json!({"width": 40})).unwrap();
h.run_steps(2);
let app = &h.state().app;
let para_style = &app.session.active().unwrap().doc.stories.values().next().unwrap().paras[0].style;
let style = crate::i18n::style_name(&app.ui.language, para_style).to_string();
let name = h.get_by_label(&style).rect();
let text = text_left(&h, "Narrow story");
assert!(name.width() <= 40.5, "the name {style:?} is cut to the column: {name:?}");
assert!(name.max.x <= text, "the name ends before the text: {name:?}, text at {text}");
}
/// Dragging the bar between the style names and the text resizes the column; the text moves
/// with the bar, and the width is remembered for the next time the editor opens.
#[test]
fn dragging_the_style_column_bar_resizes_the_column() {
use egui::{Event, Modifiers, PointerButton};
let mut h = story_editor_harness("Resize story");
let before = text_left(&h, "Resize story");
let a = h.get_by_label("Style name column divider").rect().center();
let b = a + egui::vec2(60.0, 0.0);
h.input_mut().events.push(Event::PointerMoved(a));
h.input_mut().events.push(Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for k in 1..=4 {
h.input_mut().events.push(Event::PointerMoved(a + (b - a) * (k as f32 / 4.0)));
h.step();
}
h.input_mut().events.push(Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
let width = h.state().app.ui.story_editor_style_width;
assert!((width - super::STYLE_COLUMN_WIDTH - 60.0).abs() < 1.0, "the column is 60 points wider: {width}");
let after = text_left(&h, "Resize story");
assert!((after - before - 60.0).abs() < 1.0, "the text moves with the bar: {before} → {after}");
let saved = serde_json::to_vec(&h.state().app.ui).unwrap();
assert_eq!(crate::UiState::from_preferences_json(&saved).unwrap().story_editor_style_width, width);
}
/// After a drag passes the widest width, moving the pointer back brings the bar back with it:
/// the width is the starting width plus how far the pointer moved, kept in range.
#[test]
fn the_style_column_bar_follows_the_pointer_back_from_a_limit() {
use egui::{Event, Modifiers, PointerButton};
let mut h = story_editor_harness("Limit story");
let a = h.get_by_label("Style name column divider").rect().center();
h.input_mut().events.push(Event::PointerMoved(a));
h.input_mut().events.push(Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
h.step();
for dx in [100.0, 200.0, 300.0, 400.0, 300.0, 200.0] {
h.input_mut().events.push(Event::PointerMoved(a + egui::vec2(dx, 0.0)));
h.step();
}
let b = a + egui::vec2(200.0, 0.0);
h.input_mut().events.push(Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(3);
let width = h.state().app.ui.story_editor_style_width;
assert!((width - super::STYLE_COLUMN_WIDTH - 200.0).abs() < 1.0, "the column is 200 points wider: {width}");
}
/// A saved width out of range, or not a number, gives a column the bar can still be dragged in.
#[test]
fn style_column_width_stays_in_range() {
assert_eq!(super::style_column_width(200.0), 200.0);
assert_eq!(super::style_column_width(-50.0), super::STYLE_COLUMN_RANGE.0);
assert_eq!(super::style_column_width(1e9), super::STYLE_COLUMN_RANGE.1);
assert_eq!(super::style_column_width(f32::NAN), super::STYLE_COLUMN_WIDTH);
assert_eq!(super::style_column_width(f32::INFINITY), super::STYLE_COLUMN_WIDTH);
}
/// Showing or hiding the style name column or the depth ruler keeps the text's focus and caret:
/// typing goes on into the story.
#[test]
fn typing_goes_on_after_the_columns_show_or_hide() {
let mut h = story_editor_harness("Focus story");
h.get_by(|n| n.role() == egui::accesskit::Role::MultilineTextInput && n.value().as_deref() == Some("Focus story")).focus();
h.run_steps(2);
h.event(egui::Event::Text("1".into()));
h.run_steps(2);
for (i, id) in ["view.storyEditorStyleColumn", "view.storyEditorDepthRuler", "view.storyEditorStyleColumn"].into_iter().enumerate() {
h.state_mut().app.run(id, json!({})).unwrap();
h.run_steps(2);
h.event(egui::Event::Text((i + 2).to_string()));
h.run_steps(2);
}
let text = story_text(&h.state().app, 0);
assert!(text.contains("1234"), "every key reaches the story at the caret: {text:?}");
}
/// `view.storyEditorStyleColumn` sets the column's width and whether it shows, as the bar and
/// the menu item do, and toggles it without either.
#[test]
fn the_style_column_command_takes_a_width() {
let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());
assert_eq!(app.run("view.storyEditorStyleColumn", json!({"width": 250})).unwrap(), json!({"on": true, "width": 250.0}));
assert_eq!(app.run("view.storyEditorStyleColumn", json!({"width": 1000})).unwrap()["width"], json!(400.0));
assert_eq!(app.run("view.storyEditorStyleColumn", json!({"width": -1e40})).unwrap()["width"], json!(40.0));
assert_eq!(app.run("view.storyEditorStyleColumn", json!({"width": 1e40})).unwrap()["width"], json!(400.0));
assert_eq!(app.run("view.storyEditorStyleColumn", json!({"on": false})).unwrap(), json!({"on": false, "width": 400.0}));
assert_eq!(app.run("view.storyEditorStyleColumn", json!({})).unwrap()["on"], json!(true));
assert!(app.run("view.storyEditorStyleColumn", json!({"width": "wide"})).is_err());
assert!(app.run("view.storyEditorStyleColumn", json!({"on": 1})).is_err());
assert_eq!((app.ui.story_editor_style_column, app.ui.story_editor_style_width), (true, 400.0));
}
#[test]
fn depth_marks_wait_for_composition_after_editing() {
fn marks(shape: &egui::epaint::Shape, tick: egui::Color32) -> usize {
@@ -517,6 +714,14 @@ mod tests {
}
}
/// The Show/Hide Style Name Column menu label is translated in every interface language.
#[test]
fn style_name_column_menu_label_is_translated_in_every_language() {
for (lang, _) in crate::i18n::LANGUAGES.iter().filter(|(code, _)| !code.is_empty()) {
assert_ne!(crate::i18n::tr(lang, "Show/Hide Style Name Column"), "Show/Hide Style Name Column", "{lang}");
}
}
/// Showing or hiding the depth ruler keeps the text's focus and caret: typing after the toggle
/// still reaches the story.
#[test]
+1 -1
View File
@@ -36,7 +36,7 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built
| Vertical text, upright CJK, rotated Latin | done: story direction per story (frames of a thread agree; IDML `StoryOrientation`); glyphs turned by transforms; arrow keys follow the vertical lines |
| Vertical metrics and shaping | done: upright runs shaped top to bottom (`vert`; `vkrn`/`vpal` when asked) with `vmtx`/`VORG` advances and origins, centred on the ideographic em box (`BASE`, else OS/2); turned runs shaped horizontally, without `vrt2`; Horizontal Kana (`hkna`) takes the vertical kana (`vkna`) in upright runs. Default location of variable fonts only (no `VVAR`) |
| Kinsoku | named (hard, soft, Chinese, Korean) and custom kinsoku sets, bunri-kinshi, rensuuji, hanging punctuation (regular, force); without a set, fixed no-start / no-end lists and a break anywhere between CJK characters; kinsoku type (push in / push out priorities) kept but not applied |
| Korean line breaking | at spaces (Hangul everywhere, hanja in Korean text); per-paragraph character-based breaking (`koreanCharBreaks`); DesignCraft-only, not in IDML |
| Korean line breaking | at spaces (Hangul everywhere, hanja in Korean text); per-paragraph character-based breaking (`koreanCharBreaks`); DesignCraft-only, not in IDML; no automatic hyphens in a paragraph with at least as many Hangul letters as ASCII Latin ones, whatever its language setting, and none invented inside a space-delimited token holding Hangul, kana or Han or reading as an address (URL, e-mail, domain, rooted or drive path) (#1688) |
| Mojikumi | applied in composition: the built-in base sets (line end half-width, line end one em, Simplified and Traditional Chinese) and the document's tables with their override rows, kept through IDML; Preflight notes tables it can't apply. In the Japanese sets consecutive punctuation closes up (JLREQ 3.1.4: 」。, 「『 touch; 」・ a quarter em, 」「 half an em apart). Still open: 、・ and ・・ take the sum of both blanks in JLREQ (Table 1 notes) |
| Aki, tsume, jidori | done ([cjk-typography.md](cjk-typography.md)) |
| Character alignment, leading model | em box top / centre / bottom, ICF top / bottom (`BASE` `icft`/`icfb`, else the em box inset by 5%), roman baseline; aki above / below, centre (centre down as centre); under aki below a line's leading is the space to the line below it; with the Japanese composers (`Composer::Japanese`, `JapaneseSingleLine`, IDML `HL Composer J` / `HL Single J`), the others set lines baseline to baseline on the Roman baseline |
+1 -1
View File
@@ -70,7 +70,7 @@ external PDF/X certification.
| 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 | | ✓ | ✓ 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, 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% |
| PSD | `.psd` | ✓ layers, comps, alpha, paths | ~ composite + Object Layer Options; embedded ICC profile and managed CMYK on screen; placed at its own resolution | layer comps partial | 1% |
| EPS | `.eps` | ✓ (PostScript) | ~ preview only (no interpreter) | | <1% |
| SVG | `.svg` | ✓ | ✓ (usvg) | | <1% |
| HEIC | `.heic` | ✓ | ✗ | | <1% |
+10 -4
View File
@@ -1,6 +1,6 @@
# Where DesignCraft falls short of InDesign
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (gap 7 closed: pull-request quality gate already runs; linked placed images and multi-image place; gap 20: automatic recovery moved off the interface thread; gap 21 shrunk: pt-BR translates the whole interface; placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (gap 7 closed: pull-request quality gate already runs; linked placed images and multi-image place; gap 20: automatic recovery moved off the interface thread; gap 21 shrunk: pt-BR translates the whole interface; gap 29 added: document tabs can't be reordered (overflowing tabs now scroll); placed graphic layer-option preservation and explicit rendering warnings; gap 16 shrunk: File › File Info; gap 16: Convert Variable to Text; gap 28 added: placed-PDF font repair remains after visible unembedded font detection, #909; gap 26 shrunk: autoflow fills the following pages before it adds pages at the end; gap 6 shrunk: Type › Reload Fonts reads fonts installed, edited or removed while running (#328); gap 3: Package links are relative, #340; gap 27 closed: the loaded text cursor threads into a frame inside a group (#1075); .indd and .indt open through indd-utils; gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers; bounded control click/drag input; swatches on placed greyscale and bitmap images) · **Target:** Adobe InDesign 2026 (21.6)
Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops an
InDesign professional from doing real work. This is the work list: agents pick from the top.
@@ -147,8 +147,8 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format ·
### 12. Tables in depth (F)
- **Missing:** anchored objects in cells not drawn (#163); Table ▸ Table Options and Cell Options
submenus as InDesign lays them out, Diagonal Lines, Edit Header/Footer; general reliability
(#20).
submenus as InDesign lays them out, diagonal lines in IDML, Edit Header/Footer; general
reliability (#20).
- **Estimate:** 25–40 h.
### 13. Hyphenation and spelling languages (T, L)
@@ -185,7 +185,7 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format ·
Profile / Edit Original, File ▸ Open PDF / Document and Print Presets / User
Settings, Type ▸ Size presets, Table ▸ Table Options / Cell Options submenus, Paste Before/After,
Convert Columns, Object ▸ Interactive ▸ Convert to (form fields),
View ▸ Extras badges and Story Editor options (Show/Hide Depth Ruler is there). Overriding a
View ▸ Extras badges and Story Editor options (Show/Hide Depth Ruler and Show/Hide Style Name Column are there). Overriding a
base parent's items on a parent spread itself (overrides work on document pages only); Save
as Parent; new parents for an alternate layout (its pages keep their source pages' parents).
- **Estimate:** 40–70 h (most are thin wrappers over existing engine features).
@@ -272,6 +272,11 @@ Kind: **F** feature · **U** UI/UX · **T** typography · **FF** file format ·
- **Missing:** screen-reader exposure of panels and dialogs (egui AccessKit coverage unverified);
PDF/UA validation of exports. **Estimate:** 15–25 h.
### 29. Document tabs can't be reordered (U)
- **Missing:** dragging a document tab to reorder it, and dragging it out into its own window. Tabs scroll,
list every document and keep the active one in view when they overflow.
- **Estimate:** 3–5 h.
## Out of scope (by design)
Adobe cloud services (CC Libraries, Stock, Adobe Fonts activation, Publish Online, Share for
@@ -284,6 +289,7 @@ Cue. These are excluded from every percentage.
|---|---|---|
| 2026-11-15 | trivial | Gap 7 closed: the quality gate already runs on every pull request and push to main (#1352) |
| 2026-11-14 | minor | Gaps 19 and 20 shrunk: placed files are linked with proxies and a hash (save format 5); multi-image place cursor, grid and contact sheet |
| 2026-11-05 | minor | Gap 29 added: document tabs can't be reordered (overflowing tabs now scroll) |
| 2026-11-04 | trivial | Gap 21 shrunk: pt-BR translates 2,936 of 2,939 strings, all but three Control panel captions (61% before) |
| 2026-10-22 | minor | Gap 26 shrunk: autoflow threads a frame per column on the pages that follow the story's last frame, then adds pages at the end of the document |
| 2026-10-19 | minor | Gap 28 added for remaining placed-PDF font embedding, substitution or outlining; visible unembedded font detection now ships in PDF/X-4 export and `validate-pdf`, with invisible text exempt and operation- or depth-limited checks reported incomplete (#909) |
+5 -2
View File
@@ -142,8 +142,11 @@ config works across the suite) keep the agent to the folders you give it:
its nearest existing folder's links are followed and the rest must be plain names, so `..` below a
folder that doesn't exist is refused, as is a link that leads nowhere (writing through it would
create its target). The result is compared with each root by whole folder names: `/work2/x` is not
inside `/work`. On Windows case is ignored, UNC paths (`\\server\share\...`) are resolved like
drive-letter ones, and device names (`CON`, `NUL`, `COM1`, `COM¹`, including before a colon) are refused.
inside `/work`. On Windows case is ignored, and device names (`CON`, `NUL`, `COM1`, `COM¹`, including before a colon) are refused.
A network path (`\\server\share\...`, `\\?\UNC\...`, WebDAV's `\\host@SSL\share\...`), a device path (`\\.\...`) or a
verbatim path that isn't a disk (a volume by its `\\?\Volume{…}` name is local) is refused by its name before anything looks it up, since looking it up would
contact that host, unless a root is on the same server and share (or the same verbatim prefix). A link whose
target is one of those is refused from the link's text, before it is followed. A \\?\ path with a `..` in it is refused, since Windows opens such a path as written and would follow a link before the `..`. On Windows a name that ends in a period or a space, in a path or as a link's target, is refused too, since Windows trims it where it looks a name up.
- A refused path is an ordinary tool error the agent can read and correct, for example
`automation path rejected: outside the write root /work/project/out: /etc/x.designcraft` (with
several, `outside the write roots /work/project/out, /tmp/scratch: ...`) or
+1 -1
View File
@@ -63,7 +63,7 @@ set exists; depth gaps are in gaps.md.
| M5 | Graphics & links | ✅ core; EPS preview only |
| M6 | Files & export (native, IDML, PDF, PNG/JPEG) | IDML ✅, PDF ✅ (X-4, A-2b, tagged); INDD read ✅ (via indd-utils); PDF/X-1a ✅; PDF/X-3 and presets ✗ |
| M7 | Long documents (sections, TOC, index, footnotes, books) | ✅ except Books (shallow) |
| M8 | Tables | ✅ core (table/cell styles, rotation); diagonal lines, anchored objects in cells (#163) |
| M8 | Tables | ✅ core (table/cell styles, rotation); diagonal lines in IDML, anchored objects in cells (#163) |
| M9 | Performance (MT composition, tiles) | in progress: parallel compose 6.7×, damage regions; incremental composition next |
| M10 | Find/Change, spelling, Preflight | ✅ (spelling English only) |
| M11 | Layout power features (liquid/alternate layouts, data merge) | present, shallow; Flex Layout (new in InDesign 2026) ✗ |
+2 -1
View File
@@ -213,7 +213,7 @@ table is the one summed.
| Type & text frames | 99% | 45% | 40–60 | Primary Text Frame pages users can't delete (alpha blocker, #165); autoflow sets new frames on following pages instead of flowing into their primary text frame; caret formatting discarded (#289); Notes/Track Changes menus; frame grids |
| Typography | 100% | 45% | (typography dimension) | see [typography-parity.md](typography-parity.md) |
| Styles | 100% | 60% | 15–25 | Paragraph Styles edit/delete reported failing (#169); style options depth |
| Tables | 100% | 55% | 25–40 | anchored objects in cells not drawn (#163); Table ▸ Table Options submenus, Diagonal Lines, Edit Header/Footer |
| Tables | 100% | 55% | 25–40 | anchored objects in cells not drawn (#163); Table ▸ Table Options submenus, Edit Header/Footer |
| Long documents | 100% | 45% | 30–50 | Books are shallow (sync, book pagination, book PDF/TOC/index); Table of Contents Styles |
| Interactivity & digital | 100% | 40% | 30–50 | HTML export basic (#314); fixed-layout EPUB is page images; no animation, timing, media playback |
| Output & production | 92% | 55% | 40–70 | PDF/X-4 only (no X-1a/X-3), with visible unembedded font detection (below); no PDF/print presets or `.joboptions`, print via craft-print (CUPS/Windows), no trapping; Output Preview panel |
@@ -375,6 +375,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- 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`).
- Cell strokes: with cells selected (or the cursor in a cell) the Stroke panel edits the chosen cell edges, picked on a drawn edge proxy (top, bottom, left, right, inner horizontal, inner vertical); Table › Cell Options › Strokes and Fills… does the same with the cell fill. Weight, every stroke type, colour, tint, gap colour and gap tint draw on screen and in PDF and round-trip through IDML (`table.setCell` `stroke.edges`, `table.getCellStroke`).
- Diagonal lines in cells: Table › Cell Options › Diagonal Lines… draws a line from the top left corner to the bottom right, from the top right to the bottom left, or both, with the same weight, type, color, tint, gap color and gap tint as cell edges, in front of the cell's contents or behind them (Draw: Diagonal In Front or Content In Front). They draw on screen, in PDF and in PowerPoint export and are saved in the native format; IDML import and export do not carry them (`table.setCell` `diagonal`, `table.getCellDiagonal`).
- 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 or PDF/A).
+40
View File
@@ -0,0 +1,40 @@
# Variable-font paragraph style regressions (#1210)
Default tests generate a small variable-font name/axis table around the existing bundled OFL outlines. They exercise cold catalog discovery in both the Family menu and Style popup, selection, and retry on reopening a popup after a font file was unavailable. No download or system-font installation is required. Run them with `cargo test -p designcraft-ui-egui --lib synthetic_variable`.
The real-font tests remain explicit opt-in tests: missing fonts fail rather than silently pass.
They use SIL OFL 1.1 Bricolage Grotesque from google/fonts commit
`47d54ca1ebb14fd864695f1d39dc734f39017c33`, path
`ofl/bricolagegrotesque/BricolageGrotesque[opsz,wdth,wght].ttf`.
SHA256: `413e7357809ddd12fd80a96a8a396de0e401638d4acd3cb3e37532f0472ac682`.
Download OFL.txt from the same directory; keep both outside this repository.
Set `DESIGNCRAFT_TEST_VARIABLE_FONT` to the absolute font file path. Then run:
```text
cargo test -p designcraft-ui-egui cold_family_menu_contains_named_instances -- --ignored --nocapture
cargo test -p designcraft-ui-egui named_instance_style_widget_and_api_agree -- --ignored --nocapture
```
On Windows, for the cold Style-combo test, make a temporary directory containing
`Microsoft/Windows/Fonts/` with that font inside. Set `LOCALAPPDATA` **only for the test
process** to this temporary directory, then run the following test alone in a fresh process:
```text
cargo test -p designcraft-ui-egui cold_style_combo_contains_named_instances -- --ignored --nocapture
```
Do not install the fixture globally or preload it through add_font for this cold test.
On other platforms use the platform's test font directory before the process starts.
The test asserts that SemiBold is absent before loading, without depending on the default style name.
It then opens the actual Style combo, selects SemiBold and verifies c.fontStyle.
The menu-cache test creates an isolated database whose font directory holds the fixture.
The warm widget test clicks Regular -> SemiBold -> Bold -> Regular, compares Confirm with
style.paragraph.edit, preserves an inherited family and Based On, serializes/reopens the
native document, and verifies Preview off, Cancel and single-step Confirm/Undo/Redo.
Before the patch, both cold tests fail: the menu caches only `96pt ExtraBold`, and the
Style combo offers no SemiBold. After preloading, selection and persistence already work.
This proves a discovery/availability failure, not a loss of a selected style in the engine.
No font binaries should be committed. A desktop visual/manual check on macOS and Linux
is separate from these headless egui input tests.
+1 -1
View File
@@ -50,7 +50,7 @@ basics of editing fail for too many users on Windows and Linux.
| Panels: Pages, Layers, Swatches, Color, Stroke, Character, Paragraph, Styles, Links, Effects, Text Wrap, Align, Pathfinder, Table, Index, TOC, Hyperlinks, Bookmarks, Articles, Tags, Notes, Track Changes, Object States, Buttons and Forms, Preflight, Data Merge, Library, Scripts, Glyphs, Info, Tabs, Story | ✓ | all present | ~ | Navigator, Trap Presets, Animation, Timing missing; pull-down panels can't scroll on Linux (#267) |
| Dialogs: New Document, Document Setup, Preferences (all pages), Paragraph/Character/Object/Table/Cell Style Options, Export PDF, Print, Package, Find/Change | ✓ | present | ~ | a Custom text variable whose text is typed as a number shows its digits (`variables.define` takes a string, a number or a boolean for `text` and refuses anything else; #2093); generated command dialogs fill the long tail; depth varies |
| Workspaces | Essentials, Essentials Classic, Advanced, Book, Digital Publishing, Interactive for PDF, Printing and Proofing, Review, Typography, Touch | ✓ named workspaces (Essentials Classic: Control panel and iconic panel groups) + custom; Window › Workspace; no Review or Touch | ~ | tab bar overlaps menus in Book/Advanced (#182) |
| Story Editor | ✓ | ✓ | ~ | depth ruler and View › Story Editor › Show/Hide Depth Ruler (`story_editor.rs` `depth_ruler_shows_and_hides_from_the_view_menu`); hiding or resizing the style-name column missing |
| Story Editor | ✓ | ✓ | ~ | depth ruler and View › Story Editor › Show/Hide Depth Ruler (`story_editor.rs` `depth_ruler_shows_and_hides_from_the_view_menu`); Show/Hide Style Name Column and dragging the column's width (`style_name_column_shows_and_hides_from_the_view_menu`, `dragging_the_style_column_bar_resizes_the_column`); Expand/Collapse All Footnotes and Show/Hide Paragraph Break Marks missing |
| Undo granularity (a drag = one step) | ✓ | ✓ (Begin/Preview/Commit) | ✓ | |
| Closing with unsaved changes asks | ✓ | ✓ File › Close and window/menu quit (#146, #545) | ✓ | macOS Dock Quit still bypasses the prompt (#544) |
| UI scaling, System appearance | ✓ | scaling ✓ (#281); follows macOS light/dark ✗ (#237) | ~ | |