Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
438f90c751 | ||
|
|
11fceda13e | ||
|
|
ea814b3fac | ||
|
|
b5e39048df | ||
|
|
762bd6b927 | ||
|
|
033ceaff41 | ||
|
|
a2e4206155 | ||
|
|
771981e2b1 | ||
|
|
c7aeaa637f | ||
|
|
965fc449e1 | ||
|
|
977e5d1967 | ||
|
|
b73e19eef2 | ||
|
|
4792bd82a2 | ||
|
|
d5e6be1565 | ||
|
|
a469568c7d | ||
|
|
53b4845f6f | ||
|
|
5f92f5eb7f | ||
|
|
409af66699 | ||
|
|
65f35f20a6 | ||
|
|
2b10c15d7a | ||
|
|
712f4316e0 | ||
|
|
0716a0d104 | ||
|
|
a29563fb92 | ||
|
|
c640a04612 | ||
|
|
e22d22a4ce | ||
|
|
9ec940222b | ||
|
|
9e2fb37f3a | ||
|
|
4411688b3d | ||
|
|
6b2c90f756 | ||
|
|
1ee36c2c07 | ||
|
|
f365dc1c74 | ||
|
|
e9de045f06 | ||
|
|
58a3a68d83 | ||
|
|
a366e4ff79 | ||
|
|
8b81d58845 | ||
|
|
d9b5eea18d | ||
|
|
8ccafe1187 | ||
|
|
f3b90fb93f | ||
|
|
fc052cb001 | ||
|
|
896f8efea8 | ||
|
|
921e60f4fc | ||
|
|
b843fe8af3 | ||
|
|
aa5e8f46e9 | ||
|
|
9dec49ed03 | ||
|
|
dc157c6c5b | ||
|
|
aa125bfff1 | ||
|
|
22008b4e68 | ||
|
|
2497713779 | ||
|
|
e037064b2d | ||
|
|
564a3ae662 | ||
|
|
106abe639f | ||
|
|
54eed6ec4c | ||
|
|
67af21c6db | ||
|
|
e0b1f55250 | ||
|
|
8d5b52965c | ||
|
|
33f38cef08 | ||
|
|
8a18a74daf | ||
|
|
1a1119b1d4 | ||
|
|
79a67e2642 | ||
|
|
f7761bf5bc | ||
|
|
d9a2cfe7f9 | ||
|
|
dc6f138a72 | ||
|
|
6def232852 | ||
|
|
0df8231334 | ||
|
|
37d4477362 | ||
|
|
7e82dbc05b | ||
|
|
cfe8eaafaf | ||
|
|
611deeda46 | ||
|
|
674aef95b0 | ||
|
|
1d013959cb | ||
|
|
b1f7d5ad7d |
No files matched your search
Generated
+3
@@ -4352,6 +4352,7 @@ dependencies = [
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde_json",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -4362,6 +4363,8 @@ dependencies = [
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-svg",
|
||||
"vectorcraft-testkit",
|
||||
"vectorcraft-text",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -194,7 +194,7 @@ milestones, and honest time-to-parity estimates.
|
||||
"a power user can't tell the difference". Everyday vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, EPS, DXF, EMF/WMF, raster formats and PSD, Print, Package). The interface
|
||||
speaks English, Japanese, Traditional and Simplified Chinese, Spanish, Italian and Russian (and Czech and Brazilian Portuguese in the menus).
|
||||
speaks English, Japanese, Traditional and Simplified Chinese, Spanish, French, Italian and Russian (and Czech and Brazilian Portuguese in the menus).
|
||||
The scores are
|
||||
self-assessed, so the [honest assessment](ROADMAP.md#honest-assessment-2026-10-05) explains how far to trust them.
|
||||
|
||||
|
||||
+19
-18
@@ -4,7 +4,7 @@ VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adob
|
||||
|
||||
This file tracks **how far we are and what's left**. Time estimates are wall-clock hours of continuous Claude Opus 5.5 agent work (including builds and the CI gate), given both for **one agent** and for **4–6 parallel agents** on disjoint crates. They are counted from the remaining work (see [Parity estimate](#parity-estimate)), calibrated against measured throughput, and updated as work lands.
|
||||
|
||||
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
_Last updated: 2026-10-09 (after placed documents (File › Place of a `.vectorcraft` file, linked), M4.14–M4.98, M8.1–M8.20, M14.4–M14.7, the MCP prompts, resource templates, completions and logging, the 2026-10-07 issue fixes, the Layers panel rework and the 2026-10-08 community contributions: Pen and shape-tool modifiers, path editing, Layers, Artboards, Swatches/Brushes and dialogs, Japanese composition and PDF text, Hebrew/Arabic type, interface languages (Spanish among them), the font menu, saved selections, MCP and EPS, the missing-font export warning (#319), open paths in the Shape Builder (#374), PDF/`.ai` import keeping strokes live and hidden and nested layers (#372), per-corner Live Corners (#381), SVG type opening at the size it draws at (#396), the Wayland clipboard with copied-file paste (#398), ruler guides that can be selected, moved and deleted (#414), two batches of Preferences options that were stored but unused (#394), skeleton reads with `document.find` for large documents over MCP (#416) and anchors dragged with Direct Selection snapping to points, segments and smart guides, clipped SVG layers opening as clipping layers (#420), PDF/`.ai` layers read on pages of tens of millions of operators (#419), Document Color Mode putting RGB greys on the black plate on request and converting pattern tiles (#421) and movable dialogs with Offset Path's Joins dropdown (#423) and numeric fields scrubbed by dragging their label (#400), stroke weight presets in the stroke unit (#426), the Appearance panel's Opacity popup (#430), type on a path brackets, flip and Type on a Path Options that keep the type in place (#429), Layers rows dragged with a ghost and dropped on the trash or New Layer (#435), tool flyouts opening on a right or corner press (#436), tool flyouts torn off into floating toolbars (#437), the Shape Builder's erase mode deleting edges too (#439), installed fonts registered outside the font folders and fonts installed while the app runs listed in the font menus (#443), alike circular corners on rectangles that aren't square (#442), tool cursors as OS cursors so the pointer no longer trails over the canvas (#444), artboards copied and pasted with their art (#446), guides dragged out of the rulers snapping to the art's side midpoints and the artboards, artboard guides (#451), the toolbar's double arrow and Window › Toolbars › Double Column switching between one and two columns in any window height (#455), the Smart Guides display options and Snapping Tolerance (#394), Font Size and Leading combo boxes with preset lists in the Character and Properties panels and the Control bar (#458), screenshots pasted from the clipboard on macOS, Windows and the web (#457), the Properties panel's Fill and Stroke matching the Control bar's, Illustrator's Window menu panel keys (Shift+F7 for Align…) and Alt-wheel zoom whatever the wheel preference (Discord feedback), the point/area type widget (Discord feedback), groups in legacy Illustrator .ai files (Discord feedback), a rotating desktop log file (#465), image controls in the Control bar and Properties panel: Image Trace with its presets, Mask, Crop Image, Embed/Unembed, and an Image Trace object's preset, Expand and Release (Discord feedback), the Pen working as the Anchor Point tool with Alt held over a selected path's handles and anchors, and anchor buttons that convert, connect and cut paths at the selected anchors (Discord feedback), Japanese hanging punctuation (burasagari, #463), Escape leaving Presentation Mode with no screen mode saved across restarts, documents dropped on the desktop app opening as tabs of their own and a note that an `.ai` file's art off its artboards isn't in the part read (#472), Add/Delete Anchor Point tool icons drawn from the Pen tool's (#479), EPS import running more of PostScript Level 3 (patterns, Type 3 fonts, mesh shadings, masked images, VM and resource probes), and a preview that stands in saying why (Discord feedback, #466, #469, #474), chords with modifiers recorded in Edit › Keyboard Shortcuts (#487), Type Object Selection by Path Only (#394), Anti-aliased Artwork (#394), Show Pixel Grid (#394), pen and touch taps pressed and lifted within one frame clicking where they tapped and the Linux/Wayland pen-tablet workaround (#491), bounding-box resizes landing on the other objects' anchors and centres with labels, and the Rotate, Scale, Shear and Reflect tools snapping their drags (#482), Shift-drag marquees that toggle the objects or anchors they reach and a Lasso whose Alt subtraction keeps the rest of the selection (#483), the mouse wheel stepping the focused numeric field, the dialogs' and preferences' drag values made such fields (#485), Show The Home Screen When No Documents Are Open (#394), Numbers Without Units Are Points (#394), Auto-Collapse Iconic Panels (#394), the Contextual Task Bar moved by its handle and its More Options menu pinning and resetting its position, a designed macOS DMG windoLine truncated
|
||||
|
||||
## Where we are
|
||||
|
||||
@@ -34,7 +34,7 @@ since 2026-10-01.
|
||||
| Dimension | Estimate | Evidence and what's missing |
|
||||
|---|---|---|
|
||||
| **Breadth:** menus, tools and panels exist | ~90% | 13 menu items still stubbed; every tool implemented except Touch Type; 51 panel modules |
|
||||
| **Depth:** each feature behaves like Illustrator | ~69–75% | Strong: paint, appearance and colour (M3), Pathfinder and booleans, selection, drawing, files (M4). Weak: advanced type (~45%), brushes and symbols (in progress), raster effects (~20%) |
|
||||
| **Depth:** each feature behaves like Illustrator | ~69–75% | Strong: paint, appearance and colour (M3), Pathfinder and booleans, selection, drawing, files (M4). Weak: advanced type (~45%; inline symbols in text are beyond parity and don't raise it), brushes and symbols (in progress), raster effects (~20%) |
|
||||
| **Large missing subsystems** | 0–20% | 3D & Materials (0%), Photoshop-style raster effects and the Effect Gallery (~1 of ~56 filters), SVG Filters, CJK composition (vertical type with kinsoku, tate-chu-yoko and the font's vertical metrics; ruby, mojikumi and proportional vertical metrics open), Variables (data merge), scripting |
|
||||
| **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first |
|
||||
| **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured |
|
||||
@@ -52,7 +52,7 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
|
||||
1. **Interaction fidelity:** go tool by tool and panel by panel against `plan/illustrator/05-tools.md`,
|
||||
`06-panels.md` and `09-shortcuts.md`, covering modifier keys, cursors, the Properties panel per context and
|
||||
isolation mode. Do it side by side with Illustrator where the owner allows. 60–90 h.
|
||||
isolation mode. The Shaper’s rough-square recognition and shape orientation steps are corrected; Shaper Groups now retain editable originals for region merges/punches and separate fill/stroke edits; their construction-mode widget and gesture refinements remain. 60–90 h.
|
||||
2. **Photoshop-style raster effects and the Effect Gallery:** about 55 filters (Artistic, Brush Strokes, Distort,
|
||||
Pixelate, Sketch, Stylize, Texture, Video) on the raster pipeline that drop shadows already use, applied at
|
||||
Document Raster Effects Settings resolution. Parallelizes well across agents. 28–42 h.
|
||||
@@ -63,7 +63,7 @@ Ordered by how much each gap blocks someone from switching. Sizes are one-agent
|
||||
tate-chu-yoko), Optical Margin Alignment, the hyphenation and justification options (the Every-line/Single-line
|
||||
composer choice is done), tab leaders, a
|
||||
spell-check dictionary (open licence), Touch Type and Snap to Glyph. Vertical point, area and path type have
|
||||
initial support. 35–48 h across type core and advanced.
|
||||
initial support. 34–47 h across type core and advanced.
|
||||
5. **Brushes, symbols and libraries:** brush options depth; original brush, symbol and graphic-style libraries
|
||||
generated in code (never Adobe's); dynamic symbols; Start Global Edit; brushes driven by pen tilt, bearing and
|
||||
barrel rotation (6D art pens, #372), which needs tablet input beyond pressure on every platform. 20–32 h.
|
||||
@@ -102,7 +102,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- Tool flyouts tear off: dragging or clicking the tear-off bar on a flyout's right side (or releasing the long press over it) floats its group as a strip of tool buttons, moved by the same bar and put back in the toolbar by the × at its top (`window.floatTools`). While a group floats, the presses that would open its flyout raise the strip instead. Floating strips are kept with the preferences and in user workspaces. Not done: turning a strip vertical, docking it.
|
||||
- Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel inside the window, and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on the dock, which lights up under the pointer, its panels go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating panels and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, docking a panel into a dock group it doesn't belong to, reordering tabs by dragging, collapsing a floating group to icons, resizing floating panels.
|
||||
- The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done.
|
||||
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish, Italian and Russian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
|
||||
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Spanish, French, Italian and Russian ship complete, and Czech and Brazilian Portuguese cover every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a VectorCraft ▸ Language menu and a Language preference. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
|
||||
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
|
||||
- The macOS menu bar is built from the in-window menus (one model, `native_menu`) and laid out as a Mac app's: the VectorCraft menu holds About, Settings ▸ (each Preferences page, General… ⌘K), Language ▸, Appearance ▸ (UI brightness), Services, Hide VectorCraft ⌃⌘H (⌘H stays Hide Edges), Hide Others, Show All and Quit; Window gains Minimize ⌃⌘M, Zoom and Bring All to Front, and Help the system's search field. Its key equivalents go back to egui as key presses, so user shortcuts, focused text fields and the Type tool's input method behave as in the window, and nothing fires twice; enabled, check marks and labels update in place. `--in-window-menus` or `VECTORCRAFT_IN_WINDOW_MENUS=1` keeps the menus in the window; `ui.inspect` reports `nativeMenuBar`.
|
||||
- macOS: Finder opens every format File › Open reads with VectorCraft (double-click, Open With, a drop on the Dock icon, `open -a`), at launch or while it runs; the release and `cargo xtask bundle` apps share one `Info.plist` that declares those document types, owning only VectorCraft's own formats. The DMG opens on a designed Finder window, VectorCraft.app beside the `Applications` link over a background with the app icon (#493).
|
||||
@@ -118,6 +118,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected).
|
||||
- On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one.
|
||||
- **Tools:**
|
||||
- **Shaper:** uneven squares and rectangles become live rectangles even when drawing begins mid-edge. Recognition uses uniformly spaced samples and closed-loop corners, fits rectangle edges/angles rather than requiring a nearly perfect bounding-box fill, and includes the pointer-release position. Rectangles/squares and ellipses snap to 45° steps, hexagons to 90°, and triangles point up or down; lines keep their free angle even with Shift. Shaper Groups retain the live originals, merge regions with the gesture-origin fill, punch fills independently from strokes, remove boundaries on exiting scribbles and trim protruding stroke pieces. Source moves/resizes re-evaluate the result in the same undo step; double-click enters construction editing. Native save/reopen, face recoloring, Release and Expand are covered. The construction-mode widget and finer gesture heuristics remain.
|
||||
- **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct and Group Selection (#483); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it).
|
||||
- **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Not yet: Update Selection and the Layers panel's saved-selection menu.
|
||||
- **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners.
|
||||
@@ -133,18 +134,18 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool.
|
||||
- **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it.
|
||||
- **Tool double-clicks:** double-clicking a tool's button opens its options: Hand fits the artboard in the window, Zoom shows 100 %, Rotate, Scale, Reflect and Shear open their Object › Transform dialogs, the Selection, Direct Selection and Group Selection tools the Move dialog (Enter opens these seven tools' dialogs too), Gradient, Eyedropper, Blend and the Liquify tools their panels or options, and the Pencil, Paintbrush, Smooth, Blob Brush and Eraser tools their Tool Options (Fidelity, fill, the tolerances, the brush size).
|
||||
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting.
|
||||
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638).
|
||||
- **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes.
|
||||
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472).
|
||||
- **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard and fits it, and Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, F from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them).
|
||||
- **Geometry and effects:**
|
||||
- Pathfinder (10 exact curve booleans), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart.
|
||||
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters).
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline or the em box top/right, centre or bottom/left (ICF top and bottom not yet); Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Type:** Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. Variation axis sliders are not done. Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `<use>` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458).
|
||||
- **Interface languages, vertical type:** VectorCraft ▸ Language (or Preferences ▸ User Interface) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) and Russian (every `ru-*` locale) cover the whole interface, Czech and Brazilian Portuguese every menu label, Brazilian Portuguese the shell's `tl!` literals too (tested); Spanish, French, Italian and Russian also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, Spanish, French, Italian and Russian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku (the strict set) applies to horizontal and vertical Japanese, and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a wrapped line flush with its start, and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines.
|
||||
- **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `<mask>` and PDF soft masks.
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own; filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points or an image over 64 megapixels is refused with advice rather than running out of memory, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), the Image Trace panel and Expand, plus Release in Properties; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641; the View modes are not done), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror).
|
||||
- **Paint and appearance (M3):**
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved and loaded as `.vcswatches`, `.gpl` or CSS. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl` or CSS, and loaded from `.vcswatches`, `.gpl` and swatch exchange (`.ase`) files (RGB, CMYK, Lab and Gray; global, spot and process; groups). Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate.
|
||||
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel follows each colour's own model and Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
|
||||
- **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles snap and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh.
|
||||
- **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty more arrowheads, and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance.
|
||||
@@ -157,7 +158,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs).
|
||||
- **Files (M4):**
|
||||
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320).
|
||||
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export. EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole).
|
||||
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
|
||||
- Place and the Links panel, Package, File Info, Print with print presets, PostScript output and print tiling, slices and Save for Web, Export for Screens and Asset Export, CSS Properties, PNG/PDF/SVG/text clipboard flavours; files copied in a file manager paste as art (SVG, PDF, EMF/WMF, bitmaps) on every desktop platform, and Linux/Wayland reads the compositor's clipboard (#398); on Linux the Paste menu checks the clipboard off the UI thread, so an X11 owner that never answers can't freeze the window (#510); screenshots and other copied pictures paste as embedded images at the view centre everywhere, the web included (#457).
|
||||
@@ -171,12 +172,12 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
|---|---|---|---|
|
||||
| M0 | Skeleton + vertical slice | ✅ done | — |
|
||||
| M1 | Selection, transform, layers, MCP | ✅ mostly done (transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 |
|
||||
| M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper, the remaining Pen modifier nuances) | 15–20 |
|
||||
| M2 | Drawing tools + smart guides | ✅ mostly done (Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; construction widget/refinements pending) | 12–18 |
|
||||
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool, Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 |
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out, EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, Asset Export, clipboard flavours, File Info. Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, polish | 3–6 |
|
||||
| M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 |
|
||||
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, Area Type Options (with Width/Height and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Character/Paragraph Styles, per-paragraph paragraph attributes, Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import, variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel, inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 |
|
||||
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 |
|
||||
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder and Color Adjustments; SVG Filters, Document Raster Effects Settings, 3D pending | 86–135 |
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; brushes/symbols in progress | 23–37 |
|
||||
@@ -203,7 +204,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Area | Weight | Done | Missing (main items) | One agent (h) |
|
||||
|---|---:|---:|---|---:|
|
||||
| Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done) | 4–6 |
|
||||
| Drawing tools | 7 | 85% | Shaper Groups (merge/punch overlapping shapes), pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners on corners between curved sides (and Relative rounding) | 10–15 |
|
||||
| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners on corners between curved sides (and Relative rounding) | 8–13 |
|
||||
| Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 |
|
||||
| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4 |
|
||||
| Strokes, brushes, width profiles | 5 | 88% | brush options depth, brush libraries (generated in code), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 12–20 |
|
||||
@@ -211,10 +212,10 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters | 6–10 |
|
||||
| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 20% | ~55 Photoshop-style filters (Artistic, Brush Strokes, Distort, Pixelate, Sketch, Stylize, Texture, Video) and the Effect Gallery; Document Raster Effects Settings and raster effects in PDF are done | 28–42 |
|
||||
| 3D and Materials | 4 | 0% | Extrude & Bevel, Revolve, Inflate, Rotate, lighting, materials (software renderer) | 50–80 |
|
||||
| Type core | 9 | 79% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
|
||||
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko, Character Alignment on the ICF top and bottom), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support | 20–28 |
|
||||
| Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, digit types, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, Transform Again after a type-area resize (it scales the type), partial selection of type-area anchors by marquee | 14–19 |
|
||||
| Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), kinsoku sets and the Mojikumi Settings dialog —, proportional vertical metrics, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 |
|
||||
| Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | symbol libraries (original), dynamic symbols, envelope Anti-Alias/Preserve Shape output and warp point editing, brush interpolation in blends (M8 fidelity pass done) | 5–8 |
|
||||
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image) (Vector Halftone is done) | 6–10 |
|
||||
| Image Trace, graphs, image tools | 3 | 70% | graph Design/Column/Marker, Create Object Mosaic, Crop Image polish (an on-canvas crop box), Image Trace View modes (Outlines, Source Image), per-feature stroke/fill choice and varying widths in Create Strokes (Vector Halftone is done) | 6–10 |
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, Collect for Export, row context menus, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers, drag-scrolling a long panel while dragging rows; artboard presets/rearrange polish (Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 84% | global/video rulers, Spacing Guides, Smart Guides' angle and distance readouts while drawing, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506) | 2–4 |
|
||||
|
||||
@@ -22,7 +22,14 @@ vectorcraft-geom = { workspace = true }
|
||||
vectorcraft-svg = { workspace = true }
|
||||
vectorcraft-mcp = { workspace = true }
|
||||
vectorcraft-render = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# DirectWrite's system font collection (the desktop app's src/system_fonts.rs, shared): fonts that
|
||||
# font services such as Adobe Fonts load in place (#579). MIT OR Apache-2.0.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000]
|
||||
//! ```
|
||||
#![forbid(unsafe_code)]
|
||||
// Denied, not forbidden: the DirectWrite font lister shared with the desktop app (Windows) allows
|
||||
// it for its COM calls, and nothing else may.
|
||||
#![deny(unsafe_code)]
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::ExitCode;
|
||||
@@ -35,6 +37,10 @@ macro_rules! out {
|
||||
}
|
||||
|
||||
mod perf;
|
||||
/// The desktop app's DirectWrite font lister, shared: exports and MCP find the same fonts.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
#[path = "../../vectorcraft/src/system_fonts.rs"]
|
||||
mod system_fonts;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
|
||||
@@ -93,6 +99,9 @@ fn usage() -> String {
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
// Before any font lookup: the fonts font services load (#579).
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
system_fonts::install();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let r = match args.first().map(String::as_str) {
|
||||
Some("mcp") => mcp(&args[1..]),
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour};
|
||||
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address};
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore};
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
@@ -200,7 +200,8 @@ fn track_paste(pasted: &Rc<RefCell<Pasted>>) {
|
||||
let on_paste = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::ClipboardEvent)>::new(move |e: web_sys::ClipboardEvent| {
|
||||
let Some(data) = e.clipboard_data() else { return };
|
||||
let Some(files) = data.files().filter(|f| f.length() > 0) else { return };
|
||||
if data.get_data("text").is_ok_and(|t| !t.is_empty()) {
|
||||
// Text is egui's, but for the address a browser's Copy Image puts next to the picture.
|
||||
if data.get_data("text").is_ok_and(|t| !t.is_empty() && !is_address(&t)) {
|
||||
return;
|
||||
}
|
||||
e.prevent_default();
|
||||
|
||||
@@ -34,6 +34,7 @@ mod window;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::picks::PickRequest;
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
|
||||
struct App {
|
||||
@@ -185,9 +186,22 @@ fn save_prefs(app: &VectorcraftApp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A native file dialog showing `pick`'s file types, folder and suggested name.
|
||||
fn file_dialog(pick: &FilePick) -> rfd::FileDialog {
|
||||
let d = pick.filters.iter().fold(rfd::FileDialog::new(), |d, (name, exts)| d.add_filter(*name, exts));
|
||||
/// The window file dialogs belong to.
|
||||
type Parent = Option<std::sync::Arc<winit::window::Window>>;
|
||||
|
||||
/// A native file dialog for `request` over `parent` (Windows and Linux, where the portal then
|
||||
/// shows it over the window and keeps it in front; macOS shows them as before).
|
||||
fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog {
|
||||
let d = match parent {
|
||||
Some(w) if !cfg!(target_os = "macos") => rfd::FileDialog::new().set_parent(&**w),
|
||||
_ => rfd::FileDialog::new(),
|
||||
};
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => return fileio::place_filters().fold(d.set_title("Place"), |d, (name, exts)| d.add_filter(name, exts)),
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| d.add_filter(*name, exts));
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.set_directory(folder),
|
||||
None => d,
|
||||
@@ -195,6 +209,28 @@ fn file_dialog(pick: &FilePick) -> rfd::FileDialog {
|
||||
if pick.name.is_empty() { d } else { d.set_file_name(&pick.name) }
|
||||
}
|
||||
|
||||
/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked.
|
||||
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest) -> Vec<String> {
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(pick) => {
|
||||
// The Templates folder may not exist yet.
|
||||
if let Some(folder) = &pick.folder {
|
||||
let _ = std::fs::create_dir_all(folder);
|
||||
}
|
||||
dialog.save_file().into_iter().collect()
|
||||
}
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
|
||||
/// Show the dialog for `request` over `parent` now → the paths picked.
|
||||
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<String> {
|
||||
show_dialog(file_dialog(&request, parent), &request)
|
||||
}
|
||||
|
||||
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
|
||||
fn reveal(path: &str) -> Result<(), String> {
|
||||
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
|
||||
@@ -230,25 +266,31 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn services() -> Services {
|
||||
/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the
|
||||
/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then
|
||||
/// offers to kill the window as not responding (#592).
|
||||
fn start_pick(request: PickRequest, parent: &Parent) -> Option<std::sync::mpsc::Receiver<Vec<String>>> {
|
||||
let dialog = file_dialog(&request, parent);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("file-dialog".into())
|
||||
.spawn(move || {
|
||||
// The app gone meanwhile has no use for the answer.
|
||||
let _ = tx.send(show_dialog(dialog, &request));
|
||||
})
|
||||
.ok()?;
|
||||
Some(rx)
|
||||
}
|
||||
|
||||
fn services(parent: Parent) -> Services {
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
Services {
|
||||
pick_open: Some(Box::new(|pick: &FilePick| file_dialog(pick).pick_file().map(|p| p.to_string_lossy().to_string()))),
|
||||
pick_open_multi: Some(Box::new(|| {
|
||||
fileio::place_filters()
|
||||
.fold(rfd::FileDialog::new().set_title("Place"), |d, (name, exts)| d.add_filter(name, exts))
|
||||
.pick_files()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.collect()
|
||||
})),
|
||||
pick_save: Some(Box::new(|pick: &FilePick| {
|
||||
// The Templates folder may not exist yet.
|
||||
if let Some(folder) = &pick.folder {
|
||||
let _ = std::fs::create_dir_all(folder);
|
||||
}
|
||||
file_dialog(pick).save_file().map(|p| p.to_string_lossy().to_string())
|
||||
})),
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Windows and macOS dialogs run the window's events while they are open; Linux's don't.
|
||||
start_pick: cfg!(all(unix, not(target_os = "macos")))
|
||||
.then(|| Box::new(move |request: PickRequest| start_pick(request, &p5)) as vectorcraft_ui_egui::picks::StartPick),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
write: Some(Box::new(write_file)),
|
||||
// Background Save and Export write from a worker thread.
|
||||
@@ -266,7 +308,7 @@ fn services() -> Services {
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
pick_folder: Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
@@ -397,7 +439,7 @@ fn main() -> std::process::ExitCode {
|
||||
"VectorCraft",
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), services());
|
||||
let mut app = VectorcraftApp::new(Session::new(), services(cc.winit_window().cloned()));
|
||||
load_prefs(&mut app, saved);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
if let Some(w) = cc.winit_window() {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Windows: the font files in DirectWrite's system font collection, scanned with the font folders
|
||||
//! (`vectorcraft_text::set_platform_font_files`).
|
||||
//! (`vectorcraft_text::set_platform_font_files`). The desktop app and `vectorcraft-cli` (exports,
|
||||
//! MCP) both install it; the CLI shares this file.
|
||||
//!
|
||||
//! Font services such as Adobe Fonts load their fonts with GDI at run time, from files in their
|
||||
//! own folders, without installing them: the font folders and the registry don't list them. Since
|
||||
|
||||
@@ -31,3 +31,7 @@ sync_github_name = true
|
||||
|
||||
[people.omd0]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Swatch library files: the native `.vcswatches` JSON (colour models, global, spot, gradients
|
||||
//! and colour groups exactly), `.gpl` palettes (8-bit RGB; colour groups as `# Group:` comment
|
||||
//! headers) and CSS custom properties (written only).
|
||||
//! headers) and CSS custom properties (written only). Swatch exchange files (`.ase`) are read
|
||||
//! only ([`read_bytes`]).
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -58,6 +61,15 @@ struct NativeFile {
|
||||
const NATIVE_FORMAT: &str = "vcswatches";
|
||||
const GPL_HEADER: &str = "GIMP Palette";
|
||||
const GPL_GROUP: &str = "# Group:";
|
||||
const ASE_SIGNATURE: &[u8] = b"ASEF";
|
||||
const ASE_GROUP_START: u16 = 0xC001;
|
||||
const ASE_GROUP_END: u16 = 0xC002;
|
||||
const ASE_COLOR: u16 = 0x0001;
|
||||
/// The most colors and groups read from one `.ase` file.
|
||||
const ASE_MAX_ENTRIES: usize = 100_000;
|
||||
/// The most UTF-16 code units of a name that are kept.
|
||||
const ASE_MAX_NAME: usize = 1024;
|
||||
const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short";
|
||||
|
||||
/// Write `lib` in `format`. Pattern swatches (their tiles live in a document) and None are left
|
||||
/// out; `.gpl` keeps solid colours only, as 8-bit RGB.
|
||||
@@ -199,16 +211,34 @@ pub fn sniff(text: &str) -> bool {
|
||||
t.starts_with(GPL_HEADER) || (t.starts_with('{') && t.contains(NATIVE_FORMAT))
|
||||
}
|
||||
|
||||
/// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or
|
||||
/// `.gpl` library ([`read`]). `name` names it when the file doesn't.
|
||||
pub fn read_bytes(bytes: &[u8], name: &str) -> Result<SwatchLibrary, String> {
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return read_ase(bytes, name);
|
||||
}
|
||||
read(&String::from_utf8_lossy(bytes), name)
|
||||
}
|
||||
|
||||
/// Are `bytes` a library [`read_bytes`] understands? Text that isn't valid UTF-8 is checked as
|
||||
/// [`read_bytes`] reads it, with the invalid bytes replaced (its first KiB is enough).
|
||||
pub fn sniff_bytes(bytes: &[u8]) -> bool {
|
||||
bytes.starts_with(ASE_SIGNATURE)
|
||||
|| std::str::from_utf8(bytes).is_ok_and(sniff)
|
||||
|| sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes)))
|
||||
}
|
||||
|
||||
/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colours are
|
||||
/// named by their values; repeated names get a number.
|
||||
/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are
|
||||
/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets
|
||||
/// a number ([`UniqueNames`]).
|
||||
fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names: Vec<String> = vec![];
|
||||
let mut names = UniqueNames::default();
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
lib.groups.push(SwatchGroup { name: g.trim().to_string(), swatches: vec![] });
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] });
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = line.strip_prefix("Name:") {
|
||||
@@ -221,9 +251,7 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let rest = words[3..].join(" ");
|
||||
let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest };
|
||||
let name = (1..).map(|i| if i == 1 { base.clone() } else { format!("{base} {i}") }).find(|n| !names.contains(n)).unwrap_or(base);
|
||||
names.push(name.clone());
|
||||
let w = Swatch { name, paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false };
|
||||
match lib.groups.last_mut() {
|
||||
Some(grp) => grp.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
@@ -232,6 +260,184 @@ fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary {
|
||||
lib
|
||||
}
|
||||
|
||||
/// `.ase`, from public descriptions of the format: the layout from
|
||||
/// <https://www.selapa.net/swatches/colors/fileformats.php>, the component ranges from
|
||||
/// <https://github.com/nsfmc/swatch>. After the signature come, big-endian, a `u16` major (1) and
|
||||
/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and
|
||||
/// the body. A group start's body is a name. A color's body is a name, a four-character model
|
||||
/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16`
|
||||
/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a
|
||||
/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness
|
||||
/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero
|
||||
/// included, then the units.
|
||||
///
|
||||
/// Color groups become groups: a group start inside an open group ends that group, and a group
|
||||
/// left open ends with the file. Blocks of other types and colors in other models are skipped.
|
||||
/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or
|
||||
/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than
|
||||
/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error.
|
||||
fn read_ase(bytes: &[u8], fallback: &str) -> Result<SwatchLibrary, String> {
|
||||
let mut data = AseData(bytes);
|
||||
data.bytes(ASE_SIGNATURE.len())?;
|
||||
let (major, minor) = (data.u16()?, data.u16()?);
|
||||
if major != 1 {
|
||||
return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"));
|
||||
}
|
||||
let blocks = data.u32()?;
|
||||
let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() };
|
||||
let mut names = UniqueNames::default();
|
||||
let (mut in_group, mut entries) = (false, 0usize);
|
||||
for _ in 0..blocks {
|
||||
let kind = data.u16()?;
|
||||
let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX);
|
||||
let mut body = AseData(data.bytes(len)?);
|
||||
if matches!(kind, ASE_GROUP_START | ASE_COLOR) {
|
||||
entries += 1;
|
||||
if entries > ASE_MAX_ENTRIES {
|
||||
return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups"));
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] });
|
||||
in_group = true;
|
||||
}
|
||||
ASE_GROUP_END => in_group = false,
|
||||
ASE_COLOR => {
|
||||
let Some(mut w) = ase_swatch(&mut body)? else { continue };
|
||||
w.name = names.unique(std::mem::take(&mut w.name));
|
||||
match lib.groups.last_mut().filter(|_| in_group) {
|
||||
Some(g) => g.swatches.push(w),
|
||||
None => lib.swatches.push(w),
|
||||
}
|
||||
}
|
||||
// Other blocks are skipped.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(lib)
|
||||
}
|
||||
|
||||
/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray.
|
||||
/// Components are clamped to their ranges.
|
||||
fn ase_swatch(body: &mut AseData) -> Result<Option<Swatch>, String> {
|
||||
let name = body.name()?;
|
||||
let unit = |v: f32| v.clamp(0.0, 1.0);
|
||||
let color = match &body.array::<4>()? {
|
||||
b"RGB " => {
|
||||
let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::rgb(unit(r), unit(g), unit(b))
|
||||
}
|
||||
b"CMYK" => {
|
||||
let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?];
|
||||
Color::cmyk(unit(c), unit(m), unit(y), unit(k))
|
||||
}
|
||||
// Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a
|
||||
// value above 1.
|
||||
b"LAB " => {
|
||||
let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?];
|
||||
let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 };
|
||||
Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0))
|
||||
}
|
||||
// A gray level (1 is white); a gray color holds its ink.
|
||||
b"Gray" => Color::gray(1.0 - unit(body.f32()?)),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
// Some writers leave the color type out, which makes a process color.
|
||||
let kind = if body.0.len() >= 2 { body.u16()? } else { 2 };
|
||||
// Spot colors are global.
|
||||
let (global, spot) = match kind {
|
||||
0 => (true, false),
|
||||
1 => (true, true),
|
||||
_ => (false, false),
|
||||
};
|
||||
let name = if name.is_empty() { value_name(color) } else { name };
|
||||
Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot }))
|
||||
}
|
||||
|
||||
/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0",
|
||||
/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30").
|
||||
fn value_name(c: Color) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
let byte = |v: f32| (v * 255.0).round();
|
||||
match c {
|
||||
Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)),
|
||||
Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)),
|
||||
Color::Gray { k } => format!("Gray K={}", pct(k)),
|
||||
// `+ 0.0` turns a rounded -0 into 0.
|
||||
Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// `.ase` data, read field by field; reading past its end is an error.
|
||||
struct AseData<'a>(&'a [u8]);
|
||||
|
||||
impl<'a> AseData<'a> {
|
||||
fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(head)
|
||||
}
|
||||
fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>().ok_or(ASE_CUT_SHORT)?;
|
||||
self.0 = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16, String> {
|
||||
self.array().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
self.array().map(u32::from_be_bytes)
|
||||
}
|
||||
/// A component; one that isn't a finite number reads as 0.
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
let v = f32::from_be_bytes(self.array()?);
|
||||
Ok(if v.is_finite() { v } else { 0.0 })
|
||||
}
|
||||
/// A name up to its terminating zero, trimmed. A block that ends before it has no name.
|
||||
fn name(&mut self) -> Result<String, String> {
|
||||
if self.0.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(self.u16()?);
|
||||
let (units, _) = self.bytes(n * 2)?.as_chunks::<2>();
|
||||
let units: Vec<u16> = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect();
|
||||
Ok(String::from_utf16_lossy(&units).trim().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's name as a file gives it, trimmed; "Color Group" when it has none.
|
||||
fn group_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
if name.is_empty() { "Color Group".into() } else { name.to_string() }
|
||||
}
|
||||
|
||||
/// The swatch and group names a reader has handed out. Swatches and color groups share one set of
|
||||
/// names, as in a document, and a name already taken gets the first free number ("Black 2").
|
||||
#[derive(Default)]
|
||||
struct UniqueNames {
|
||||
taken: HashSet<String>,
|
||||
/// The last number tried for each repeated name.
|
||||
last: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl UniqueNames {
|
||||
fn unique(&mut self, base: String) -> String {
|
||||
if self.taken.insert(base.clone()) {
|
||||
return base;
|
||||
}
|
||||
// Each pass tries the next number, and only finitely many names are taken.
|
||||
let n = self.last.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let name = format!("{base} {n}");
|
||||
if self.taken.insert(name.clone()) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -294,6 +500,11 @@ mod tests {
|
||||
assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]);
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255)));
|
||||
assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback");
|
||||
// Colors and groups share names; an unnamed group is "Color Group".
|
||||
let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap();
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -321,4 +532,117 @@ mod tests {
|
||||
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks` (type, body).
|
||||
fn ase(blocks: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in blocks {
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend((body.len() as u32).to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it.
|
||||
fn ase_name(name: &str) -> Vec<u8> {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut out = (units.len() as u16).to_be_bytes().to_vec();
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
out
|
||||
}
|
||||
|
||||
/// A color block: name, model, components and color type.
|
||||
fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec<u8>) {
|
||||
let mut body = ase_name(name);
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
(ASE_COLOR, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_reads_color_models_kinds_and_groups() {
|
||||
let bytes = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2),
|
||||
]);
|
||||
assert!(sniff_bytes(&bytes));
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let expected = SwatchLibrary {
|
||||
name: "Brand".into(),
|
||||
swatches: vec![
|
||||
sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false),
|
||||
sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true),
|
||||
sw("Paper", Color::WHITE, false, false),
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)],
|
||||
}],
|
||||
};
|
||||
assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process");
|
||||
// A lightness above 1 is L* itself.
|
||||
let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap();
|
||||
assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0)));
|
||||
// Text libraries read through the same call, also when they aren't valid UTF-8.
|
||||
assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0]));
|
||||
assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1);
|
||||
let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n";
|
||||
assert!(sniff_bytes(latin1));
|
||||
assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() {
|
||||
let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2);
|
||||
untyped.1.truncate(untyped.1.len() - 2);
|
||||
let bytes = ase(&[
|
||||
ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2),
|
||||
ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0),
|
||||
ase_color("Red", b"Gray", &[0.0], 2),
|
||||
untyped,
|
||||
ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2),
|
||||
(0x0042, vec![1, 2, 3]),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("")),
|
||||
(ASE_GROUP_START, ase_name("Red")),
|
||||
ase_color("Red", b"Gray", &[1.0], 2),
|
||||
]);
|
||||
let lib = read_bytes(&bytes, "x").unwrap();
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped");
|
||||
assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0");
|
||||
assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process");
|
||||
// A group start ends the open group, and groups and colors share names.
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]);
|
||||
assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_ase_files_are_errors() {
|
||||
let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]);
|
||||
assert_eq!(read_bytes(&good, "x").unwrap().len(), 1);
|
||||
for n in ASE_SIGNATURE.len()..good.len() {
|
||||
assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}");
|
||||
}
|
||||
let mut v2 = good.clone();
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0");
|
||||
// Too many colors, or too many groups (empty group starts take 6 bytes each).
|
||||
let colors: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect();
|
||||
assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than"));
|
||||
let groups: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect();
|
||||
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
|
||||
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -44,6 +44,8 @@ impl Hit {
|
||||
/// Options for hit testing.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct HitOptions {
|
||||
/// The isolated construction container, whose retained Shaper sources are hittable.
|
||||
pub scope: Option<NodeId>,
|
||||
/// Tolerance in document units (screen tolerance / zoom).
|
||||
pub tol: f64,
|
||||
/// Outline mode: only outlines are hittable.
|
||||
@@ -58,7 +60,7 @@ pub struct HitOptions {
|
||||
|
||||
impl Default for HitOptions {
|
||||
fn default() -> Self {
|
||||
Self { tol: 3.0, outline: false, path_only: false, type_path_only: false }
|
||||
Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, scope: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +72,7 @@ pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option<Hit> {
|
||||
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
|
||||
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
|
||||
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
|
||||
let mut tops: Vec<NodeId> = vec![];
|
||||
// Each round leaves out the objects found so far (and everything inside them).
|
||||
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id)).map(|h| h.top_object(scope)) {
|
||||
@@ -131,13 +134,20 @@ fn hit_children(parent: &Node, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for c in children.iter().rev() {
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
if parent.shaper.is_some() {
|
||||
let construction = children.first().is_some_and(|source| Some(source.id) == opt.scope);
|
||||
if (i == 0) != construction {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Hidden, locked and template sublayers block clicks like top-level layers do.
|
||||
if !c.visible || c.locked || c.is_template() || skip(c.id) {
|
||||
continue;
|
||||
}
|
||||
// (An envelope's content sits where it was, not where the envelope draws it.)
|
||||
if !edits_contents(c)
|
||||
if !(edits_contents(c)
|
||||
|| c.shaper.is_some() && c.children().and_then(|children| children.first()).is_some_and(|source| Some(source.id) == opt.scope))
|
||||
&& let Some(b) = c.reach_bounds()
|
||||
&& !b.inflate(opt.tol, opt.tol).contains(p)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Inline graphics in text ([`crate::TextRun::inline`]): resolving each inline symbol's art bounds
|
||||
//! from the document's symbols, which the text layout needs to size and place it.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::{Document, NodeId, NodeKind, TextObject};
|
||||
|
||||
/// The document key under which the app records each symbol's natural size (`{name: [w, h]}`).
|
||||
pub const SYMBOL_SIZES: &str = "symbolSizes";
|
||||
/// Half the side of the square symbol art is normalised to.
|
||||
pub const SYMBOL_HALF: f64 = 10.0;
|
||||
|
||||
/// Usable art bounds: finite, non-degenerate.
|
||||
fn usable(r: Option<Rect>) -> Option<Rect> {
|
||||
r.filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) && r.width() >= 0.0 && r.height() > 1e-9)
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Symbol space → the symbol's art at its natural size. Symbols made in the app keep their
|
||||
/// art in a 20 × 20 square around the origin and their size as drawn in the document's
|
||||
/// `symbolSizes` (an instance is placed with that scale); other symbols are as they are.
|
||||
pub fn symbol_natural_xf(&self, name: &str) -> Affine {
|
||||
let size = self.unknown.get(SYMBOL_SIZES).and_then(|m| m.get(name)).and_then(|v| Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)));
|
||||
match size {
|
||||
Some((w, h)) if w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 => {
|
||||
Affine::scale_non_uniform(w / (2.0 * SYMBOL_HALF), h / (2.0 * SYMBOL_HALF))
|
||||
}
|
||||
_ => Affine::IDENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds of the art of the symbol named `name` at its natural size (see
|
||||
/// [`Self::symbol_natural_xf`]), if it exists and has a usable extent.
|
||||
pub fn symbol_art_bounds(&self, name: &str) -> Option<Rect> {
|
||||
let s = self.symbols.iter().find(|s| s.name == name)?;
|
||||
let b = usable(s.art.visual_bounds().or_else(|| s.art.geometric_bounds()))?;
|
||||
usable(Some(self.symbol_natural_xf(name).transform_rect_bbox(b)))
|
||||
}
|
||||
|
||||
/// Does `t` have inline graphics whose resolved bounds differ from the document's symbols?
|
||||
fn inline_stale(&self, t: &TextObject) -> bool {
|
||||
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != self.symbol_art_bounds(&a.symbol))
|
||||
}
|
||||
|
||||
/// `t` with its inline graphics' art bounds resolved from this document's symbols (borrowed
|
||||
/// when nothing changes). Renderers and exporters lay text out through this, so they never
|
||||
/// depend on the cached bounds being current.
|
||||
pub fn inline_resolved<'a>(&self, t: &'a TextObject) -> Cow<'a, TextObject> {
|
||||
if !self.inline_stale(t) {
|
||||
return Cow::Borrowed(t);
|
||||
}
|
||||
let mut t = t.clone();
|
||||
self.resolve_text_inline(&mut t);
|
||||
Cow::Owned(t)
|
||||
}
|
||||
|
||||
/// Fill in the art bounds of `t`'s inline graphics; returns whether any changed (the text's
|
||||
/// cached layout bounds are then cleared).
|
||||
pub fn resolve_text_inline(&self, t: &mut TextObject) -> bool {
|
||||
let mut changed = false;
|
||||
for r in &mut t.runs {
|
||||
if let Some(a) = &mut r.inline {
|
||||
let b = self.symbol_art_bounds(&a.symbol);
|
||||
if a.bounds != b {
|
||||
a.bounds = b;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
t.cached_bounds = None;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Resolve the inline graphics of every text object in the layers (after opening a document
|
||||
/// or changing its symbols). Returns the ids of the texts that changed: their cached layout
|
||||
/// bounds were cleared and need recomputing.
|
||||
pub fn resolve_inline_art(&mut self) -> Vec<NodeId> {
|
||||
let mut stale = vec![];
|
||||
self.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& t.runs.iter().any(|r| r.inline.is_some())
|
||||
&& self.inline_stale(t)
|
||||
{
|
||||
stale.push(n.id);
|
||||
}
|
||||
});
|
||||
let mut out = vec![];
|
||||
for id in stale {
|
||||
let Some(mut t) = self.node(id).and_then(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.clone()),
|
||||
_ => None,
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if self.resolve_text_inline(&mut t)
|
||||
&& let Some(n) = self.node_mut(id)
|
||||
{
|
||||
n.kind = NodeKind::Text(t);
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -14,6 +14,8 @@ pub mod corners;
|
||||
pub mod graph;
|
||||
pub mod hit;
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
|
||||
pub mod links;
|
||||
pub mod live;
|
||||
pub mod marks;
|
||||
@@ -33,6 +35,7 @@ mod reach;
|
||||
pub mod recolor;
|
||||
pub mod selection;
|
||||
pub mod setup;
|
||||
pub mod shaper;
|
||||
pub mod slices;
|
||||
pub mod style_libs;
|
||||
pub mod swatches;
|
||||
@@ -82,8 +85,9 @@ pub use setup::{Background, DocSetup, ExportText, GridSize, Quotes};
|
||||
pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOptions, SliceSource};
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::{
|
||||
AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle,
|
||||
PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, FirstBaseline, InlineArt, Justify, LeadingModel, Mojikumi,
|
||||
ParaDirection, ParaStyle, PathAlign, PathEffect, ScriptMetrics, TabAlign, TabStop, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use vectorcraft_color as color;
|
||||
pub use vectorcraft_geom as geom;
|
||||
@@ -606,6 +610,11 @@ pub struct Document {
|
||||
/// save time only, so changing the view never marks the document modified.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_view: Option<SavedView>,
|
||||
/// The layers, sublayers and groups open in the Layers panel when the document was saved; they
|
||||
/// reopen that way. `None`: the default, only the top-level layers open. Written at save time
|
||||
/// only, like [`Document::last_view`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layers_open: Option<Vec<NodeId>>,
|
||||
/// Edit → Assign Profile: the profiles the document is tagged with (files before format v3
|
||||
/// kept them in `unknown`, see [`Document::migrate_color_profiles`]).
|
||||
#[serde(default, skip_serializing_if = "ColorProfiles::is_empty")]
|
||||
@@ -698,6 +707,7 @@ impl Document {
|
||||
metadata: DocMetadata::default(),
|
||||
raster_effects: RasterEffectsSettings::default(),
|
||||
last_view: None,
|
||||
layers_open: None,
|
||||
color_profiles: ColorProfiles::default(),
|
||||
export_settings: Default::default(),
|
||||
extra: Default::default(),
|
||||
|
||||
+11
-2
@@ -472,6 +472,9 @@ pub struct Node {
|
||||
/// Graph object: the group's children are generated from this spec (Object → Graph).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub graph: Option<Box<crate::graph::GraphSpec>>,
|
||||
/// Editable Shaper composition; the original art is retained in its source child.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub shaper: Option<Box<crate::shaper::ShaperSpec>>,
|
||||
pub kind: NodeKind,
|
||||
/// The [`crate::GraphicStyle::id`] last applied to this object. It stays linked while it keeps
|
||||
/// that style's look: editing its appearance or transparency breaks the link.
|
||||
@@ -536,6 +539,7 @@ impl Node {
|
||||
trace: None,
|
||||
wrap: None,
|
||||
graph: None,
|
||||
shaper: None,
|
||||
kind,
|
||||
graphic_style: None,
|
||||
attrs: None,
|
||||
@@ -707,6 +711,7 @@ impl Node {
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => children
|
||||
.iter()
|
||||
.skip(usize::from(self.shaper.is_some()))
|
||||
.filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. }))
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds())),
|
||||
NodeKind::Text(t) => self.projected(t.bounds()),
|
||||
@@ -738,7 +743,11 @@ impl Node {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
// The container's own strokes paint around its members.
|
||||
let o = self.appearance.outset();
|
||||
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual_bounds())).map(|b| b.inflate(o, o))
|
||||
children
|
||||
.iter()
|
||||
.skip(usize::from(self.shaper.is_some()))
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual_bounds()))
|
||||
.map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Blend { children, spec } => {
|
||||
let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual_bounds()));
|
||||
@@ -965,7 +974,7 @@ impl Node {
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter().filter(|c| c.visible) {
|
||||
for c in children.iter().skip(usize::from(self.shaper.is_some())).filter(|c| c.visible) {
|
||||
c.push_clip_shapes(text, out);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Persistent Shaper edits over retained source paths. Source indices (not document ids) keep
|
||||
//! recipes valid when a group is copied. Selector anchors use source-relative bounding boxes,
|
||||
//! so the intended face or stroke follows source art when it moves or resizes.
|
||||
use crate::Appearance;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
pub const SOURCES: &str = "Shaper Sources";
|
||||
pub const FILL_PREFIX: &str = "Shaper Fill ";
|
||||
pub const STROKE_PREFIX: &str = "Shaper Stroke ";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ShaperSpec {
|
||||
pub faces: Vec<FaceEdit>,
|
||||
pub edges: Vec<EdgeEdit>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FaceSelector {
|
||||
pub sources: Vec<usize>,
|
||||
pub anchor: Point,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FaceEdit {
|
||||
pub selector: FaceSelector,
|
||||
pub erase: bool,
|
||||
pub erase_edges: bool,
|
||||
pub paint_source: Option<usize>,
|
||||
pub merge: Option<u64>,
|
||||
pub paint: Option<Appearance>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct EdgeEdit {
|
||||
pub source: usize,
|
||||
pub sides: [Vec<usize>; 2],
|
||||
pub anchor: Point,
|
||||
pub erase: bool,
|
||||
pub paint: Option<Appearance>,
|
||||
}
|
||||
+290
-3
@@ -93,8 +93,9 @@ pub struct CharStyle {
|
||||
}
|
||||
|
||||
/// Where a character smaller than the largest on its line lines up with it: on the Roman
|
||||
/// baseline, or at the top (right, in vertical type), centre or bottom (left) of the ideographic
|
||||
/// em boxes.
|
||||
/// baseline, at the top (right, in vertical type), centre or bottom (left) of the ideographic
|
||||
/// em boxes, or at the top (right) or bottom (left) of the ideographic character faces (ICF, the
|
||||
/// average box of the ideographs inside the em box: OpenType's `icft` and `icfb` baselines).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CharAlign {
|
||||
@@ -103,6 +104,8 @@ pub enum CharAlign {
|
||||
EmBoxTop,
|
||||
EmBoxCenter,
|
||||
EmBoxBottom,
|
||||
IcfTop,
|
||||
IcfBottom,
|
||||
}
|
||||
|
||||
/// Superscript or subscript proportions in percent of the font size (Document Setup → Type).
|
||||
@@ -664,6 +667,9 @@ pub struct AreaOptions {
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column.
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub fit: AreaFit,
|
||||
}
|
||||
|
||||
impl Default for AreaOptions {
|
||||
@@ -676,6 +682,67 @@ impl Default for AreaOptions {
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
fit: AreaFit::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How area type and its frame fit each other. Serialized as `"none"`, `"autoHeight"` or
|
||||
/// `{"shrinkText": {"minPercent": 50}}`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AreaFit {
|
||||
/// The frame keeps its size; text that doesn't fit overflows.
|
||||
#[default]
|
||||
None,
|
||||
/// The frame's height follows the text (Illustrator's Auto Size): resolved by the engine after
|
||||
/// each edit, for rectangular frames of horizontal type in one row.
|
||||
AutoHeight,
|
||||
/// Text that overflows is scaled down (size, leading and baseline shift; not paragraph
|
||||
/// spacing) by the largest factor down to `min_percent` % that makes it fit, at layout time.
|
||||
ShrinkText {
|
||||
#[serde(rename = "minPercent", default = "AreaFit::default_min_percent")]
|
||||
min_percent: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AreaFit {
|
||||
/// The smallest Shrink Text to Fit percentage allowed.
|
||||
pub const MIN_PERCENT: f64 = 10.0;
|
||||
/// The Shrink Text to Fit percentage new settings start with.
|
||||
pub const DEFAULT_MIN_PERCENT: f64 = 50.0;
|
||||
fn default_min_percent() -> f64 {
|
||||
Self::DEFAULT_MIN_PERCENT
|
||||
}
|
||||
/// Its id: `none`, `autoHeight` or `shrinkText`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AreaFit::None => "none",
|
||||
AreaFit::AutoHeight => "autoHeight",
|
||||
AreaFit::ShrinkText { .. } => "shrinkText",
|
||||
}
|
||||
}
|
||||
/// The fit an id names (case, spaces, dashes and underscores ignored), with `min_percent`
|
||||
/// for Shrink Text (clamped to 10..100; a non-finite value gives the default).
|
||||
pub fn parse(id: &str, min_percent: Option<f64>) -> Option<Self> {
|
||||
match id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
|
||||
"none" | "off" => Some(AreaFit::None),
|
||||
"autoheight" | "autosize" => Some(AreaFit::AutoHeight),
|
||||
"shrinktext" | "shrinktexttofit" | "shrink" => {
|
||||
Some(AreaFit::ShrinkText { min_percent: Self::clamp_percent(min_percent.unwrap_or(Self::DEFAULT_MIN_PERCENT)) })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A Shrink Text minimum percentage within 10..100 (the default when not finite).
|
||||
pub fn clamp_percent(p: f64) -> f64 {
|
||||
if p.is_finite() { p.clamp(Self::MIN_PERCENT, 100.0) } else { Self::DEFAULT_MIN_PERCENT }
|
||||
}
|
||||
/// Shrink Text's minimum scale factor (0.1..1), if this is Shrink Text.
|
||||
pub fn min_scale(self) -> Option<f64> {
|
||||
match self {
|
||||
AreaFit::ShrinkText { min_percent } => Some(Self::clamp_percent(min_percent) / 100.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -694,6 +761,70 @@ pub struct TextStyleDef {
|
||||
pub struct TextRun {
|
||||
pub text: String,
|
||||
pub style: CharStyle,
|
||||
/// An inline graphic: the run is one [`INLINE_CHAR`] drawn as a document symbol that flows
|
||||
/// with the text like a glyph (InDesign-style inline anchored object). Its `style` still sets
|
||||
/// the size and tracking; fills and strokes don't apply to the art.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub inline: Option<InlineArt>,
|
||||
}
|
||||
|
||||
impl TextRun {
|
||||
/// A plain text run.
|
||||
pub fn new(text: impl Into<String>, style: CharStyle) -> Self {
|
||||
Self { text: text.into(), style, inline: None }
|
||||
}
|
||||
/// An inline graphic run showing `art`.
|
||||
pub fn inline(art: InlineArt, style: CharStyle) -> Self {
|
||||
Self { text: INLINE_CHAR.to_string(), style, inline: Some(art) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The object replacement character: the plain text of an inline graphic run.
|
||||
pub const INLINE_CHAR: char = '\u{FFFC}';
|
||||
|
||||
/// Largest inline graphic scale (× the run's size) accepted from input.
|
||||
pub const INLINE_MAX_SCALE: f64 = 100.0;
|
||||
|
||||
/// A document symbol placed inline in text ([`TextRun::inline`]).
|
||||
///
|
||||
/// Placement: the art is scaled uniformly so its height (visual bounds) is `scale` × the run's
|
||||
/// font size, its left edge at the pen position, and its vertical centre on the middle of the
|
||||
/// run's cap height, raised by `baseline_shift` (points, positive = up). Centred on the cap
|
||||
/// height the art lines up with capitals and figures (like a mana symbol in rules text) and, at
|
||||
/// the default scale, stays inside the font's ascent and descent so the leading doesn't change.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InlineArt {
|
||||
/// Name of the document symbol ([`crate::Symbol::name`]).
|
||||
pub symbol: String,
|
||||
/// Art height as a multiple of the run's font size.
|
||||
#[serde(default = "one")]
|
||||
pub scale: f64,
|
||||
/// Extra raise in points (positive = up).
|
||||
#[serde(default)]
|
||||
pub baseline_shift: f64,
|
||||
/// The symbol art's visual bounds at its natural size, resolved from the document's symbols by
|
||||
/// [`crate::Document::resolve_inline_art`] (not saved). `None`: not resolved or missing; the
|
||||
/// layout then reserves a one-em square and nothing is drawn.
|
||||
#[serde(skip)]
|
||||
pub bounds: Option<Rect>,
|
||||
}
|
||||
|
||||
fn one() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
impl InlineArt {
|
||||
pub fn new(symbol: impl Into<String>) -> Self {
|
||||
Self { symbol: symbol.into(), scale: 1.0, baseline_shift: 0.0, bounds: None }
|
||||
}
|
||||
/// `scale`, made finite and positive (untrusted input).
|
||||
pub fn safe_scale(&self) -> f64 {
|
||||
if self.scale.is_finite() && self.scale > 0.0 { self.scale.min(INLINE_MAX_SCALE) } else { 1.0 }
|
||||
}
|
||||
/// `baseline_shift`, made finite (untrusted input).
|
||||
pub fn safe_shift(&self) -> f64 {
|
||||
if self.baseline_shift.is_finite() { self.baseline_shift.clamp(-1e5, 1e5) } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -748,6 +879,11 @@ fn reverse_from_end(path: &mut PathData) {
|
||||
}
|
||||
|
||||
/// A text object. `runs` split into paragraphs at `\n`.
|
||||
///
|
||||
/// Paragraph attributes: `para` is paragraph 0's (and, while `paras` is empty, every
|
||||
/// paragraph's). Invariant (kept by [`TextObject::normalize_paras`]): `paras` is either empty —
|
||||
/// every paragraph uses `para` — or holds one style per paragraph with `paras[0] == para` and at
|
||||
/// least two different styles. Readers that only know `para` see the first paragraph's style.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextObject {
|
||||
/// Top-to-bottom, right-to-left writing. Defaults to horizontal for old documents.
|
||||
@@ -759,6 +895,9 @@ pub struct TextObject {
|
||||
pub runs: Vec<TextRun>,
|
||||
#[serde(default)]
|
||||
pub para: ParaStyle,
|
||||
/// Per-paragraph attributes (see the type's docs); empty = every paragraph uses `para`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paras: Vec<ParaStyle>,
|
||||
/// Area Type Options (area type only).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub area: AreaOptions,
|
||||
@@ -791,8 +930,9 @@ impl TextObject {
|
||||
vertical: false,
|
||||
kind: TextKind::Point,
|
||||
xf: Affine::translate(origin.to_vec2()),
|
||||
runs: vec![TextRun { text: text.into(), style }],
|
||||
runs: vec![TextRun::new(text, style)],
|
||||
para: ParaStyle::default(),
|
||||
paras: Vec::new(),
|
||||
area: AreaOptions::default(),
|
||||
path_effect: PathEffect::default(),
|
||||
path_align: PathAlign::default(),
|
||||
@@ -805,6 +945,103 @@ impl TextObject {
|
||||
pub fn plain_text(&self) -> String {
|
||||
self.runs.iter().map(|r| r.text.as_str()).collect()
|
||||
}
|
||||
/// Number of paragraphs (`\n`-separated; empty text has one).
|
||||
pub fn paragraph_count(&self) -> usize {
|
||||
1 + self.runs.iter().map(|r| r.text.bytes().filter(|&b| b == b'\n').count()).sum::<usize>()
|
||||
}
|
||||
/// Attributes of paragraph `i` (the last paragraph's past the end).
|
||||
pub fn para_at(&self, i: usize) -> &ParaStyle {
|
||||
self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para)
|
||||
}
|
||||
/// Every paragraph's attributes, one per paragraph.
|
||||
pub fn paragraph_styles(&self) -> Vec<ParaStyle> {
|
||||
(0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect()
|
||||
}
|
||||
/// Set every paragraph's attributes from `styles` (one per paragraph; a short list repeats its
|
||||
/// last entry, a long one is cut).
|
||||
pub fn set_paragraph_styles(&mut self, styles: Vec<ParaStyle>) {
|
||||
if let Some(first) = styles.first() {
|
||||
self.para = first.clone();
|
||||
}
|
||||
self.paras = styles;
|
||||
self.normalize_paras();
|
||||
}
|
||||
/// The same attributes for every paragraph.
|
||||
pub fn set_all_paras(&mut self, style: ParaStyle) {
|
||||
self.para = style;
|
||||
self.paras.clear();
|
||||
}
|
||||
/// Re-establish the `paras` invariant: one entry per paragraph (cut, or extended with the
|
||||
/// last), `paras[0] == para`, and empty when every paragraph is alike.
|
||||
pub fn normalize_paras(&mut self) {
|
||||
if self.paras.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = self.paragraph_count();
|
||||
let last = self.paras.last().cloned().unwrap_or_default();
|
||||
self.paras.resize(n, last);
|
||||
if let Some(first) = self.paras.first_mut() {
|
||||
first.clone_from(&self.para);
|
||||
}
|
||||
if self.paras.iter().all(|p| *p == self.para) {
|
||||
self.paras.clear();
|
||||
}
|
||||
}
|
||||
/// Indices of the paragraphs that byte range `start..end` of the plain text touches (a caret
|
||||
/// touches its paragraph).
|
||||
pub fn paragraphs_in(&self, start: usize, end: usize) -> std::ops::Range<usize> {
|
||||
let text = self.plain_text();
|
||||
let (a, b) = (start.min(end).min(text.len()), start.max(end).min(text.len()));
|
||||
let index = |byte: usize| text.as_bytes().get(..byte).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count());
|
||||
index(a)..index(b) + 1
|
||||
}
|
||||
/// Apply `f` to the attributes of paragraphs `range` (indices; None = every paragraph).
|
||||
pub fn edit_paras(&mut self, range: Option<std::ops::Range<usize>>, mut f: impl FnMut(&mut ParaStyle)) {
|
||||
match range {
|
||||
None => {
|
||||
f(&mut self.para);
|
||||
for p in &mut self.paras {
|
||||
f(p);
|
||||
}
|
||||
}
|
||||
Some(r) => {
|
||||
let mut v = self.paragraph_styles();
|
||||
for p in v.iter_mut().take(r.end).skip(r.start) {
|
||||
f(p);
|
||||
}
|
||||
self.set_paragraph_styles(v);
|
||||
}
|
||||
}
|
||||
self.normalize_paras();
|
||||
}
|
||||
/// Every stored paragraph style (`para` and the per-paragraph ones), for scans and renames.
|
||||
pub fn para_styles_mut(&mut self) -> impl Iterator<Item = &mut ParaStyle> {
|
||||
std::iter::once(&mut self.para).chain(self.paras.iter_mut())
|
||||
}
|
||||
/// Every stored paragraph style (`para` and the per-paragraph ones).
|
||||
pub fn para_styles(&self) -> impl Iterator<Item = &ParaStyle> {
|
||||
std::iter::once(&self.para).chain(self.paras.iter())
|
||||
}
|
||||
/// Update the paragraph styles for replacing bytes `start..end` of the current plain text by
|
||||
/// `insert` (call before changing the runs). The paragraph the range starts in keeps its
|
||||
/// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that
|
||||
/// style too (Return continues the paragraph it splits); later paragraphs keep theirs.
|
||||
pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) {
|
||||
if self.paras.is_empty() {
|
||||
return;
|
||||
}
|
||||
let r = self.paragraphs_in(start, end);
|
||||
let v = self.paragraph_styles();
|
||||
let Some(keep) = v.get(r.start).cloned() else { return };
|
||||
let added = insert.bytes().filter(|&b| b == b'\n').count();
|
||||
let mut out: Vec<ParaStyle> = v.iter().take(r.start + 1).cloned().collect();
|
||||
out.extend(std::iter::repeat_n(keep, added));
|
||||
out.extend(v.iter().skip(r.end).cloned());
|
||||
self.paras = out;
|
||||
if let Some(first) = self.paras.first() {
|
||||
self.para = first.clone();
|
||||
}
|
||||
}
|
||||
pub fn first_style(&self) -> CharStyle {
|
||||
self.runs.first().map(|r| r.style.clone()).unwrap_or_default()
|
||||
}
|
||||
@@ -932,6 +1169,56 @@ mod tests {
|
||||
assert_eq!(CharStyle::default().effective_leading(), 14.399999999999999);
|
||||
}
|
||||
|
||||
fn justified(j: Justify) -> ParaStyle {
|
||||
ParaStyle { justify: j, ..ParaStyle::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_styles_split_merge_and_normalize() {
|
||||
let mut t = TextObject::point(Point::ZERO, "one\ntwo\nthree", CharStyle::default());
|
||||
assert_eq!((t.paragraph_count(), t.paras.len()), (3, 0), "one style for all: nothing stored");
|
||||
assert_eq!(t.paragraphs_in(0, 0), 0..1);
|
||||
assert_eq!(t.paragraphs_in(4, 4), 1..2);
|
||||
assert_eq!(t.paragraphs_in(2, 9), 0..3);
|
||||
assert_eq!(t.paragraphs_in(99, 99), 2..3, "clamped to the text");
|
||||
t.edit_paras(Some(1..2), |p| p.justify = Justify::Center);
|
||||
let js = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.justify).collect::<Vec<_>>();
|
||||
assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]);
|
||||
// Return inside "two": the new paragraph continues its style.
|
||||
t.splice_paras(5, 5, "\n");
|
||||
t.runs[0].text.insert(5, '\n');
|
||||
assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Left]);
|
||||
// Deleting the break between "one" and "t": the first paragraph's style wins.
|
||||
t.splice_paras(3, 4, "");
|
||||
t.runs[0].text.remove(3);
|
||||
assert_eq!(t.plain_text(), "onet\nwo\nthree");
|
||||
assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left]);
|
||||
// An edit that skips the splice is repaired by normalizing (the last style continues).
|
||||
t.runs[0].text.push_str("\nfour");
|
||||
t.normalize_paras();
|
||||
assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Left, Justify::Left]);
|
||||
// `para` is paragraph 0's; all alike collapses to `para` alone.
|
||||
t.edit_paras(Some(0..1), |p| p.justify = Justify::Right);
|
||||
assert_eq!(t.para.justify, Justify::Right);
|
||||
t.edit_paras(None, |p| p.justify = Justify::Right);
|
||||
assert!(t.paras.is_empty() && t.para.justify == Justify::Right);
|
||||
// A short list repeats its last entry, a long one is cut.
|
||||
t.set_paragraph_styles(vec![justified(Justify::Left), justified(Justify::Center)]);
|
||||
assert_eq!(js(&t), [Justify::Left, Justify::Center, Justify::Center, Justify::Center]);
|
||||
t.set_paragraph_styles(vec![justified(Justify::Center); 9]);
|
||||
assert!(t.paras.is_empty() && t.para.justify == Justify::Center);
|
||||
// Old documents (no `paras`) load; new ones keep paragraph 0 in `para`.
|
||||
t.edit_paras(Some(3..4), |p| p.space_before = 4.0);
|
||||
let json = serde_json::to_value(&t).unwrap();
|
||||
assert_eq!(json["para"]["justify"], json["paras"][0]["justify"]);
|
||||
let mut old = json.clone();
|
||||
old.as_object_mut().unwrap().remove("paras");
|
||||
let back: TextObject = serde_json::from_value(old).unwrap();
|
||||
assert!(back.paras.is_empty() && back.para_at(3).justify == Justify::Center);
|
||||
let back: TextObject = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back.para_at(3).space_before, 4.0);
|
||||
}
|
||||
|
||||
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
|
||||
fn area_type() -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
|
||||
|
||||
@@ -803,9 +803,10 @@ impl Picked {
|
||||
run_attrs(&mut r.style, &placed, ap);
|
||||
}
|
||||
if let Some((_, para)) = text.filter(|_| a.paragraph) {
|
||||
t.para = para.clone();
|
||||
// The source's first paragraph's attributes, on every paragraph.
|
||||
t.set_all_paras(para.clone());
|
||||
}
|
||||
if text.is_some() && a.character {
|
||||
if text.is_some() && (a.character || a.paragraph) {
|
||||
super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -18,10 +18,10 @@ use super::edit::selected_roots;
|
||||
use super::*;
|
||||
use crate::EngineError;
|
||||
|
||||
const SIZES_KEY: &str = "symbolSizes";
|
||||
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
|
||||
const CURRENT_SYMBOL: &str = "currentSymbol";
|
||||
/// Half the instance box `Node::geometric_bounds` uses for symbol instances.
|
||||
const HALF: f64 = 10.0;
|
||||
const HALF: f64 = vectorcraft_doc::SYMBOL_HALF;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, StrokeLayer};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, colors: 2-256, paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines}} → {id, paths, anchors, colors}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\", threshold: 0-255, colors: 2-256, paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite, snapCurvesToLines, fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10)}} → {id, paths, anchors, colors}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -648,7 +648,14 @@ fn trace_params(p: &Value) -> Result<tr::TraceParams> {
|
||||
for (k, val) in src {
|
||||
o.insert(k.clone(), val.clone());
|
||||
}
|
||||
serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))
|
||||
let params: tr::TraceParams = serde_json::from_value(v).map_err(|e| bad("imageTrace.make", e.to_string()))?;
|
||||
if !params.fills && !params.strokes {
|
||||
return Err(bad("imageTrace.make", "Create needs fills, strokes or both"));
|
||||
}
|
||||
if !(params.stroke_width.is_finite() && params.stroke_width > 0.0) {
|
||||
return Err(bad("imageTrace.make", "strokeWidth must be a positive number of pixels"));
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
/// The most anchor points an Image Trace may make: a photo traced at high fidelity can make
|
||||
@@ -692,6 +699,8 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
let sx = img.width.max(1) as f64 / raster.width.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.height.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
let id = s.edit(label, |d, sel| {
|
||||
@@ -714,7 +723,19 @@ fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
|
||||
for tp in res.paths {
|
||||
let path = tp.path.transformed(xf);
|
||||
let mut n = shape_node(d, path, None);
|
||||
n.appearance = fill_only(Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2])));
|
||||
let paint = Paint::solid(Color::rgb8(tp.color[0], tp.color[1], tp.color[2]));
|
||||
n.appearance = match tp.stroke {
|
||||
// Traced lines: round ends and corners, as drawn lines have.
|
||||
Some(width) => Appearance {
|
||||
items: vec![AppearanceItem::Stroke(StrokeLayer {
|
||||
cap: LineCap::Round,
|
||||
join: LineJoin::Round,
|
||||
..StrokeLayer::new(paint, width * unit)
|
||||
})],
|
||||
..Default::default()
|
||||
},
|
||||
None => fill_only(paint),
|
||||
};
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
|
||||
@@ -21,7 +21,7 @@ use vectorcraft_color::Swatch;
|
||||
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef};
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
pub use flavours::{BITMAP, EMF, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour};
|
||||
pub use flavours::{BITMAP, EMF, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address};
|
||||
pub(crate) use resources::SwatchChoices;
|
||||
|
||||
use super::*;
|
||||
@@ -220,6 +220,25 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
/// The address a browser's Copy Image puts next to the picture (#597), and text that isn't one.
|
||||
#[test]
|
||||
fn an_address_alone_is_told_from_other_text() {
|
||||
for a in [
|
||||
"https://example.com/cat.png",
|
||||
" http://x.org/a?b=1
|
||||
",
|
||||
"HTTPS://EXAMPLE.COM",
|
||||
"file:///C:/art/cat.png",
|
||||
"data:image/png;base64,iVBOR",
|
||||
"blob:https://x.org/1",
|
||||
] {
|
||||
assert!(is_address(a), "{a}");
|
||||
}
|
||||
for t in ["Pasted words", "see https://example.com", "https://a.org https://b.org", "https://", "example.com/cat.png", ""] {
|
||||
assert!(!is_address(t), "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_exports_svg_that_round_trips_through_paste() {
|
||||
let mut s = session();
|
||||
@@ -240,6 +259,26 @@ mod tests {
|
||||
assert!((b.width() - 30.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_type_gets_its_layout_bounds_cache() {
|
||||
// Reported from Illustrator: pasted type kept no layout bounds, so its box (and alignment)
|
||||
// fell back to the rough estimate until the file was saved and reopened.
|
||||
let mut s = session();
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="500" height="120"><text x="0" y="80" font-family="Source Sans 3" font-size="40">WWWWWWWW</text></svg>"#;
|
||||
s.execute("clipboard.importSvg", &json!({"svg": svg})).unwrap();
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
let mut checked = 0;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { return };
|
||||
let cached = t.cached_bounds.expect("pasted type computed its bounds");
|
||||
let real = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).bounds;
|
||||
assert!((cached.width() - real.width()).abs() < 1e-6, "{cached:?} {real:?}");
|
||||
assert!(cached.width() > t.estimate_bounds().width() + 1.0, "{cached:?} is just the estimate");
|
||||
checked += 1;
|
||||
});
|
||||
assert_eq!(checked, 1, "one text object pasted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_never_lands_in_an_object_that_reused_an_undone_layers_id() {
|
||||
// Found by the model-based test: undo restores the id counter, so a compound path made
|
||||
|
||||
@@ -30,6 +30,15 @@ pub const EMF: &str = "image/emf";
|
||||
/// What Paste reads from other apps, best first: vector art before text, text before bitmaps
|
||||
/// (word processors offer a picture of copied text too).
|
||||
pub const PASTE_ORDER: [&str; 5] = [SVG, PDF, EMF, TEXT, BITMAP];
|
||||
/// Is `text` only an address (a web page's, an image's, a file's)? A browser's Copy Image puts the
|
||||
/// image's address as text next to the picture: then the picture is what Paste takes (#597). An
|
||||
/// address alone pastes as text, and nothing is fetched.
|
||||
pub fn is_address(text: &str) -> bool {
|
||||
const SCHEMES: [&str; 6] = ["http://", "https://", "file://", "ftp://", "data:", "blob:"];
|
||||
let t = text.trim();
|
||||
!t.chars().any(char::is_whitespace) && SCHEMES.iter().any(|s| t.get(..s.len()).is_some_and(|h| h.eq_ignore_ascii_case(s)) && t.len() > s.len())
|
||||
}
|
||||
|
||||
/// How much of a copied file [`file_flavour`] needs to tell what it is.
|
||||
pub const FILE_HEAD: usize = 4096;
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
f(Ref::Name(Res::CharStyle, s));
|
||||
}
|
||||
}
|
||||
if let Some(s) = &t.para.style_name {
|
||||
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
|
||||
f(Ref::Name(Res::ParaStyle, s));
|
||||
}
|
||||
}
|
||||
@@ -440,8 +440,10 @@ impl Relink {
|
||||
self.name(Res::CharStyle, s);
|
||||
}
|
||||
}
|
||||
if let Some(s) = &mut t.para.style_name {
|
||||
self.name(Res::ParaStyle, s);
|
||||
for pa in t.para_styles_mut() {
|
||||
if let Some(s) = &mut pa.style_name {
|
||||
self.name(Res::ParaStyle, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
|
||||
|
||||
@@ -9,8 +9,16 @@ use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("shape.rectangle", "Rectangle", [], None, "{x, y, width, height, radius?: pt} → {id}", has_doc, rectangle),
|
||||
cmd!("shape.ellipse", "Ellipse", [], None, "{x, y, width, height} → {id}", has_doc, ellipse),
|
||||
cmd!(
|
||||
"shape.rectangle",
|
||||
"Rectangle",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, radius?: pt, rotation?: deg (about centre)} → {id}",
|
||||
has_doc,
|
||||
rectangle
|
||||
),
|
||||
cmd!("shape.ellipse", "Ellipse", [], None, "{x, y, width, height, rotation?: deg (about centre)} → {id}", has_doc, ellipse),
|
||||
cmd!("shape.polygon", "Polygon", [], None, "{cx, cy, radius, sides=6, rotation?: deg} → {id}", has_doc, polygon),
|
||||
cmd!("shape.star", "Star", [], None, "{cx, cy, radius1, radius2, points=5, rotation?: deg} → {id}", has_doc, star),
|
||||
cmd!(
|
||||
@@ -50,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id}",
|
||||
"{x, y, text, vertical?: bool = false, size?: pt, font?: family, style?, color?, area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -163,6 +171,17 @@ fn rect_of(p: &Value, cmd: &str) -> Result<Rect> {
|
||||
Ok(Rect::new(x, y, x + w, y + h).abs())
|
||||
}
|
||||
|
||||
fn rect_transform(r: Rect, p: &Value, cmd: &str) -> Result<Affine> {
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", cmd)? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad(cmd, "rotation must be finite"));
|
||||
}
|
||||
if rotation == 0.0 {
|
||||
return Ok(Affine::translate(r.origin().to_vec2()));
|
||||
}
|
||||
Ok(Affine::translate(r.center().to_vec2()) * Affine::rotate(rotation.to_radians()) * Affine::translate((-r.width() / 2.0, -r.height() / 2.0)))
|
||||
}
|
||||
|
||||
fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = rect_of(p, "shape.rectangle")?;
|
||||
let radius = f64_or(p, "radius", 0.0).max(0.0);
|
||||
@@ -171,7 +190,7 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
h: r.height(),
|
||||
radii: [radius; 4],
|
||||
kinds: Default::default(),
|
||||
xf: Affine::translate(r.origin().to_vec2()),
|
||||
xf: rect_transform(r, p, "shape.rectangle")?,
|
||||
};
|
||||
let label = if radius > 0.0 { "Rounded Rectangle" } else { "Rectangle" };
|
||||
add_art(s, label, path_kind(live.to_path(), Some(live)), None)
|
||||
@@ -179,7 +198,7 @@ fn rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = rect_of(p, "shape.ellipse")?;
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: rect_transform(r, p, "shape.ellipse")? };
|
||||
add_art(s, "Ellipse", path_kind(live.to_path(), Some(live)), None)
|
||||
}
|
||||
|
||||
@@ -415,10 +434,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let w = f64_or(a, "width", 200.0);
|
||||
let h = f64_or(a, "height", 100.0);
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
|
||||
t.area.fit = new_area_fit(s, a, "text.create")?;
|
||||
}
|
||||
if bool_or(p, "placeholder", false) {
|
||||
super::typemenu::fill_with_placeholder(&mut t);
|
||||
} else {
|
||||
// Lays the text out (and sizes an Auto Size frame).
|
||||
super::typecmd::refresh_bounds(&mut t);
|
||||
}
|
||||
add_node(s, "Type", NodeKind::Text(Box::new(t)), Appearance::default(), None)
|
||||
@@ -426,8 +447,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of
|
||||
/// each paragraph's direction (left, right for Hebrew and Arabic), Japanese punctuation composed
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari (as in Illustrator). Imported text
|
||||
/// keeps its own.
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari. Imported text keeps its own.
|
||||
pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
|
||||
vectorcraft_doc::ParaStyle {
|
||||
justify: vectorcraft_doc::Justify::Auto,
|
||||
@@ -471,6 +491,13 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
|
||||
/// them), else Auto Size when the "Auto Size New Area Type" preference is on.
|
||||
pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result<vectorcraft_doc::AreaFit> {
|
||||
let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None };
|
||||
Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
|
||||
}
|
||||
|
||||
/// The character style new type gets: `size`, `font`, `style` and `color` from `p`, else the
|
||||
/// defaults, filled with the current fill unless that is None or white (black then).
|
||||
pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
|
||||
@@ -381,6 +381,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
}
|
||||
}
|
||||
sel.set(new_ids.iter().copied());
|
||||
// Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are
|
||||
// right away (opening the file later would, but paste must not depend on a reopen).
|
||||
super::typecmd::refresh_bounds_of(d, &new_ids);
|
||||
Ok((new_ids, imported, artboard))
|
||||
})?;
|
||||
// The Artboard tool takes the pasted artboard.
|
||||
|
||||
@@ -216,15 +216,20 @@ fn is_svg(f: &Format) -> bool {
|
||||
matches!(f.id, "svg" | "svgz")
|
||||
}
|
||||
|
||||
/// The document as written: native files carry the view to reopen at.
|
||||
/// The document as written: native files carry the view to reopen at and the Layers panel's open
|
||||
/// rows.
|
||||
fn doc_to_save(st: &DocState, f: &Format) -> Arc<Document> {
|
||||
if is_native(f) && st.doc.last_view != st.view {
|
||||
let mut d = (*st.doc).clone();
|
||||
d.last_view = st.view.clone();
|
||||
Arc::new(d)
|
||||
} else {
|
||||
st.doc.clone()
|
||||
if !is_native(f) {
|
||||
return st.doc.clone();
|
||||
}
|
||||
let open = st.layers_open.saved(&st.doc);
|
||||
if st.doc.last_view == st.view && st.doc.layers_open == open {
|
||||
return st.doc.clone();
|
||||
}
|
||||
let mut d = (*st.doc).clone();
|
||||
d.last_view = st.view.clone();
|
||||
d.layers_open = open;
|
||||
Arc::new(d)
|
||||
}
|
||||
|
||||
/// What a format loses against a native file (reported whenever a save writes it).
|
||||
@@ -274,6 +279,7 @@ fn artboard_doc(doc: &Document, i: usize) -> Document {
|
||||
d.artboards = vec![a.clone()];
|
||||
// It opens fitted to its artboard, not at the master file's view.
|
||||
d.last_view = None;
|
||||
d.layers_open = None;
|
||||
for layer in &mut d.layers {
|
||||
keep_on(layer, r);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
//! Inline graphics in text: document symbols placed in a run of text, flowing like a glyph
|
||||
//! (beyond Illustrator; InDesign's inline anchored objects). See [`vectorcraft_doc::InlineArt`].
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::text::INLINE_MAX_SCALE;
|
||||
use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"text.insertInline",
|
||||
"Insert Inline Symbol",
|
||||
["Type"],
|
||||
None,
|
||||
"{id?: text id (default: the text the Type tool edits), at?: byte offset (default: the Type tool's selection, which it replaces; clamped to the text), symbol?: symbol name (default: the Symbols panel's current symbol), scale?: art height ÷ font size = 1 (0 < scale ≤ 100), shift?: pt raise = 0} place a document symbol inline in the text as one character (U+FFFC) that flows like a glyph: its art is scaled to `scale` × the font size tall, its vertical centre on the middle of the cap height raised by `shift`. Typing, Backspace and Delete over it remove it whole → {id, caret}",
|
||||
has_doc,
|
||||
insert_inline
|
||||
)]
|
||||
}
|
||||
|
||||
/// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols,
|
||||
/// resolve the inline art of every text again (only texts whose art changed are touched).
|
||||
pub(crate) fn refresh(before: &Document, d: &mut Document) {
|
||||
if before.symbols.is_empty() && d.symbols.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in d.resolve_inline_art() {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.insertInline";
|
||||
let tool = s.tool_options();
|
||||
let editing = tool.get("editing").and_then(Value::as_u64).map(NodeId);
|
||||
let id = match p.get("id") {
|
||||
None | Some(Value::Null) => editing.ok_or_else(|| bad(C, "give `id` (no text is being edited)"))?,
|
||||
Some(_) => id_param(p, "id").ok_or_else(|| bad(C, "`id` must be a node id"))?,
|
||||
};
|
||||
let doc = &s.doc()?.doc;
|
||||
let NodeKind::Text(t) = &doc.node(id).ok_or(EngineError::NoNode(id))?.kind else {
|
||||
return Err(bad(C, format!("node {} is not text", id.0)));
|
||||
};
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let from_tool = editing == Some(id);
|
||||
let (a, b) = match p.get("at") {
|
||||
None | Some(Value::Null) if from_tool => {
|
||||
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
|
||||
let (x, y) = (g("start"), g("end"));
|
||||
(x.min(y), x.max(y))
|
||||
}
|
||||
None | Some(Value::Null) => (len, len),
|
||||
Some(v) => {
|
||||
let at = v.as_u64().ok_or_else(|| bad(C, "`at` must be a byte offset"))?.min(len as u64) as usize;
|
||||
(at, at)
|
||||
}
|
||||
};
|
||||
let symbol = match str_param(p, "symbol") {
|
||||
Some(n) if doc.symbols.iter().any(|s| s.name == n) => n.to_string(),
|
||||
Some(n) => return Err(bad(C, format!("no symbol named `{n}`"))),
|
||||
None if p.get("symbol").is_some_and(|v| !v.is_null()) => return Err(bad(C, "`symbol` must be a symbol name")),
|
||||
None => current_symbol(doc).ok_or_else(|| EngineError::Other("the document has no symbols".into()))?,
|
||||
};
|
||||
let scale = match p.get("scale") {
|
||||
None | Some(Value::Null) => 1.0,
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|k| k.is_finite() && *k > 0.0 && *k <= INLINE_MAX_SCALE)
|
||||
.ok_or_else(|| bad(C, "`scale` must be a number in (0, 100]"))?,
|
||||
};
|
||||
let shift = match p.get("shift") {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|k| k.is_finite() && k.abs() <= 1e5).ok_or_else(|| bad(C, "`shift` must be a number of points"))?,
|
||||
};
|
||||
// A typing session ends first: the insertion is a step of its own.
|
||||
let typing = tool.get("typing").and_then(Value::as_bool) == Some(true);
|
||||
if typing && from_tool {
|
||||
s.set_tool_option("commitTyping", &Value::Bool(true));
|
||||
s.commit_interaction()?;
|
||||
}
|
||||
let caret = s.edit("Insert Inline Symbol", |d, _| {
|
||||
let mut art = InlineArt { scale, baseline_shift: shift, ..InlineArt::new(symbol.clone()) };
|
||||
art.bounds = d.symbol_art_bounds(&symbol);
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(id)) };
|
||||
let style = edit::insertion_style(&t.runs, a, b);
|
||||
let caret = edit::replace_range_styled(&mut t.runs, a, b, &[TextRun::inline(art, style)]);
|
||||
refresh_bounds(t);
|
||||
Ok(caret)
|
||||
})?;
|
||||
if from_tool {
|
||||
s.set_tool_option("select", &json!({"start": caret, "end": caret}));
|
||||
}
|
||||
Ok(json!({"id": id.0, "caret": caret}))
|
||||
}
|
||||
|
||||
/// The Symbols panel's current symbol, else the first one.
|
||||
fn current_symbol(d: &Document) -> Option<String> {
|
||||
d.unknown
|
||||
.get("currentSymbol")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|n| d.symbols.iter().any(|s| s.name == *n))
|
||||
.map(str::to_string)
|
||||
.or_else(|| d.symbols.first().map(|s| s.name.clone()))
|
||||
}
|
||||
@@ -29,6 +29,7 @@ pub(crate) mod gradient;
|
||||
pub(crate) mod graph;
|
||||
mod halftone;
|
||||
pub mod help;
|
||||
pub(crate) mod inline;
|
||||
mod layer;
|
||||
mod layerpanel;
|
||||
pub mod links;
|
||||
@@ -59,6 +60,7 @@ pub mod rasterfx;
|
||||
mod recolor;
|
||||
pub mod recovery;
|
||||
mod select;
|
||||
pub(crate) mod shaper;
|
||||
pub(crate) mod slices;
|
||||
mod stroke;
|
||||
mod style;
|
||||
@@ -217,6 +219,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(colormgmt::specs());
|
||||
v.extend(typemenu::specs());
|
||||
v.extend(textedit::specs());
|
||||
v.extend(inline::specs());
|
||||
v.extend(textstyles::specs());
|
||||
v.extend(fonts::specs());
|
||||
v.extend(help::specs());
|
||||
@@ -231,6 +234,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(docinfo::specs());
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
v.extend(shaper::specs());
|
||||
v.extend(brushsym::specs());
|
||||
v.extend(patterncmds::specs());
|
||||
v.extend(prefscmds::specs());
|
||||
|
||||
@@ -722,7 +722,8 @@ fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if st.doc.node(id).is_none_or(|n| !n.is_container()) {
|
||||
return Err(bad("object.isolate", "only groups and layers can be isolated"));
|
||||
}
|
||||
st.isolation = Some(id);
|
||||
let isolation = st.doc.node(id).filter(|n| n.shaper.is_some()).and_then(|n| n.children()).and_then(|c| c.first()).map_or(id, |n| n.id);
|
||||
st.isolation = Some(isolation);
|
||||
st.selection.clear();
|
||||
st.revision += 1;
|
||||
ok()
|
||||
@@ -732,7 +733,8 @@ fn exit_isolation(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc_mut()?;
|
||||
if let Some(i) = st.isolation.take() {
|
||||
super::distortcmds::finish_edit_text(st, i);
|
||||
st.selection.set([i]);
|
||||
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.shaper.is_some())).unwrap_or(i);
|
||||
st.selection.set([target]);
|
||||
}
|
||||
st.revision += 1;
|
||||
ok()
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character / Paragraph",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt, hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default)}",
|
||||
"{ids?|id?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), hyphenate?: bool, mojikumi?: \"none\"|\"lineEndHalf\" (Japanese punctuation spacing), direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), composer?: \"singleLine\"|\"everyLine\" (line breaking, Every-line by default), start?: byte, end?: byte} (with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text)",
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
@@ -180,6 +180,9 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
|
||||
fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.setFormat";
|
||||
let ids: Vec<NodeId> = {
|
||||
@@ -268,11 +271,11 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, "`burasagari` must be \"none\", \"standard\" or \"forced\"")),
|
||||
}),
|
||||
};
|
||||
let range = super::typecmd::TextRange::parse(p, C)?;
|
||||
s.edit("Character", |d, _| {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
for r in &mut t.runs {
|
||||
let st = &mut r.style;
|
||||
super::typecmd::style_chars(t, range, |st| {
|
||||
if let Some(k) = kerning {
|
||||
st.kerning = k;
|
||||
}
|
||||
@@ -306,41 +309,43 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = char_align {
|
||||
st.char_align = v;
|
||||
}
|
||||
}
|
||||
let para = &mut t.para;
|
||||
if let Some(v) = num("leftIndent") {
|
||||
para.left_indent = v;
|
||||
}
|
||||
if let Some(v) = num("rightIndent") {
|
||||
para.right_indent = v;
|
||||
}
|
||||
if let Some(v) = num("firstLineIndent") {
|
||||
para.first_line_indent = v;
|
||||
}
|
||||
if let Some(v) = num("spaceBefore") {
|
||||
para.space_before = v;
|
||||
}
|
||||
if let Some(v) = num("spaceAfter") {
|
||||
para.space_after = v;
|
||||
}
|
||||
if let Some(v) = flag("hyphenate") {
|
||||
para.hyphenate = v;
|
||||
}
|
||||
if let Some(v) = mojikumi {
|
||||
para.mojikumi = v;
|
||||
}
|
||||
if let Some(v) = direction {
|
||||
para.direction = v;
|
||||
}
|
||||
if let Some(v) = leading_model {
|
||||
para.leading_model = v;
|
||||
}
|
||||
if let Some(v) = burasagari {
|
||||
para.burasagari = v;
|
||||
}
|
||||
if let Some(v) = composer {
|
||||
para.composer = v;
|
||||
}
|
||||
});
|
||||
let span = super::typecmd::para_span(range, t);
|
||||
t.edit_paras(span, |para| {
|
||||
if let Some(v) = num("leftIndent") {
|
||||
para.left_indent = v.clamp(-MAX_PARA, MAX_PARA);
|
||||
}
|
||||
if let Some(v) = num("rightIndent") {
|
||||
para.right_indent = v.clamp(-MAX_PARA, MAX_PARA);
|
||||
}
|
||||
if let Some(v) = num("firstLineIndent") {
|
||||
para.first_line_indent = v.clamp(-MAX_PARA, MAX_PARA);
|
||||
}
|
||||
if let Some(v) = num("spaceBefore") {
|
||||
para.space_before = v.clamp(-MAX_PARA, MAX_PARA);
|
||||
}
|
||||
if let Some(v) = num("spaceAfter") {
|
||||
para.space_after = v.clamp(-MAX_PARA, MAX_PARA);
|
||||
}
|
||||
if let Some(v) = flag("hyphenate") {
|
||||
para.hyphenate = v;
|
||||
}
|
||||
if let Some(v) = mojikumi {
|
||||
para.mojikumi = v;
|
||||
}
|
||||
if let Some(v) = direction {
|
||||
para.direction = v;
|
||||
}
|
||||
if let Some(v) = leading_model {
|
||||
para.leading_model = v;
|
||||
}
|
||||
if let Some(v) = burasagari {
|
||||
para.burasagari = v;
|
||||
}
|
||||
if let Some(v) = composer {
|
||||
para.composer = v;
|
||||
}
|
||||
});
|
||||
super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
//! Shaper compositions are groups of generated fills/strokes with transparent, editable source
|
||||
//! art retained underneath. Recipes select topology regions; source edits re-evaluate them in
|
||||
//! the same undo transaction. Rendering and exporters only see ordinary groups and paths.
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use vectorcraft_doc::shaper::{EdgeEdit, FILL_PREFIX, FaceEdit, FaceSelector, SOURCES, STROKE_PREFIX, ShaperSpec};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, Shape as _};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_tools::builder::{self as b, BuilderMap, Hit};
|
||||
|
||||
const MAX_SOURCES: usize = 64;
|
||||
const MAX_POINTS: usize = 4096;
|
||||
const MAX_EDITS: usize = 8192;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"shaper.scribble",
|
||||
"Shaper",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…], ids?: [id…] (default: nearby art), tolerance?: pt (4)} interior scribbles remove fills; scribbles through several regions merge with the origin fill; ending outside removes fills and boundary strokes; outside scribbles erase stroke pieces. Originals remain editable → {id, regions, strokes}",
|
||||
has_doc,
|
||||
scribble
|
||||
),
|
||||
cmd!(
|
||||
"shaper.select",
|
||||
"Select Shaper Face",
|
||||
[],
|
||||
None,
|
||||
"{point: [x,y], source?: bool} click selects a group, then a face; source enters construction isolation and selects an original → {id}",
|
||||
has_doc,
|
||||
select
|
||||
),
|
||||
cmd!(
|
||||
"shaper.release",
|
||||
"Release Shaper Group",
|
||||
["Object", "Shaper"],
|
||||
None,
|
||||
"{id? (default: selection)} restore the original paths → {ids}",
|
||||
has_doc,
|
||||
release
|
||||
),
|
||||
cmd!(
|
||||
"shaper.expand",
|
||||
"Expand Shaper Group",
|
||||
["Object", "Shaper"],
|
||||
None,
|
||||
"{id? (default: selection)} keep the visible result as ordinary paths → {id}",
|
||||
has_doc,
|
||||
expand
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn source_group(n: &Node) -> Option<&Node> {
|
||||
n.shaper.as_ref()?;
|
||||
n.children()?.first().map(AsRef::as_ref).filter(|g| g.name.as_deref() == Some(SOURCES))
|
||||
}
|
||||
fn sources(n: &Node) -> Vec<Arc<Node>> {
|
||||
source_group(n).and_then(Node::children).cloned().unwrap_or_default()
|
||||
}
|
||||
fn finite(p: Point) -> bool {
|
||||
p.x.is_finite() && p.y.is_finite() && p.x.abs() <= 1e9 && p.y.abs() <= 1e9
|
||||
}
|
||||
|
||||
fn map_of(src: &[Arc<Node>]) -> Result<BuilderMap> {
|
||||
if src.is_empty() || src.len() > MAX_SOURCES {
|
||||
return Err(bad("shaper.scribble", "Shaper needs 1–64 source paths"));
|
||||
}
|
||||
let mut count = 0usize;
|
||||
let mut shapes = vec![];
|
||||
for (i, n) in src.iter().enumerate() {
|
||||
let (mut path, rule) = b::node_outline(n).ok_or_else(|| bad("shaper.scribble", "use paths or compound paths"))?;
|
||||
count = count.saturating_add(path.subpaths.iter().map(|s| s.segment_count()).sum::<usize>());
|
||||
if count > 4096 || path.subpaths.iter().flat_map(|s| &s.anchors).any(|a| !finite(a.p) || !finite(a.h_in) || !finite(a.h_out)) {
|
||||
return Err(bad("shaper.scribble", "source paths are too large for Shaper"));
|
||||
}
|
||||
if !n.visible {
|
||||
path = PathData::default();
|
||||
} else if !n.appearance.fill_paint().is_none() {
|
||||
for sub in path.subpaths.iter_mut().filter(|s| !s.closed) {
|
||||
sub.closed = po::encloses_area(sub);
|
||||
}
|
||||
}
|
||||
shapes.push(po::Shape::new(path, rule, i as u64));
|
||||
}
|
||||
let arrangement = po::shape_builder(&shapes, true);
|
||||
let bounded = |pieces: Vec<po::Shape>| pieces.into_iter().filter_map(|p| p.path.bounds().map(|b| (p, b))).collect();
|
||||
let regions = arrangement
|
||||
.regions
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let bounds = r.path.bounds()?;
|
||||
let path = r.path.to_bezpath();
|
||||
Some((r, path, bounds))
|
||||
})
|
||||
.collect();
|
||||
let map = BuilderMap { shapes, regions, edges: bounded(arrangement.edges), lines: bounded(arrangement.lines) };
|
||||
if map.regions.is_empty() && map.lines.is_empty() && map.edges.is_empty() {
|
||||
return Err(bad("shaper.scribble", "these paths are too degenerate for Shaper"));
|
||||
}
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
fn relative(src: &[Arc<Node>], i: usize, p: Point) -> Point {
|
||||
let b = src.get(i).and_then(|n| n.geometric_bounds()).unwrap_or(Rect::ZERO);
|
||||
Point::new((p.x - b.x0) / b.width().max(1e-9), (p.y - b.y0) / b.height().max(1e-9))
|
||||
}
|
||||
fn absolute(src: &[Arc<Node>], i: usize, p: Point) -> Point {
|
||||
let b = src.get(i).and_then(|n| n.geometric_bounds()).unwrap_or(Rect::ZERO);
|
||||
Point::new(b.x0 + p.x * b.width(), b.y0 + p.y * b.height())
|
||||
}
|
||||
fn face_selector(map: &BuilderMap, src: &[Arc<Node>], i: usize) -> Option<FaceSelector> {
|
||||
let (r, _, bounds) = map.regions.get(i)?;
|
||||
let source = *r.sources.first()?;
|
||||
let point = po::interior_point(&r.path).unwrap_or(bounds.center());
|
||||
Some(FaceSelector { sources: r.sources.clone(), anchor: relative(src, source, point) })
|
||||
}
|
||||
fn selected_face(map: &BuilderMap, src: &[Arc<Node>], selector: &FaceSelector) -> Option<usize> {
|
||||
let point = absolute(src, *selector.sources.first()?, selector.anchor);
|
||||
map.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (r, _, _))| r.sources == selector.sources)
|
||||
.min_by(|(_, a), (_, b)| {
|
||||
let distance = |r: &b::Face| if r.1.winding(point) != 0 { 0.0 } else { r.2.center().distance(point) };
|
||||
distance(a).total_cmp(&distance(b))
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
fn piece_point(path: &PathData) -> Option<Point> {
|
||||
use vectorcraft_geom::ParamCurve as _;
|
||||
let sub = path.subpaths.first()?;
|
||||
(sub.segment_count() > 0).then(|| sub.segment(sub.segment_count() / 2).eval(0.5))
|
||||
}
|
||||
fn pieces(map: &BuilderMap) -> Vec<&po::Shape> {
|
||||
map.edges.iter().chain(&map.lines).map(|(p, _)| p).collect()
|
||||
}
|
||||
fn side_sources(map: &BuilderMap, p: &po::Shape) -> [Vec<usize>; 2] {
|
||||
let mut sides = map.sides(p).map(|i| i.and_then(|i| map.regions.get(i)).map_or(vec![], |r| r.0.sources.clone()));
|
||||
sides.sort();
|
||||
sides
|
||||
}
|
||||
fn edge_selector(map: &BuilderMap, src: &[Arc<Node>], piece: &po::Shape) -> Option<EdgeEdit> {
|
||||
let source = usize::try_from(piece.key).ok()?;
|
||||
Some(EdgeEdit { source, sides: side_sources(map, piece), anchor: relative(src, source, piece_point(&piece.path)?), erase: true, paint: None })
|
||||
}
|
||||
fn selected_edge(map: &BuilderMap, src: &[Arc<Node>], edit: &EdgeEdit) -> Option<usize> {
|
||||
let point = absolute(src, edit.source, edit.anchor);
|
||||
pieces(map)
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| p.key == edit.source as u64 && side_sources(map, p) == edit.sides)
|
||||
.filter_map(|(i, p)| p.path.nearest(point).map(|(_, _, _, _, distance)| (i, distance)))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|p| p.0)
|
||||
}
|
||||
fn face_edits<'a>(map: &BuilderMap, src: &[Arc<Node>], spec: &'a ShaperSpec) -> BTreeMap<usize, &'a FaceEdit> {
|
||||
spec.faces.iter().filter_map(|e| selected_face(map, src, &e.selector).map(|i| (i, e))).collect()
|
||||
}
|
||||
fn fill_source(src: &[Arc<Node>], r: &po::Region) -> Option<usize> {
|
||||
r.sources.iter().rev().copied().find(|i| src.get(*i).is_some_and(|s| s.visible && !s.appearance.fill_paint().is_none()))
|
||||
}
|
||||
/// Regions separated only by covered strokes are one visible face. A visible line
|
||||
/// through a circle still separates two faces, even though their fills have the same source.
|
||||
fn visible_components(map: &BuilderMap, src: &[Arc<Node>], edits: &BTreeMap<usize, &FaceEdit>) -> Vec<usize> {
|
||||
fn root(parents: &[usize], mut i: usize) -> usize {
|
||||
for _ in 0..parents.len() {
|
||||
let Some(&next) = parents.get(i) else { return i };
|
||||
if next == i {
|
||||
return i;
|
||||
}
|
||||
i = next;
|
||||
}
|
||||
i
|
||||
}
|
||||
let owner = |i: usize| {
|
||||
let edit = edits.get(&i);
|
||||
if edit.is_some_and(|e| e.erase || e.paint.as_ref().is_some_and(|a| a.fill_paint().is_none())) {
|
||||
return None;
|
||||
}
|
||||
edit.and_then(|e| e.paint_source).or_else(|| map.regions.get(i).and_then(|r| fill_source(src, &r.0)))
|
||||
};
|
||||
let mut parents: Vec<usize> = (0..map.regions.len()).collect();
|
||||
for piece in pieces(map) {
|
||||
let [Some(a), Some(b)] = map.sides(piece) else { continue };
|
||||
let (Some(left), Some(right)) = (owner(a), owner(b)) else { continue };
|
||||
let merge = |i| edits.get(&i).and_then(|e| e.merge);
|
||||
let merged = merge(a).is_some() && merge(a) == merge(b);
|
||||
let covered = left as u64 > piece.key && right as u64 > piece.key;
|
||||
let unstroked = src.get(piece.key as usize).is_none_or(|n| !n.visible || n.appearance.stroke_paint().is_none());
|
||||
if (left == right || merged) && (merged || covered || unstroked) {
|
||||
let (a, b) = (root(&parents, a), root(&parents, b));
|
||||
if let Some(parent) = parents.get_mut(a) {
|
||||
*parent = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
(0..parents.len()).map(|i| root(&parents, i)).collect()
|
||||
}
|
||||
|
||||
fn fill_style(mut a: Appearance) -> Appearance {
|
||||
a.items.retain(AppearanceItem::is_fill);
|
||||
a
|
||||
}
|
||||
fn stroke_style(mut a: Appearance) -> Appearance {
|
||||
a.items.retain(|i| !i.is_fill());
|
||||
a
|
||||
}
|
||||
|
||||
/// Join compatible strokes at two-way junctions. Branches stay separate; a line
|
||||
/// crossing a circle must not turn into the circle's outline at the intersection.
|
||||
fn join_strokes(nodes: Vec<Arc<Node>>) -> Vec<Arc<Node>> {
|
||||
const TOL: f64 = 1e-5;
|
||||
type End = (usize, bool);
|
||||
let mut buckets: BTreeMap<(i64, i64), Vec<(End, Point)>> = BTreeMap::new();
|
||||
let key = |p: Point| finite(p).then(|| ((p.x / TOL).floor() as i64, (p.y / TOL).floor() as i64));
|
||||
for (i, n) in nodes.iter().enumerate() {
|
||||
let Some(sp) = n.path_data().filter(|p| p.subpaths.len() == 1).and_then(|p| p.subpaths.first()).filter(|p| !p.closed) else { continue };
|
||||
for (last, a) in [(false, sp.anchors.first()), (true, sp.anchors.last())] {
|
||||
if let Some(a) = a
|
||||
&& let Some(key) = key(a.p)
|
||||
{
|
||||
buckets.entry(key).or_default().push(((i, last), a.p));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut connections: BTreeMap<End, End> = BTreeMap::new();
|
||||
for entries in buckets.values() {
|
||||
for &(end, p) in entries {
|
||||
let Some((x, y)) = key(p) else { continue };
|
||||
let mut near = vec![];
|
||||
for dx in -1..=1 {
|
||||
for dy in -1..=1 {
|
||||
if let Some(entries) = buckets.get(&(x + dx, y + dy)) {
|
||||
near.extend(entries.iter().filter(|(_, q)| p.distance(*q) <= TOL).map(|(end, _)| *end));
|
||||
}
|
||||
}
|
||||
}
|
||||
if near.len() != 2 {
|
||||
continue;
|
||||
}
|
||||
let Some(other) = near.into_iter().find(|e| *e != end) else { continue };
|
||||
let Some((a, b)) = nodes.get(end.0).zip(nodes.get(other.0)) else { continue };
|
||||
if a.appearance == b.appearance && a.opacity == b.opacity && a.blend == b.blend {
|
||||
connections.insert(end, other);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
let mut out = vec![];
|
||||
// Open chains first, then closed loops. This avoids beginning in a chain's middle.
|
||||
let starts = nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, _)| [(i, false), (i, true)])
|
||||
.filter(|e| !connections.contains_key(e))
|
||||
.chain(nodes.iter().enumerate().map(|(i, _)| (i, false)));
|
||||
for start in starts {
|
||||
if seen.contains(&start.0) {
|
||||
continue;
|
||||
}
|
||||
if let Some(node) = nodes.get(start.0).filter(|n| n.path_data().is_none_or(|p| p.subpaths.len() != 1)) {
|
||||
seen.insert(start.0);
|
||||
out.push(node.clone());
|
||||
continue;
|
||||
}
|
||||
let mut end = start;
|
||||
let mut prototype = start.0;
|
||||
let mut path = vectorcraft_geom::SubPath::default();
|
||||
loop {
|
||||
if !seen.insert(end.0) {
|
||||
break;
|
||||
}
|
||||
prototype = prototype.min(end.0);
|
||||
let Some(mut next) = nodes.get(end.0).and_then(|n| n.path_data()).and_then(|p| p.subpaths.first()).cloned() else { break };
|
||||
if end.1 {
|
||||
next.reverse();
|
||||
}
|
||||
if path.anchors.is_empty() {
|
||||
path = next;
|
||||
} else {
|
||||
if let Some((a, b)) = path.anchors.last_mut().zip(next.anchors.first()) {
|
||||
*a = vectorcraft_geom::Anchor::with_handles(a.p, a.h_in, b.h_out);
|
||||
}
|
||||
path.anchors.extend(next.anchors.into_iter().skip(1));
|
||||
}
|
||||
let Some(&next) = connections.get(&(end.0, !end.1)) else { break };
|
||||
if next == start {
|
||||
if let Some(last) = path.anchors.pop()
|
||||
&& let Some(first) = path.anchors.first_mut()
|
||||
{
|
||||
*first = vectorcraft_geom::Anchor::with_handles(first.p, last.h_in, first.h_out);
|
||||
}
|
||||
path.closed = true;
|
||||
break;
|
||||
}
|
||||
end = next;
|
||||
}
|
||||
if let Some(mut node) = nodes.get(prototype).cloned() {
|
||||
if let Some(p) = Arc::make_mut(&mut node).path_data_mut() {
|
||||
*p = PathData::new(vec![path]);
|
||||
}
|
||||
out.push(node);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn generated(d: &mut Document, src: &[Arc<Node>], spec: &ShaperSpec, map: &BuilderMap) -> Result<Vec<Arc<Node>>> {
|
||||
if spec.faces.len() + spec.edges.len() > MAX_EDITS {
|
||||
return Err(bad("shaper.scribble", "too many Shaper edits"));
|
||||
}
|
||||
let edits = face_edits(map, src, spec);
|
||||
let mut fills: BTreeMap<(Option<u64>, usize), Vec<usize>> = BTreeMap::new();
|
||||
for (i, (r, _, _)) in map.regions.iter().enumerate() {
|
||||
let edit = edits.get(&i);
|
||||
if edit.is_some_and(|e| e.erase) {
|
||||
continue;
|
||||
}
|
||||
if edit.and_then(|e| e.paint_source).or_else(|| fill_source(src, r)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let merge = edit.and_then(|e| e.merge);
|
||||
fills.entry((merge, if merge.is_some() { 0 } else { i })).or_default().push(i);
|
||||
}
|
||||
let mut out = vec![];
|
||||
for indices in fills.values() {
|
||||
let Some(&i) = indices.first() else { continue };
|
||||
let Some((region, _, _)) = map.regions.get(i) else { continue };
|
||||
let edit = edits.get(&i);
|
||||
let Some(source) = edit.and_then(|e| e.paint_source).or_else(|| fill_source(src, region)).and_then(|i| src.get(i)) else { continue };
|
||||
let path = po::unite_all(&indices.iter().filter_map(|i| map.regions.get(*i).map(|r| (&r.0.path, FillRule::NonZero))).collect::<Vec<_>>());
|
||||
let style = edit.and_then(|e| e.paint.clone()).unwrap_or_else(|| source.appearance.clone());
|
||||
let mut n = Node::path(d.alloc_id(), path, fill_style(style));
|
||||
n.opacity = source.opacity;
|
||||
n.blend = source.blend;
|
||||
n.name = Some(format!("{FILL_PREFIX}{i}"));
|
||||
out.push(Arc::new(n));
|
||||
}
|
||||
let edge_edits: BTreeMap<usize, &EdgeEdit> = spec.edges.iter().filter_map(|e| selected_edge(map, src, e).map(|i| (i, e))).collect();
|
||||
let mut strokes = vec![];
|
||||
for (i, piece) in pieces(map).into_iter().enumerate() {
|
||||
let sides = map.sides(piece);
|
||||
let merge = |r: Option<usize>| r.and_then(|r| edits.get(&r)).and_then(|e| e.merge);
|
||||
let merged_inside = merge(sides[0]).is_some() && merge(sides[0]) == merge(sides[1]);
|
||||
// An exiting scribble removes the exposed stroke around the deleted area.
|
||||
// Its shared boundary with surviving art still closes that art's contour.
|
||||
let erased_boundary =
|
||||
sides.iter().any(Option::is_some) && sides.iter().all(|r| r.is_none_or(|r| edits.get(&r).is_some_and(|e| e.erase && e.erase_edges)));
|
||||
let occluded = sides
|
||||
.iter()
|
||||
.all(|r| r.and_then(|r| map.regions.get(r)).and_then(|r| fill_source(src, &r.0)).is_some_and(|source| source as u64 > piece.key));
|
||||
if merged_inside || erased_boundary || occluded || edge_edits.get(&i).is_some_and(|e| e.erase) {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = src.get(piece.key as usize) else { continue };
|
||||
let style = edge_edits.get(&i).and_then(|e| e.paint.clone()).unwrap_or_else(|| source.appearance.clone());
|
||||
if style.stroke_paint().is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut n = Node::path(d.alloc_id(), piece.path.clone(), stroke_style(style));
|
||||
n.opacity = source.opacity;
|
||||
n.blend = source.blend;
|
||||
n.name = Some(format!("{STROKE_PREFIX}{i}"));
|
||||
strokes.push(Arc::new(n));
|
||||
}
|
||||
out.extend(join_strokes(strokes));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Re-evaluate only groups whose original art changed. Errors reach Session::edit's rollback.
|
||||
pub(crate) fn refresh(before: &Document, d: &mut Document) -> Result<()> {
|
||||
let mut ids = vec![];
|
||||
d.walk(|n| {
|
||||
if n.shaper.is_some() {
|
||||
ids.push(n.id)
|
||||
}
|
||||
});
|
||||
for id in ids {
|
||||
let Some(current) = d.node(id).cloned() else { continue };
|
||||
let Some(old) = before.node(id) else { continue };
|
||||
let src = sources(¤t);
|
||||
let source_changed = sources(old) != src;
|
||||
let output_changed = current.children().is_some_and(|children| {
|
||||
children
|
||||
.iter()
|
||||
.skip(1)
|
||||
.any(|n| old.children().and_then(|c| c.iter().find(|o| o.id == n.id)).is_some_and(|o| o.appearance != n.appearance))
|
||||
});
|
||||
if !source_changed && !output_changed {
|
||||
continue;
|
||||
}
|
||||
if src.is_empty() {
|
||||
d.remove(id)?;
|
||||
continue;
|
||||
}
|
||||
let map = map_of(&src)?;
|
||||
let mut spec = current.shaper.as_deref().cloned().unwrap_or_default();
|
||||
let previous = sources(old);
|
||||
if previous.iter().map(|s| s.id).ne(src.iter().map(|s| s.id)) {
|
||||
// Source insertion, deletion or reordering updates the index-based recipes.
|
||||
let index = |i: usize| previous.get(i).and_then(|old| src.iter().position(|n| n.id == old.id));
|
||||
spec.faces.retain_mut(|e| {
|
||||
let Some(indices) = e.selector.sources.iter().map(|i| index(*i)).collect::<Option<Vec<_>>>() else { return false };
|
||||
let paint_source = match e.paint_source {
|
||||
Some(i) => {
|
||||
let Some(i) = index(i) else { return false };
|
||||
Some(i)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
e.selector.sources = indices;
|
||||
e.selector.sources.sort();
|
||||
e.paint_source = paint_source;
|
||||
true
|
||||
});
|
||||
spec.edges.retain_mut(|e| {
|
||||
let Some(source) = index(e.source) else { return false };
|
||||
for side in &mut e.sides {
|
||||
let Some(indices) = side.iter().map(|i| index(*i)).collect::<Option<Vec<_>>>() else { return false };
|
||||
*side = indices;
|
||||
side.sort();
|
||||
}
|
||||
e.sides.sort();
|
||||
e.source = source;
|
||||
true
|
||||
});
|
||||
}
|
||||
if output_changed {
|
||||
for n in current.children().into_iter().flatten().skip(1) {
|
||||
let Some(o) = old.children().and_then(|c| c.iter().find(|o| o.id == n.id)) else { continue };
|
||||
if o.appearance == n.appearance {
|
||||
continue;
|
||||
}
|
||||
if let Some(i) = n.name.as_deref().and_then(|s| s.strip_prefix(FILL_PREFIX)).and_then(|s| s.parse::<usize>().ok()) {
|
||||
let existing = face_edits(&map, &src, &spec);
|
||||
let merge = existing.get(&i).and_then(|e| e.merge);
|
||||
let components = visible_components(&map, &src, &existing);
|
||||
let related: Vec<usize> = if let Some(m) = merge {
|
||||
existing.iter().filter(|(_, e)| e.merge == Some(m)).map(|(i, _)| *i).collect()
|
||||
} else {
|
||||
components.iter().enumerate().filter(|(_, c)| Some(*c) == components.get(i)).map(|(i, _)| i).collect()
|
||||
};
|
||||
for i in related {
|
||||
let Some(selector) = face_selector(&map, &src, i) else { continue };
|
||||
if let Some(e) = spec.faces.iter_mut().rev().find(|e| e.selector == selector) {
|
||||
e.paint = Some(n.appearance.clone());
|
||||
} else {
|
||||
spec.faces.push(FaceEdit {
|
||||
selector,
|
||||
erase: false,
|
||||
erase_edges: false,
|
||||
paint_source: None,
|
||||
merge,
|
||||
paint: Some(n.appearance.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if n.name.as_deref().is_some_and(|s| s.starts_with(STROKE_PREFIX)) {
|
||||
// One joined output may contain pieces from several original paths.
|
||||
for piece in pieces(&map) {
|
||||
let contained = piece
|
||||
.path
|
||||
.subpaths
|
||||
.iter()
|
||||
.flat_map(|s| &s.anchors)
|
||||
.all(|a| n.path_data().and_then(|p| p.nearest(a.p)).is_some_and(|p| p.4 < 1e-5))
|
||||
&& piece_point(&piece.path).is_some_and(|point| n.path_data().and_then(|p| p.nearest(point)).is_some_and(|p| p.4 < 1e-5));
|
||||
if contained && let Some(mut e) = edge_selector(&map, &src, piece) {
|
||||
e.erase = false;
|
||||
e.paint = Some(n.appearance.clone());
|
||||
spec.edges.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut children = current.children().and_then(|c| c.first()).cloned().into_iter().collect::<Vec<_>>();
|
||||
let old_ids: BTreeMap<&str, NodeId> =
|
||||
current.children().into_iter().flatten().skip(1).filter_map(|n| n.name.as_deref().map(|name| (name, n.id))).collect();
|
||||
for mut n in generated(d, &src, &spec, &map)? {
|
||||
if let Some(id) = n.name.as_deref().and_then(|name| old_ids.get(name)) {
|
||||
Arc::make_mut(&mut n).id = *id;
|
||||
}
|
||||
children.push(n);
|
||||
}
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
n.shaper = Some(Box::new(spec));
|
||||
if let Some(ch) = n.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn candidates(s: &Session, p: &Value, points: &[Point], tolerance: f64) -> Result<Vec<NodeId>> {
|
||||
let st = s.doc()?;
|
||||
let area = points.iter().fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| b.union_pt(*p)).inflate(tolerance, tolerance);
|
||||
let supplied = p.get("ids").and_then(Value::as_array).map(|v| v.iter().filter_map(Value::as_u64).map(NodeId).collect::<Vec<_>>());
|
||||
let expand = supplied.is_none() && st.selection.objects.len() < 2;
|
||||
let ids = supplied.unwrap_or_else(|| if st.selection.objects.len() > 1 { st.selection.objects.clone() } else { st.doc.selectable_art() });
|
||||
let eligible: Vec<NodeId> = ids
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
st.doc.is_editable(*id)
|
||||
&& st.doc.node(*id).is_some_and(|n| {
|
||||
!matches!(n.kind, NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. })
|
||||
&& (n.shaper.is_some() || b::node_outline(n).is_some())
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let bounds = |id| st.doc.node(id).and_then(Node::geometric_bounds).map(|b| b.inflate(tolerance, tolerance));
|
||||
let overlaps = |a: Rect, b: Rect| a.intersect(b).area() > 0.0;
|
||||
let mut ids: Vec<NodeId> = eligible.iter().copied().filter(|id| bounds(*id).is_some_and(|b| overlaps(b, area))).collect();
|
||||
if expand {
|
||||
// A protruding line must still be split at the shape it passes through, even when
|
||||
// the scribble itself never enters that shape. Include the connected neighbourhood.
|
||||
loop {
|
||||
let next: Vec<NodeId> = eligible
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
!ids.contains(id)
|
||||
&& bounds(*id).is_some_and(|bb| {
|
||||
ids.iter()
|
||||
.any(|other| st.doc.parent_of(*other) == st.doc.parent_of(*id) && bounds(*other).is_some_and(|b| overlaps(bb, b)))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if next.is_empty() {
|
||||
break;
|
||||
}
|
||||
ids.extend(next);
|
||||
if ids.len() > MAX_SOURCES {
|
||||
return Err(bad("shaper.scribble", "too many overlapping paths for Shaper"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = b::sorted_roots(&st.doc, &ids);
|
||||
let parent = ids.first().and_then(|id| st.doc.position(*id)).map(|p| p.0);
|
||||
if ids.iter().any(|id| st.doc.position(*id).map(|p| p.0) != parent) {
|
||||
return Err(bad("shaper.scribble", "overlapping Shaper paths must be in the same layer or group"));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn scribble(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shaper.scribble";
|
||||
let input = p
|
||||
.get("points")
|
||||
.and_then(Value::as_array)
|
||||
.filter(|a| !a.is_empty() && a.len() <= MAX_POINTS)
|
||||
.ok_or_else(|| bad(C, "points must contain 1–4096 coordinates"))?;
|
||||
let pts = input
|
||||
.iter()
|
||||
.map(|v| point_param(&json!({"p": v}), "p").filter(|p| finite(*p)).ok_or_else(|| bad(C, "invalid point")))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let tolerance = f64_or(p, "tolerance", 4.0);
|
||||
if !tolerance.is_finite() || !(0.01..=1000.0).contains(&tolerance) {
|
||||
return Err(bad(C, "invalid tolerance"));
|
||||
}
|
||||
let step = (tolerance / 2.0).max(0.5);
|
||||
let sample_count = pts.windows(2).map(|w| (w[0].distance(w[1]) / step).ceil()).sum::<f64>();
|
||||
if sample_count > 65_536.0 {
|
||||
return Err(bad(C, "scribble is too long"));
|
||||
}
|
||||
let points = b::sample_polyline(&pts, step);
|
||||
let roots = candidates(s, p, &points, tolerance)?;
|
||||
if roots.is_empty() {
|
||||
return Ok(json!({"id": null, "regions": 0, "strokes": 0}));
|
||||
}
|
||||
let mut src = vec![];
|
||||
let mut spec = ShaperSpec::default();
|
||||
let mut next_merge = 1u64;
|
||||
for id in &roots {
|
||||
let n = s.doc()?.doc.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
if let Some(previous) = n.shaper.as_deref() {
|
||||
let offset = src.len();
|
||||
let merge_offset = next_merge;
|
||||
for mut e in previous.faces.clone() {
|
||||
for i in &mut e.selector.sources {
|
||||
*i = i.saturating_add(offset);
|
||||
}
|
||||
e.paint_source = e.paint_source.map(|i| i.saturating_add(offset));
|
||||
e.merge = e.merge.map(|i| i.saturating_add(merge_offset));
|
||||
next_merge = next_merge.max(e.merge.unwrap_or(0).saturating_add(1));
|
||||
spec.faces.push(e);
|
||||
}
|
||||
for mut e in previous.edges.clone() {
|
||||
e.source = e.source.saturating_add(offset);
|
||||
for side in &mut e.sides {
|
||||
for i in side {
|
||||
*i = i.saturating_add(offset);
|
||||
}
|
||||
}
|
||||
spec.edges.push(e);
|
||||
}
|
||||
src.extend(sources(n));
|
||||
} else {
|
||||
src.push(Arc::new(n.clone()));
|
||||
}
|
||||
}
|
||||
let map = map_of(&src)?;
|
||||
let edits = face_edits(&map, &src, &spec);
|
||||
let filled = |i: usize| edits.get(&i).is_none_or(|e| !e.erase) && map.regions.get(i).and_then(|r| fill_source(&src, &r.0)).is_some();
|
||||
let components = visible_components(&map, &src, &edits);
|
||||
let faces: std::collections::BTreeSet<usize> =
|
||||
points.iter().filter_map(|p| map.region_at(*p)).filter(|i| filled(*i)).filter_map(|i| components.get(i).copied()).collect();
|
||||
let touched: Vec<usize> = components.iter().enumerate().filter(|(_, c)| faces.contains(c)).map(|(i, _)| i).collect();
|
||||
let first = points.first().copied().unwrap_or(Point::ZERO);
|
||||
let last = points.last().copied().unwrap_or(first);
|
||||
let origin = map.region_at(first).filter(|i| filled(*i));
|
||||
let exits = map.region_at(last).is_none();
|
||||
let merge = origin.is_some() && faces.len() > 1 && !exits;
|
||||
let paint_source =
|
||||
origin.and_then(|i| edits.get(&i).and_then(|e| e.paint_source).or_else(|| map.regions.get(i).and_then(|r| fill_source(&src, &r.0))));
|
||||
let origin_paint = origin.and_then(|i| edits.get(&i).and_then(|e| e.paint.clone()));
|
||||
for &i in &touched {
|
||||
if let Some(selector) = face_selector(&map, &src, i) {
|
||||
spec.faces.push(FaceEdit {
|
||||
selector,
|
||||
erase: !merge,
|
||||
erase_edges: exits,
|
||||
paint_source,
|
||||
merge: merge.then_some(next_merge),
|
||||
paint: origin_paint.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut strokes = 0;
|
||||
if touched.is_empty() {
|
||||
let mut piece_ids = vec![];
|
||||
for point in &points {
|
||||
let index = match map.hit(*point, Some(tolerance)) {
|
||||
Some(Hit::Line(i)) => Some(map.edges.len() + i),
|
||||
Some(Hit::Edge(i)) => Some(i),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(i) = index
|
||||
&& !piece_ids.contains(&i)
|
||||
{
|
||||
piece_ids.push(i);
|
||||
}
|
||||
}
|
||||
for i in piece_ids {
|
||||
if let Some(e) = pieces(&map).get(i).and_then(|p| edge_selector(&map, &src, p)) {
|
||||
spec.edges.push(e);
|
||||
strokes += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if touched.is_empty() && strokes == 0 {
|
||||
return Ok(json!({"id": null, "regions": 0, "strokes": 0}));
|
||||
}
|
||||
let id = s.edit("Shaper", |d, sel| {
|
||||
let top = *roots.last().ok_or_else(|| bad(C, "no source art"))?;
|
||||
let (parent, index, _) = d.position(top).ok_or(EngineError::NoNode(top))?;
|
||||
let earlier = roots.iter().filter(|id| **id != top && d.position(**id).is_some_and(|p| p.1 < index)).count();
|
||||
let source_id = d.alloc_id();
|
||||
let mut source = Node::group(source_id, src.clone());
|
||||
source.name = Some(SOURCES.into());
|
||||
source.opacity = 0.0;
|
||||
let mut children = vec![Arc::new(source)];
|
||||
children.extend(generated(d, &src, &spec, &map)?);
|
||||
let id = d.alloc_id();
|
||||
let mut group = Node::group(id, children);
|
||||
group.name = Some("Shaper Group".into());
|
||||
group.shaper = Some(Box::new(spec));
|
||||
for id in &roots {
|
||||
d.remove(*id)?;
|
||||
}
|
||||
d.insert(parent, index.saturating_sub(earlier), group)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
s.doc_mut()?.isolation = None;
|
||||
Ok(json!({"id": id.0, "regions": touched.len(), "strokes": strokes}))
|
||||
}
|
||||
|
||||
fn group_at(d: &Document, point: Point, construction: bool) -> Option<NodeId> {
|
||||
let mut groups = vec![];
|
||||
d.walk(|n| {
|
||||
if n.shaper.is_some()
|
||||
&& d.is_editable(n.id)
|
||||
&& (if construction { source_group(n).and_then(Node::geometric_bounds) } else { n.geometric_bounds() })
|
||||
.is_some_and(|b| b.inflate(6.0, 6.0).contains(point))
|
||||
{
|
||||
groups.push(n.id)
|
||||
}
|
||||
});
|
||||
groups.last().copied()
|
||||
}
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let point = point_param(p, "point").filter(|p| finite(*p)).ok_or_else(|| bad("shaper.select", "missing point"))?;
|
||||
let st = s.doc()?;
|
||||
let source = bool_or(p, "source", false);
|
||||
let Some(group) = group_at(&st.doc, point, source) else { return Ok(json!({"id": null})) };
|
||||
let node = st.doc.node(group).ok_or(EngineError::NoNode(group))?;
|
||||
let target = if source {
|
||||
sources(node)
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|n| {
|
||||
b::node_outline(n)
|
||||
.is_some_and(|(path, _)| path.to_bezpath().winding(point) != 0 || path.nearest(point).is_some_and(|(_, _, _, _, d)| d < 6.0))
|
||||
})
|
||||
.map(|n| n.id)
|
||||
.unwrap_or(group)
|
||||
} else if st.selection.contains(group) {
|
||||
node.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.skip(1)
|
||||
.find(|n| {
|
||||
n.name.as_deref().is_some_and(|n| n.starts_with(FILL_PREFIX)) && n.path_data().is_some_and(|p| p.to_bezpath().winding(point) != 0)
|
||||
})
|
||||
.map_or(group, |n| n.id)
|
||||
} else {
|
||||
group
|
||||
};
|
||||
let isolation = source.then(|| source_group(node).map(|n| n.id)).flatten();
|
||||
s.select(|_, sel| sel.set([target]))?;
|
||||
if let Some(id) = isolation {
|
||||
s.doc_mut()?.isolation = Some(id);
|
||||
}
|
||||
Ok(json!({"id": target.0}))
|
||||
}
|
||||
fn target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
let id = id_param(p, "id")
|
||||
.or_else(|| s.active().and_then(|d| d.selection.objects.first().copied()))
|
||||
.ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
|
||||
s.doc()?.doc.node(id).filter(|n| n.shaper.is_some()).ok_or_else(|| bad("shaper.release", "select a Shaper group"))?;
|
||||
Ok(id)
|
||||
}
|
||||
fn release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = target(s, p)?;
|
||||
let ids = s.edit("Release Shaper Group", |d, sel| {
|
||||
let original = d.node(id).map(sources).ok_or(EngineError::NoNode(id))?;
|
||||
let (parent, index, _) = d.position(id).ok_or(EngineError::NoNode(id))?;
|
||||
d.remove(id)?;
|
||||
let mut ids = vec![];
|
||||
for (i, n) in original.into_iter().enumerate() {
|
||||
ids.push(d.insert(parent, index + i, (*n).clone())?);
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
s.doc_mut()?.isolation = None;
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = target(s, p)?;
|
||||
s.edit("Expand Shaper Group", |d, sel| {
|
||||
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
|
||||
n.shaper = None;
|
||||
n.name = None;
|
||||
if let Some(children) = n.children_mut()
|
||||
&& children.first().is_some_and(|c| c.name.as_deref() == Some(SOURCES))
|
||||
{
|
||||
children.remove(0);
|
||||
}
|
||||
sel.set([id]);
|
||||
Ok(())
|
||||
})?;
|
||||
s.doc_mut()?.isolation = None;
|
||||
Ok(json!({"id": id.0}))
|
||||
}
|
||||
@@ -70,8 +70,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
impl LibraryFile for StyleLibrary {
|
||||
const EXTS: &'static [&'static str] = &[STYLES_EXT];
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
|
||||
style_libs::read(text, stem)
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
style_libs::read(&String::from_utf8_lossy(bytes), stem)
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Other Library…",
|
||||
["Window", "Swatch Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches or .gpl library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl or .ase (swatch exchange) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
@@ -98,23 +98,24 @@ struct Extra<L> {
|
||||
pub trait LibraryFile: Sized {
|
||||
/// The extensions of its files (lower case).
|
||||
const EXTS: &'static [&'static str];
|
||||
/// Read a library file whose name without the extension is `stem` (an unnamed library's name).
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String>;
|
||||
/// Read the bytes of a library file whose name without the extension is `stem` (an unnamed
|
||||
/// library's name).
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
impl LibraryFile for SwatchLibrary {
|
||||
const EXTS: &'static [&'static str] = LIBRARY_EXTS;
|
||||
fn read(text: &str, stem: &str) -> std::result::Result<Self, String> {
|
||||
palette_io::read(text, stem)
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
palette_io::read_bytes(bytes, stem)
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// The extensions of library files [`palette_io::read`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl"];
|
||||
/// The extensions of library files [`palette_io::read_bytes`] reads.
|
||||
pub const LIBRARY_EXTS: &[&str] = &["vcswatches", "gpl", "ase"];
|
||||
|
||||
impl<L: LibraryFile> Libraries<L> {
|
||||
pub fn user_dir(&self) -> Option<&str> {
|
||||
@@ -133,7 +134,7 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
let Some(dir) = self.user_dir.clone() else { return };
|
||||
for path in library_files(&dir, L::EXTS) {
|
||||
let file = file_name(&path);
|
||||
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&String::from_utf8_lossy(&b), stem(&file)).ok()) else { continue };
|
||||
let Some(lib) = read_file(&path).ok().and_then(|b| L::read(&b, stem(&file)).ok()) else { continue };
|
||||
let info = LibraryInfo { id: format!("user/{file}"), name: lib.name().to_string(), category: "user" };
|
||||
self.extra.push(Extra { info, path: Some(path), lib: Arc::new(lib) });
|
||||
}
|
||||
@@ -351,12 +352,11 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "swatch.library.load";
|
||||
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
|
||||
// A library file, or a document whose swatches become the library.
|
||||
match std::str::from_utf8(bytes).ok().filter(|t| palette_io::sniff(t)) {
|
||||
Some(t) => palette_io::read(t, stem(file)).map_err(|e| bad(C, e)),
|
||||
None => {
|
||||
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
|
||||
document_library(&doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
if palette_io::sniff_bytes(bytes) {
|
||||
palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e))
|
||||
} else {
|
||||
let doc = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?.doc;
|
||||
document_library(&doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
@@ -417,12 +417,17 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.edit("Add to Swatches", |d, _| {
|
||||
let mut out = vec![];
|
||||
// Each library group goes into one document group: the group of that name the document
|
||||
// already had, or one made here.
|
||||
let before = d.swatch_groups.len();
|
||||
let mut placed: Vec<(&str, usize)> = vec![];
|
||||
for (group, w) in fresh {
|
||||
let name = d.free_swatch_name(&w.name);
|
||||
let sw = Swatch { name: name.clone(), ..(*w).clone() };
|
||||
match group {
|
||||
Some(g) => {
|
||||
let i = match d.swatch_groups.iter().position(|x| x.name == *g) {
|
||||
let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i);
|
||||
let i = match found.or_else(|| d.swatch_groups.iter().take(before).position(|x| x.name == *g)) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let name = d.free_swatch_name(g);
|
||||
@@ -430,6 +435,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.swatch_groups.len() - 1
|
||||
}
|
||||
};
|
||||
if found.is_none() {
|
||||
placed.push((g, i));
|
||||
}
|
||||
d.swatch_groups[i].swatches.push(sw);
|
||||
}
|
||||
None => d.swatches.push(sw),
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeKind, TabAlign, TabStop};
|
||||
|
||||
use super::typecmd::{refresh_bounds, text_targets};
|
||||
use super::typecmd::{TextRange, para_span, refresh_bounds, text_targets};
|
||||
use super::*;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -13,12 +13,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Tab Stops",
|
||||
["Window", "Tabs"],
|
||||
None,
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?} replace the tab stops of the selected text",
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches)",
|
||||
has_selection,
|
||||
set
|
||||
),
|
||||
cmd!(query "text.tabs.get", "Tab Stops", [], None, "{ids?} → {stops} of the first selected text object", has_selection, get),
|
||||
cmd!("text.tabs.clear", "Clear All Tabs", ["Window", "Tabs"], None, "{ids?}", has_selection, |s, p| apply(s, p, vec![], "Clear All Tabs")),
|
||||
cmd!(
|
||||
query "text.tabs.get",
|
||||
"Tab Stops",
|
||||
[],
|
||||
None,
|
||||
"{ids?, start?: byte} → {stops} of the first selected text object (its paragraph at `start`; default the first)",
|
||||
has_selection,
|
||||
get
|
||||
),
|
||||
cmd!("text.tabs.clear", "Clear All Tabs", ["Window", "Tabs"], None, "{ids?, start?: byte, end?: byte}", has_selection, |s, p| apply(
|
||||
s,
|
||||
p,
|
||||
vec![],
|
||||
"Clear All Tabs"
|
||||
)),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -54,11 +67,13 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result<Value> {
|
||||
let ids = text_targets(s, p, "text.tabs.set")?;
|
||||
let range = TextRange::parse(p, "text.tabs.set")?;
|
||||
let n = stops.len();
|
||||
s.edit(label, |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
t.para.tabs = stops.clone();
|
||||
let span = para_span(range, t);
|
||||
t.edit_paras(span, |pa| pa.tabs = stops.clone());
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
@@ -69,9 +84,10 @@ fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = text_targets(s, p, "text.tabs.get")?;
|
||||
let range = TextRange::parse(p, "text.tabs.get")?;
|
||||
let st = s.doc()?;
|
||||
let tabs = ids.iter().find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => Some(t.para.tabs.clone()),
|
||||
Some(NodeKind::Text(t)) => Some(t.para_at(para_span(range, t).map_or(0, |r| r.start)).tabs.clone()),
|
||||
_ => None,
|
||||
});
|
||||
Ok(json!({ "stops": serde_json::to_value(tabs.unwrap_or_default()).unwrap_or(Value::Null) }))
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
|
||||
"{id, start?: byte, end?: byte (default: all text), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\"} style a character range (runs are split at the range ends) → {id, runs}",
|
||||
has_doc,
|
||||
set_range_style
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area / Path Type",
|
||||
[],
|
||||
None,
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, placeholder?: bool (placeholder text instead, as text.create), leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id}",
|
||||
has_doc,
|
||||
create_in_path
|
||||
),
|
||||
@@ -135,6 +135,13 @@ fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let insert = str_param(p, "insert").unwrap_or("").to_string();
|
||||
let caret = s.edit("Typing", |d, _| {
|
||||
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
|
||||
// Paragraph styles follow the edit: a split paragraph's new one continues its style, a
|
||||
// merge keeps the first paragraph's.
|
||||
let inserted: String = match &styled {
|
||||
Some(r) => r.iter().map(|r| r.text.as_str()).collect(),
|
||||
None => insert.clone(),
|
||||
};
|
||||
t.splice_paras(a, b, &inserted);
|
||||
let caret = match &styled {
|
||||
Some(r) => edit::replace_range_styled(&mut t.runs, a, b, r),
|
||||
None => edit::replace_range(&mut t.runs, a, b, &insert),
|
||||
@@ -191,7 +198,7 @@ pub(crate) fn features_param(p: &Value, cmd: &str) -> Result<Option<Vec<String>>
|
||||
Ok(Some(vectorcraft_text::OtFeatures::default().with_tags(tags).to_tags()))
|
||||
}
|
||||
|
||||
/// `charAlign: "romanBaseline"|"emBoxTop"|"emBoxCenter"|"emBoxBottom"` (Character Alignment).
|
||||
/// `charAlign: "romanBaseline"|"emBoxTop"|"emBoxCenter"|"emBoxBottom"|"icfTop"|"icfBottom"` (Character Alignment).
|
||||
pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result<Option<vectorcraft_doc::CharAlign>> {
|
||||
use vectorcraft_doc::CharAlign;
|
||||
let Some(v) = p.get("charAlign").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
@@ -200,7 +207,14 @@ pub(crate) fn char_align_param(p: &Value, cmd: &str) -> Result<Option<vectorcraf
|
||||
Some("emBoxTop") => CharAlign::EmBoxTop,
|
||||
Some("emBoxCenter") => CharAlign::EmBoxCenter,
|
||||
Some("emBoxBottom") => CharAlign::EmBoxBottom,
|
||||
_ => return Err(bad(cmd, "`charAlign` must be \"romanBaseline\", \"emBoxTop\", \"emBoxCenter\" or \"emBoxBottom\"")),
|
||||
Some("icfTop") => CharAlign::IcfTop,
|
||||
Some("icfBottom") => CharAlign::IcfBottom,
|
||||
_ => {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
"`charAlign` must be \"romanBaseline\", \"emBoxTop\", \"emBoxCenter\", \"emBoxBottom\", \"icfTop\" or \"icfBottom\"",
|
||||
));
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -461,8 +475,9 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
vertical: p.get("vertical").and_then(Value::as_bool).unwrap_or(false),
|
||||
kind,
|
||||
xf: Affine::IDENTITY,
|
||||
runs: vec![TextRun { text, style }],
|
||||
runs: vec![TextRun { text, style, inline: None }],
|
||||
para: super::create::new_type_para(),
|
||||
paras: Vec::new(),
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
@@ -472,6 +487,9 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cached_baselines: Vec::new(),
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
t.area.fit = super::create::new_area_fit(s, p, C)?;
|
||||
}
|
||||
if bool_or(p, "placeholder", false) {
|
||||
super::typemenu::fill_with_placeholder(&mut t);
|
||||
} else {
|
||||
@@ -597,6 +615,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
xf: Affine::IDENTITY,
|
||||
runs: head.clone(),
|
||||
para: Default::default(),
|
||||
paras: Vec::new(),
|
||||
area: Default::default(),
|
||||
path_effect: Default::default(),
|
||||
path_align: Default::default(),
|
||||
|
||||
@@ -66,7 +66,7 @@ macro_rules! style_cmds {
|
||||
concat!($p, ".apply"),
|
||||
concat!("Apply ", $what, " Style"),
|
||||
&[],
|
||||
"{name, clearOverrides?, ids?|id + start?/end? (a Type tool range)} → {count}",
|
||||
"{name, clearOverrides?, ids?|id + start?/end? (a Type tool range: character styles style it, paragraph styles apply to the paragraphs it touches)} → {count}",
|
||||
|s, p| apply(s, p, $kind),
|
||||
true,
|
||||
),
|
||||
@@ -179,7 +179,7 @@ fn text_mut(d: &mut Document, id: NodeId) -> Option<&mut vectorcraft_doc::TextOb
|
||||
}
|
||||
}
|
||||
|
||||
/// How many runs (char) or text objects (para) use `name`.
|
||||
/// How many runs (char) or paragraphs (para) use `name`.
|
||||
fn uses(d: &Document, kind: Kind, name: &str) -> usize {
|
||||
let target = (name != kind.normal()).then_some(name);
|
||||
let mut n = 0;
|
||||
@@ -187,7 +187,7 @@ fn uses(d: &Document, kind: Kind, name: &str) -> usize {
|
||||
if let NodeKind::Text(t) = &node.kind {
|
||||
n += match kind {
|
||||
Kind::Char => t.runs.iter().filter(|r| r.style.style_name.as_deref() == target).count(),
|
||||
Kind::Para => usize::from(t.para.style_name.as_deref() == target),
|
||||
Kind::Para => (0..t.paragraph_count()).filter(|&i| t.para_at(i).style_name.as_deref() == target).count(),
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -210,9 +210,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map<String, Valu
|
||||
}
|
||||
}
|
||||
Kind::Para => {
|
||||
if t.para.style_name == target {
|
||||
t.para = restyle(&t.para, old, new);
|
||||
changed = true;
|
||||
for pa in t.para_styles_mut() {
|
||||
if pa.style_name == target {
|
||||
*pa = restyle(pa, old, new);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,12 +233,11 @@ fn selection_attrs(s: &Session, p: &Value, kind: Kind) -> Result<Option<Map<Stri
|
||||
None => text_targets(s, &json!({}), "").ok().and_then(|v| v.first().copied()),
|
||||
};
|
||||
let Some(NodeKind::Text(t)) = id.and_then(|i| d.node(i)).map(|n| &n.kind) else { return Ok(None) };
|
||||
let at = p.get("start").and_then(Value::as_u64).map_or(0, |v| usize::try_from(v).unwrap_or(usize::MAX));
|
||||
Ok(Some(match kind {
|
||||
Kind::Char => {
|
||||
let at = p.get("start").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
to_attrs(&vectorcraft_text::edit::style_at(&t.runs, at))
|
||||
}
|
||||
Kind::Para => to_attrs(&t.para),
|
||||
Kind::Char => to_attrs(&vectorcraft_text::edit::style_at(&t.runs, at)),
|
||||
// The paragraph at `start`.
|
||||
Kind::Para => to_attrs(t.para_at(t.paragraphs_in(at, at).start)),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -329,8 +330,9 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let normal = kind.attrs(d, kind.normal()).unwrap_or_default();
|
||||
let clear = bool_or(p, "clearOverrides", false);
|
||||
let style_name = (name != kind.normal()).then(|| name.clone());
|
||||
// A Type tool range (character styles only) or whole text objects.
|
||||
let range = id_param(p, "id").filter(|_| kind == Kind::Char && (p.get("start").is_some() || p.get("end").is_some()));
|
||||
// A Type tool range or whole text objects.
|
||||
let text_range = super::typecmd::TextRange::parse(p, &c)?;
|
||||
let range = id_param(p, "id").filter(|_| text_range.is_some());
|
||||
let ids = match range.or_else(|| id_param(p, "id")) {
|
||||
Some(id) => vec![id],
|
||||
None => text_targets(s, p, &c)?,
|
||||
@@ -376,7 +378,17 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
Kind::Para => t.para = para_fn(&t.para)?,
|
||||
Kind::Para => {
|
||||
let mut v = t.paragraph_styles();
|
||||
let span = match (range, text_range) {
|
||||
(Some(_), Some(r)) => r.paras(t),
|
||||
_ => 0..v.len(),
|
||||
};
|
||||
for st in v.iter_mut().take(span.end).skip(span.start) {
|
||||
*st = para_fn(st)?;
|
||||
}
|
||||
t.set_paragraph_styles(v);
|
||||
}
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
@@ -447,7 +459,7 @@ fn rename(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
};
|
||||
match kind {
|
||||
Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)),
|
||||
Kind::Para => fix(&mut t.para.style_name),
|
||||
Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -472,7 +484,7 @@ fn delete(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
};
|
||||
match kind {
|
||||
Kind::Char => t.runs.iter_mut().for_each(|r| fix(&mut r.style.style_name)),
|
||||
Kind::Para => fix(&mut t.para.style_name),
|
||||
Kind::Para => t.para_styles_mut().for_each(|pa| fix(&mut pa.style_name)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -75,14 +75,24 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
});
|
||||
// The story: live frames' runs, plus the text of frames deleted by this edit.
|
||||
let mut story: Vec<TextRun> = vec![];
|
||||
let mut sources: Vec<TextObject> = vec![];
|
||||
let mut later_wins = vec![];
|
||||
let mut live = vec![];
|
||||
for id in &thread {
|
||||
match (text_of(doc, *id), text_of(before, *id)) {
|
||||
(Some(t), _) => {
|
||||
(Some(t), old) => {
|
||||
story.extend(t.runs.iter().cloned());
|
||||
// A frame whose first paragraph was just restyled gives the paragraph it
|
||||
// shares with the frame before it that style.
|
||||
later_wins.push(old.is_some_and(|o| o.para_at(0) != t.para_at(0)));
|
||||
sources.push(t.clone());
|
||||
live.push(*id);
|
||||
}
|
||||
(None, Some(old)) => story.extend(old.runs.iter().cloned()),
|
||||
(None, Some(old)) => {
|
||||
story.extend(old.runs.iter().cloned());
|
||||
later_wins.push(false);
|
||||
sources.push(old.clone());
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
@@ -92,16 +102,33 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let source_refs: Vec<&TextObject> = sources.iter().collect();
|
||||
let paras = vectorcraft_text::thread::story_paras(&source_refs, &later_wins);
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
if live.len() >= 2 {
|
||||
// Threaded frames keep their size: Auto Size is off for them (as in Illustrator).
|
||||
for id in &live {
|
||||
if text_of(doc, *id).is_some_and(|t| t.area.fit == vectorcraft_doc::AreaFit::AutoHeight)
|
||||
&& let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
|
||||
{
|
||||
t.area.fit = vectorcraft_doc::AreaFit::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let frames: Vec<TextObject> = live.iter().filter_map(|id| text_of(doc, *id).cloned()).collect();
|
||||
let refs: Vec<&TextObject> = frames.iter().collect();
|
||||
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story);
|
||||
for (id, runs) in live.iter().zip(parts) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind)
|
||||
&& t.runs != runs
|
||||
{
|
||||
t.runs = runs;
|
||||
refresh_bounds(t);
|
||||
let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s);
|
||||
for (id, part) in live.iter().zip(parts) {
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) {
|
||||
let mut next = (**t).clone();
|
||||
next.runs = part.runs;
|
||||
next.set_paragraph_styles(part.paras);
|
||||
if next.runs != t.runs || next.para != t.para || next.paras != t.paras {
|
||||
t.runs = next.runs;
|
||||
t.para = next.para;
|
||||
t.paras = next.paras;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if live.len() >= 2 {
|
||||
@@ -183,15 +210,17 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let mut story: Vec<TextRun> = vec![];
|
||||
for id in &thread {
|
||||
if let Some(t) = text_of(d, *id) {
|
||||
story.extend(t.runs.iter().cloned());
|
||||
}
|
||||
let sources: Vec<TextObject> = thread.iter().filter_map(|id| text_of(d, *id).cloned()).collect();
|
||||
for t in &sources {
|
||||
story.extend(t.runs.iter().cloned());
|
||||
}
|
||||
let paras = vectorcraft_text::thread::story_paras(&sources.iter().collect::<Vec<_>>(), &[]);
|
||||
let style = story.first().map(|r| r.style.clone()).unwrap_or_default();
|
||||
let first_para = paras.first().cloned().unwrap_or_default();
|
||||
for id in &out {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
t.runs = vec![TextRun { text: String::new(), style: style.clone() }];
|
||||
t.runs = vec![TextRun { text: String::new(), style: style.clone(), inline: None }];
|
||||
t.set_all_paras(first_para.clone());
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
@@ -200,6 +229,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
{
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
t.runs = story;
|
||||
t.set_paragraph_styles(paras);
|
||||
}
|
||||
let i = d.text_threads.iter().position(|t| *t == thread).unwrap_or(0);
|
||||
d.text_threads[i] = keep;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Justify, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::{AreaFit, Document, Justify, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (none given: query) → the first object's options",
|
||||
"{ids?, width?: pt, height?: pt, rows?, columns?, gutter?: pt, inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style?, size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, features?: [\"dlig\", \"-liga\", …] OpenType}",
|
||||
"{ids?|id?, font?, style?, size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, features?: [\"dlig\", \"-liga\", …] OpenType, start?: byte, end?: byte} (with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text)",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -97,13 +97,110 @@ fn orientation(s: &mut Session, p: &Value, vertical: bool) -> Result<Value> {
|
||||
Ok(json!({"vertical": vertical, "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit.
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing
|
||||
/// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo
|
||||
/// step as the edit.
|
||||
pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
// Edits that changed the paragraph count keep one paragraph style per paragraph.
|
||||
t.normalize_paras();
|
||||
auto_height(t);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
t.cached_baselines = lay.baselines();
|
||||
}
|
||||
|
||||
/// The text-space bounds of area type's frame, when Auto Size can fit it: a rectangle (one
|
||||
/// subpath, as large as its bounds) of horizontal type in one row, with some height.
|
||||
fn auto_height_frame(t: &TextObject) -> Option<vectorcraft_geom::Rect> {
|
||||
use vectorcraft_geom::Shape;
|
||||
let vectorcraft_doc::TextKind::Area { frame } = &t.kind else { return None };
|
||||
if t.area.fit != vectorcraft_doc::AreaFit::AutoHeight || t.vertical || t.area.rows > 1 || frame.subpaths.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let b = frame.bounds()?;
|
||||
let area = frame.to_bezpath().area().abs();
|
||||
let finite = [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite());
|
||||
(finite && b.height() > 1e-6 && b.width() > 1e-6 && (area - b.area()).abs() <= b.area() * 1e-6).then_some(b)
|
||||
}
|
||||
|
||||
/// Auto Size: move the bottom of a rectangular area type frame to just below its last line (plus
|
||||
/// the inset), so the frame's height follows the text. Text in several columns gets the least
|
||||
/// height (to 0.01 pt) at which it fits. True when the frame changed.
|
||||
fn auto_height(t: &mut TextObject) -> bool {
|
||||
use vectorcraft_geom::Shape;
|
||||
let Some(b) = auto_height_frame(t) else { return false };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Lay out in a frame as tall as the canvas allows: everything the width lets through flows.
|
||||
let tall = (crate::MAX_COORD - b.y0).min(1.0e5);
|
||||
if tall <= 1.0 {
|
||||
return false;
|
||||
}
|
||||
let mut probe = t.clone();
|
||||
let with_size = |probe: &mut TextObject, w: f64, h: f64| {
|
||||
if let vectorcraft_doc::TextKind::Area { frame } = &mut probe.kind {
|
||||
*frame = PathData::from_bezpath(&vectorcraft_geom::Rect::new(b.x0, b.y0, b.x0 + w, b.y0 + h).to_path(0.1));
|
||||
}
|
||||
};
|
||||
// Columns: all the text in one column as wide as each of them is surely tall enough.
|
||||
let cols = t.area.columns.max(1);
|
||||
let col_w = if cols > 1 { ((b.width() - t.area.gutter.max(0.0) * (cols - 1) as f64) / cols as f64).max(1.0) } else { b.width() };
|
||||
with_size(&mut probe, col_w, tall);
|
||||
probe.area.columns = 1;
|
||||
let lay = vectorcraft_text::layout(db, &probe);
|
||||
let inset = t.area.inset.max(0.0);
|
||||
let Some(bottom) = lay.lines.iter().map(|l| l.baseline + l.descent).filter(|y| y.is_finite()).reduce(f64::max) else { return false };
|
||||
// The layout's fit test is `baseline + descent <= bottom + 0.01`: the last line fits exactly.
|
||||
let mut h = (bottom + inset - b.y0).clamp(1.0, tall);
|
||||
if cols > 1 {
|
||||
// The least height (to 0.01 pt) at which the columns hold the text.
|
||||
probe.area.columns = cols;
|
||||
let fits = |probe: &mut TextObject, h: f64| {
|
||||
with_size(probe, b.width(), h);
|
||||
!vectorcraft_text::layout(db, probe).overflow
|
||||
};
|
||||
if !fits(&mut probe, h) {
|
||||
return false;
|
||||
}
|
||||
let (mut lo, mut hi) = (1.0, h);
|
||||
for _ in 0..24 {
|
||||
if hi - lo <= 0.01 {
|
||||
break;
|
||||
}
|
||||
let mid = (lo + hi) * 0.5;
|
||||
if fits(&mut probe, mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
h = hi;
|
||||
}
|
||||
if (h - b.height()).abs() <= 1e-6 {
|
||||
return false;
|
||||
}
|
||||
// Scale the frame about its top edge, keeping its anchors (and their order) as they are.
|
||||
let a = Affine::translate((0.0, b.y0)) * Affine::scale_non_uniform(1.0, h / b.height()) * Affine::translate((0.0, -b.y0));
|
||||
let vectorcraft_doc::TextKind::Area { frame } = &mut t.kind else { return false };
|
||||
let mut next = frame.clone();
|
||||
next.transform(a);
|
||||
if next.bounds().is_none_or(|nb| ![nb.x0, nb.y0, nb.x1, nb.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD)) {
|
||||
return false;
|
||||
}
|
||||
*frame = next;
|
||||
true
|
||||
}
|
||||
|
||||
/// Recompute the layout bounds cache for the text among `ids` (and their descendants) that lacks
|
||||
/// it. Pasted or imported type arrives without the cache (not serialized), so selection boxes, the
|
||||
/// Transform panel and hit testing would fall back to [`TextObject::estimate_bounds`] (a rough
|
||||
/// 0.55 em per character) until the text is edited — the box comes up short and alignment looks off.
|
||||
pub(crate) fn refresh_bounds_of(d: &mut Document, ids: &[NodeId]) {
|
||||
for id in text_ids(d, ids) {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind)
|
||||
&& t.cached_bounds.is_none()
|
||||
{
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Text objects among `ids` and their descendants.
|
||||
fn text_ids(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
@@ -133,7 +230,16 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let NodeKind::Text(t) = &n.kind else { continue };
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let mut children = vec![];
|
||||
for g in &lay.glyphs {
|
||||
for (gi, g) in lay.glyphs.iter().enumerate() {
|
||||
// Inline graphics become instances of their symbols, in place.
|
||||
if let Some(ig) = lay.inlines.iter().find(|i| i.glyph == gi)
|
||||
&& let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref())
|
||||
{
|
||||
let id = d.alloc_id();
|
||||
let xf = t.xf * ig.xf * d.symbol_natural_xf(&art.symbol);
|
||||
children.push(Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: art.symbol.clone(), xf })));
|
||||
continue;
|
||||
}
|
||||
let path = PathData::from_bezpath(&g.outline).transformed(t.xf);
|
||||
if path.is_empty() {
|
||||
continue;
|
||||
@@ -174,6 +280,60 @@ pub(crate) fn text_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Node
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
/// Optional `start`/`end` byte offsets of a text command: the character range it styles and the
|
||||
/// paragraphs it touches. Without either, the command applies to all the text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct TextRange {
|
||||
start: Option<usize>,
|
||||
end: Option<usize>,
|
||||
}
|
||||
|
||||
impl TextRange {
|
||||
/// `start`/`end` of `p`, if either is given (non-negative integers).
|
||||
pub(crate) fn parse(p: &Value, cmd: &str) -> Result<Option<Self>> {
|
||||
let get = |k: &str| -> Result<Option<usize>> {
|
||||
match p.get(k) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => {
|
||||
v.as_u64().map(|n| Some(usize::try_from(n).unwrap_or(usize::MAX))).ok_or_else(|| bad(cmd, format!("`{k}` must be a byte offset")))
|
||||
}
|
||||
}
|
||||
};
|
||||
let (start, end) = (get("start")?, get("end")?);
|
||||
Ok((start.is_some() || end.is_some()).then_some(Self { start, end }))
|
||||
}
|
||||
/// The byte range in `t`, clamped and ordered.
|
||||
pub(crate) fn bytes(&self, t: &TextObject) -> (usize, usize) {
|
||||
let len = vectorcraft_text::edit::runs_len(&t.runs);
|
||||
let a = self.start.unwrap_or(0).min(len);
|
||||
let b = self.end.unwrap_or(len).min(len);
|
||||
(a.min(b), a.max(b))
|
||||
}
|
||||
/// The paragraphs of `t` the range touches.
|
||||
pub(crate) fn paras(&self, t: &TextObject) -> std::ops::Range<usize> {
|
||||
let (a, b) = self.bytes(t);
|
||||
t.paragraphs_in(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraphs of `t` an optional range touches (None: every paragraph).
|
||||
pub(crate) fn para_span(range: Option<TextRange>, t: &TextObject) -> Option<std::ops::Range<usize>> {
|
||||
range.map(|r| r.paras(t))
|
||||
}
|
||||
|
||||
/// Apply `f` to the character styles of `range` of `t` (None: every run).
|
||||
pub(crate) fn style_chars(t: &mut TextObject, range: Option<TextRange>, mut f: impl FnMut(&mut vectorcraft_doc::CharStyle)) {
|
||||
match range {
|
||||
None => t.runs.iter_mut().for_each(|r| f(&mut r.style)),
|
||||
Some(r) => {
|
||||
let (a, b) = r.bytes(t);
|
||||
if a < b {
|
||||
vectorcraft_text::edit::style_range(&mut t.runs, a, b, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string();
|
||||
let ids = text_targets(s, p, "text.setText")?;
|
||||
@@ -181,7 +341,9 @@ fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let style = t.first_style();
|
||||
t.runs = vec![vectorcraft_doc::TextRun { text: text.clone(), style }];
|
||||
// Every paragraph of the new text takes the first paragraph's attributes.
|
||||
t.splice_paras(0, vectorcraft_text::edit::runs_len(&t.runs), &text);
|
||||
t.runs = vec![vectorcraft_doc::TextRun { text: text.clone(), style, inline: None }];
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
@@ -238,14 +400,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "nothing to change"));
|
||||
}
|
||||
let range = TextRange::parse(p, C)?;
|
||||
let ids = text_targets(s, p, C)?;
|
||||
let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some());
|
||||
s.edit("Character", |d, _| {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let before = protect.then(|| t.runs.clone());
|
||||
for r in &mut t.runs {
|
||||
let st = &mut r.style;
|
||||
style_chars(t, range, |st| {
|
||||
if let Some(f) = &font {
|
||||
st.font_family = f.clone();
|
||||
}
|
||||
@@ -267,12 +429,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(f) = &features {
|
||||
st.features = f.clone();
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(before) = before {
|
||||
super::textedit::protect_missing_glyphs(&before, &mut t.runs);
|
||||
}
|
||||
if let Some(j) = justify {
|
||||
t.para.justify = j;
|
||||
let span = para_span(range, t);
|
||||
t.edit_paras(span, |pa| pa.justify = j);
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
@@ -292,10 +455,18 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
let height = |t: &TextObject| auto_height_frame(t).map(|b| b.height());
|
||||
let was = height(t);
|
||||
if !(f(t) && within(t)) {
|
||||
t.kind = before;
|
||||
return false;
|
||||
}
|
||||
// Setting the height by hand turns Auto Size off (as in Illustrator); a new width keeps it.
|
||||
if let (Some(a), Some(b)) = (was, height(t))
|
||||
&& (a - b).abs() > 1e-6
|
||||
{
|
||||
t.area.fit = vectorcraft_doc::AreaFit::None;
|
||||
}
|
||||
refresh_bounds(t);
|
||||
true
|
||||
}
|
||||
@@ -334,6 +505,60 @@ fn size_area(t: &mut TextObject, w: Option<f64>, h: Option<f64>) -> bool {
|
||||
reshape_area_with(t, |t| t.transform_area(a))
|
||||
}
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent`
|
||||
/// while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaFit>> {
|
||||
let min = p.get("fitMinPercent").and_then(Value::as_f64);
|
||||
let cur_min = match cur {
|
||||
AreaFit::ShrinkText { min_percent } => Some(min_percent),
|
||||
_ => None,
|
||||
};
|
||||
let fit = match p.get("fit") {
|
||||
None | Some(Value::Null) => match (cur, min) {
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m },
|
||||
_ => return Ok(None),
|
||||
},
|
||||
Some(Value::String(id)) => {
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))?
|
||||
}
|
||||
Some(v) => match serde_json::from_value::<AreaFit>(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
};
|
||||
Ok(Some(match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as
|
||||
/// its id and `fitMinPercent` beside it, the frame's `width` and `height`, and whether the text
|
||||
/// `overflow`s its frame at `fitScale` (Shrink Text to Fit's factor; 1 unshrunk).
|
||||
pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("fit".into(), json!(t.area.fit.id()));
|
||||
let min = match t.area.fit {
|
||||
AreaFit::ShrinkText { min_percent } => min_percent,
|
||||
_ => AreaFit::DEFAULT_MIN_PERCENT,
|
||||
};
|
||||
o.insert("fitMinPercent".into(), json!(min));
|
||||
if let Some((w, h, _)) = area_size(t) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
}
|
||||
o.insert("overflow".into(), json!(lay.overflow));
|
||||
o.insert("fitScale".into(), json!(lay.fit_scale));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The [`vectorcraft_doc::AreaOptions`] keys `text.areaOptions` merges as they are.
|
||||
const AREA_KEYS: [&str; 7] = ["rows", "columns", "gutter", "inset", "firstBaseline", "firstBaselineMin", "verticalAlign"];
|
||||
|
||||
fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.areaOptions";
|
||||
let ids: Vec<NodeId> = {
|
||||
@@ -343,34 +568,35 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
|
||||
let options = |s: &Session| -> Result<Value> {
|
||||
let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?;
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if let (Some(o), Some((w, h, _))) = (v.as_object_mut(), area_size(t)) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
}
|
||||
Ok(v)
|
||||
area_options_json(t)
|
||||
};
|
||||
let mut v = options(s)?;
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, h) = (size("width"), size("height"));
|
||||
let mut changed = w.is_some() || h.is_some();
|
||||
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
|
||||
let fit = fit_param(p, cur.fit, C)?;
|
||||
let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, mut h) = (size("width"), size("height"));
|
||||
let mut changed = w.is_some() || h.is_some() || fit.is_some();
|
||||
if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) {
|
||||
for (k, val) in src {
|
||||
if o.contains_key(k) && !matches!(k.as_str(), "ids" | "width" | "height") {
|
||||
o.insert(k.clone(), val.clone());
|
||||
changed = true;
|
||||
}
|
||||
for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) {
|
||||
o.insert(k.clone(), val.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return Ok(v);
|
||||
return options(s);
|
||||
}
|
||||
let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?;
|
||||
opts.rows = opts.rows.clamp(1, 100);
|
||||
opts.columns = opts.columns.clamp(1, 100);
|
||||
opts.gutter = opts.gutter.clamp(0.0, 10_000.0);
|
||||
opts.inset = opts.inset.clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = opts.first_baseline_min.clamp(0.0, 10_000.0);
|
||||
let finite = |x: f64| if x.is_finite() { x } else { 0.0 };
|
||||
opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0);
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
opts.fit = fit.unwrap_or(cur.fit);
|
||||
if opts.fit == AreaFit::AutoHeight {
|
||||
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
|
||||
h = None;
|
||||
}
|
||||
s.edit("Area Type Options", |d, _| {
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
@@ -426,7 +652,7 @@ mod area_tests {
|
||||
NodeKind::Text(t) => t.para.clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
// New type: Standard, as in Illustrator.
|
||||
// New type: Standard.
|
||||
assert_eq!(para(&s).burasagari, Burasagari::Standard);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
assert!(s.execute("text.setFormat", &json!({"burasagari": "strong"})).is_err());
|
||||
@@ -563,6 +789,12 @@ mod area_tests {
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 3, "end": 6, "charAlign": "emBoxTop"})).unwrap();
|
||||
let aligns: Vec<_> = runs(&s).iter().map(|r| (r.text.clone(), r.style.char_align)).collect();
|
||||
assert_eq!(aligns, [("雅".to_string(), CharAlign::RomanBaseline), ("楽".to_string(), CharAlign::EmBoxTop)]);
|
||||
// The ideographic character face's top and bottom.
|
||||
for (key, want) in [("icfTop", CharAlign::IcfTop), ("icfBottom", CharAlign::IcfBottom)] {
|
||||
s.execute("text.setFormat", &json!({"charAlign": key})).unwrap();
|
||||
assert!(runs(&s).iter().all(|r| r.style.char_align == want));
|
||||
assert_eq!(serde_json::to_value(&runs(&s)[0].style).unwrap()["charAlign"], key);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -644,7 +876,8 @@ fn headline_fit(t: &TextObject, tracking: f64) -> Option<(f64, f64, usize)> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe);
|
||||
let cell = lay.frames.first()?;
|
||||
let line = lay.lines.first()?;
|
||||
let avail = cell.width() - 2.0 * t.area.inset - t.para.left_indent - t.para.right_indent;
|
||||
let para = t.para_at(0);
|
||||
let avail = cell.width() - 2.0 * t.area.inset - para.left_indent - para.right_indent;
|
||||
Some((line.x1 - line.x0, avail, lay.lines.iter().filter(|l| l.start < para_end).count()))
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,8 @@ fn edit_runs<S: Default>(s: &mut Session, label: &str, ids: &[NodeId], f: impl F
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
let mut st = S::default();
|
||||
let mut any = false;
|
||||
for r in &mut t.runs {
|
||||
// Inline graphics are art, not characters to rewrite.
|
||||
for r in t.runs.iter_mut().filter(|r| r.inline.is_none()) {
|
||||
let n = f(&r.text, &mut st);
|
||||
if n != r.text {
|
||||
r.text = n;
|
||||
@@ -272,7 +273,7 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0);
|
||||
let slack = size * 0.5;
|
||||
// Slack goes where the alignment leaves room, so the text doesn't move or rewrap.
|
||||
let (sl, sr) = match t.para.justify {
|
||||
let (sl, sr) = match t.para_at(0).justify {
|
||||
Justify::Center | Justify::JustifyCenter => (slack * 0.5, slack * 0.5),
|
||||
Justify::Right | Justify::JustifyRight => (slack, 0.0),
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => (slack, 0.0),
|
||||
@@ -315,20 +316,33 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
breaks.sort_unstable();
|
||||
breaks.dedup();
|
||||
for b in breaks.into_iter().rev() {
|
||||
// Each wrapped line becomes a paragraph with its paragraph's attributes.
|
||||
if plain.as_bytes().get(b - 1) == Some(&b' ') {
|
||||
if let Some((ri, bi)) = locate(&t.runs, b - 1) {
|
||||
t.splice_paras(b - 1, b, "\n");
|
||||
t.runs[ri].text.replace_range(bi..bi + 1, "\n");
|
||||
}
|
||||
} else if let Some((ri, bi)) = locate(&t.runs, b) {
|
||||
t.runs[ri].text.insert(bi, '\n');
|
||||
t.splice_paras(b, b, "\n");
|
||||
// Never inside an inline graphic's run: at the end of the run before it, or a
|
||||
// run of its own.
|
||||
match t.runs.get(ri) {
|
||||
Some(r) if r.inline.is_some() => match ri.checked_sub(1).and_then(|p| t.runs.get_mut(p)) {
|
||||
Some(prev) if prev.inline.is_none() => prev.text.push('\n'),
|
||||
_ => {
|
||||
let style = t.runs.get(ri).map(|r| r.style.clone()).unwrap_or_default();
|
||||
t.runs.insert(ri, TextRun::new("\n", style));
|
||||
}
|
||||
},
|
||||
_ => t.runs[ri].text.insert(bi, '\n'),
|
||||
}
|
||||
}
|
||||
}
|
||||
// The point origin sits where the alignment anchors the first line.
|
||||
let (x0, x1) = lay
|
||||
.lines
|
||||
.first()
|
||||
.map_or((fb.x0, fb.x1), |l| (l.avail.0 - t.para.left_indent - t.para.first_line_indent, l.avail.1 + t.para.right_indent));
|
||||
let ox = match t.para.justify {
|
||||
let p0 = t.para_at(0);
|
||||
let (x0, x1) =
|
||||
lay.lines.first().map_or((fb.x0, fb.x1), |l| (l.avail.0 - p0.left_indent - p0.first_line_indent, l.avail.1 + p0.right_indent));
|
||||
let ox = match p0.justify {
|
||||
Justify::Center | Justify::JustifyCenter => (x0 + x1) * 0.5,
|
||||
Justify::Right | Justify::JustifyRight => x1,
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1,
|
||||
@@ -479,7 +493,7 @@ pub(crate) fn fill_with_placeholder(t: &mut TextObject) {
|
||||
}
|
||||
_ => PLACEHOLDER.split(". ").next().unwrap_or(PLACEHOLDER).to_string() + ".",
|
||||
};
|
||||
t.runs = vec![TextRun { text, style }];
|
||||
t.runs = vec![TextRun { text, style, inline: None }];
|
||||
refresh_bounds(t);
|
||||
}
|
||||
|
||||
@@ -529,8 +543,13 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
match t.runs.last_mut() {
|
||||
Some(r) => r.text.push_str(&text),
|
||||
None => t.runs.push(TextRun { text: text.clone(), style: CharStyle::default() }),
|
||||
Some(r) if r.inline.is_none() => r.text.push_str(&text),
|
||||
// After an inline graphic: a run of its own, in its style.
|
||||
Some(r) => {
|
||||
let style = r.style.clone();
|
||||
t.runs.push(TextRun::new(text.clone(), style));
|
||||
}
|
||||
None => t.runs.push(TextRun { text: text.clone(), style: CharStyle::default(), inline: None }),
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
@@ -645,8 +664,8 @@ fn find_next(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn strip_formatting(n: &mut vectorcraft_doc::Node) {
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
let text = t.plain_text();
|
||||
t.runs = vec![TextRun { text, style: CharStyle::default() }];
|
||||
t.para = Default::default();
|
||||
t.runs = vec![TextRun { text, style: CharStyle::default(), inline: None }];
|
||||
t.set_all_paras(Default::default());
|
||||
refresh_bounds(t);
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
|
||||
@@ -80,7 +80,19 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts) -> Value {
|
||||
v["anchors"] = json!(path.anchor_count());
|
||||
v["closed"] = json!(path.is_closed());
|
||||
}
|
||||
NodeKind::Text(t) => v["text"] = json!(t.plain_text()),
|
||||
NodeKind::Text(t) => {
|
||||
v["text"] = json!(t.plain_text());
|
||||
// Area type and type on a path: does the text fit (the red overflow "+")? Area type
|
||||
// also reports its fit and Shrink Text's factor (1 unshrunk).
|
||||
if !matches!(t.kind, vectorcraft_doc::TextKind::Point) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
v["overflow"] = json!(lay.overflow);
|
||||
if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) {
|
||||
v["fit"] = json!(t.area.fit.id());
|
||||
v["fitScale"] = json!(lay.fit_scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
|
||||
+90
-21
@@ -153,6 +153,8 @@ pub struct DocState {
|
||||
pub recovery: Option<cmd::recovery::RecoveryCopy>,
|
||||
/// View → Show Print Tiling, per document (view state: not saved, not undoable).
|
||||
pub print_tiling: bool,
|
||||
/// The rows open in the Layers panel (view state: not undoable; native files keep it).
|
||||
pub layers_open: OpenRows,
|
||||
/// Transform Again after a perspective move or scale (Perspective Selection tool): the
|
||||
/// `perspective.transform` params it repeats. `None` once an ordinary transform follows.
|
||||
pub last_perspective: Option<Value>,
|
||||
@@ -160,11 +162,61 @@ pub struct DocState {
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
|
||||
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
|
||||
/// its top-level layers open.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct OpenRows {
|
||||
ids: std::collections::HashSet<NodeId>,
|
||||
/// Counts the changes, so views can keep what they work out from the open rows.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
impl OpenRows {
|
||||
/// The rows `saved` in a file, else `doc`'s top-level layers.
|
||||
fn new(doc: &Document, saved: Option<Vec<NodeId>>) -> Self {
|
||||
let ids = match saved {
|
||||
Some(ids) => ids.into_iter().collect(),
|
||||
None => doc.layers.iter().map(|l| l.id).collect(),
|
||||
};
|
||||
Self { ids, generation: 0 }
|
||||
}
|
||||
pub fn contains(&self, id: NodeId) -> bool {
|
||||
self.ids.contains(&id)
|
||||
}
|
||||
/// Open or close row `id`.
|
||||
pub fn set(&mut self, id: NodeId, open: bool) {
|
||||
let changed = if open { self.ids.insert(id) } else { self.ids.remove(&id) };
|
||||
self.generation += u64::from(changed);
|
||||
}
|
||||
/// Changes so far: the same number means the same open rows.
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
/// What a native file keeps of the open rows: those of `doc` that hold others, in id order;
|
||||
/// `None` when they are the default (only the top-level layers).
|
||||
pub fn saved(&self, doc: &Document) -> Option<Vec<NodeId>> {
|
||||
let mut ids = vec![];
|
||||
doc.walk(|n| {
|
||||
if n.children().is_some() && self.ids.contains(&n.id) {
|
||||
ids.push(n.id);
|
||||
}
|
||||
});
|
||||
ids.sort_unstable();
|
||||
let mut layers: Vec<NodeId> = doc.layers.iter().map(|l| l.id).collect();
|
||||
layers.sort_unstable();
|
||||
(ids != layers).then_some(ids)
|
||||
}
|
||||
}
|
||||
|
||||
impl DocState {
|
||||
pub fn new(mut doc: Document, path: Option<String>) -> Self {
|
||||
let active_layer = doc.default_layer();
|
||||
// The saved view lives here while the document is open (saves write it back).
|
||||
// The saved view and open Layers rows live here while the document is open (saves write
|
||||
// them back).
|
||||
let view = doc.last_view.take();
|
||||
let saved_open = doc.layers_open.take();
|
||||
let layers_open = OpenRows::new(&doc, saved_open);
|
||||
let doc = Arc::new(doc);
|
||||
Self {
|
||||
saved_doc: doc.clone(),
|
||||
@@ -190,6 +242,7 @@ impl DocState {
|
||||
recovered: false,
|
||||
recovery: None,
|
||||
print_tiling: false,
|
||||
layers_open,
|
||||
last_perspective: None,
|
||||
}
|
||||
}
|
||||
@@ -908,6 +961,8 @@ impl Session {
|
||||
/// Text layout bounds are a cache (not saved): compute them for a document just read, or
|
||||
/// selection boxes and hit testing would use the rough estimate until each text is edited.
|
||||
fn refresh_text_bounds(doc: &mut Document) {
|
||||
// Inline graphics in text take their size from their symbols' art (not saved either).
|
||||
doc.resolve_inline_art();
|
||||
let mut texts = vec![];
|
||||
doc.walk(|n| {
|
||||
if matches!(n.kind, NodeKind::Text(_)) {
|
||||
@@ -954,6 +1009,7 @@ impl Session {
|
||||
st.save_options = old.save_options.clone();
|
||||
st.converted = old.converted;
|
||||
st.view = old.view.clone();
|
||||
st.layers_open = old.layers_open.clone();
|
||||
let old = std::mem::replace(&mut self.docs[index], st);
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
@@ -1100,27 +1156,32 @@ impl Session {
|
||||
let before_sel = st.selection.clone();
|
||||
let doc = Arc::make_mut(&mut st.doc);
|
||||
let result = match f(doc, &mut st.selection) {
|
||||
Ok(v) => {
|
||||
// Text Wrap: area type follows its wrap objects; then threads re-flow.
|
||||
cmd::textwrap::refresh(Arc::make_mut(&mut st.doc));
|
||||
// Opacity-mask editing: the mask follows its art on the editing layer.
|
||||
if st.doc.mask_edit.is_some() {
|
||||
cmd::maskedit::sync(Arc::make_mut(&mut st.doc));
|
||||
Ok(v) => match cmd::shaper::refresh(&before, Arc::make_mut(&mut st.doc)) {
|
||||
Err(e) => Err(e),
|
||||
Ok(()) => {
|
||||
// Inline graphics in text follow their symbols.
|
||||
cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc));
|
||||
// Text Wrap: area type follows its wrap objects; then threads re-flow.
|
||||
cmd::textwrap::refresh(Arc::make_mut(&mut st.doc));
|
||||
// Opacity-mask editing: the mask follows its art on the editing layer.
|
||||
if st.doc.mask_edit.is_some() {
|
||||
cmd::maskedit::sync(Arc::make_mut(&mut st.doc));
|
||||
}
|
||||
// Threaded text re-flows when any of its frames changed.
|
||||
if !st.doc.text_threads.is_empty() {
|
||||
cmd::threads::reflow(&before, Arc::make_mut(&mut st.doc));
|
||||
}
|
||||
// Asset Export: assets let go of deleted art.
|
||||
if !st.doc.assets.is_empty() {
|
||||
Arc::make_mut(&mut st.doc).prune_assets();
|
||||
}
|
||||
if doc_sane(&st.doc, &st.selection) {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()))
|
||||
}
|
||||
}
|
||||
// Threaded text re-flows when any of its frames changed.
|
||||
if !st.doc.text_threads.is_empty() {
|
||||
cmd::threads::reflow(&before, Arc::make_mut(&mut st.doc));
|
||||
}
|
||||
// Asset Export: assets let go of deleted art.
|
||||
if !st.doc.assets.is_empty() {
|
||||
Arc::make_mut(&mut st.doc).prune_assets();
|
||||
}
|
||||
if doc_sane(&st.doc, &st.selection) {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into()))
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match result {
|
||||
@@ -1293,6 +1354,8 @@ mod tests_adjust;
|
||||
#[cfg(test)]
|
||||
mod tests_appearance;
|
||||
#[cfg(test)]
|
||||
mod tests_areafit;
|
||||
#[cfg(test)]
|
||||
mod tests_assets;
|
||||
#[cfg(test)]
|
||||
mod tests_attributes;
|
||||
@@ -1383,6 +1446,8 @@ mod tests_gradpanel;
|
||||
#[cfg(test)]
|
||||
mod tests_halftone;
|
||||
#[cfg(test)]
|
||||
mod tests_inline;
|
||||
#[cfg(test)]
|
||||
mod tests_journal;
|
||||
#[cfg(test)]
|
||||
mod tests_knockout;
|
||||
@@ -1429,6 +1494,8 @@ mod tests_paintproxy;
|
||||
#[cfg(test)]
|
||||
mod tests_panelcmds;
|
||||
#[cfg(test)]
|
||||
mod tests_paragraphs;
|
||||
#[cfg(test)]
|
||||
mod tests_pathops;
|
||||
#[cfg(test)]
|
||||
mod tests_pathtype;
|
||||
@@ -1491,6 +1558,8 @@ mod tests_saveoptions;
|
||||
#[cfg(test)]
|
||||
mod tests_scalestrokes;
|
||||
#[cfg(test)]
|
||||
mod tests_shaper;
|
||||
#[cfg(test)]
|
||||
mod tests_slices;
|
||||
#[cfg(test)]
|
||||
mod tests_smartguides;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
fn session() -> Session {
|
||||
@@ -695,7 +696,7 @@ fn snap_to_pixel_rounds_drawing_and_moves() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_delete() {
|
||||
fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_punch_fills() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
@@ -725,10 +726,86 @@ fn shaper_turns_rough_strokes_into_live_shapes_and_scribbles_delete() {
|
||||
"{:?}",
|
||||
n.kind_label()
|
||||
);
|
||||
// A zig-zag over it deletes it.
|
||||
// A zig-zag inside it clears its fill while retaining the editable original and stroke.
|
||||
let zig: Vec<(f64, f64)> = (0..30).map(|i| (150.0 + (i % 2) as f64 * 80.0, 120.0 + i as f64 * 2.0)).collect();
|
||||
stroke(&mut s, &zig);
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap(), &n);
|
||||
let group = s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap();
|
||||
assert!(group.shaper.is_some());
|
||||
assert!(group.children().unwrap().iter().skip(1).all(|n| n.appearance.fill_paint().is_none()));
|
||||
assert!(group.children().unwrap().iter().skip(1).any(|n| !n.appearance.stroke_paint().is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_square_started_mid_edge_closes_on_pointer_release_and_undoes_once() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (kind, x, y) in [
|
||||
(PointerKind::Down, 150.0, 100.0),
|
||||
(PointerKind::Drag, 200.0, 105.0),
|
||||
(PointerKind::Drag, 194.0, 200.0),
|
||||
(PointerKind::Drag, 110.0, 191.0),
|
||||
(PointerKind::Drag, 100.0, 100.0),
|
||||
(PointerKind::Up, 150.0, 100.0),
|
||||
] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
|
||||
}
|
||||
let id = *s.doc().unwrap().selection.objects.first().expect("recognized square");
|
||||
assert!(matches!(
|
||||
s.doc().unwrap().doc.node(id).unwrap().kind,
|
||||
vectorcraft_doc::NodeKind::Path { live: Some(vectorcraft_doc::LiveShape::Rectangle { .. }), .. }
|
||||
));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_creates_upright_or_inverted_live_triangles_with_one_undo_step() {
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
for direction in [0.0_f64, 180.0] {
|
||||
let mut s = session();
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let corners: Vec<Point> = (0..3)
|
||||
.map(|i| {
|
||||
let angle = (direction + 7.0 - 90.0).to_radians() + std::f64::consts::TAU * i as f64 / 3.0;
|
||||
Point::new(200.0 + 70.0 * angle.cos(), 200.0 + 70.0 * angle.sin())
|
||||
})
|
||||
.collect();
|
||||
let mut pts = vec![];
|
||||
for i in 0..3 {
|
||||
for j in 0..20 {
|
||||
pts.push(corners[i] + (corners[(i + 1) % 3] - corners[i]) * (j as f64 / 20.0));
|
||||
}
|
||||
}
|
||||
// Begin midway along an edge; the release closes the final segment.
|
||||
pts.rotate_left(7);
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].x, pts[0].y), v).unwrap();
|
||||
for p in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, p.x, p.y), v).unwrap();
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, pts[0].x, pts[0].y), v).unwrap();
|
||||
let id = *s.doc().unwrap().selection.objects.first().expect("recognized triangle");
|
||||
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let vectorcraft_doc::NodeKind::Path { live: Some(vectorcraft_doc::LiveShape::Polygon { sides: 3, xf, .. }), .. } = &node.kind else {
|
||||
panic!("expected live triangle, got {:?}", node.kind_label());
|
||||
};
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (sin, cos) = direction.to_radians().sin_cos();
|
||||
for (actual, expected) in [(a, cos), (b, sin), (c, -sin), (d, cos)] {
|
||||
assert!((actual - expected).abs() < 1e-12, "direction {direction}, transform {xf:?}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(id).is_none());
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(id).unwrap(), &node);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Area type fitting: Auto Size (the frame's height follows the text), Shrink Text to Fit, and
|
||||
//! overflow reporting.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AreaFit, NodeKind, TextKind, TextObject};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
|
||||
const STORY: &str = "The quick brown fox jumps over the lazy dog. A second sentence follows the first one here. Then a third one ends it.";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn area(s: &mut Session, w: f64, h: f64, text: &str, extra: Value) -> NodeId {
|
||||
let mut a = json!({"width": w, "height": h});
|
||||
if let (Some(a), Some(e)) = (a.as_object_mut(), extra.as_object()) {
|
||||
a.extend(e.clone());
|
||||
}
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": a, "text": text})).unwrap()["id"].as_u64().unwrap();
|
||||
NodeId(id)
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(s: &Session, id: NodeId) -> Rect {
|
||||
match text(s, id).kind {
|
||||
TextKind::Area { frame } => frame.bounds().unwrap(),
|
||||
k => panic!("not area type: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn overflows(s: &Session, id: NodeId) -> bool {
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).overflow
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_options_set_and_report_the_fit() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({}));
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
assert_eq!((q["fit"].as_str(), q["fitMinPercent"].as_f64()), (Some("none"), Some(50.0)));
|
||||
assert_eq!((q["overflow"].as_bool(), q["fitScale"].as_f64()), (Some(true), Some(1.0)));
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("text.areaOptions", &json!({"fit": "shrinkText", "fitMinPercent": 20})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
assert_eq!((r["fit"].as_str(), r["fitMinPercent"].as_f64()), (Some("shrinkText"), Some(20.0)));
|
||||
assert_eq!(r["overflow"], false, "{r}");
|
||||
let f = r["fitScale"].as_f64().unwrap();
|
||||
assert!((0.2..1.0).contains(&f), "{f}");
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 20.0 });
|
||||
assert_eq!(text(&s, id).runs[0].style.size, 12.0, "the stored size stays");
|
||||
// The minimum alone, clamped; the object form; and bad values.
|
||||
s.execute("text.areaOptions", &json!({"fitMinPercent": 3})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 10.0 });
|
||||
s.execute("text.areaOptions", &json!({"fit": {"shrinkText": {"minPercent": 95}}})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::ShrinkText { min_percent: 95.0 });
|
||||
assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["overflow"], true, "95 % is not enough");
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": 7})).is_err());
|
||||
// The reply's own keys go back in unchanged (the dialog sends everything).
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
let again = s.execute("text.areaOptions", &q).unwrap();
|
||||
assert_eq!(again, q);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
// Undo back to no fit.
|
||||
while text(&s, id).area.fit != AreaFit::None {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(overflows(&s, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_reports_overflow_and_fit_scale() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({"fit": "shrinkText", "fitMinPercent": 10}));
|
||||
s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap();
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let kids = doc["layers"][0]["children"].as_array().unwrap();
|
||||
let node = kids.iter().find(|k| k["id"] == id.0).unwrap();
|
||||
assert_eq!(node["overflow"], false);
|
||||
assert_eq!(node["fit"], "shrinkText");
|
||||
assert!(node["fitScale"].as_f64().unwrap() < 1.0);
|
||||
let point = kids.iter().find(|k| k["id"] != id.0).unwrap();
|
||||
assert!(point.get("overflow").is_none() && point.get("fitScale").is_none(), "point type never overflows");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("text.areaOptions", &json!({"fit": "none"})).unwrap();
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id.0).unwrap().clone();
|
||||
assert_eq!((node["overflow"].as_bool(), node["fitScale"].as_f64(), node["fit"].as_str()), (Some(true), Some(1.0), Some("none")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_edits_in_the_same_undo_step() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 200.0, 300.0, "One line", json!({"fit": "autoHeight"}));
|
||||
let one = frame(&s, id);
|
||||
assert!(one.height() < 30.0, "the frame fits one line: {one:?}");
|
||||
assert_eq!((one.x0, one.y0, one.width()), (0.0, 0.0, 200.0), "top and width stay");
|
||||
assert!(!overflows(&s, id));
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.editRange", &json!({"id": id.0, "start": 8, "insert": format!(" {STORY}")})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let grown = frame(&s, id);
|
||||
assert!(grown.height() > one.height() * 2.0, "{grown:?}");
|
||||
assert!(!overflows(&s, id), "the grown frame holds the text");
|
||||
// Tight: a point less overflows.
|
||||
let mut t = text(&s, id);
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 200.0, grown.height() - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Character changes resize it too.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 3, "size": 40})).unwrap();
|
||||
assert!(frame(&s, id).height() > grown.height());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), grown);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), one, "one undo restores the text and the frame");
|
||||
assert_eq!(text(&s, id).plain_text(), "One line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_typing_with_the_type_tool() {
|
||||
let mut s = session();
|
||||
s.prefs.auto_size_area_type = true;
|
||||
// An empty frame (no placeholder text), so its first height is one line.
|
||||
s.prefs.placeholder_text = false;
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for (kind, (x, y)) in [(PointerKind::Down, (100.0, 100.0)), (PointerKind::Drag, (300.0, 400.0)), (PointerKind::Up, (300.0, 400.0))] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), v).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::AutoHeight, "the preference gives new area type Auto Size");
|
||||
let empty = frame(&s, id);
|
||||
assert!(empty.height() < 30.0, "{empty:?}");
|
||||
let n = undo_len(&s);
|
||||
for word in STORY.split_inclusive(' ') {
|
||||
s.tool_text(word, v).unwrap();
|
||||
}
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), STORY);
|
||||
assert_eq!(undo_len(&s), n + 1, "one typing step");
|
||||
let typed = frame(&s, id);
|
||||
assert!(typed.height() > empty.height() * 2.0, "{typed:?}");
|
||||
assert!(!overflows(&s, id));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), empty);
|
||||
assert_eq!(text(&s, id).plain_text(), "");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(frame(&s, id), typed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_in_columns_and_by_hand() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, &STORY.repeat(3), json!({"fit": "autoHeight"}));
|
||||
let one = frame(&s, id).height();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Height is ignored while Auto Size is on.
|
||||
let r = s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 12, "height": 500})).unwrap();
|
||||
let two = r["height"].as_f64().unwrap();
|
||||
assert!(two < 500.0 && two > one * 0.5, "{one} → {two}");
|
||||
assert_eq!(r["overflow"], false);
|
||||
assert_eq!(r["fit"], "autoHeight");
|
||||
// The least height the two columns fit: a point less overflows, and both columns are used.
|
||||
let mut t = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
assert!(lay.glyphs.iter().any(|g| g.origin.x > 160.0), "text flows into the second column");
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 300.0, two - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow);
|
||||
// Dragging the bottom edge sets the height by hand: Auto Size goes off.
|
||||
let b = frame(&s, id);
|
||||
s.execute("text.reshapeArea", &json!({"id": id.0, "anchors": [[0, 2], [0, 3]], "dx": 0, "dy": 50})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::None);
|
||||
assert!((frame(&s, id).height() - (b.height() + 50.0)).abs() < 1e-6);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A new width keeps it: the height follows the reflow.
|
||||
s.execute("text.reshapeArea", &json!({"id": id.0, "anchors": [[0, 1], [0, 2]], "dx": 100, "dy": 0})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::AutoHeight);
|
||||
assert!(frame(&s, id).height() < b.height());
|
||||
// Point type has no frame to size.
|
||||
let p = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "x"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [p]})).unwrap();
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "autoHeight"})).is_err(), "point type has no area options");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_round_trips_through_the_native_format() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 120.0, 30.0, STORY, json!({"fit": "shrinkText", "fitMinPercent": 35}));
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(id).unwrap().kind else { panic!() };
|
||||
assert_eq!(t.area.fit, AreaFit::ShrinkText { min_percent: 35.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_height_follows_the_leading_model_and_character_alignment() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 200.0, 300.0, STORY, json!({"fit": "autoHeight"}));
|
||||
let roman = frame(&s, id);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
// Top-to-Top leading: the first line moves up to touch the frame, the frame follows.
|
||||
s.execute("text.setFormat", &json!({"leadingModel": "emBoxTop"})).unwrap();
|
||||
let em = frame(&s, id);
|
||||
assert_ne!(em.height(), roman.height());
|
||||
assert!(!overflows(&s, id), "the frame holds the text under emBoxTop");
|
||||
// Mixed sizes aligned on the em box centre still fit exactly.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 3, "size": 30})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"charAlign": "emBoxCenter"})).unwrap();
|
||||
let mixed = frame(&s, id);
|
||||
assert!(mixed.height() > em.height());
|
||||
assert!(!overflows(&s, id));
|
||||
let mut t = text(&s, id);
|
||||
t.area.fit = AreaFit::None;
|
||||
t.kind = TextKind::Area {
|
||||
frame: vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::Shape::to_path(&Rect::new(0.0, 0.0, 200.0, mixed.height() - 1.0), 0.1)),
|
||||
};
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "tight");
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, Node, NodeKind};
|
||||
use vectorcraft_doc::{AppearanceItem, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Rect};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
|
||||
@@ -669,6 +669,39 @@ fn image_trace_make_and_expand_and_color_presets() {
|
||||
assert!(s.execute("imageTrace.make", &json!({"params": {"mode": "rainbow"}})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_create_strokes_makes_stroked_centre_lines() {
|
||||
let mut s = session();
|
||||
// A 3 px wide horizontal line from x = 10 to 90 at y = 50, placed at 2× from (100, 100).
|
||||
let r =
|
||||
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| if (10..90).contains(&x) && (49..52).contains(&y) { [0, 0, 0, 255] } else { [255; 4] });
|
||||
add_image(&mut s, &r, Affine::translate((100.0, 100.0)) * Affine::scale(2.0));
|
||||
let res = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true, "strokes": true, "strokeWidth": 5}})).unwrap();
|
||||
assert_eq!(res["paths"], 1);
|
||||
let g = NodeId(res["id"].as_u64().unwrap());
|
||||
let paths = traced_paths(&node(&s, g));
|
||||
let line = &paths[0];
|
||||
assert!(line.appearance.fill_paint().color().is_none(), "not filled");
|
||||
let st = line.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(st) = i { Some(st) } else { None }).expect("stroked");
|
||||
assert!((st.width - 6.0).abs() < 1.0, "3 px at 2× is about 6 pt: {}", st.width);
|
||||
assert_eq!((st.cap, st.join), (LineCap::Round, LineJoin::Round));
|
||||
assert_eq!(st.paint, Paint::solid(Color::rgb8(0, 0, 0)));
|
||||
let sp = &line.path_data().unwrap().subpaths[0];
|
||||
assert!(!sp.closed);
|
||||
let (a, b) = (sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p);
|
||||
assert!((a.y - 201.0).abs() < 1.5 && (b.y - 201.0).abs() < 1.5 && (a.x - b.x).abs() > 140.0, "{a:?} … {b:?}");
|
||||
let t = node(&s, g).trace.unwrap();
|
||||
assert_eq!((t["params"]["strokes"].as_bool(), t["params"]["strokeWidth"].as_f64()), (Some(true), Some(5.0)));
|
||||
// Expand keeps the stroked line.
|
||||
s.execute("imageTrace.expand", &json!({})).unwrap();
|
||||
assert!(node(&s, g).children().unwrap()[0].appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))));
|
||||
// Create needs Fills or Strokes, and a stroke width.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
for p in [json!({"fills": false, "strokes": false}), json!({"strokes": true, "strokeWidth": 0}), json!({"strokeWidth": -3})] {
|
||||
assert!(s.execute("imageTrace.make", &json!({"id": g.0, "params": p})).is_err(), "{p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_presets_query_and_errors() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Inline graphics in text: `text.insertInline`, editing over them, undo, following their symbol.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// A symbol `name` made of a circle `d` points across (drawn in code), its instance deleted.
|
||||
fn circle_symbol(s: &mut Session, name: &str, d: f64) {
|
||||
s.execute("shape.ellipse", &json!({"x": 600, "y": 500, "width": d, "height": d})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": name})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
fn text(s: &mut Session, t: &str) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": t, "size": 20})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn obj(s: &Session, id: NodeId) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_count(t: &TextObject) -> usize {
|
||||
t.runs.iter().filter(|r| r.inline.is_some()).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_inline_places_a_symbol_as_one_character() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Tap", 10.0);
|
||||
let id = text(&mut s, "Tap: add");
|
||||
let before = obj(&s, id).bounds().unwrap();
|
||||
let r = s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap", "scale": 1.5, "shift": 1})).unwrap();
|
||||
assert_eq!(r, json!({"id": id.0, "caret": INLINE_CHAR.len_utf8()}));
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(t.plain_text(), format!("{INLINE_CHAR}Tap: add"));
|
||||
let art = t.runs[0].inline.as_ref().unwrap();
|
||||
assert_eq!((art.symbol.as_str(), art.scale, art.baseline_shift), ("Tap", 1.5, 1.0));
|
||||
// Resolved from the symbol (a 10 pt circle), and the text grew by the art (30 pt wide).
|
||||
let b = art.bounds.unwrap();
|
||||
assert!((b.width() - 10.0).abs() < 0.5 && (b.height() - 10.0).abs() < 0.5, "{b:?}");
|
||||
let after = t.bounds().unwrap();
|
||||
assert!((after.width() - before.width() - 30.0).abs() < 1.0, "{before:?} → {after:?}");
|
||||
// It takes the style of the text it sits in.
|
||||
assert_eq!(t.runs[0].style.size, 20.0);
|
||||
// text.getRange reports it.
|
||||
let g = s.execute("text.getRange", &json!({"id": id.0, "start": 0, "end": 3})).unwrap();
|
||||
assert_eq!(g["runs"][0]["inline"], json!({"symbol": "Tap", "scale": 1.5, "baseline_shift": 1.0}));
|
||||
assert_eq!(g["text"], json!(INLINE_CHAR.to_string()));
|
||||
// One undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(inline_count(&obj(&s, id)), 0);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(inline_count(&obj(&s, id)), 1);
|
||||
// Deleting any part of its character deletes it whole.
|
||||
s.execute("text.editRange", &json!({"id": id.0, "start": 1, "end": 3})).unwrap();
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(t.plain_text(), "Tap: add");
|
||||
assert_eq!(inline_count(&t), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_inline_rejects_junk() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Dot", 8.0);
|
||||
let id = text(&mut s, "abc");
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
for p in [
|
||||
json!({"id": id.0, "symbol": "Nope"}),
|
||||
json!({"id": id.0, "symbol": 7}),
|
||||
json!({"id": id.0, "symbol": "Dot", "scale": 0}),
|
||||
json!({"id": id.0, "symbol": "Dot", "scale": -1}),
|
||||
json!({"id": id.0, "symbol": "Dot", "scale": 1e9}),
|
||||
json!({"id": id.0, "symbol": "Dot", "shift": "up"}),
|
||||
json!({"id": id.0, "symbol": "Dot", "at": -3}),
|
||||
json!({"id": "x", "symbol": "Dot"}),
|
||||
json!({"id": rect["id"], "symbol": "Dot"}),
|
||||
json!({"id": 999999, "symbol": "Dot"}),
|
||||
json!({"symbol": "Dot"}),
|
||||
] {
|
||||
assert!(s.execute("text.insertInline", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(inline_count(&obj(&s, id)), 0);
|
||||
// Offsets past the end are clamped; mid-character offsets land on a boundary.
|
||||
let r = s.execute("text.insertInline", &json!({"id": id.0, "at": 99, "symbol": "Dot"})).unwrap();
|
||||
assert_eq!(r["caret"], json!(3 + INLINE_CHAR.len_utf8()));
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 4, "symbol": "Dot"})).unwrap();
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(t.plain_text(), format!("abc{INLINE_CHAR}{INLINE_CHAR}"));
|
||||
assert_eq!(inline_count(&t), 2);
|
||||
// A document without symbols has nothing to insert.
|
||||
let mut s = session();
|
||||
let id = text(&mut s, "abc");
|
||||
assert!(s.execute("text.insertInline", &json!({"id": id.0})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_tool_inserts_at_its_caret_and_deletes_the_graphic_whole() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Mana", 10.0);
|
||||
s.execute("symbol.setCurrent", &json!({"name": "Mana"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("type", v).unwrap();
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
s.tool_text("Pay ", v).unwrap();
|
||||
// The menu item: no params, inside a typing session.
|
||||
let r = s.execute("text.insertInline", &json!({})).unwrap();
|
||||
assert_eq!(r["id"], json!(id.0));
|
||||
assert_eq!(s.tool_options()["caret"], json!(4 + INLINE_CHAR.len_utf8()));
|
||||
s.tool_text(" now", v).unwrap();
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(t.plain_text(), format!("Pay {INLINE_CHAR} now"));
|
||||
assert_eq!(inline_count(&t), 1);
|
||||
assert_eq!(t.runs.iter().find(|r| r.inline.is_some()).unwrap().inline.as_ref().unwrap().symbol, "Mana");
|
||||
// Back over " now", then the graphic: one Backspace removes it whole.
|
||||
for _ in 0..5 {
|
||||
s.tool_key(ToolKey::Backspace, Mods::default(), v).unwrap();
|
||||
}
|
||||
let t = obj(&s, id);
|
||||
assert_eq!(t.plain_text(), "Pay ");
|
||||
assert_eq!(inline_count(&t), 0);
|
||||
// Undo brings it back.
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(inline_count(&obj(&s, id)), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_graphics_follow_their_symbol() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Dot", 10.0);
|
||||
let id = text(&mut s, "ab");
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Dot", "scale": 1})).unwrap();
|
||||
let w0 = obj(&s, id).bounds().unwrap().width();
|
||||
// Redefine the symbol as a 2:1 ellipse: the graphic (20 pt tall) widens to 40 pt.
|
||||
let e = s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [e["id"]]})).unwrap();
|
||||
s.execute("symbol.update", &json!({"name": "Dot"})).unwrap();
|
||||
let t = obj(&s, id);
|
||||
let b = t.runs[1].inline.as_ref().unwrap().bounds.unwrap();
|
||||
assert!((b.width() / b.height() - 2.0).abs() < 0.1, "{b:?}");
|
||||
let w1 = t.bounds().unwrap().width();
|
||||
assert!((w1 - w0 - 20.0).abs() < 1.5, "{w0} → {w1}");
|
||||
// Deleting the symbol leaves an empty slot (nothing drawn), and doesn't crash rendering.
|
||||
s.execute("symbol.delete", &json!({"name": "Dot"})).unwrap();
|
||||
let t = obj(&s, id);
|
||||
assert!(t.runs[1].inline.as_ref().unwrap().bounds.is_none());
|
||||
let _ = s.execute("document.serialize", &json!({"format": "png"})).unwrap();
|
||||
let _ = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let _ = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_documents_keep_inline_graphics() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Dot", 10.0);
|
||||
let id = text(&mut s, "ab");
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 1, "symbol": "Dot", "scale": 2})).unwrap();
|
||||
let doc = (*s.doc().unwrap().doc).clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("\"inline\""));
|
||||
let mut back = vectorcraft_format::load(&bytes).unwrap();
|
||||
// Bounds aren't saved: opening resolves them.
|
||||
let mut s2 = Session::new();
|
||||
back.title = "copy".into();
|
||||
s2.add_document(back, None);
|
||||
let t = obj(&s2, id);
|
||||
let art = t.runs[1].inline.as_ref().unwrap();
|
||||
assert_eq!((art.symbol.as_str(), art.scale), ("Dot", 2.0));
|
||||
assert!(art.bounds.is_some());
|
||||
assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_outlines_turns_inline_graphics_into_symbol_instances() {
|
||||
let mut s = session();
|
||||
circle_symbol(&mut s, "Dot", 10.0);
|
||||
let id = text(&mut s, "a b");
|
||||
s.execute("text.insertInline", &json!({"id": id.0, "at": 2, "symbol": "Dot"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let r = s.execute("type.createOutlines", &json!({})).unwrap();
|
||||
let g = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let kids = d.node(g).unwrap().children().unwrap();
|
||||
let inst = kids.iter().filter(|c| matches!(&c.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot")).count();
|
||||
assert_eq!(inst, 1);
|
||||
// Between the outlines of `a` and `b`.
|
||||
let pos = kids.iter().position(|c| matches!(c.kind, NodeKind::SymbolInstance { .. })).unwrap();
|
||||
assert!(pos > 0 && pos + 1 < kids.len(), "{pos} of {}", kids.len());
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Paragraph attributes per paragraph: ranged Paragraph panel commands, paragraph styles on one
|
||||
//! paragraph, splitting and merging paragraphs while editing, undo and threaded text.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Justify, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn area(s: &mut Session, text: &str) -> u64 {
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 300, "height": 300}})).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn justs(s: &Session, id: u64) -> Vec<Justify> {
|
||||
text(s, id).paragraph_styles().iter().map(|p| p.justify).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranged_paragraph_commands_touch_only_their_paragraphs() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, "one\ntwo\nthree");
|
||||
// A caret in "two" (byte 5): only the second paragraph.
|
||||
s.execute("text.setStyle", &json!({"id": id, "justify": "center", "start": 5, "end": 5})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Auto]);
|
||||
// A selection from "one" into "two": both.
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "spaceBefore": 9, "leftIndent": 4, "start": 1, "end": 5})).unwrap();
|
||||
let t = text(&s, id);
|
||||
let sb: Vec<f64> = t.paragraph_styles().iter().map(|p| p.space_before).collect();
|
||||
assert_eq!(sb, [9.0, 9.0, 0.0]);
|
||||
assert_eq!(t.para.left_indent, 4.0, "paragraph 0 is `para`");
|
||||
// Character attributes of setFormat follow the range too.
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "underline": true, "start": 4, "end": 7})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.runs.iter().any(|r| r.text == "two" && r.style.underline));
|
||||
assert!(t.runs.iter().any(|r| r.text.starts_with("one") && !r.style.underline));
|
||||
// The layout sees each paragraph's alignment.
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
assert!(lay.lines[1].x0 > lay.lines[0].x0 + 20.0, "the centred line sits right of the left one");
|
||||
// No range: every paragraph (as before).
|
||||
s.execute("text.setStyle", &json!({"id": id, "justify": "right"})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Right; 3]);
|
||||
// Undo steps back through the ranged edits.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Auto]);
|
||||
// Tabs per paragraph; a query reads the paragraph at `start`.
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "stops": [{"position": 40}], "start": 9, "end": 9})).unwrap();
|
||||
assert_eq!(s.execute("text.tabs.get", &json!({"ids": [id], "start": 9})).unwrap()["stops"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(s.execute("text.tabs.get", &json!({"ids": [id]})).unwrap()["stops"], json!([]));
|
||||
// Junk ranges are errors, not panics.
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id], "spaceAfter": 1, "start": -3})).is_err());
|
||||
assert!(s.execute("text.setStyle", &json!({"id": id, "justify": "left", "end": "x"})).is_err());
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "spaceAfter": 1, "start": 1_000_000, "end": u64::MAX})).unwrap();
|
||||
assert_eq!(text(&s, id).para_at(2).space_after, 1.0, "past the end: the last paragraph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_splits_and_merges_paragraph_styles() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, "one\ntwo\nthree");
|
||||
s.execute("text.setStyle", &json!({"id": id, "justify": "center", "start": 5, "end": 5})).unwrap();
|
||||
// A break inside "two": both halves keep its style.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 5, "end": 5, "insert": "\n"})).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), "one\nt\nwo\nthree");
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Center, Justify::Auto]);
|
||||
// Deleting the break after "one": the first paragraph's style wins.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 3, "end": 4})).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), "onet\nwo\nthree");
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Auto]);
|
||||
// Pasting styled runs with breaks in "wo": the new paragraphs continue it.
|
||||
let runs = json!([{"text": "A\nB\n", "style": text(&s, id).runs[0].style}]);
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 6, "end": 6, "runs": runs})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Center, Justify::Center, Justify::Auto]);
|
||||
// Undo restores the styles with the text.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Center, Justify::Center, Justify::Auto]);
|
||||
// Replacing all the text: every paragraph takes the first one's attributes.
|
||||
s.execute("text.setText", &json!({"ids": [id], "text": "x\ny"})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Auto, Justify::Auto]);
|
||||
assert!(text(&s, id).paras.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_in_the_type_tool_continues_the_paragraph_it_splits() {
|
||||
let mut s = session();
|
||||
let v = ViewInfo::default();
|
||||
let id = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "one\ntwo", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setStyle", &json!({"id": id, "justify": "right", "start": 0, "end": 0})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"id": id, "justify": "center", "start": 5, "end": 5})).unwrap();
|
||||
s.select_tool("type", v).unwrap();
|
||||
// Click into the first line (right-aligned: it ends at the origin), then End and Return.
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id));
|
||||
let l0 = &lay.lines[0];
|
||||
let (x, y) = (100.0 + (l0.x0 + l0.x1) / 2.0, 100.0 + l0.baseline - 5.0);
|
||||
for k in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(k, x, y), v).unwrap();
|
||||
}
|
||||
s.tool_key(ToolKey::End, Mods::default(), v).unwrap();
|
||||
s.tool_key(ToolKey::Enter, Mods::default(), v).unwrap();
|
||||
s.tool_text("new", v).unwrap();
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), "one\nnew\ntwo");
|
||||
assert_eq!(justs(&s, id), [Justify::Right, Justify::Right, Justify::Center]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Right, Justify::Center]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_style_applies_to_one_paragraph() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, "Title\nBody text");
|
||||
// The second paragraph keeps new type's attributes, whatever they are.
|
||||
let body = text(&s, id).para_at(1).clone();
|
||||
s.execute("paraStyle.new", &json!({"name": "Head", "attrs": {"justify": "Center", "space_after": 8.0}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Head", "id": id, "start": 2, "end": 2})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.para_at(0).style_name.as_deref(), Some("Head"));
|
||||
assert_eq!((t.para_at(0).justify, t.para_at(0).space_after), (Justify::Center, 8.0));
|
||||
assert_eq!(t.para_at(1), &body, "new type's");
|
||||
let list = s.execute("paraStyle.list", &json!({})).unwrap();
|
||||
assert_eq!(list["styles"][1]["uses"], 1, "one paragraph uses it");
|
||||
assert_eq!(list["styles"][0]["uses"], 1, "the other is Normal");
|
||||
// Redefining updates that paragraph only; renaming follows it.
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Head", "attrs": {"justify": "Right"}})).unwrap();
|
||||
assert_eq!(justs(&s, id), [Justify::Right, Justify::Auto]);
|
||||
s.execute("paraStyle.rename", &json!({"name": "Head", "to": "Heading"})).unwrap();
|
||||
assert_eq!(text(&s, id).para_at(0).style_name.as_deref(), Some("Heading"));
|
||||
// New from the selection reads the caret's paragraph.
|
||||
s.execute("paraStyle.new", &json!({"name": "From body", "id": id, "start": 8})).unwrap();
|
||||
let defs = &s.doc().unwrap().doc.para_styles;
|
||||
assert_eq!(defs.iter().find(|d| d.name == "From body").unwrap().attrs["justify"], "Auto");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threaded_frames_keep_each_paragraphs_style() {
|
||||
let mut s = session();
|
||||
let story = "The quick brown fox jumps over the lazy dog and keeps running. ".repeat(3) + "\nSecond paragraph.\nThird.";
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
let joined = |s: &Session| format!("{}{}", text(s, a).plain_text(), text(s, b).plain_text());
|
||||
assert_eq!(joined(&s), story);
|
||||
// Centre the second paragraph (in frame b) and right-align the third.
|
||||
let tb = text(&s, b).plain_text();
|
||||
let second = tb.find("Second").unwrap();
|
||||
s.execute("text.setStyle", &json!({"id": b, "justify": "center", "start": second, "end": second})).unwrap();
|
||||
let third = text(&s, b).plain_text().find("Third").unwrap();
|
||||
s.execute("text.setStyle", &json!({"id": b, "justify": "right", "start": third, "end": third})).unwrap();
|
||||
assert_eq!(justs(&s, b), [Justify::Auto, Justify::Center, Justify::Right]);
|
||||
// Typing in the first frame re-flows the story: the styles move with their paragraphs.
|
||||
s.execute("text.editRange", &json!({"id": a, "start": 0, "end": 0, "insert": "More words at the start of the story. "})).unwrap();
|
||||
let (ja, jb) = (justs(&s, a), justs(&s, b));
|
||||
assert_eq!(ja, [Justify::Auto]);
|
||||
assert_eq!(jb, [Justify::Auto, Justify::Center, Justify::Right]);
|
||||
// A break in the first frame makes a new paragraph there; the later ones keep their styles.
|
||||
s.execute("text.editRange", &json!({"id": a, "start": 4, "end": 4, "insert": "\n"})).unwrap();
|
||||
let all: Vec<Justify> = [justs(&s, a), justs(&s, b)].concat();
|
||||
assert_eq!(all.iter().filter(|j| **j == Justify::Center).count(), 1);
|
||||
assert_eq!(all.last(), Some(&Justify::Right));
|
||||
// Restyling the paragraph that continues into frame b (its first) sticks after the re-flow.
|
||||
s.execute("text.setStyle", &json!({"id": b, "justify": "justifyAll", "start": 0, "end": 0})).unwrap();
|
||||
assert_eq!(justs(&s, b)[0], Justify::JustifyAll);
|
||||
assert_eq!(*justs(&s, a).last().unwrap(), Justify::JustifyAll, "the paragraph's part in frame a follows");
|
||||
}
|
||||
|
||||
/// Upstream's paragraph attributes (direction, mojikumi, leading model) follow a range like the
|
||||
/// others: only the touched paragraphs change, and the layout reads each paragraph's own.
|
||||
#[test]
|
||||
fn ranged_set_format_sets_direction_mojikumi_and_leading_model_per_paragraph() {
|
||||
use vectorcraft_doc::{LeadingModel, Mojikumi, ParaDirection};
|
||||
let mut s = session();
|
||||
let id = area(&mut s, "Hello.\nHello.");
|
||||
// A caret in the second paragraph (byte 9).
|
||||
s.execute(
|
||||
"text.setFormat",
|
||||
&json!({"ids": [id], "direction": "rightToLeft", "leadingModel": "emBoxTop", "mojikumi": "none", "start": 9, "end": 9}),
|
||||
)
|
||||
.unwrap();
|
||||
let t = text(&s, id);
|
||||
let (p0, p1) = (t.para_at(0).clone(), t.para_at(1).clone());
|
||||
assert_eq!((p0.direction, p0.leading_model, p0.mojikumi), (None, LeadingModel::RomanBaseline, Mojikumi::LineEndHalf));
|
||||
assert_eq!((p1.direction, p1.leading_model, p1.mojikumi), (Some(ParaDirection::RightToLeft), LeadingModel::EmBoxTop, Mojikumi::None));
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
assert!(!lay.lines[0].rtl && lay.lines[1].rtl, "each paragraph's direction");
|
||||
// Return in the right-to-left paragraph continues it.
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 13, "end": 13, "insert": "\nX"})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.para_at(2).direction, Some(ParaDirection::RightToLeft));
|
||||
// No range: every paragraph.
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "direction": "auto"})).unwrap();
|
||||
assert!(text(&s, id).paragraph_styles().iter().all(|p| p.direction.is_none()));
|
||||
}
|
||||
@@ -260,6 +260,37 @@ fn the_saved_view_round_trips_without_dirtying() {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_layers_rows_round_trip_without_dirtying() {
|
||||
let d = dir("open-rows");
|
||||
let mut s = session();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
// A document starts with its top-level layers open, and a file keeps nothing for that.
|
||||
assert!(s.doc().unwrap().layers_open.contains(layer) && !s.doc().unwrap().layers_open.contains(g));
|
||||
let native = path(&d, "rows.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": native})).unwrap();
|
||||
let bytes = std::fs::read(&native).unwrap();
|
||||
assert_eq!(vectorcraft_format::load(&bytes).unwrap().layers_open, None);
|
||||
// Opening the group and closing the layer is view state: not an edit, kept by the file.
|
||||
let st = s.doc_mut().unwrap();
|
||||
st.layers_open.set(g, true);
|
||||
st.layers_open.set(layer, false);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
s.execute("document.save", &json!({"path": native})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.layers_open, None, "only the written file carries it");
|
||||
let mut again = session();
|
||||
again.execute("document.open", &json!({"path": native})).unwrap();
|
||||
let open = &again.doc().unwrap().layers_open;
|
||||
assert!(open.contains(g) && !open.contains(layer));
|
||||
// Older files (none saved) open with the top-level layers open.
|
||||
let doc = vectorcraft_format::load(&vectorcraft_format::save(&vectorcraft_doc::Document::new(5.0, 5.0), false)).unwrap();
|
||||
assert_eq!(doc.layers_open, None);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_plans_suggest_names_and_folders() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::shaper::{FILL_PREFIX, SOURCES, STROKE_PREFIX};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeKind};
|
||||
use vectorcraft_geom::{Point, Shape as _};
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap();
|
||||
s
|
||||
}
|
||||
fn rectangle(s: &mut Session, x: f64, fill: &str) -> NodeId {
|
||||
s.execute("paint.setFill", &json!({"color": fill, "ids": []})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x":x,"y":0,"width":100,"height":100})).unwrap()["id"].as_u64().unwrap();
|
||||
NodeId(id)
|
||||
}
|
||||
fn scribble(s: &mut Session, pts: &[[f64; 2]]) -> NodeId {
|
||||
NodeId(s.execute("shaper.scribble", &json!({"points":pts})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
fn node(s: &Session, id: NodeId) -> &Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap()
|
||||
}
|
||||
fn fill(s: &Session, id: NodeId, x: f64, y: f64) -> Option<String> {
|
||||
node(s, id)
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref() != Some(SOURCES))
|
||||
.rev()
|
||||
.find(|n| {
|
||||
n.name.as_deref().is_some_and(|n| n.starts_with(FILL_PREFIX))
|
||||
&& n.path_data().is_some_and(|p| p.to_bezpath().winding(Point::new(x, y)) != 0)
|
||||
})
|
||||
.map(|n| n.appearance.fill_paint().label())
|
||||
}
|
||||
fn stroke(s: &Session, id: NodeId, x: f64, y: f64) -> bool {
|
||||
node(s, id).children().unwrap().iter().filter(|n| n.name.as_deref() != Some(SOURCES)).any(|n| {
|
||||
n.name.as_deref().is_some_and(|n| n.starts_with(STROKE_PREFIX))
|
||||
&& !n.appearance.stroke_paint().is_none()
|
||||
&& n.path_data().and_then(|p| p.nearest(Point::new(x, y))).is_some_and(|(_, _, _, _, d)| d < 0.1)
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_merges_with_origin_color_keeps_live_originals_and_undoes_once() {
|
||||
for reverse in [false, true] {
|
||||
let mut s = session();
|
||||
let a = rectangle(&mut s, 0.0, "#ff0000");
|
||||
let b = rectangle(&mut s, 50.0, "#0000ff");
|
||||
let originals = [node(&s, a).clone(), node(&s, b).clone()];
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let mut pts = vec![[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0], [75.0, 80.0], [125.0, 85.0]];
|
||||
if reverse {
|
||||
pts.reverse();
|
||||
}
|
||||
let g = scribble(&mut s, &pts);
|
||||
let color = if reverse { "#0000ff" } else { "#ff0000" };
|
||||
for x in [25.0, 75.0, 125.0] {
|
||||
assert_eq!(fill(&s, g, x, 50.0).as_deref(), Some(color));
|
||||
}
|
||||
for n in &originals {
|
||||
assert_eq!(node(&s, n.id), n);
|
||||
}
|
||||
assert_eq!(node(&s, g).children().unwrap()[0].name.as_deref(), Some(SOURCES));
|
||||
assert!(!stroke(&s, g, 50.0, 50.0));
|
||||
assert!(stroke(&s, g, 0.0, 50.0));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
for n in &originals {
|
||||
assert_eq!(node(&s, n.id), n);
|
||||
}
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(fill(&s, g, 75.0, 50.0).as_deref(), Some(color));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_interior_punch_removes_the_whole_visible_front_face() {
|
||||
let mut s = session();
|
||||
let a = rectangle(&mut s, 0.0, "#ff0000");
|
||||
let b = rectangle(&mut s, 50.0, "#0000ff");
|
||||
let originals = [node(&s, a).clone(), node(&s, b).clone()];
|
||||
let g = scribble(&mut s, &[[65.0, 20.0], [85.0, 40.0], [65.0, 60.0], [85.0, 80.0]]);
|
||||
assert_eq!(fill(&s, g, 75.0, 50.0), None);
|
||||
assert_eq!(fill(&s, g, 25.0, 50.0).as_deref(), Some("#ff0000"));
|
||||
assert_eq!(fill(&s, g, 125.0, 50.0), None);
|
||||
assert!(stroke(&s, g, 50.0, 50.0) && stroke(&s, g, 150.0, 50.0));
|
||||
for n in &originals {
|
||||
assert_eq!(node(&s, n.id), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_exiting_scribble_erases_only_touched_fill_and_boundary_strokes() {
|
||||
let mut s = session();
|
||||
rectangle(&mut s, 0.0, "#ff0000");
|
||||
rectangle(&mut s, 50.0, "#0000ff");
|
||||
let g = scribble(&mut s, &[[110.0, 20.0], [140.0, 35.0], [110.0, 50.0], [140.0, 65.0], [200.0, 70.0]]);
|
||||
assert_eq!(fill(&s, g, 125.0, 50.0), None);
|
||||
assert!(!stroke(&s, g, 150.0, 50.0));
|
||||
assert_eq!(fill(&s, g, 25.0, 50.0).as_deref(), Some("#ff0000"));
|
||||
assert_eq!(fill(&s, g, 75.0, 50.0), None);
|
||||
assert!(stroke(&s, g, 0.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_erases_only_protruding_stroke_pieces_keeps_fill_and_original_line() {
|
||||
let mut s = session();
|
||||
s.execute("paint.setFill", &json!({"color":"#ffff00"})).unwrap();
|
||||
let circle = NodeId(s.execute("shape.ellipse", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap()["id"].as_u64().unwrap());
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1":50,"y1":150,"x2":250,"y2":150})).unwrap()["id"].as_u64().unwrap());
|
||||
let original_line = node(&s, line).clone();
|
||||
let g = scribble(&mut s, &[[60.0, 140.0], [70.0, 160.0], [80.0, 140.0], [90.0, 160.0]]);
|
||||
assert!(!stroke(&s, g, 75.0, 150.0));
|
||||
assert!(stroke(&s, g, 150.0, 150.0));
|
||||
assert!(stroke(&s, g, 225.0, 150.0));
|
||||
assert_eq!(fill(&s, g, 150.0, 130.0).as_deref(), Some("#ffff00"));
|
||||
assert_eq!(node(&s, line), &original_line);
|
||||
assert!(matches!(node(&s, circle).kind, NodeKind::Path { live: Some(LiveShape::Ellipse { .. }), .. }));
|
||||
let g = scribble(&mut s, &[[210.0, 140.0], [220.0, 160.0], [230.0, 140.0], [240.0, 160.0]]);
|
||||
assert!(!stroke(&s, g, 225.0, 150.0));
|
||||
assert!(stroke(&s, g, 150.0, 150.0));
|
||||
assert_eq!(node(&s, line), &original_line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_source_move_resize_native_roundtrip_and_release_preserve_live_art() {
|
||||
let mut s = session();
|
||||
let a = rectangle(&mut s, 0.0, "#ff0000");
|
||||
let b = rectangle(&mut s, 50.0, "#0000ff");
|
||||
let g = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]);
|
||||
s.execute("object.move", &json!({"ids":[a.0],"dx":20,"dy":10})).unwrap();
|
||||
assert_eq!(fill(&s, g, 30.0, 15.0).as_deref(), Some("#ff0000"));
|
||||
assert_eq!(node(&s, a).geometric_bounds().unwrap().x0, 20.0);
|
||||
s.execute("select.set", &json!({"ids":[a.0]})).unwrap();
|
||||
s.execute("object.setBounds", &json!({"width":120.0,"height":110.0,"reference":0})).unwrap();
|
||||
assert!(matches!(node(&s, a).kind, NodeKind::Path { live: Some(LiveShape::Rectangle { .. }), .. }));
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc, false)).unwrap();
|
||||
assert_eq!(back.layers, doc.layers);
|
||||
let originals = [node(&s, a).clone(), node(&s, b).clone()];
|
||||
s.execute("shaper.release", &json!({"id":g.0})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.node(g).is_none());
|
||||
for n in &originals {
|
||||
assert_eq!(node(&s, n.id), n);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_face_paint_survives_source_edits_and_expand_discards_only_sources() {
|
||||
let mut s = session();
|
||||
let a = rectangle(&mut s, 0.0, "#ff0000");
|
||||
rectangle(&mut s, 50.0, "#0000ff");
|
||||
let g = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]);
|
||||
s.execute("shaper.select", &json!({"point":[75,50]})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color":"#00ff00"})).unwrap();
|
||||
s.execute("object.move", &json!({"ids":[a.0],"dx":5,"dy":0})).unwrap();
|
||||
assert_eq!(fill(&s, g, 75.0, 50.0).as_deref(), Some("#00ff00"));
|
||||
s.execute("shaper.expand", &json!({"id":g.0})).unwrap();
|
||||
assert!(node(&s, g).shaper.is_none());
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none());
|
||||
assert_eq!(fill(&s, g, 75.0, 50.0).as_deref(), Some("#00ff00"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_double_click_selects_an_original_for_construction_editing() {
|
||||
let mut s = session();
|
||||
let a = rectangle(&mut s, 0.0, "#ff0000");
|
||||
rectangle(&mut s, 50.0, "#0000ff");
|
||||
let g = scribble(&mut s, &[[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]);
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
let requests = s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 25.0, 50.0), v).unwrap();
|
||||
assert!(requests.iter().any(|r| matches!(r, UiRequest::SwitchTool(tool) if tool == "selection")));
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a]);
|
||||
assert_eq!(s.doc().unwrap().isolation, Some(node(&s, g).children().unwrap()[0].id));
|
||||
assert!(s.doc().unwrap().doc.is_editable(a));
|
||||
s.execute("object.move", &json!({"dx":10,"dy":0})).unwrap();
|
||||
assert_eq!(fill(&s, g, 15.0, 50.0).as_deref(), Some("#ff0000"));
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![g]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_lines_keep_free_angles_with_or_without_shift() {
|
||||
for shift in [false, true] {
|
||||
let mut s = session();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
for (kind, x, y) in [(PointerKind::Down, 30.0, 40.0), (PointerKind::Drag, 130.0, 70.0), (PointerKind::Up, 230.0, 100.0)] {
|
||||
s.pointer(&PointerEvent::new(kind, x, y).with_mods(Mods { shift, ..Default::default() }), v).unwrap();
|
||||
}
|
||||
let n = node(&s, s.doc().unwrap().selection.objects[0]);
|
||||
assert!(matches!(n.kind,NodeKind::Path{live:Some(LiveShape::Line{a,b}),..} if a==Point::new(30.0,40.0) && b==Point::new(230.0,100.0)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_rejects_oversized_or_invalid_gestures_without_changing_art() {
|
||||
let mut s = session();
|
||||
rectangle(&mut s, 0.0, "#ff0000");
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = s.doc().unwrap().history.undo.len();
|
||||
for params in [json!({"points":vec![[1.0,1.0];4097]}), json!({"points":[[1,1],[2,2]],"tolerance":0}), json!({"points":[[1e100,0]]})] {
|
||||
assert!(s.execute("shaper.scribble", ¶ms).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_tool_trims_both_diagonal_ends_and_only_construction_can_pick_them() {
|
||||
use vectorcraft_doc::hit::{HitOptions, hit_test};
|
||||
let mut s = session();
|
||||
s.execute("paint.setFill", &json!({"color":"#ffff00"})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap();
|
||||
let rotate = |x: f64, y: f64| {
|
||||
let (x, y) = (x - 150.0, y - 150.0);
|
||||
Point::new(150.0 + (x + y) / 2.0f64.sqrt(), 150.0 + (y - x) / 2.0f64.sqrt())
|
||||
};
|
||||
let (a, b) = (rotate(50.0, 150.0), rotate(250.0, 150.0));
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1":a.x,"y1":a.y,"x2":b.x,"y2":b.y})).unwrap()["id"].as_u64().unwrap());
|
||||
let original = node(&s, line).clone();
|
||||
let v = ViewInfo { smart_guides: false, ..Default::default() };
|
||||
s.select_tool("shaper", v).unwrap();
|
||||
for offset in [0.0, 150.0] {
|
||||
let points = [(60.0, 140.0), (70.0, 160.0), (80.0, 140.0), (90.0, 160.0)];
|
||||
for (i, (x, y)) in points.into_iter().enumerate() {
|
||||
let p = rotate(x + offset, y);
|
||||
let kind = if i == 0 {
|
||||
PointerKind::Down
|
||||
} else if i == 3 {
|
||||
PointerKind::Up
|
||||
} else {
|
||||
PointerKind::Drag
|
||||
};
|
||||
s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap();
|
||||
}
|
||||
}
|
||||
let g = s.doc().unwrap().selection.objects[0];
|
||||
assert!(node(&s, g).shaper.is_some());
|
||||
assert_eq!(node(&s, line), &original);
|
||||
assert!(stroke(&s, g, 150.0, 150.0));
|
||||
assert_eq!(fill(&s, g, 150.0, 130.0).as_deref(), Some("#ffff00"));
|
||||
let sources = node(&s, g).children().unwrap()[0].id;
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
for x in [75.0, 225.0] {
|
||||
let p = rotate(x, 150.0);
|
||||
assert!(!stroke(&s, g, p.x, p.y));
|
||||
assert!(!node(&s, g).geometric_bounds().unwrap().contains(p));
|
||||
assert!(!node(&s, g).visual_bounds().unwrap().contains(p));
|
||||
assert!(hit_test(doc, p, HitOptions { tol: 0.5, ..Default::default() }).is_none());
|
||||
assert_eq!(hit_test(doc, p, HitOptions { tol: 0.5, scope: Some(sources), ..Default::default() }).unwrap().leaf, line);
|
||||
}
|
||||
let p = rotate(75.0, 150.0);
|
||||
s.execute("shaper.select", &json!({"point":[p.x,p.y],"source":true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![line]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_three_circles_erase_a_visible_fill_and_keep_the_complete_shared_curve() {
|
||||
for exits in [false, true] {
|
||||
let mut s = session();
|
||||
let mut originals = vec![];
|
||||
for (x, y, fill) in [(100.0, 20.0, "#ff0000"), (20.0, 130.0, "#ffffff"), (170.0, 130.0, "#ffff00")] {
|
||||
s.execute("paint.setFill", &json!({"color":fill,"ids":[]})).unwrap();
|
||||
let id = NodeId(s.execute("shape.ellipse", &json!({"x":x,"y":y,"width":200,"height":200})).unwrap()["id"].as_u64().unwrap());
|
||||
originals.push(node(&s, id).clone());
|
||||
}
|
||||
let mut points = vec![[290.0, 210.0], [330.0, 225.0], [290.0, 240.0], [330.0, 255.0]];
|
||||
if exits {
|
||||
points.push([410.0, 260.0]);
|
||||
}
|
||||
let g = scribble(&mut s, &points);
|
||||
for (x, y) in [(330.0, 230.0), (190.0, 230.0), (250.0, 180.0)] {
|
||||
assert_eq!(fill(&s, g, x, y), None, "all of the visible yellow face is erased, including covered intersections");
|
||||
}
|
||||
assert_eq!(stroke(&s, g, 370.0, 230.0), !exits);
|
||||
for angle in [145.0_f64, 160.0, 180.0, 200.0, 220.0, 240.0, 260.0, 280.0] {
|
||||
let (sin, cos) = angle.to_radians().sin_cos();
|
||||
assert!(stroke(&s, g, 270.0 + 100.0 * cos, 230.0 + 100.0 * sin), "shared curve remains complete at {angle}°, exiting {exits}");
|
||||
}
|
||||
if exits {
|
||||
// The two new corners must be actual path joins, rather than meeting butt caps.
|
||||
for corner in [Point::new(298.975, 134.288), Point::new(195.0, 296.144)] {
|
||||
assert!(
|
||||
node(&s, g)
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| n.name.as_deref().is_some_and(|s| s.starts_with(STROKE_PREFIX)))
|
||||
.flat_map(|n| n.path_data().unwrap().subpaths.iter())
|
||||
.flat_map(|sp| &sp.anchors)
|
||||
.any(|a| a.p.distance(corner) < 0.1 && a.has_in() && a.has_out()),
|
||||
"joined corner at {corner:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(fill(&s, g, 110.0, 230.0).as_deref(), Some("#ffffff"));
|
||||
assert_eq!(fill(&s, g, 200.0, 80.0).as_deref(), Some("#ff0000"));
|
||||
for n in originals {
|
||||
assert_eq!(node(&s, n.id), &n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_visible_dividing_stroke_keeps_fill_erasure_on_one_side() {
|
||||
let mut s = session();
|
||||
s.execute("paint.setFill", &json!({"color":"#ffff00","ids":[]})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap();
|
||||
s.execute("shape.line", &json!({"x1":100,"y1":150,"x2":200,"y2":150})).unwrap();
|
||||
let g = scribble(&mut s, &[[140.0, 125.0], [160.0, 135.0], [140.0, 140.0], [160.0, 145.0]]);
|
||||
assert_eq!(fill(&s, g, 150.0, 130.0), None);
|
||||
assert_eq!(fill(&s, g, 150.0, 170.0).as_deref(), Some("#ffff00"));
|
||||
assert!(stroke(&s, g, 150.0, 150.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shaper_joined_outline_keeps_its_stroke_paint_after_source_edits() {
|
||||
let mut s = session();
|
||||
let mut ids = vec![];
|
||||
for (x, color) in [(0, "#ff0000"), (50, "#ffff00")] {
|
||||
s.execute("paint.setFill", &json!({"color":color,"ids":[]})).unwrap();
|
||||
ids.push(NodeId(s.execute("shape.ellipse", &json!({"x":x,"y":0,"width":100,"height":100})).unwrap()["id"].as_u64().unwrap()));
|
||||
}
|
||||
let g = scribble(&mut s, &[[20.0, 40.0], [70.0, 45.0], [30.0, 50.0], [125.0, 55.0], [75.0, 60.0], [125.0, 65.0]]);
|
||||
let outlines: Vec<_> =
|
||||
node(&s, g).children().unwrap().iter().filter(|n| n.name.as_deref().is_some_and(|s| s.starts_with(STROKE_PREFIX))).collect();
|
||||
assert_eq!(outlines.len(), 1);
|
||||
assert!(outlines[0].path_data().unwrap().subpaths[0].closed);
|
||||
let outline = outlines[0].id;
|
||||
s.execute("paint.setStroke", &json!({"color":"#00ff00","ids":[outline.0]})).unwrap();
|
||||
s.execute("object.move", &json!({"ids":[ids[0].0],"dx":10,"dy":0})).unwrap();
|
||||
let outlines: Vec<_> =
|
||||
node(&s, g).children().unwrap().iter().filter(|n| n.name.as_deref().is_some_and(|s| s.starts_with(STROKE_PREFIX))).collect();
|
||||
assert_eq!(outlines.len(), 1);
|
||||
assert_eq!(outlines[0].appearance.stroke_paint().label(), "#00ff00");
|
||||
assert!(outlines[0].path_data().unwrap().subpaths[0].closed);
|
||||
for id in ids {
|
||||
assert_ne!(node(&s, id).appearance.stroke_paint().label(), "#00ff00");
|
||||
}
|
||||
}
|
||||
@@ -197,6 +197,74 @@ fn another_documents_swatches_load_as_a_library() {
|
||||
assert!(s.execute("swatch.library.load", &json!({"data": "hello", "name": "x.txt"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_files_load_add_and_list_as_user_libraries() {
|
||||
let bytes = vectorcraft_testkit::ase::sample();
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Brand.ase"}));
|
||||
assert_eq!((r["library"].as_str(), r["name"].as_str(), r["count"].as_u64()), (Some("loaded/Brand.ase"), Some("Brand"), Some(4)));
|
||||
let g = run(&mut s, "swatch.library.get", json!({"library": r["library"]}));
|
||||
let swatches = g["swatches"].as_array().unwrap();
|
||||
let kinds: Vec<(&str, bool, bool)> =
|
||||
swatches.iter().map(|w| (w["name"].as_str().unwrap(), w["global"].as_bool().unwrap(), w["spot"].as_bool().unwrap())).collect();
|
||||
assert_eq!(kinds, [("Sky", true, false), ("Ink", true, true), ("Mist", false, false), ("Clay", false, false)]);
|
||||
assert_eq!(swatches[3]["color"], json!({"model": "lab", "l": 50.0, "a": 20.0, "b": -30.0}));
|
||||
// Added to the document, the spot color stays a spot color and the group stays a color group.
|
||||
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
|
||||
let d = doc(&s);
|
||||
assert!(d.swatch("Ink").is_some_and(|w| w.spot && w.global));
|
||||
assert_eq!(d.swatch_groups.iter().find(|g| g.name == "Neutrals").map(|g| g.swatches.len()), Some(2));
|
||||
// A damaged file is an error from the swatch exchange reader, not from the document loader.
|
||||
let cut = vectorcraft_format::base64_encode(&bytes[..bytes.len() - 1]);
|
||||
let e = s.execute("swatch.library.load", &json!({"dataBase64": cut, "name": "Cut.ase"})).unwrap_err().to_string();
|
||||
assert!(e.contains("cut short"), "{e}");
|
||||
// `.ase` files in the user library folder are User Defined libraries.
|
||||
let dir = temp_dir("ase");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Brand.ase"), &bytes).unwrap();
|
||||
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let user: Vec<(&str, u64)> = list["libraries"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|l| l["category"] == "user")
|
||||
.map(|l| (l["id"].as_str().unwrap(), l["count"].as_u64().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(user, [("user/Brand.ase", 4)]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_group_stays_one_group_when_a_swatch_has_its_name() {
|
||||
use vectorcraft_testkit::ase::{Block, ase};
|
||||
let mut s = session();
|
||||
assert!(doc(&s).swatch("Blue").is_some(), "a new document has a swatch named Blue");
|
||||
let bytes = ase(&[
|
||||
Block::GroupStart("Blue"),
|
||||
Block::Color("Deep", b"RGB ", &[0.0, 0.0, 0.4], 2),
|
||||
Block::Color("Pale", b"RGB ", &[0.6, 0.7, 1.0], 2),
|
||||
Block::GroupEnd,
|
||||
Block::GroupStart("Blue 2"),
|
||||
Block::Color("Frost", b"RGB ", &[0.9, 0.95, 1.0], 2),
|
||||
Block::GroupEnd,
|
||||
]);
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Blues.ase"}));
|
||||
run(&mut s, "swatch.library.add", json!({"library": r["library"]}));
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
doc(&s).swatch_groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert!(groups.contains(&("Blue 2", vec!["Deep", "Pale"])), "{groups:?}");
|
||||
assert!(groups.contains(&("Blue 2 2", vec!["Frost"])), "the library's own Blue 2 stays apart: {groups:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_libraries_sent_as_bytes_load_when_they_are_not_valid_utf8() {
|
||||
let mut s = session();
|
||||
let latin1 = vectorcraft_format::base64_encode(b"GIMP Palette\n237 28 36 Rouge fonc\xe9\n");
|
||||
let r = run(&mut s, "swatch.library.load", json!({"dataBase64": latin1, "name": "Rouge.gpl"}));
|
||||
assert_eq!(r["count"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_libraries_are_listed_and_gradient_swatches_rename_and_take_new_gradients() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -247,10 +247,13 @@ fn artboard_tool_moves_with_art_creates_and_deletes() {
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 2);
|
||||
assert_eq!(s.tool_options()["active"], 1);
|
||||
assert_eq!(s.doc().unwrap().doc.artboards[1].rect, Rect::new(1000.0, 0.0, 1200.0, 100.0));
|
||||
// Delete it.
|
||||
// Delete it: the tool takes the key ahead of the Clear shortcut (the UI only hands Delete to a
|
||||
// tool that claims it).
|
||||
assert!(s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
|
||||
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
// The last artboard can't be deleted.
|
||||
// The last artboard can't be deleted, so Delete stays the shortcut's.
|
||||
assert!(!s.tool_claims_key(ToolKey::Delete, ViewInfo::default()));
|
||||
s.tool_key(ToolKey::Delete, Mods::default(), ViewInfo::default()).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
|
||||
@@ -274,6 +274,15 @@ fn structured_junk() {
|
||||
("text.create", json!({"x": 0, "y": 0, "text": "\u{0}\u{FFFF}\u{1F600}", "size": -1})),
|
||||
("text.create", json!({"x": 0, "y": 0, "text": "a", "size": 1e308, "area": {"width": -1, "height": 0}})),
|
||||
("text.setStyle", json!({"size": 0, "leading": -1, "tracking": 1e308})),
|
||||
("text.setStyle", json!({"justify": "center", "start": u64::MAX, "end": 0})),
|
||||
("text.setStyle", json!({"justify": "right", "start": -1, "end": "x"})),
|
||||
("text.setFormat", json!({"spaceBefore": 1e308, "leftIndent": -1e308, "start": 3, "end": u64::MAX})),
|
||||
("text.setFormat", json!({"hyphenate": true, "underline": true, "start": 1.5, "end": null})),
|
||||
("text.setFormat", json!({"ids": [u64::MAX, 2], "firstLineIndent": 5, "start": 0, "end": 0})),
|
||||
("text.tabs.set", json!({"stops": [{"position": 10}], "start": u64::MAX, "end": u64::MAX})),
|
||||
("text.tabs.get", json!({"start": -5})),
|
||||
("paraStyle.apply", json!({"name": "[Normal Paragraph Style]", "id": 2, "start": u64::MAX, "end": 1})),
|
||||
("paraStyle.new", json!({"id": 2, "start": u64::MAX})),
|
||||
("document.setUnits", json!({"units": "Parsecs"})),
|
||||
("document.open", json!({"name": "x.svg", "dataBase64": "!!!"})),
|
||||
("document.open", json!({"name": "x.svg", "dataBase64": "PHN2Zz4="})),
|
||||
@@ -311,6 +320,54 @@ fn structured_junk() {
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Area Type Options with junk fit values, on selected area type (the fixtures have none), with
|
||||
/// text that overflows: never a panic, the document stays sound, and editing still works.
|
||||
#[test]
|
||||
fn area_options_fit_junk() {
|
||||
let cases = [
|
||||
json!({"fit": "shrinkText", "fitMinPercent": 1e308}),
|
||||
json!({"fit": "shrinkText", "fitMinPercent": -1e308}),
|
||||
json!({"fit": "shrinkText", "fitMinPercent": "x"}),
|
||||
json!({"fit": {"shrinkText": {"minPercent": -5}}}),
|
||||
json!({"fit": {"shrinkText": {"minPercent": "a"}}}),
|
||||
json!({"fit": {"shrinkText": null}}),
|
||||
json!({"fit": {"autoHeight": 1}}),
|
||||
json!({"fit": {"bogus": {}}}),
|
||||
json!({"fit": [1, 2]}),
|
||||
json!({"fit": ""}),
|
||||
json!({"fit": "AUTO-HEIGHT", "height": 1e308, "width": -1e308}),
|
||||
json!({"fit": "autoHeight", "columns": u64::MAX, "gutter": 1e308, "inset": 1e308}),
|
||||
json!({"fit": "autoHeight", "rows": 5, "inset": -1}),
|
||||
json!({"fit": "shrinkText", "columns": 100, "gutter": 0, "inset": 10000}),
|
||||
json!({"fitMinPercent": 50}),
|
||||
json!({"fit": "none", "fitMinPercent": 1e-308}),
|
||||
];
|
||||
let story = "Words that overflow a small frame. ".repeat(40);
|
||||
let mut failures = vec![];
|
||||
for (size, (w, h)) in [(12.0, (120.0, 40.0)), (0.1, (1.0, 1.0)), (1296.0, (100_000.0, 1.0))] {
|
||||
for p in &cases {
|
||||
let mut s = Fixture::Multi.session();
|
||||
let made = s.execute("text.create", &json!({"x": 10, "y": 10, "size": size, "text": story, "area": {"width": w, "height": h}}));
|
||||
let Ok(made) = made else { continue };
|
||||
let id = made["id"].as_u64().unwrap_or(0);
|
||||
let r = catch_quiet(|| s.execute("text.areaOptions", p));
|
||||
match r {
|
||||
Err(m) => failures.push(format!("PANIC text.areaOptions {p} [{size} pt, {w}×{h}]: {m}")),
|
||||
Ok(_) => {
|
||||
let typed = catch_quiet(|| s.execute("text.editRange", &json!({"id": id, "start": 0, "insert": "More words. "})));
|
||||
if typed.is_err() {
|
||||
failures.push(format!("PANIC typing after text.areaOptions {p}"));
|
||||
}
|
||||
if let Err(e) = check_session(&s) {
|
||||
failures.push(format!("text.areaOptions {p} [{size} pt]: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// After a successful fuzzed call, the document still round-trips and exports.
|
||||
#[test]
|
||||
fn fuzzed_calls_keep_documents_serializable() {
|
||||
@@ -444,3 +501,81 @@ fn envelope_commands_with_junk_params_on_envelopes() {
|
||||
failures.dedup();
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.iter().take(40).cloned().collect::<Vec<_>>().join("\n"));
|
||||
}
|
||||
|
||||
/// Inline graphics in text (a symbol set in a run of type): text commands with `{}`, junk and
|
||||
/// structured junk (bad symbol names, offsets inside or past the graphic's character, malformed
|
||||
/// inline runs) never panic, leave an interaction open or break the tree, and the document still
|
||||
/// round-trips and exports.
|
||||
#[test]
|
||||
fn text_commands_with_junk_params_on_inline_graphics() {
|
||||
use vectorcraft_testkit::fixtures::{ellipse, exec, id_of, select};
|
||||
let path = safe_path();
|
||||
let setup = || {
|
||||
let mut s = Fixture::Multi.session();
|
||||
let e = ellipse(&mut s, 400.0, 300.0, 20.0, 20.0);
|
||||
select(&mut s, &[e]);
|
||||
exec(&mut s, "symbol.new", json!({"name": "Dot"}));
|
||||
let t = id_of(&exec(&mut s, "text.create", json!({"x": 20, "y": 200, "text": "ab cd", "size": 20})));
|
||||
exec(&mut s, "text.insertInline", json!({"id": t.0, "at": 2, "symbol": "Dot", "scale": 2}));
|
||||
select(&mut s, &[t]);
|
||||
(s, t)
|
||||
};
|
||||
let (_, t) = setup();
|
||||
let t = t.0;
|
||||
let style = json!({"font_family": "Source Sans 3", "size": 12, "fill": {"type": "none"}});
|
||||
let structured = [
|
||||
("text.insertInline", json!({"id": t, "at": u64::MAX, "symbol": "Dot", "scale": 100})),
|
||||
("text.insertInline", json!({"id": t, "at": 3, "symbol": "Dot", "scale": 1e-300, "shift": -1e5})),
|
||||
("text.insertInline", json!({"id": t, "at": 3, "symbol": "\u{0}", "scale": 1})),
|
||||
("text.insertInline", json!({"id": t, "at": 3, "symbol": "", "scale": f64::MAX})),
|
||||
("text.insertInline", json!({"id": u64::MAX, "symbol": "Dot"})),
|
||||
("text.insertInline", json!({"id": t, "at": "3", "symbol": ["Dot"], "scale": "big", "shift": null})),
|
||||
("text.editRange", json!({"id": t, "start": 3, "end": 4, "insert": "x"})),
|
||||
("text.editRange", json!({"id": t, "start": 4, "end": 3})),
|
||||
(
|
||||
"text.editRange",
|
||||
json!({"id": t, "start": 0, "end": 0, "runs": [{"text": "\u{FFFC}\u{FFFC}x", "style": style, "inline": {"symbol": "Dot", "scale": 1e308, "baseline_shift": -1e308}}]}),
|
||||
),
|
||||
("text.editRange", json!({"id": t, "start": 0, "end": 0, "runs": [{"text": "\u{FFFC}", "style": style, "inline": {"symbol": "Missing"}}]})),
|
||||
("text.editRange", json!({"id": t, "start": 0, "end": 0, "runs": [{"text": "", "style": style, "inline": {"symbol": "Dot", "scale": -5}}]})),
|
||||
("text.editRange", json!({"id": t, "runs": [{"text": "\u{FFFC}", "style": style, "inline": {"symbol": 5}}]})),
|
||||
("text.setRangeStyle", json!({"id": t, "start": 3, "end": 4, "size": 1e308, "tracking": -1e308})),
|
||||
("text.getRange", json!({"id": t, "start": 3, "end": 4})),
|
||||
("type.insert", json!({"text": "\u{FFFC}"})),
|
||||
("type.changeCase", json!({"case": "upper"})),
|
||||
("type.smartPunctuation", json!({"quotes": true, "dashes": true, "ellipsis": true, "scope": "selection"})),
|
||||
("type.convertToAreaType", json!({})),
|
||||
("type.createOutlines", json!({})),
|
||||
("symbol.delete", json!({"name": "Dot"})),
|
||||
("symbol.delete", json!({"name": "Dot", "expandInstances": false})),
|
||||
("symbol.update", json!({"name": "Dot"})),
|
||||
];
|
||||
let mut failures = vec![];
|
||||
let mut run = |id: &str, p: &Value| {
|
||||
let (mut s, _) = setup();
|
||||
match catch_quiet(|| s.execute(id, p)) {
|
||||
Err(msg) => failures.push(format!("PANIC {id} {p}: {msg}")),
|
||||
Ok(r) => {
|
||||
if s.in_interaction() {
|
||||
failures.push(format!("{id} {p}: left an interaction open"));
|
||||
} else if let Err(e) = check_session(&s) {
|
||||
failures.push(format!("{id} {p}: {e}"));
|
||||
} else if r.is_ok()
|
||||
&& let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}")))
|
||||
{
|
||||
failures.push(format!("{id} {p}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
for (id, p) in &structured {
|
||||
run(id, p);
|
||||
}
|
||||
for id in ["text.insertInline", "text.editRange", "text.getRange", "text.setRangeStyle", "type.insert"] {
|
||||
let spec = command_specs().iter().find(|c| c.id == id).unwrap();
|
||||
for p in std::iter::once(json!({})).chain(junk_params(spec.params, &path)) {
|
||||
run(id, &p);
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Untrusted files never crash the app: garbage, truncated, mutated and hostile SVG, PDF and DXF input,
|
||||
//! mutated raster images placed with File → Place, and swatch (`.vcswatches`, `.gpl`), graphic style (`.vcstyles`) and flattener preset
|
||||
//! mutated raster images placed with File → Place, and swatch (`.vcswatches`, `.gpl`, `.ase`), graphic style (`.vcstyles`) and flattener preset
|
||||
//! (`.vcflattener`) libraries, and native files (compressed, damaged, saved for older versions),
|
||||
//! must load as an error or as a document that then renders and exports, without a panic; nor may
|
||||
//! bitmaps, PDF and text pasted from other apps, nor EMF and WMF pictures (damaged files, records
|
||||
@@ -529,12 +529,21 @@ fn saved(cmd: &str, params: Value) -> String {
|
||||
rich_session().execute(cmd, ¶ms).unwrap()["data"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// `r`, after failing the case if the command panicked. The engine's guard reports a panic as
|
||||
/// `EngineError::Internal`.
|
||||
fn no_panic(r: Result<Value, vectorcraft_engine::EngineError>) -> Result<Value, vectorcraft_engine::EngineError> {
|
||||
if let Err(vectorcraft_engine::EngineError::Internal { cmd, msg }) = &r {
|
||||
panic!("{cmd} panicked: {msg}");
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Library file `data` loaded with `load`; what it holds is then used on the rich document
|
||||
/// (`then`, given the load's result), which renders and exports.
|
||||
fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut vectorcraft_engine::Session, &Value)) -> Result<(), TestCaseError> {
|
||||
survive(what, || {
|
||||
let mut s = rich_session();
|
||||
let r = s.execute(load, &json!({"data": data, "name": "fuzz"})).ok()?;
|
||||
let r = no_panic(s.execute(load, &json!({"data": data, "name": "fuzz"}))).ok()?;
|
||||
then(&mut s, &r);
|
||||
Some((*s.doc().ok()?.doc).clone())
|
||||
})
|
||||
@@ -542,27 +551,55 @@ fn survive_library(what: &str, load: &str, data: &str, then: impl FnOnce(&mut ve
|
||||
|
||||
fn swatches(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "swatch.library.load", data, |s, r| {
|
||||
let _ = s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"}));
|
||||
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
|
||||
})
|
||||
}
|
||||
|
||||
fn styles(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "graphicStyle.loadLibrary", data, |s, r| {
|
||||
let _ = s.execute("select.all", &json!({}));
|
||||
let _ = s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true}));
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
let _ = no_panic(s.execute("graphicStyle.addFromLibrary", &json!({"library": r["library"], "apply": true})));
|
||||
})
|
||||
}
|
||||
|
||||
fn flattener_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "flattener.presets.import", data, |s, r| {
|
||||
let _ = s.execute("select.all", &json!({}));
|
||||
let _ = no_panic(s.execute("select.all", &json!({})));
|
||||
if let Some(name) = r["imported"].get(0) {
|
||||
let _ = s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"}));
|
||||
let _ = s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36}));
|
||||
let _ = no_panic(s.execute("flattener.preview", &json!({"preset": name, "highlight": "allAffected"})));
|
||||
let _ = no_panic(s.execute("object.flattenTransparency", &json!({"preset": name, "lineArtPpi": 36, "gradientPpi": 36})));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Swatch exchange (`.ase`) bytes loaded as a swatch library, then added to the rich document.
|
||||
fn swatch_exchange(what: &str, bytes: &[u8]) -> Result<(), TestCaseError> {
|
||||
survive(what, || {
|
||||
let mut s = rich_session();
|
||||
let load = json!({"dataBase64": vectorcraft_format::base64_encode(bytes), "name": "fuzz.ase"});
|
||||
let r = no_panic(s.execute("swatch.library.load", &load)).ok()?;
|
||||
let _ = no_panic(s.execute("swatch.library.add", &json!({"library": r["library"], "apply": "fill"})));
|
||||
Some((*s.doc().ok()?.doc).clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// A random swatch exchange block (type, body). The body holds a name, a color model when the block
|
||||
/// is a color, and random bytes for the rest.
|
||||
fn arb_ase_block() -> impl Strategy<Value = (u16, Vec<u8>)> {
|
||||
let kind = prop::sample::select(vec![0xC001u16, 0xC002, 0x0001, 0x0042]);
|
||||
let model = prop::sample::select(vec![*b"RGB ", *b"CMYK", *b"LAB ", *b"Gray", *b"HSB "]);
|
||||
(kind, "[ -~]{0,8}", model, prop::collection::vec(any::<u8>(), 0..24)).prop_map(|(kind, name, model, rest)| {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut body = (units.len() as u16).to_be_bytes().to_vec();
|
||||
body.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
if kind == 0x0001 {
|
||||
body.extend(model);
|
||||
}
|
||||
body.extend(rest);
|
||||
(kind, body)
|
||||
})
|
||||
}
|
||||
|
||||
/// Characters that break JSON and GPL palettes.
|
||||
fn arb_edit() -> impl Strategy<Value = (usize, char)> {
|
||||
(0usize..20_000, prop::sample::select(vec!['{', '}', '[', ']', '"', ':', ',', '-', '9', 'e', '.', ' ', '\n', '#', 'n', 'x', '\t']))
|
||||
@@ -596,6 +633,32 @@ proptest! {
|
||||
let text = saved("flattener.presets.export", json!({"names": ["high", "medium", "low"]}));
|
||||
flattener_presets("mutated flattener presets", &mutate_text(&text, cut, &edits))?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_exchange_garbage_never_panics(blocks in prop::collection::vec(arb_ase_block(), 0..12), tail in prop::collection::vec(any::<u8>(), 0..16)) {
|
||||
let mut bytes = b"ASEF\0\x01\0\0".to_vec();
|
||||
bytes.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in &blocks {
|
||||
bytes.extend(kind.to_be_bytes());
|
||||
bytes.extend((body.len() as u32).to_be_bytes());
|
||||
bytes.extend(body);
|
||||
}
|
||||
bytes.extend(tail);
|
||||
swatch_exchange("swatch exchange garbage", &bytes)?;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutated_swatch_exchange_files_never_panic(cut in prop::option::of(0usize..200), edits in prop::collection::vec((0usize..200, any::<u8>()), 0..12)) {
|
||||
let mut bytes = vectorcraft_testkit::ase::sample();
|
||||
for (at, b) in edits {
|
||||
let n = bytes.len();
|
||||
bytes[at % n] = b;
|
||||
}
|
||||
if let Some(cut) = cut {
|
||||
bytes.truncate(cut);
|
||||
}
|
||||
swatch_exchange("mutated swatch exchange file", &bytes)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// A small image of each raster format Place reads, with resolution metadata where it has some.
|
||||
@@ -704,8 +767,8 @@ proptest! {
|
||||
fn pdf_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "pdf.preset.import", data, |s, r| {
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let _ = s.execute("document.exportPdf", &json!({"preset": name}));
|
||||
let _ = s.execute("document.save", &json!({"format": "ai", "preset": name}));
|
||||
let _ = no_panic(s.execute("document.exportPdf", &json!({"preset": name})));
|
||||
let _ = no_panic(s.execute("document.save", &json!({"format": "ai", "preset": name})));
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1219,14 +1282,14 @@ proptest! {
|
||||
/// each one imported.
|
||||
fn print_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "print.presets.import", data, |s, r| {
|
||||
let list = s.execute("print.presets.list", &json!({})).unwrap_or_default();
|
||||
let list = no_panic(s.execute("print.presets.list", &json!({}))).unwrap_or_default();
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let Some(p) = list["presets"].as_array().into_iter().flatten().find(|p| &p["name"] == name) else { continue };
|
||||
let settings = json!({ "settings": p["settings"] });
|
||||
let pages = s.execute("print.preview", &settings).ok().and_then(|v| v["pages"].as_u64());
|
||||
let _ = s.execute("print.setup", &settings);
|
||||
let pages = no_panic(s.execute("print.preview", &settings)).ok().and_then(|v| v["pages"].as_u64());
|
||||
let _ = no_panic(s.execute("print.setup", &settings));
|
||||
if pages.is_some_and(|n| n <= 8) {
|
||||
let _ = s.execute("file.print", &settings);
|
||||
let _ = no_panic(s.execute("file.print", &settings));
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -1256,9 +1319,11 @@ proptest! {
|
||||
fn perspective_presets(what: &str, data: &str) -> Result<(), TestCaseError> {
|
||||
survive_library(what, "perspective.presets.import", data, |s, r| {
|
||||
for name in r["imported"].as_array().into_iter().flatten() {
|
||||
let _ = s.execute("perspective.grid.preset", &json!({"name": name}));
|
||||
let _ = s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3}));
|
||||
let _ = s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}}));
|
||||
let _ = no_panic(s.execute("perspective.grid.preset", &json!({"name": name})));
|
||||
let _ = no_panic(s.execute("perspective.grid.define", &json!({"name": name, "gridline": 3})));
|
||||
let _ = no_panic(
|
||||
s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": {"x": 300, "y": 400, "width": 40, "height": 30}})),
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Inline graphics in text drawn on the canvas and written to SVG and PDF: a symbol (a red
|
||||
//! circle drawn in code) set inline in a line of type.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_testkit::fixtures::{self, exec, id_of};
|
||||
use vectorcraft_testkit::raster;
|
||||
|
||||
/// A session with a red circle symbol "Dot" (its instance deleted) and the point type
|
||||
/// "Tap now" (20 pt, baseline at y = 100) with the symbol inline after "Tap ".
|
||||
fn setup(inline: bool) -> (vectorcraft_engine::Session, NodeId) {
|
||||
let mut s = fixtures::session_with(400.0, 300.0);
|
||||
fixtures::ellipse(&mut s, 300.0, 250.0, 20.0, 20.0);
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
exec(&mut s, "paint.setStroke", json!({"none": true}));
|
||||
exec(&mut s, "symbol.new", json!({"name": "Dot"}));
|
||||
exec(&mut s, "edit.clear", json!({}));
|
||||
// Type is painted with the current fill: black, not the circle's red.
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#000000"}));
|
||||
let id = id_of(&exec(&mut s, "text.create", json!({"x": 20, "y": 100, "text": "Tap now", "size": 20})));
|
||||
if inline {
|
||||
exec(&mut s, "text.insertInline", json!({"id": id.0, "at": 4, "symbol": "Dot"}));
|
||||
}
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn doc(s: &vectorcraft_engine::Session) -> Document {
|
||||
(*s.doc().unwrap().doc).clone()
|
||||
}
|
||||
|
||||
fn text(d: &Document, id: NodeId) -> TextObject {
|
||||
match &d.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the inline art lands, in document space.
|
||||
fn art_rect(d: &Document, id: NodeId) -> Rect {
|
||||
let t = text(d, id);
|
||||
let l = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
assert_eq!(l.inlines.len(), 1);
|
||||
t.xf.transform_rect_bbox(l.inlines[0].bounds)
|
||||
}
|
||||
|
||||
fn red(p: [u8; 3]) -> bool {
|
||||
p[0] > 200 && p[1] < 80 && p[2] < 80
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_draws_the_symbol_where_the_layout_puts_it() {
|
||||
let (s, id) = setup(true);
|
||||
let d = doc(&s);
|
||||
let r = art_rect(&d, id);
|
||||
// 20 pt tall at 20 pt type, on the pen after "Tap ", centred on the cap-height middle.
|
||||
assert!((r.height() - 20.0).abs() < 0.5 && (r.width() - 20.0).abs() < 0.5, "{r:?}");
|
||||
assert!(r.x0 > 50.0 && r.x0 < 70.0, "{r:?}");
|
||||
assert!(r.center().y < 100.0 && r.center().y > 90.0, "{r:?}");
|
||||
let img = raster::render_region(&d, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
let px = |x: f64, y: f64| img.over_white((x * 2.0) as u32, (y * 2.0) as u32);
|
||||
assert!(red(px(r.center().x, r.center().y)), "{:?} at {:?}", px(r.center().x, r.center().y), r.center());
|
||||
// Only there: just outside the circle, no red.
|
||||
assert!(!red(px(r.x0 - 3.0, r.center().y)) && !red(px(r.center().x, r.y0 - 3.0)));
|
||||
// Without the graphic nothing is red, and the text after it sits further left.
|
||||
let (plain, pid) = setup(false);
|
||||
let pd = doc(&plain);
|
||||
let img = raster::render_region(&pd, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
assert_eq!(img.count(|p| p[0] > 200 && p[1] < 80 && p[2] < 80 && p[3] > 200), 0);
|
||||
let w = text(&d, id).bounds().unwrap().width() - text(&pd, pid).bounds().unwrap().width();
|
||||
assert!((w - 20.0).abs() < 0.5, "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canvas_applies_the_text_objects_opacity_to_its_inline_art() {
|
||||
let (mut s, id) = setup(true);
|
||||
exec(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
exec(&mut s, "transparency.set", json!({"opacity": 50}));
|
||||
let d = doc(&s);
|
||||
let r = art_rect(&d, id);
|
||||
let img = raster::render_region(&d, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
let p = img.over_white((r.center().x * 2.0) as u32, (r.center().y * 2.0) as u32);
|
||||
// Half red over white: pink.
|
||||
assert!(p[0] > 240 && (100..180).contains(&p[1]) && (100..180).contains(&p[2]), "{p:?}");
|
||||
}
|
||||
|
||||
fn svg_of(s: &mut vectorcraft_engine::Session, params: Value) -> String {
|
||||
let v = exec(s, "document.serialize", params);
|
||||
v["text"]
|
||||
.as_str()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| String::from_utf8(vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_keeps_live_text_and_draws_the_symbol() {
|
||||
let (mut s, id) = setup(true);
|
||||
let svg = svg_of(&mut s, json!({"format": "svg", "outlineText": false}));
|
||||
// Live text without the object replacement character; the text after the graphic is placed
|
||||
// after it.
|
||||
assert!(svg.contains("<text") && svg.contains(">Tap") && svg.contains("now<"), "{svg}");
|
||||
assert!(!svg.contains('\u{FFFC}'), "{svg}");
|
||||
// The symbol's art: a <symbol> def and a <use> of it.
|
||||
assert!(svg.contains("<symbol id=\"Dot\""), "{svg}");
|
||||
assert!(svg.matches("xlink:href=\"#Dot\"").count() == 1, "{svg}");
|
||||
// Re-imported, the art is a red circle where the canvas draws it.
|
||||
let back = vectorcraft_svg::import(&svg).unwrap();
|
||||
let img = raster::render_region(&back, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
let r = art_rect(&doc(&s), id);
|
||||
let p = img.over_white((r.center().x * 2.0) as u32, (r.center().y * 2.0) as u32);
|
||||
assert!(red(p), "{p:?}");
|
||||
// Text as outlines and fewer tspans still draw it.
|
||||
for params in [json!({"format": "svg", "outlineText": true}), json!({"format": "svg", "outlineText": false, "fewerTspans": true})] {
|
||||
let svg = svg_of(&mut s, params.clone());
|
||||
assert!(svg.contains("xlink:href=\"#Dot\""), "{params}: {svg}");
|
||||
assert!(!svg.contains('\u{FFFC}'), "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_draws_the_symbol_art() {
|
||||
let (mut s, id) = setup(true);
|
||||
let v = exec(&mut s, "document.serialize", json!({"format": "pdf"}));
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let back = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
let r = art_rect(&doc(&s), id);
|
||||
let img = raster::render_region(&back, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
let p = img.over_white((r.center().x * 2.0) as u32, (r.center().y * 2.0) as u32);
|
||||
assert!(red(p), "{p:?} at {:?}", r.center());
|
||||
// Without it, nothing red.
|
||||
let (mut plain, _) = setup(false);
|
||||
let v = exec(&mut plain, "document.serialize", json!({"format": "pdf"}));
|
||||
let back = vectorcraft_pdf::import(&vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()).unwrap();
|
||||
let img = raster::render_region(&back, Rect::new(0.0, 0.0, 200.0, 150.0), 2.0);
|
||||
assert_eq!(img.count(|p| p[0] > 200 && p[1] < 80 && p[2] < 80 && p[3] > 200), 0);
|
||||
}
|
||||
@@ -53,8 +53,10 @@ fn area_type_vertical_alignment_round_trips() {
|
||||
let area = |d: &Document| {
|
||||
let mut found = None;
|
||||
d.walk(|n| {
|
||||
// The fixture's centred area type, by its text (the fixture has other area type).
|
||||
if let NodeKind::Text(t) = &n.kind
|
||||
&& matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })
|
||||
&& t.runs.iter().map(|r| r.text.as_str()).collect::<String>() == "Centred area type"
|
||||
{
|
||||
found = Some(t.area.vertical_align);
|
||||
}
|
||||
@@ -63,7 +65,20 @@ fn area_type_vertical_alignment_round_trips() {
|
||||
};
|
||||
assert_eq!(area(&back), vectorcraft_doc::VerticalAlign::Center);
|
||||
// Files from before the option open top-aligned.
|
||||
let old = text.replacen("\"verticalAlign\":\"center\",", "", 1).replacen(",\"verticalAlign\":\"center\"", "", 1);
|
||||
// (Every area type the fixture has writes its options, so the key goes from all of them.)
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
Value::Object(m) => {
|
||||
m.remove("verticalAlign");
|
||||
m.values_mut().for_each(strip);
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(strip),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut v = json_of(text.as_bytes());
|
||||
strip(&mut v);
|
||||
let old = serde_json::to_string(&v).unwrap();
|
||||
assert!(!old.contains("verticalAlign"));
|
||||
assert_eq!(area(&load(old.as_bytes()).unwrap()), vectorcraft_doc::VerticalAlign::Top);
|
||||
}
|
||||
@@ -149,11 +164,12 @@ fn text_composer_round_trips() {
|
||||
});
|
||||
v
|
||||
};
|
||||
// The point type set to Single-line, then the area type left at the default.
|
||||
assert_eq!(composers(&d), [Composer::SingleLine, Composer::EveryLine]);
|
||||
// The point type set to Single-line comes first; the fixture's other type keeps the default.
|
||||
let single_then_default = |c: &[Composer]| c.len() > 1 && c[0] == Composer::SingleLine && c[1..].iter().all(|c| *c == Composer::EveryLine);
|
||||
assert!(single_then_default(&composers(&d)), "{:?}", composers(&d));
|
||||
let bytes = save(&d, false);
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("\"composer\":\"singleLine\""));
|
||||
assert_eq!(composers(&load(&bytes).unwrap()), [Composer::SingleLine, Composer::EveryLine]);
|
||||
assert_eq!(composers(&load(&bytes).unwrap()), composers(&d));
|
||||
// Files without the key (older files, Every-line text) read as Every-line.
|
||||
fn strip(v: &mut Value) {
|
||||
match v {
|
||||
@@ -168,7 +184,7 @@ fn text_composer_round_trips() {
|
||||
let mut v = json_of(&bytes);
|
||||
strip(&mut v);
|
||||
let d2 = load(&serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
assert_eq!(composers(&d2), [Composer::EveryLine, Composer::EveryLine]);
|
||||
assert!(composers(&d2).iter().all(|c| *c == Composer::EveryLine), "{:?}", composers(&d2));
|
||||
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
|
||||
}
|
||||
|
||||
@@ -261,3 +277,26 @@ fn artboard_guides_round_trip_and_canvas_guides_save_as_before() {
|
||||
let old = load(&serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
assert_eq!(old.guides, [Guide::new(false, 20.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_graphics_in_text_round_trip() {
|
||||
let d = rich_doc();
|
||||
let inline = |d: &Document| {
|
||||
let mut found = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
found.extend(t.runs.iter().filter_map(|r| r.inline.clone().map(|a| (r.text.clone(), a.symbol, a.scale, a.baseline_shift))));
|
||||
}
|
||||
});
|
||||
found
|
||||
};
|
||||
let want = inline(&d);
|
||||
assert_eq!(want, vec![("\u{FFFC}".to_string(), "Dot".to_string(), 1.0, 0.0)]);
|
||||
let bytes = save(&d, false);
|
||||
let saved = json_of(&bytes).to_string();
|
||||
assert!(saved.contains("\"inline\":{") && saved.contains("\"symbol\":\"Dot\""), "{saved}");
|
||||
let back = load(&bytes).unwrap();
|
||||
assert_eq!(inline(&back), want);
|
||||
assert_eq!(doc_json(&back), doc_json(&d));
|
||||
check_native_roundtrip(&d).unwrap();
|
||||
}
|
||||
+391
-57
@@ -1,11 +1,11 @@
|
||||
//! Shape recognition for the Shaper tool: a rough freehand stroke becomes a clean shape.
|
||||
//!
|
||||
//! The stroke is classified by how closed it is, how many corners survive a coarse polyline
|
||||
//! simplification (Douglas–Peucker at a fraction of the stroke's size) and how well it fills its
|
||||
//! bounding box. A zig-zag stroke with several reversals is a scribble (the Shaper deletes what it
|
||||
//! covers).
|
||||
//! simplification independent of where drawing began, its edge/angle fit and how well it fills
|
||||
//! its bounding box. Samples are spaced by distance so pointer speed does not bias the fit.
|
||||
//! A zig-zag stroke with several reversals is a scribble (the Shaper deletes what it covers).
|
||||
|
||||
use crate::{Point, Rect, Vec2};
|
||||
use crate::{Affine, Point, Rect, Vec2};
|
||||
|
||||
/// What the Shaper recognised.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -14,10 +14,16 @@ pub enum Recognized {
|
||||
a: Point,
|
||||
b: Point,
|
||||
},
|
||||
/// Axis-aligned rectangle (squares snap when the sides are within 10%).
|
||||
Rectangle(Rect),
|
||||
/// Axis-aligned ellipse in `rect` (circles snap when the axes are within 10%).
|
||||
Ellipse(Rect),
|
||||
/// Rectangle at a 45° step (squares snap when the sides are within 10%).
|
||||
Rectangle {
|
||||
rect: Rect,
|
||||
rotation: f64,
|
||||
},
|
||||
/// Ellipse at a 45° step (circles snap when the axes are within 10%).
|
||||
Ellipse {
|
||||
rect: Rect,
|
||||
rotation: f64,
|
||||
},
|
||||
/// Regular polygon (triangle, pentagon, hexagon…): centre, radius, side count and the rotation
|
||||
/// (degrees) of the first vertex from straight up.
|
||||
Polygon {
|
||||
@@ -48,30 +54,174 @@ fn dist_to_segment(p: Point, a: Point, b: Point) -> f64 {
|
||||
p.distance(a + ab * t)
|
||||
}
|
||||
|
||||
/// Douglas–Peucker simplification.
|
||||
/// Douglas–Peucker simplification with bounded stack use, even for noisy strokes.
|
||||
fn simplify(pts: &[Point], tol: f64) -> Vec<Point> {
|
||||
if pts.len() < 3 {
|
||||
return pts.to_vec();
|
||||
}
|
||||
let (a, b) = (pts[0], pts[pts.len() - 1]);
|
||||
let (i, d) = pts[1..pts.len() - 1]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| (i + 1, dist_to_segment(*p, a, b)))
|
||||
.fold((0, 0.0), |m, x| if x.1 > m.1 { x } else { m });
|
||||
if d <= tol {
|
||||
return vec![a, b];
|
||||
let mut keep = vec![false; pts.len()];
|
||||
if let Some(first) = keep.first_mut() {
|
||||
*first = true;
|
||||
}
|
||||
let mut left = simplify(&pts[..=i], tol);
|
||||
let right = simplify(&pts[i..], tol);
|
||||
left.pop();
|
||||
left.extend(right);
|
||||
left
|
||||
if let Some(last) = keep.last_mut() {
|
||||
*last = true;
|
||||
}
|
||||
let mut pending = vec![(0, pts.len() - 1)];
|
||||
while let Some((start, end)) = pending.pop() {
|
||||
let Some(window) = pts.get(start..=end) else { continue };
|
||||
let (Some(&a), Some(&b)) = (window.first(), window.last()) else { continue };
|
||||
let (offset, deviation) = window
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(1)
|
||||
.take(window.len().saturating_sub(2))
|
||||
.map(|(i, p)| (i, dist_to_segment(*p, a, b)))
|
||||
.fold((0, 0.0), |best, candidate| if candidate.1 > best.1 { candidate } else { best });
|
||||
if deviation > tol {
|
||||
let split = start + offset;
|
||||
if let Some(k) = keep.get_mut(split) {
|
||||
*k = true;
|
||||
}
|
||||
if split > start + 1 {
|
||||
pending.push((start, split));
|
||||
}
|
||||
if end > split + 1 {
|
||||
pending.push((split, end));
|
||||
}
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter_map(|(p, keep)| keep.then_some(*p)).collect()
|
||||
}
|
||||
|
||||
/// Sample by distance, so pointer speed/density cannot bias the shape fit. Bounds and length
|
||||
/// still come from the complete stroke, but simplification works on at most 256 samples.
|
||||
fn resample(pts: &[Point], length: f64) -> Vec<Point> {
|
||||
const SAMPLES: usize = 256;
|
||||
let (Some(&first), Some(&last)) = (pts.first(), pts.last()) else { return Vec::new() };
|
||||
let mut out = vec![first];
|
||||
let mut walked = 0.0;
|
||||
for (&a, &b) in pts.iter().zip(pts.iter().skip(1)) {
|
||||
let segment = a.distance(b);
|
||||
if segment <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
while out.len() < SAMPLES - 1 {
|
||||
let target = length * (out.len() as f64 / (SAMPLES - 1) as f64);
|
||||
if target > walked + segment {
|
||||
break;
|
||||
}
|
||||
out.push(a + (b - a) * ((target - walked) / segment).clamp(0.0, 1.0));
|
||||
}
|
||||
walked += segment;
|
||||
}
|
||||
out.push(last);
|
||||
out
|
||||
}
|
||||
|
||||
/// A closed stroke has no special starting corner. Split at distant points and simplify both
|
||||
/// halves, then discard collinear seam points instead of counting them as polygon vertices.
|
||||
fn closed_corners(pts: &[Point], tol: f64) -> Vec<Point> {
|
||||
let Some(&first) = pts.first() else { return Vec::new() };
|
||||
let start = pts.iter().enumerate().max_by(|(_, a), (_, b)| a.distance(first).total_cmp(&b.distance(first))).map_or(0, |(i, _)| i);
|
||||
let ring: Vec<Point> = pts.iter().skip(start).chain(pts.iter().take(start)).copied().collect();
|
||||
let Some(&first) = ring.first() else { return Vec::new() };
|
||||
let split = ring.iter().enumerate().max_by(|(_, a), (_, b)| a.distance(first).total_cmp(&b.distance(first))).map_or(0, |(i, _)| i);
|
||||
let (Some(left), Some(right)) = (ring.get(..=split), ring.get(split..)) else { return Vec::new() };
|
||||
let mut corners = simplify(left, tol);
|
||||
corners.pop();
|
||||
let other: Vec<Point> = right.iter().copied().chain(std::iter::once(first)).collect();
|
||||
let mut other = simplify(&other, tol);
|
||||
other.pop();
|
||||
corners.extend(other);
|
||||
while corners.len() > 3 {
|
||||
let n = corners.len();
|
||||
let redundant = corners.iter().enumerate().find_map(|(i, p)| {
|
||||
let (&a, &b) = (corners.get((i + n - 1) % n)?, corners.get((i + 1) % n)?);
|
||||
(dist_to_segment(*p, a, b) <= tol).then_some(i)
|
||||
});
|
||||
let Some(i) = redundant else { break };
|
||||
corners.remove(i);
|
||||
}
|
||||
corners
|
||||
}
|
||||
|
||||
fn area(poly: &[Point]) -> f64 {
|
||||
let n = poly.len();
|
||||
(0..n).map(|i| poly[i].to_vec2().cross(poly[(i + 1) % n].to_vec2())).sum::<f64>().abs() / 2.0
|
||||
let Some(&origin) = poly.first() else { return 0.0 };
|
||||
// Translating to the first point avoids cancellation far from the document origin.
|
||||
poly.iter().zip(poly.iter().skip(1)).map(|(&a, &b)| (a - origin).cross(b - origin)).sum::<f64>().abs() / 2.0
|
||||
}
|
||||
|
||||
/// Four substantial, approximately perpendicular edges, even with uneven sides and corners.
|
||||
fn is_rectangle(pts: &[Point], corners: &[Point], size: f64) -> bool {
|
||||
if corners.len() != 4 || !is_polygonal(pts, corners, size, 0.055) {
|
||||
return false;
|
||||
}
|
||||
right_angles(corners, size)
|
||||
}
|
||||
|
||||
fn right_angles(corners: &[Point], size: f64) -> bool {
|
||||
let around: Vec<Point> = corners.iter().cycle().take(corners.len() + 2).copied().collect();
|
||||
around.windows(3).all(|w| {
|
||||
let [a, b, c] = w else { return false };
|
||||
let (u, v) = (*b - *a, *c - *b);
|
||||
let (lu, lv) = (u.hypot(), v.hypot());
|
||||
lu > 0.03 * size && lv > 0.03 * size && (u.dot(v) / (lu * lv)).abs() < 0.45
|
||||
})
|
||||
}
|
||||
|
||||
/// Fit all vertices, so neither the starting point nor drawing direction picks the orientation.
|
||||
fn polygon_rotation(corners: &[Point], step: f64) -> f64 {
|
||||
let Some(&origin) = corners.first() else { return 0.0 };
|
||||
let n = corners.len() as f64;
|
||||
let center = origin + corners.iter().fold(Vec2::ZERO, |sum, p| sum + (*p - origin) / n);
|
||||
let period = 360.0 / n;
|
||||
let error = |rotation: f64| {
|
||||
corners
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let angle = (*p - center).atan2().to_degrees() + 90.0;
|
||||
let delta = (angle - rotation).rem_euclid(period);
|
||||
delta.min(period - delta).powi(2)
|
||||
})
|
||||
.sum::<f64>()
|
||||
};
|
||||
[0.0, 90.0, 180.0, 270.0].into_iter().filter(|r| r % step == 0.0).min_by(|a, b| error(*a).total_cmp(&error(*b))).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
fn rectangle_rotation(corners: &[Point]) -> f64 {
|
||||
let (sin, cos) = corners.iter().zip(corners.iter().cycle().skip(1)).fold((0.0, 0.0), |(sin, cos), (&a, &b)| {
|
||||
let angle = (b - a).atan2() * 4.0;
|
||||
(sin + angle.sin(), cos + angle.cos())
|
||||
});
|
||||
(sin.atan2(cos).to_degrees() / 4.0 / 45.0).round().mul_add(45.0, 0.0).rem_euclid(180.0)
|
||||
}
|
||||
|
||||
fn ellipse_rotation(pts: &[Point]) -> f64 {
|
||||
let Some(&origin) = pts.first() else { return 0.0 };
|
||||
let n = pts.len() as f64;
|
||||
let center = origin + pts.iter().fold(Vec2::ZERO, |sum, p| sum + (*p - origin) / n);
|
||||
let (xx, yy, xy) = pts.iter().fold((0.0, 0.0, 0.0), |(xx, yy, xy), p| {
|
||||
let v = *p - center;
|
||||
(xx + v.x * v.x, yy + v.y * v.y, xy + v.x * v.y)
|
||||
});
|
||||
// A near-circle has no useful orientation; keep it upright rather than following noise.
|
||||
if (xx - yy).hypot(2.0 * xy) < 0.1 * (xx + yy) {
|
||||
return 0.0;
|
||||
}
|
||||
((2.0 * xy).atan2(xx - yy).to_degrees() / 2.0 / 45.0).round().mul_add(45.0, 0.0).rem_euclid(180.0)
|
||||
}
|
||||
|
||||
/// Dimensions in the fitted frame, but the centre stays in document coordinates.
|
||||
fn oriented_bounds(pts: &[Point], rotation: f64) -> Rect {
|
||||
if rotation == 0.0 {
|
||||
return bbox(pts);
|
||||
}
|
||||
let origin = pts.first().copied().unwrap_or(Point::ZERO);
|
||||
let rotate = Affine::rotate(rotation.to_radians());
|
||||
let inverse = Affine::rotate(-rotation.to_radians());
|
||||
let local: Vec<Point> = pts.iter().map(|p| inverse * (*p - origin).to_point()).collect();
|
||||
let b = bbox(&local);
|
||||
Rect::from_center_size(origin + (rotate * b.center()).to_vec2(), (b.width(), b.height()))
|
||||
}
|
||||
|
||||
/// Number of sharp direction reversals (turns of more than 120°) along the stroke.
|
||||
@@ -87,22 +237,35 @@ fn reversals(pts: &[Point], min_seg: f64) -> usize {
|
||||
|
||||
/// Recognise a freehand stroke (document points, in drawing order).
|
||||
pub fn recognize(pts: &[Point]) -> Option<Recognized> {
|
||||
if pts.len() < 2 {
|
||||
if pts.len() < 2 || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let b = bbox(pts);
|
||||
let size = b.width().max(b.height());
|
||||
if size < 2.0 {
|
||||
if size < 2.0 || !size.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let len = path_len(pts);
|
||||
let (first, last) = (pts[0], pts[pts.len() - 1]);
|
||||
if !len.is_finite() || len <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let original = pts;
|
||||
let samples = resample(pts, len);
|
||||
let pts = samples.as_slice();
|
||||
let (&first, &last) = (pts.first()?, pts.last()?);
|
||||
let chord = first.distance(last);
|
||||
// Scribble: several sharp reversals packed into a small area relative to the stroke length.
|
||||
if reversals(pts, size * 0.08) >= 3 && len > 3.0 * size {
|
||||
return Some(Recognized::Scribble(b));
|
||||
if reversals(pts, size * 0.08) >= 2 && len > 1.5 * size {
|
||||
// An equilateral triangle turns 120° at its vertices: drawing noise can make all
|
||||
// three turns just exceed the reversal threshold. Its closed, straight edges and
|
||||
// substantial area distinguish it from a deletion scribble.
|
||||
let corners = closed_corners(pts, size * 0.12);
|
||||
let triangle = chord <= 0.25 * size && corners.len() == 3 && area(pts) > 0.2 * size * size && is_polygonal(pts, &corners, size, 0.055);
|
||||
if !triangle {
|
||||
return Some(Recognized::Scribble(b));
|
||||
}
|
||||
}
|
||||
// Line: every point near the chord.
|
||||
let chord = first.distance(last);
|
||||
let max_dev = pts.iter().map(|p| dist_to_segment(*p, first, last)).fold(0.0, f64::max);
|
||||
if chord > 0.5 * size && max_dev < 0.08 * chord.max(1.0) && len < 1.3 * chord {
|
||||
return Some(Recognized::Line { a: first, b: last });
|
||||
@@ -111,13 +274,11 @@ pub fn recognize(pts: &[Point]) -> Option<Recognized> {
|
||||
if chord > 0.25 * size {
|
||||
return None;
|
||||
}
|
||||
let mut closed: Vec<Point> = pts.to_vec();
|
||||
closed.push(first);
|
||||
let mut corners = simplify(&closed, size * 0.12);
|
||||
if corners.len() > 1 && corners[0].distance(corners[corners.len() - 1]) < size * 0.15 {
|
||||
corners.pop();
|
||||
}
|
||||
let corners = closed_corners(pts, size * 0.12);
|
||||
let fill = area(pts) / (b.width() * b.height()).max(1e-9);
|
||||
if !fill.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let center = b.center();
|
||||
let square = |r: Rect| {
|
||||
let (w, h) = (r.width(), r.height());
|
||||
@@ -131,33 +292,36 @@ pub fn recognize(pts: &[Point]) -> Option<Recognized> {
|
||||
match corners.len() {
|
||||
3 => {
|
||||
let radius = corners.iter().map(|p| p.distance(center)).sum::<f64>() / 3.0;
|
||||
// Rotation of the vertex nearest straight up (y grows downward).
|
||||
let top = corners.iter().copied().min_by(|a, b| a.y.total_cmp(&b.y)).unwrap_or(center);
|
||||
let rot = (top - center).atan2().to_degrees() + 90.0;
|
||||
Some(Recognized::Polygon { center, radius, sides: 3, rotation: rot })
|
||||
Some(Recognized::Polygon { center, radius, sides: 3, rotation: polygon_rotation(&corners, 180.0) })
|
||||
}
|
||||
4 if fill > 0.86 => Some(Recognized::Rectangle(square(b))),
|
||||
// A diamond: a square standing on a corner.
|
||||
4 if (0.4..0.62).contains(&fill) => {
|
||||
let radius = corners.iter().map(|p| p.distance(center)).sum::<f64>() / 4.0;
|
||||
Some(Recognized::Polygon { center, radius, sides: 4, rotation: 0.0 })
|
||||
4 if is_rectangle(pts, &corners, size) => {
|
||||
let rotation = rectangle_rotation(&corners);
|
||||
Some(Recognized::Rectangle { rect: square(oriented_bounds(original, rotation)), rotation })
|
||||
}
|
||||
n @ 5..=8 if fill > 0.6 && fill < 0.85 && is_polygonal(pts, &corners, size) => {
|
||||
n @ 5..=8 if fill > 0.6 && fill < 0.85 && is_polygonal(pts, &corners, size, 0.02) => {
|
||||
let radius = corners.iter().map(|p| p.distance(center)).sum::<f64>() / n as f64;
|
||||
Some(Recognized::Polygon { center, radius, sides: n as u32, rotation: 0.0 })
|
||||
Some(Recognized::Polygon { center, radius, sides: n as u32, rotation: if n == 6 { polygon_rotation(&corners, 90.0) } else { 0.0 } })
|
||||
}
|
||||
_ => {
|
||||
let rotation = ellipse_rotation(pts);
|
||||
let rect = oriented_bounds(original, rotation);
|
||||
(area(pts) / (rect.width() * rect.height()).max(1e-9) > 0.6).then(|| Recognized::Ellipse { rect: square(rect), rotation })
|
||||
}
|
||||
_ if fill > 0.6 => Some(Recognized::Ellipse(square(b))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Do the stroke's points hug the straight edges between `corners` (rather than bulging like an
|
||||
/// ellipse)?
|
||||
fn is_polygonal(pts: &[Point], corners: &[Point], size: f64) -> bool {
|
||||
let n = corners.len();
|
||||
let dev: f64 = pts.iter().map(|p| (0..n).map(|i| dist_to_segment(*p, corners[i], corners[(i + 1) % n])).fold(f64::MAX, f64::min)).sum::<f64>()
|
||||
fn is_polygonal(pts: &[Point], corners: &[Point], size: f64, tolerance: f64) -> bool {
|
||||
if pts.is_empty() || corners.len() < 3 {
|
||||
return false;
|
||||
}
|
||||
let dev: f64 = pts
|
||||
.iter()
|
||||
.map(|p| corners.iter().zip(corners.iter().cycle().skip(1)).map(|(&a, &b)| dist_to_segment(*p, a, b)).fold(f64::MAX, f64::min))
|
||||
.sum::<f64>()
|
||||
/ pts.len() as f64;
|
||||
dev < 0.02 * size
|
||||
dev < tolerance * size
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -192,20 +356,45 @@ mod tests {
|
||||
#[test]
|
||||
fn rough_rectangle_and_square() {
|
||||
let r = wobbly(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)], 20, 2.0);
|
||||
let Some(Recognized::Rectangle(b)) = recognize(&r) else { panic!("{:?}", recognize(&r)) };
|
||||
let Some(Recognized::Rectangle { rect: b, .. }) = recognize(&r) else { panic!("{:?}", recognize(&r)) };
|
||||
assert!((b.width() - 200.0).abs() < 8.0 && (b.height() - 100.0).abs() < 8.0);
|
||||
let s = wobbly(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 95.0), Point::new(0.0, 95.0)], 20, 1.0);
|
||||
let Some(Recognized::Rectangle(b)) = recognize(&s) else { panic!() };
|
||||
let Some(Recognized::Rectangle { rect: b, .. }) = recognize(&s) else { panic!() };
|
||||
assert!((b.width() - b.height()).abs() < 1e-9, "near-squares snap to squares");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rough_squares_are_rectangles_from_any_starting_point() {
|
||||
let cases = [
|
||||
[Point::new(0.0, 0.0), Point::new(100.0, 8.0), Point::new(94.0, 100.0), Point::new(10.0, 91.0)],
|
||||
[Point::new(0.0, 8.0), Point::new(94.0, 0.0), Point::new(100.0, 95.0), Point::new(7.0, 100.0)],
|
||||
];
|
||||
for vertices in cases {
|
||||
for wobble in [0.5, 4.0] {
|
||||
let mut stroke = wobbly(&vertices, 24, wobble);
|
||||
stroke.pop();
|
||||
for start in [0, 5, 12, 20, 30, 47, 60, 79] {
|
||||
stroke.rotate_left(start);
|
||||
let mut closed = stroke.clone();
|
||||
closed.push(stroke[0] + Vec2::new(2.0, -1.0));
|
||||
assert!(
|
||||
matches!(recognize(&closed), Some(Recognized::Rectangle { .. })),
|
||||
"wobble {wobble}, start {start}: {:?}",
|
||||
recognize(&closed)
|
||||
);
|
||||
stroke.rotate_right(start);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipse_circle_triangle_hexagon_line() {
|
||||
assert!(
|
||||
matches!(recognize(&circle(Point::new(100.0, 100.0), 80.0, 40.0, 72)), Some(Recognized::Ellipse(r)) if r.width() > 150.0 && r.height() < 100.0)
|
||||
matches!(recognize(&circle(Point::new(100.0, 100.0), 80.0, 40.0, 72)), Some(Recognized::Ellipse { rect: r, .. }) if r.width() > 150.0 && r.height() < 100.0)
|
||||
);
|
||||
assert!(
|
||||
matches!(recognize(&circle(Point::new(100.0, 100.0), 50.0, 48.0, 72)), Some(Recognized::Ellipse(r)) if (r.width() - r.height()).abs() < 1e-9)
|
||||
matches!(recognize(&circle(Point::new(100.0, 100.0), 50.0, 48.0, 72)), Some(Recognized::Ellipse { rect: r, .. }) if (r.width() - r.height()).abs() < 1e-9)
|
||||
);
|
||||
let tri = wobbly(&[Point::new(100.0, 0.0), Point::new(200.0, 170.0), Point::new(0.0, 170.0)], 25, 1.5);
|
||||
assert!(matches!(recognize(&tri), Some(Recognized::Polygon { sides: 3, rotation, .. }) if rotation.abs() < 5.0), "{:?}", recognize(&tri));
|
||||
@@ -220,6 +409,151 @@ mod tests {
|
||||
assert!(matches!(recognize(&line), Some(Recognized::Line { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_and_real_polygons_keep_their_identity_across_stroke_seams() {
|
||||
for (rx, ry) in [(50.0, 50.0), (80.0, 40.0), (50.0, 40.0)] {
|
||||
let mut stroke = circle(Point::new(100.0, 100.0), rx, ry, 192);
|
||||
stroke.pop();
|
||||
for start in [0, 13, 37, 62, 109] {
|
||||
stroke.rotate_left(start);
|
||||
let mut closed = stroke.clone();
|
||||
closed.push(stroke[0]);
|
||||
assert!(matches!(recognize(&closed), Some(Recognized::Ellipse { .. })), "ellipse {rx}/{ry}, seam {start}: {:?}", recognize(&closed));
|
||||
stroke.rotate_right(start);
|
||||
}
|
||||
}
|
||||
for sides in [3, 5, 6, 8] {
|
||||
let corners: Vec<Point> = (0..sides)
|
||||
.map(|i| {
|
||||
let a = std::f64::consts::TAU * i as f64 / sides as f64;
|
||||
Point::new(100.0 + 80.0 * a.cos(), 100.0 + 80.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let mut stroke = wobbly(&corners, 24, 1.0);
|
||||
stroke.pop();
|
||||
for start in [0, 9, 17, 29, 45] {
|
||||
stroke.rotate_left(start);
|
||||
let mut closed = stroke.clone();
|
||||
closed.push(stroke[0]);
|
||||
assert!(
|
||||
matches!(recognize(&closed), Some(Recognized::Polygon { sides: n, .. }) if n == sides),
|
||||
"{sides} sides, seam {start}: {:?}",
|
||||
recognize(&closed)
|
||||
);
|
||||
stroke.rotate_right(start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rough_triangles_snap_upright_or_upside_down() {
|
||||
for direction in [0.0_f64, 180.0] {
|
||||
for tilt in [-12.0_f64, -3.0, 4.0, 11.0] {
|
||||
let corners: Vec<Point> = (0..3)
|
||||
.map(|i| {
|
||||
let a = (direction + tilt - 90.0).to_radians() + std::f64::consts::TAU * i as f64 / 3.0;
|
||||
Point::new(200.0 + 80.0 * a.cos(), 300.0 + 80.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
for reversed in [false, true] {
|
||||
let mut stroke = wobbly(&corners, 24, 1.5);
|
||||
stroke.pop();
|
||||
if reversed {
|
||||
stroke.reverse();
|
||||
}
|
||||
for seam in [0, 9, 28, 51] {
|
||||
stroke.rotate_left(seam);
|
||||
let mut closed = stroke.clone();
|
||||
closed.push(stroke[0]);
|
||||
let Some(Recognized::Polygon { sides: 3, rotation, .. }) = recognize(&closed) else {
|
||||
panic!("direction {direction}, tilt {tilt}, seam {seam}: {:?}", recognize(&closed));
|
||||
};
|
||||
assert_eq!(rotation, direction, "tilt {tilt}, seam {seam}, reversed {reversed}");
|
||||
stroke.rotate_right(seam);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognized_lines_keep_their_free_angle() {
|
||||
for (dx, dy) in [(120.0, 7.0), (-130.0, -9.0), (8.0, 90.0), (-6.0, -140.0), (60.0, 50.0), (-50.0, -60.0)] {
|
||||
let first = Point::new(200.0, 300.0);
|
||||
let last = first + Vec2::new(dx, dy);
|
||||
let stroke: Vec<Point> = (0..=30).map(|i| first + (last - first) * (i as f64 / 30.0)).collect();
|
||||
assert_eq!(recognize(&stroke), Some(Recognized::Line { a: first, b: last }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilted_rectangles_ellipses_and_hexagons_snap_to_their_angle_steps() {
|
||||
for direction in [0.0_f64, 45.0, 90.0, 135.0] {
|
||||
for tilt in [-7.0_f64, 7.0] {
|
||||
let xf = Affine::translate((200.0, 300.0)) * Affine::rotate((direction + tilt).to_radians());
|
||||
let corners: Vec<Point> =
|
||||
[(-90.0, -40.0), (90.0, -40.0), (90.0, 40.0), (-90.0, 40.0)].into_iter().map(|p| xf * Point::from(p)).collect();
|
||||
let stroke = wobbly(&corners, 24, 1.0);
|
||||
let Some(Recognized::Rectangle { rect, rotation }) = recognize(&stroke) else {
|
||||
panic!("rectangle {direction}: {:?}", recognize(&stroke))
|
||||
};
|
||||
assert_eq!(rotation % 45.0, 0.0);
|
||||
assert!(rect.center().distance(Point::new(200.0, 300.0)) < 4.0);
|
||||
assert!((rect.width().max(rect.height()) - 180.0).abs() < 15.0);
|
||||
let ellipse: Vec<Point> = circle(Point::ZERO, 90.0, 40.0, 192).into_iter().map(|p| xf * p).collect();
|
||||
let Some(Recognized::Ellipse { rect, rotation }) = recognize(&ellipse) else {
|
||||
panic!("ellipse {direction}: {:?}", recognize(&ellipse))
|
||||
};
|
||||
assert_eq!(rotation, direction);
|
||||
assert!((rect.width() - 180.0).abs() < 4.0 && (rect.height() - 80.0).abs() < 4.0);
|
||||
}
|
||||
}
|
||||
for direction in [0.0_f64, 90.0] {
|
||||
for tilt in [-7.0_f64, 7.0] {
|
||||
let corners: Vec<Point> = (0..6)
|
||||
.map(|i| {
|
||||
let a = (direction + tilt - 90.0).to_radians() + std::f64::consts::TAU * i as f64 / 6.0;
|
||||
Point::new(200.0 + 70.0 * a.cos(), 300.0 + 70.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let stroke = wobbly(&corners, 24, 0.5);
|
||||
let Some(Recognized::Polygon { sides: 6, rotation, .. }) = recognize(&stroke) else { panic!("hexagon: {:?}", recognize(&stroke)) };
|
||||
assert_eq!(rotation, direction);
|
||||
}
|
||||
}
|
||||
// Even sideways input can only produce an upright or inverted triangle.
|
||||
for direction in [83.0_f64, 97.0, 263.0, 277.0] {
|
||||
let corners: Vec<Point> = (0..3)
|
||||
.map(|i| {
|
||||
let a = (direction - 90.0).to_radians() + std::f64::consts::TAU * i as f64 / 3.0;
|
||||
Point::new(200.0 + 70.0 * a.cos(), 300.0 + 70.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
assert!(matches!(recognize(&wobbly(&corners, 24, 0.5)), Some(Recognized::Polygon { sides: 3, rotation: 0.0 | 180.0, .. })));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn square_fit_ignores_sampling_density_and_document_offset() {
|
||||
let mut stroke = wobbly(&[Point::new(0.0, 0.0), Point::new(100.0, 8.0), Point::new(94.0, 100.0), Point::new(10.0, 91.0)], 24, 4.0);
|
||||
for scale in [0.25, 1.0, 20.0] {
|
||||
let shifted: Vec<Point> = stroke.iter().map(|p| Point::new(1e9 + p.x * scale, -1e9 + p.y * scale)).collect();
|
||||
assert!(matches!(recognize(&shifted), Some(Recognized::Rectangle { .. })), "scale {scale}: {:?}", recognize(&shifted));
|
||||
}
|
||||
let dense: Vec<Point> = stroke.iter().enumerate().flat_map(|(i, p)| std::iter::repeat_n(*p, if i < 24 { 100 } else { 1 })).collect();
|
||||
assert_eq!(recognize(&stroke), recognize(&dense));
|
||||
stroke.extend(std::iter::repeat_n(*stroke.last().unwrap(), 10_000));
|
||||
assert!(matches!(recognize(&stroke), Some(Recognized::Rectangle { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_and_overflowing_strokes_are_not_shapes() {
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert_eq!(recognize(&[Point::new(0.0, 0.0), Point::new(bad, 100.0)]), None);
|
||||
}
|
||||
assert_eq!(recognize(&[Point::new(-f64::MAX, 0.0), Point::new(f64::MAX, 100.0)]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scribble_and_noise() {
|
||||
let z: Vec<Point> = (0..40).map(|i| Point::new(100.0 + (i % 2) as f64 * 60.0, 100.0 + i as f64 * 2.0)).collect();
|
||||
|
||||
@@ -296,7 +296,8 @@ Method:
|
||||
1. open_file the image: it becomes a document of its own pixel size.
|
||||
2. imageTrace.make with the preset name, adjusting `params` — mode blackAndWhite, grayscale or
|
||||
color, then threshold, colors, paths, corners, noise, method abutting or overlapping,
|
||||
ignoreWhite, snapCurvesToLines. Run imageTrace.presets to see every preset with its numbers.
|
||||
ignoreWhite, snapCurvesToLines; for line art, strokes: true (with strokeWidth, the widest
|
||||
line in pixels) traces lines as stroked centre lines instead of filled outlines. Run imageTrace.presets to see every preset with its numbers.
|
||||
Lower paths and higher corners give the clean, logo-like result; high fidelity needs paths
|
||||
near 90.
|
||||
3. apply_effect {effect} on the traced shapes. Call apply_effect with no `effect` for the
|
||||
|
||||
@@ -464,8 +464,14 @@ pub(crate) struct Exporter<'a> {
|
||||
pub overprint: bool,
|
||||
/// An overprinting fill or stroke was drawn so.
|
||||
pub overprinted: bool,
|
||||
/// Inline graphics being drawn inside inline graphics (text in a symbol shown inline in
|
||||
/// text…): deeper ones are left out.
|
||||
inline_depth: u32,
|
||||
}
|
||||
|
||||
/// How deep inline graphics nest before they are left out.
|
||||
const MAX_INLINE_DEPTH: u32 = 4;
|
||||
|
||||
impl<'a> Exporter<'a> {
|
||||
/// An exporter of `doc` writing images as `set` says; layers whose Print option is off are
|
||||
/// left out.
|
||||
@@ -491,6 +497,7 @@ impl<'a> Exporter<'a> {
|
||||
in_layer: 0,
|
||||
overprint: false,
|
||||
overprinted: false,
|
||||
inline_depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1280,7 +1287,14 @@ impl Exporter<'_> {
|
||||
true
|
||||
}
|
||||
|
||||
///
|
||||
/// Inline graphics ([`vectorcraft_doc::TextRun::inline`]) are drawn as their symbols' art
|
||||
/// (vector paths, like symbol instances) where the layout placed them; their characters
|
||||
/// write no glyph.
|
||||
fn text(&mut self, s: &mut Surface, n: &Node, t: &TextObject, page: Rect) {
|
||||
let doc = self.doc;
|
||||
let resolved = doc.inline_resolved(t);
|
||||
let t = &*resolved;
|
||||
let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let tb = t.xf.transform_rect_bbox(layout.bounds);
|
||||
// The object's own fills and strokes paint the whole outline: those below the Characters
|
||||
@@ -1331,6 +1345,18 @@ impl Exporter<'_> {
|
||||
s.set_fill(None);
|
||||
s.set_stroke(None);
|
||||
s.pop();
|
||||
if self.inline_depth < MAX_INLINE_DEPTH {
|
||||
self.inline_depth += 1;
|
||||
for ig in &layout.inlines {
|
||||
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
|
||||
let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue };
|
||||
let mut node = (*sym.art).clone();
|
||||
// Strokes scale with the art, as on the canvas.
|
||||
node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
|
||||
self.node(s, &node, page, true);
|
||||
}
|
||||
self.inline_depth -= 1;
|
||||
}
|
||||
if let Some((bp, path)) = &all {
|
||||
self.text_items(s, above, bp, path, page, tb);
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, wi
|
||||
style.leading = explicit.then_some((b.leading * 1000.0).round() / 1000.0);
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.style == style => last.text.push_str(&r.text),
|
||||
_ => runs.push(TextRun { text: r.text.clone(), style }),
|
||||
_ => runs.push(TextRun { text: r.text.clone(), style, inline: None }),
|
||||
}
|
||||
}
|
||||
// A wrapped line's space, or the end of a paragraph.
|
||||
|
||||
@@ -301,7 +301,7 @@ impl TextLine {
|
||||
if self.runs.iter().all(|(_, t)| t.trim().is_empty()) {
|
||||
return None;
|
||||
}
|
||||
let mut runs = self.runs.into_iter().map(|(look, text)| TextRun { text, style: look.style() });
|
||||
let mut runs = self.runs.into_iter().map(|(look, text)| TextRun { text, style: look.style(), inline: None });
|
||||
let first = runs.next()?;
|
||||
let mut t = TextObject::point(Point::ORIGIN, &first.text, first.style);
|
||||
t.runs.extend(runs);
|
||||
@@ -397,13 +397,13 @@ fn tracked(runs: Vec<TextRun>, tracking: f64, spaces: &[(usize, f64)]) -> Vec<Te
|
||||
let at = b - off;
|
||||
let (Some(before), Some(space)) = (r.text.get(from..at), r.text.get(at..at + 1)) else { continue };
|
||||
if !before.is_empty() {
|
||||
out.push(TextRun { text: before.to_string(), style: style.clone() });
|
||||
out.push(TextRun { text: before.to_string(), style: style.clone(), inline: None });
|
||||
}
|
||||
out.push(TextRun { text: space.to_string(), style: CharStyle { tracking: own, ..style.clone() } });
|
||||
out.push(TextRun { text: space.to_string(), style: CharStyle { tracking: own, ..style.clone() }, inline: None });
|
||||
from = at + 1;
|
||||
}
|
||||
if let Some(rest) = r.text.get(from..).filter(|t| !t.is_empty()) {
|
||||
out.push(TextRun { text: rest.to_string(), style });
|
||||
out.push(TextRun { text: rest.to_string(), style, inline: None });
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
@@ -490,7 +490,7 @@ fn to_logical(t: &mut TextObject) {
|
||||
_ => runs.push((i, c.to_string())),
|
||||
}
|
||||
}
|
||||
let runs = runs.into_iter().filter_map(|(i, text)| Some(TextRun { text, style: t.runs.get(i)?.style.clone() })).collect();
|
||||
let runs = runs.into_iter().filter_map(|(i, text)| Some(TextRun { text, style: t.runs.get(i)?.style.clone(), inline: None })).collect();
|
||||
t.runs = runs;
|
||||
t.para.direction = Some(if rtl { ParaDirection::RightToLeft } else { ParaDirection::LeftToRight });
|
||||
}
|
||||
@@ -91,9 +91,9 @@ fn real_text_lands_within_half_a_point_of_the_outlines() {
|
||||
turned.xf *= Affine::rotate(-0.5) * Affine::skew(0.2, 0.0);
|
||||
let mut mixed = TextObject::point(Point::new(200.0, 60.0), "", style(20.0));
|
||||
mixed.runs = vec![
|
||||
TextRun { text: "x".into(), style: style(20.0) },
|
||||
TextRun { text: "2".into(), style: CharStyle { baseline_shift: 8.0, v_scale: 140.0, ..style(12.0) } },
|
||||
TextRun { text: " ok".into(), style: CharStyle { rotation: 20.0, ..style(20.0) } },
|
||||
TextRun { text: "x".into(), style: style(20.0), inline: None },
|
||||
TextRun { text: "2".into(), style: CharStyle { baseline_shift: 8.0, v_scale: 140.0, ..style(12.0) }, inline: None },
|
||||
TextRun { text: " ok".into(), style: CharStyle { rotation: 20.0, ..style(20.0) }, inline: None },
|
||||
];
|
||||
let mut on_path = TextObject::point(Point::ZERO, "along the arc", style(18.0));
|
||||
on_path.kind = TextKind::OnPath { path: arc(), start: 0.0, end: None };
|
||||
|
||||
@@ -340,8 +340,17 @@ pub struct Renderer {
|
||||
/// Layer Options → Dim Images to, of the layer being drawn (screen views only): images show
|
||||
/// faded to this opacity over white.
|
||||
dim_images: Option<f32>,
|
||||
/// Inline graphics being drawn inside inline graphics (a symbol whose art holds text showing
|
||||
/// it): drawing stops at [`MAX_INLINE_DEPTH`].
|
||||
inline_depth: u32,
|
||||
}
|
||||
|
||||
/// How deep inline graphics nest (text in a symbol shown inline in text…) before they draw nothing.
|
||||
const MAX_INLINE_DEPTH: u32 = 4;
|
||||
|
||||
/// Set once a missing inline symbol has been logged (it would log every frame otherwise).
|
||||
static MISSING_INLINE_LOGGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct FrameStats {
|
||||
pub drawn: usize,
|
||||
@@ -418,6 +427,7 @@ impl Renderer {
|
||||
stroke_slices: PtrMap::default(),
|
||||
adjusted: Default::default(),
|
||||
dim_images: None,
|
||||
inline_depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,6 +804,7 @@ impl Renderer {
|
||||
&& a.blend == vectorcraft_color::BlendMode::Normal
|
||||
&& !fx::has_fx(a)
|
||||
{
|
||||
let t = &*f.doc.inline_resolved(t);
|
||||
let g = match f.text_snap(t) {
|
||||
Some(xf) => Arc::new(text_geom_snapped(t, Some(xf))),
|
||||
None => self.text_geom_of(a, t),
|
||||
@@ -1206,10 +1217,38 @@ impl Renderer {
|
||||
}
|
||||
|
||||
fn draw_text(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, t: &TextObject) {
|
||||
let t = &*f.doc.inline_resolved(t);
|
||||
let g = text_geom_snapped(t, f.text_snap(t));
|
||||
self.draw_text_geom(ctx, f, n, t, &g);
|
||||
}
|
||||
|
||||
/// Draw the inline graphics of type `t` (laid out in `g`): each symbol's art through the
|
||||
/// normal node path, placed by the layout (inside the text's own transparency group, so its
|
||||
/// opacity and blend mode apply). A missing symbol draws nothing.
|
||||
fn draw_inlines(&mut self, ctx: &mut RenderContext, f: &Frame, t: &TextObject, g: &TextGeom) {
|
||||
if g.inlines.is_empty() && !t.runs.iter().any(|r| r.inline.is_some()) {
|
||||
return;
|
||||
}
|
||||
if self.inline_depth >= MAX_INLINE_DEPTH {
|
||||
return;
|
||||
}
|
||||
for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) {
|
||||
if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol);
|
||||
}
|
||||
}
|
||||
self.inline_depth += 1;
|
||||
for ig in &g.inlines {
|
||||
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
|
||||
let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue };
|
||||
let mut node = (*sym.art).clone();
|
||||
// Strokes scale with the art (it is sized to the type, as in the SVG `<use>`).
|
||||
node.transform(t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true);
|
||||
self.draw_node(ctx, f, &node, true);
|
||||
}
|
||||
self.inline_depth -= 1;
|
||||
}
|
||||
|
||||
/// Cached glyph geometry for a text node (keyed by Arc identity like paths).
|
||||
fn text_geom_of(&mut self, a: &Arc<Node>, t: &TextObject) -> Arc<TextGeom> {
|
||||
let fonts = vectorcraft_text::FontDb::global().generation();
|
||||
@@ -1240,6 +1279,7 @@ impl Renderer {
|
||||
ctx.set_stroke(kurbo::Stroke::new(1.0));
|
||||
ctx.set_paint(peniko::Color::BLACK);
|
||||
ctx.stroke_path(&p);
|
||||
self.draw_inlines(ctx, f, t, g);
|
||||
return;
|
||||
}
|
||||
let tb = t.xf.transform_rect_bbox(g.bounds);
|
||||
@@ -1293,6 +1333,7 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
overprint(ctx, false);
|
||||
self.draw_inlines(ctx, f, t, g);
|
||||
if let Some(all) = &all {
|
||||
self.draw_text_items(ctx, f, n, above, all, tb);
|
||||
}
|
||||
@@ -1549,6 +1590,8 @@ struct TextGeom {
|
||||
/// font lacks (drawn from a fallback font): Document Setup's substitution highlights.
|
||||
substituted_fonts: BezPath,
|
||||
substituted_glyphs: BezPath,
|
||||
/// Inline graphics placed by the layout.
|
||||
inlines: Vec<vectorcraft_text::InlineGlyph>,
|
||||
}
|
||||
|
||||
fn text_geom(t: &TextObject) -> TextGeom {
|
||||
@@ -1592,7 +1635,7 @@ fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeom {
|
||||
cell.apply_affine(Affine::rotate_about(g.angle, g.origin));
|
||||
target.extend(cell.iter());
|
||||
}
|
||||
TextGeom { runs, all, bounds: layout.bounds, substituted_fonts, substituted_glyphs }
|
||||
TextGeom { runs, all, bounds: layout.bounds, substituted_fonts, substituted_glyphs, inlines: layout.inlines }
|
||||
}
|
||||
|
||||
/// Document Setup's highlight behind substituted fonts and glyphs (screen only).
|
||||
|
||||
@@ -549,6 +549,10 @@ impl Rules<'_> {
|
||||
if let Some(l) = st.leading {
|
||||
art.props.push(("line-height", self.len(l)));
|
||||
}
|
||||
// One element: the first paragraph's alignment.
|
||||
if (1..t.paragraph_count()).any(|i| t.para_at(i).justify != t.para.justify) {
|
||||
art.unsupported("paragraphs aligned differently");
|
||||
}
|
||||
let align = match t.para.justify {
|
||||
Justify::Auto | Justify::Left => None,
|
||||
Justify::Center => Some("center"),
|
||||
|
||||
+95
-26
@@ -68,6 +68,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
|
||||
symbol_nest: 0,
|
||||
fonts: Vec::new(),
|
||||
shared_images: HashMap::new(),
|
||||
layer_nest: 0,
|
||||
};
|
||||
w.assign_name_ids();
|
||||
// Page Isolated Blending / Page Knockout Group: the page content is one isolated group.
|
||||
@@ -266,6 +267,8 @@ struct Writer<'a> {
|
||||
/// Images written once in the defs and drawn with `<use>`, by key and size: the pieces an
|
||||
/// envelope cuts a distorted image into share its pixels.
|
||||
shared_images: HashMap<(String, u32, u32), String>,
|
||||
/// Layers being written inside one another (more than one: a sublayer).
|
||||
layer_nest: usize,
|
||||
}
|
||||
|
||||
/// The characters type uses from one face, under one `@font-face` description: the family the
|
||||
@@ -545,8 +548,8 @@ impl Writer<'_> {
|
||||
}
|
||||
/// ` id="…"` for a named object, plus ` data-name="…"` with the name itself when the id had to
|
||||
/// differ from it (spaces, punctuation, duplicates, the unique prefix).
|
||||
/// The id of `n`'s element (with its name when the id isn't it), then the object's own data
|
||||
/// as `data-*` attributes.
|
||||
/// The id of `n`'s element (with its name when the id isn't it), a sublayer's mark
|
||||
/// ([`crate::import::SUBLAYER`]), then the object's own data as `data-*` attributes.
|
||||
fn id_attr(&self, n: &Node) -> String {
|
||||
if self.anonymous {
|
||||
return String::new();
|
||||
@@ -556,6 +559,10 @@ impl Writer<'_> {
|
||||
(Some(id), _) => format!(" id=\"{}\"", xml_escape(id)),
|
||||
(None, _) => String::new(),
|
||||
};
|
||||
// A sublayer is marked as one, so import makes it a sublayer again, not a group.
|
||||
if !out.is_empty() && n.is_layer() && self.layer_nest > 1 {
|
||||
out.push_str(&format!(" {}=\"sublayer\"", crate::import::SUBLAYER));
|
||||
}
|
||||
for (k, v) in n.attrs.as_deref().map_or(&[][..], |a| a.data.as_slice()) {
|
||||
// Names as XML takes them; ours (`name`, `vc-…`) are written by the export itself.
|
||||
let valid = k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && k != "name" && !k.starts_with("vc-");
|
||||
@@ -1215,6 +1222,8 @@ impl Writer<'_> {
|
||||
|
||||
/// An object, inside `<a>` when it links to a URL (Attributes panel).
|
||||
fn node(&mut self, n: &Node) {
|
||||
let layer = usize::from(n.is_layer());
|
||||
self.layer_nest += layer;
|
||||
match n.url().filter(|_| n.visible && !self.anonymous) {
|
||||
Some(url) => {
|
||||
self.line(&format!("<a xlink:href=\"{}\">", xml_escape(url)));
|
||||
@@ -1225,6 +1234,7 @@ impl Writer<'_> {
|
||||
}
|
||||
None => self.node_body(n),
|
||||
}
|
||||
self.layer_nest -= layer;
|
||||
}
|
||||
|
||||
fn node_body(&mut self, n: &Node) {
|
||||
@@ -1597,9 +1607,21 @@ impl Writer<'_> {
|
||||
/// Type: its characters (live text, or glyph outlines when text is exported as outlines) and,
|
||||
/// as the canvas paints them, the object's own fills and strokes on the glyph outlines: those
|
||||
/// below the Characters row under the characters, the others over them.
|
||||
///
|
||||
/// Inline graphics ([`vectorcraft_doc::TextRun::inline`]) are written after the characters as
|
||||
/// instances of their symbols (a `<use>` of the symbol's def where it can be shared), all in
|
||||
/// one group carrying the object's transparency. The live text skips their characters and
|
||||
/// places the text after each one; type on a path with inline graphics is written as outlines
|
||||
/// (a `<textPath>` couldn't leave room for the art).
|
||||
fn text_node(&mut self, n: &Node, t: &TextObject) {
|
||||
let chars = |w: &mut Self, n: &Node| if w.opts.outline_text || t.vertical { w.text_outlines(n, t) } else { w.text(n, t) };
|
||||
if !n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()) {
|
||||
let doc = self.doc;
|
||||
let resolved = doc.inline_resolved(t);
|
||||
let t = &*resolved;
|
||||
let inline = t.runs.iter().any(|r| r.inline.is_some());
|
||||
let outlined = self.opts.outline_text || t.vertical || (inline && matches!(t.kind, TextKind::OnPath { .. }));
|
||||
let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) };
|
||||
let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none());
|
||||
if !painted && !inline {
|
||||
return chars(self, n);
|
||||
}
|
||||
let id = self.id_attr(n);
|
||||
@@ -1622,6 +1644,14 @@ impl Writer<'_> {
|
||||
let bare = Node { opacity: 1.0, blend: BlendMode::Normal, isolate: false, ..n.clone() };
|
||||
let anonymous = std::mem::replace(&mut self.anonymous, true);
|
||||
chars(self, &bare);
|
||||
for ig in &lay.inlines {
|
||||
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
|
||||
let inst = Node::new(
|
||||
NodeId(u64::MAX),
|
||||
NodeKind::SymbolInstance { symbol: art.symbol.clone(), xf: t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol) },
|
||||
);
|
||||
self.node(&inst);
|
||||
}
|
||||
glyphs(self, above);
|
||||
self.anonymous = anonymous;
|
||||
self.depth -= 1;
|
||||
@@ -1683,18 +1713,29 @@ impl Writer<'_> {
|
||||
}
|
||||
self.note_fonts(t, &lay);
|
||||
let lines = text_lines(t, &lay, self.opts.fewer_tspans);
|
||||
// A tab starts a new chunk at its stop: only lines without tabs can be anchored.
|
||||
let anchor = match t.para.justify {
|
||||
Justify::Center => Some(("middle", 0.5)),
|
||||
Justify::Right => Some(("end", 1.0)),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|_| !lines.iter().flatten().any(|s| s.brk));
|
||||
// Each line is anchored as its paragraph is aligned. A tab starts a new chunk at its
|
||||
// stop, and so does the text after an inline graphic: lines with tabs, and text with
|
||||
// inline graphics, are never anchored.
|
||||
let has_inline = t.runs.iter().any(|r| r.inline.is_some());
|
||||
let anchors: Vec<Option<(&str, f64)>> = lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
match t.para_at(l.para).justify {
|
||||
Justify::Center => Some(("middle", 0.5)),
|
||||
Justify::Right => Some(("end", 1.0)),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|_| !has_inline && !l.segs.iter().any(|s| s.brk))
|
||||
})
|
||||
.collect();
|
||||
// Every line anchored alike (the text's only paragraph style, typically): the <text>
|
||||
// carries the anchor. Otherwise each anchored line is a <tspan> carrying its own.
|
||||
let uniform = anchors.first().copied().filter(|a| a.is_some() && anchors.iter().all(|b| b == a)).flatten();
|
||||
// The <text> element's user space is text space.
|
||||
let space = (lay.bounds, Affine::IDENTITY);
|
||||
let base = TextBase { props: self.char_props(&t.first_style(), space), space, anchored: anchor.is_some() };
|
||||
let base = TextBase { props: self.char_props(&t.first_style(), space), space, anchored: uniform.is_some() };
|
||||
let mut props = base.props.clone();
|
||||
if let Some((a, _)) = anchor {
|
||||
if let Some((a, _)) = uniform {
|
||||
props.push(("text-anchor", a.into()));
|
||||
}
|
||||
props.extend(css::transparency(n));
|
||||
@@ -1702,7 +1743,7 @@ impl Writer<'_> {
|
||||
let a = self.attrs(&props);
|
||||
let m = self.xf * t.xf;
|
||||
let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) };
|
||||
let starts: Vec<Option<(f64, f64)>> = lines.iter().map(|l| line_start(l, anchor.map(|a| a.1))).collect();
|
||||
let starts: Vec<Option<(f64, f64)>> = lines.iter().zip(&anchors).map(|(l, a)| line_start(&l.segs, a.map(|a| a.1))).collect();
|
||||
// The `<text>` carries the first line's position too, so readers that place text by its
|
||||
// own x/y start where the first line does.
|
||||
let at = match starts.iter().flatten().next() {
|
||||
@@ -1710,9 +1751,17 @@ impl Writer<'_> {
|
||||
None => String::new(),
|
||||
};
|
||||
let mut s = format!("<text{id}{tr}{at} xml:space=\"preserve\"{a}>");
|
||||
for (line, start) in lines.iter().zip(starts) {
|
||||
if let Some(start) = start {
|
||||
self.text_line(&mut s, t, line, start, &base);
|
||||
for ((line, start), anchor) in lines.iter().zip(starts).zip(&anchors) {
|
||||
let Some(start) = start else { continue };
|
||||
match anchor.filter(|_| uniform.is_none()) {
|
||||
// A line anchored on its own: one positioned <tspan> with the anchor around it.
|
||||
Some((a, _)) => {
|
||||
s.push_str(&format!("<tspan x=\"{}\" y=\"{}\" text-anchor=\"{a}\">", self.num(start.0), self.num(start.1)));
|
||||
let inner = TextBase { anchored: true, ..base.clone() };
|
||||
self.text_line(&mut s, t, &line.segs, start, &inner, false);
|
||||
s.push_str("</tspan>");
|
||||
}
|
||||
None => self.text_line(&mut s, t, &line.segs, start, &base, true),
|
||||
}
|
||||
}
|
||||
s.push_str("</text>");
|
||||
@@ -1723,12 +1772,13 @@ impl Writer<'_> {
|
||||
/// (only the first of an anchored line). Fewer tspans: one positioned `<tspan>` per line with
|
||||
/// the style changes nested in it, positioned again only after tabs and justified word spaces.
|
||||
/// Baseline shifts are relative (`dy`), undone by the next segment that isn't shifted.
|
||||
fn text_line(&mut self, s: &mut String, t: &TextObject, line: &[Segment], start: (f64, f64), base: &TextBase) {
|
||||
let fewer = self.opts.fewer_tspans;
|
||||
/// `positioned`: false when the caller already positioned the line (an outer `<tspan>`).
|
||||
fn text_line(&mut self, s: &mut String, t: &TextObject, line: &[Segment], start: (f64, f64), base: &TextBase, positioned: bool) {
|
||||
let fewer = self.opts.fewer_tspans && positioned;
|
||||
if fewer {
|
||||
s.push_str(&format!("<tspan x=\"{}\" y=\"{}\">", self.num(start.0), self.num(start.1)));
|
||||
}
|
||||
let mut place = !fewer;
|
||||
let mut place = !fewer && positioned;
|
||||
let mut first = true;
|
||||
// The baseline shift the current text position carries.
|
||||
let mut shift = 0.0;
|
||||
@@ -1746,7 +1796,7 @@ impl Writer<'_> {
|
||||
shift = st.baseline_shift;
|
||||
}
|
||||
// After a tab or a justified word space the next segment is placed.
|
||||
place = seg.brk || (!fewer && !base.anchored);
|
||||
place = seg.brk || (!fewer && !base.anchored && positioned);
|
||||
if (st.h_scale - st.v_scale).abs() > 1e-9 {
|
||||
attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance)));
|
||||
}
|
||||
@@ -1848,7 +1898,7 @@ impl Writer<'_> {
|
||||
let space = (lay.bounds, self.xf * t.xf);
|
||||
let base = self.char_props(&t.first_style(), space);
|
||||
let mut props = base.clone();
|
||||
match t.para.justify {
|
||||
match t.para_at(0).justify {
|
||||
Justify::Center | Justify::JustifyCenter => props.push(("text-anchor", "middle".into())),
|
||||
Justify::Right | Justify::JustifyRight => props.push(("text-anchor", "end".into())),
|
||||
_ => {}
|
||||
@@ -1917,6 +1967,7 @@ fn has_raster(effects: &[vectorcraft_doc::Effect]) -> bool {
|
||||
}
|
||||
|
||||
/// What the lines of one `<text>` share.
|
||||
#[derive(Clone)]
|
||||
struct TextBase {
|
||||
/// The `<text>` element's character properties, which each `<tspan>` differs from.
|
||||
props: Props,
|
||||
@@ -1926,6 +1977,12 @@ struct TextBase {
|
||||
anchored: bool,
|
||||
}
|
||||
|
||||
/// One laid-out line: its paragraph (index) and its segments.
|
||||
struct Line {
|
||||
para: usize,
|
||||
segs: Vec<Segment>,
|
||||
}
|
||||
|
||||
/// Characters of one style on one line, written as one `<tspan>`.
|
||||
struct Segment {
|
||||
/// Index into `TextObject::runs`.
|
||||
@@ -1944,11 +2001,12 @@ struct Segment {
|
||||
/// on justified lines, after each word space (unless `fewer`). The text comes from the clusters
|
||||
/// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all
|
||||
/// caps are upper case.
|
||||
fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -> Vec<Vec<Segment>> {
|
||||
fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -> Vec<Line> {
|
||||
let plain = t.plain_text();
|
||||
let split_words = !fewer && !matches!(t.para.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
|
||||
let mut lines = Vec::with_capacity(lay.lines.len());
|
||||
for line in &lay.lines {
|
||||
let para = plain.as_bytes().get(..line.start).map_or(0, |b| b.iter().filter(|&&c| c == b'\n').count());
|
||||
let split_words = !fewer && !matches!(t.para_at(para).justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right);
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
let mut cluster = None;
|
||||
let source = |g: &vectorcraft_text::PositionedGlyph| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") };
|
||||
@@ -1959,8 +2017,18 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -
|
||||
glyphs = rest;
|
||||
}
|
||||
}
|
||||
let mut after_inline = false;
|
||||
for g in glyphs {
|
||||
let Some(run) = t.runs.get(g.run) else { continue };
|
||||
if run.inline.is_some() {
|
||||
// An inline graphic (written as art): the text after it is placed anew.
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.brk = true;
|
||||
}
|
||||
after_inline = true;
|
||||
cluster = None;
|
||||
continue;
|
||||
}
|
||||
if g.len > 0 && cluster == Some(g.byte) {
|
||||
// Another glyph of the same cluster.
|
||||
if let Some(last) = segs.last_mut() {
|
||||
@@ -1972,8 +2040,9 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -
|
||||
let src: String = source(g).chars().filter(|c| *c != '\u{ad}').collect();
|
||||
let piece = if run.style.all_caps { src.to_uppercase() } else { src };
|
||||
let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace));
|
||||
let fresh = std::mem::take(&mut after_inline);
|
||||
match segs.last_mut() {
|
||||
Some(last) if last.run == g.run && !last.brk => {
|
||||
Some(last) if last.run == g.run && !last.brk && !fresh => {
|
||||
last.text.push_str(&piece);
|
||||
last.advance += g.advance;
|
||||
last.brk = brk;
|
||||
@@ -1983,7 +2052,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) -
|
||||
}
|
||||
segs.retain(|s| !s.text.is_empty());
|
||||
if !segs.is_empty() {
|
||||
lines.push(segs);
|
||||
lines.push(Line { para, segs });
|
||||
}
|
||||
}
|
||||
lines
|
||||
|
||||
+105
-21
@@ -8,7 +8,7 @@ use std::sync::Arc;
|
||||
use usvg::roxmltree;
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeKind, PatternDef,
|
||||
Appearance, AppearanceItem, Dash, Document, FillLayer, ImageBlob, ImageObject, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, PatternDef,
|
||||
StrokeLayer, Unit,
|
||||
};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2, shapes};
|
||||
@@ -33,6 +33,7 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
let xml = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() })
|
||||
.map_err(|e| SvgError::Parse(e.to_string()))?;
|
||||
let units = RootUnits::of(xml.root_element());
|
||||
let root_name = root_layer_name(xml.root_element());
|
||||
let mut warnings = found.warnings;
|
||||
let (src, slots) = text::prepare(svg, &xml, units.dpi, &mut warnings);
|
||||
let files = found.files;
|
||||
@@ -65,6 +66,8 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
files,
|
||||
non_scaling: found.non_scaling,
|
||||
data: found.data,
|
||||
sublayers: found.sublayers,
|
||||
sublayer_groups: HashSet::new(),
|
||||
screen: (kx * ky).sqrt(),
|
||||
};
|
||||
if im.files.nested_text() {
|
||||
@@ -74,22 +77,32 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
// usvg wraps everything in an id-less group carrying the viewBox transform when needed.
|
||||
let mut top = tree.root();
|
||||
let mut base = Affine::scale_non_uniform(kx, ky) * aff(top.transform());
|
||||
if let [usvg::Node::Group(g)] = top.children()
|
||||
&& g.id().is_empty()
|
||||
&& is_plain(g)
|
||||
&& im.text_slot(g).is_none()
|
||||
{
|
||||
if let Some(g) = im.wrapper(top) {
|
||||
base *= aff(g.transform());
|
||||
top = g;
|
||||
}
|
||||
|
||||
// Top-level `<g id>` elements become layers (as in the reference app); otherwise all art goes
|
||||
// into "Layer 1". A clip path on one (as on an Inkscape layer, or our clipping layers) makes it
|
||||
// a clipping layer. Top-level text joins the layer below it (the first layer if none is).
|
||||
// Top-level `<g id>` elements become layers (as in the reference app), named from their
|
||||
// labels (`data-name`…) else their ids; otherwise all art goes into "Layer 1". A clip path on
|
||||
// one (as on an Inkscape layer, or our clipping layers) makes it a clipping layer. Top-level
|
||||
// text joins the layer below it (the first layer if none is).
|
||||
let is_layer = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if !g.id().is_empty() && !made_up(g.id()) && !im.links.contains_key(g.id()) && !im.uses.contains_key(g.id()) && only_clips(g) && im.text_slot(g).is_none());
|
||||
let is_text = |im: &Importer, c: &usvg::Node| matches!(c, usvg::Node::Group(g) if im.text_slot(g).is_some());
|
||||
let layer_mode = top.children().iter().any(|c| is_layer(&im, c)) && top.children().iter().all(|c| is_layer(&im, c) || is_text(&im, c));
|
||||
if layer_mode {
|
||||
let layer_mode = |im: &Importer, top: &usvg::Group| {
|
||||
top.children().iter().any(|c| is_layer(im, c)) && top.children().iter().all(|c| is_layer(im, c) || is_text(im, c))
|
||||
};
|
||||
// The layers may sit in more wrappers (a transform on all the art, a `<switch>`'s group).
|
||||
if !layer_mode(&im, top) {
|
||||
let (mut inner, mut ts) = (top, base);
|
||||
while let Some(g) = im.wrapper(inner) {
|
||||
ts *= aff(g.transform());
|
||||
inner = g;
|
||||
}
|
||||
if layer_mode(&im, inner) {
|
||||
(top, base) = (inner, ts);
|
||||
}
|
||||
}
|
||||
if layer_mode(&im, top) {
|
||||
im.doc.layers.clear();
|
||||
let mut loose = vec![];
|
||||
for c in top.children() {
|
||||
@@ -129,16 +142,68 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
im.doc.layers.push(Arc::new(l));
|
||||
}
|
||||
} else {
|
||||
// An export of a one-layer document names the layer on the root element, its art (groups
|
||||
// among it) loose inside: the one layer takes that name.
|
||||
let children = im.children(top, base);
|
||||
if let Some(l) = im.doc.layers.first_mut()
|
||||
&& let Some(ch) = Arc::make_mut(l).children_mut()
|
||||
{
|
||||
*ch = children;
|
||||
if let Some(l) = im.doc.layers.first_mut() {
|
||||
let l = Arc::make_mut(l);
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
if root_name.is_some() {
|
||||
l.name = root_name;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !im.sublayer_groups.is_empty() {
|
||||
for l in &mut im.doc.layers {
|
||||
promote_sublayers(Arc::make_mut(l), &im.sublayer_groups);
|
||||
}
|
||||
}
|
||||
Ok((im.doc, im.warnings))
|
||||
}
|
||||
|
||||
/// What marks a nested `<g>` as a sublayer rather than a group: our export writes it on the layers
|
||||
/// it writes inside layers. (Inkscape's `inkscape:groupmode="layer"` counts too.)
|
||||
pub(crate) const SUBLAYER: &str = "data-vc-layer";
|
||||
|
||||
/// The Inkscape namespace (its layers and their labels).
|
||||
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
|
||||
|
||||
/// The layer name on root element `root` (`<svg id="Main">`, or its `data-name`), as exports of
|
||||
/// one-layer documents write it. An Inkscape root's id (`svg8`) is one Inkscape made up, not a name.
|
||||
fn root_layer_name(root: XNode) -> Option<String> {
|
||||
let id = root.attribute("id").filter(|_| root.attribute((INKSCAPE, "version")).is_none());
|
||||
root.attribute("data-name").or(id).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)
|
||||
}
|
||||
|
||||
/// Is element `g` a `<g>` marked as a layer ([`SUBLAYER`])? Only one with an id counts: the id (or
|
||||
/// the label beside it) is its name.
|
||||
fn marked_layer(g: XNode) -> bool {
|
||||
g.tag_name().name() == "g"
|
||||
&& g.attribute("id").is_some_and(|id| !id.is_empty())
|
||||
&& (g.has_attribute(SUBLAYER) || g.attribute((INKSCAPE, "groupmode")) == Some("layer"))
|
||||
}
|
||||
|
||||
/// Turn the groups made of elements marked as layers (`marked`, see [`marked_layer`]) right inside
|
||||
/// layer `l` into its sublayers, in its colour, and theirs in turn. A marked group anywhere else
|
||||
/// (in a group, a mask, a symbol) stays a group: only layers hold layers.
|
||||
fn promote_sublayers(l: &mut Node, marked: &HashSet<NodeId>) {
|
||||
let NodeKind::Layer { color, children, .. } = &mut l.kind else { return };
|
||||
let color = *color;
|
||||
for c in children.iter_mut().filter(|c| marked.contains(&c.id)) {
|
||||
let c = Arc::make_mut(c);
|
||||
let NodeKind::Group { children, clip } = &mut c.kind else { continue };
|
||||
let mut sub = Node::layer(c.id, "", color);
|
||||
sub.set_clips(*clip);
|
||||
if let Some(ch) = sub.children_mut() {
|
||||
*ch = std::mem::take(children);
|
||||
}
|
||||
c.kind = sub.kind;
|
||||
promote_sublayers(c, marked);
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG's initial `font-size` (`medium`) in user units.
|
||||
pub(super) const DEFAULT_FONT_SIZE: f64 = 12.0;
|
||||
|
||||
@@ -214,6 +279,10 @@ struct Importer {
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
|
||||
sublayers: HashSet<String>,
|
||||
/// The groups made of them, made sublayers where they sit in a layer ([`promote_sublayers`]).
|
||||
sublayer_groups: HashSet<NodeId>,
|
||||
/// Points per screen pixel (the root's user unit before its `viewBox`): what a non-scaling
|
||||
/// stroke's width is measured in.
|
||||
screen: f64,
|
||||
@@ -326,6 +395,8 @@ struct Found {
|
||||
non_scaling: HashSet<String>,
|
||||
/// The `data-*` attributes of elements, by id ([`user_data`]).
|
||||
data: HashMap<String, Vec<(String, String)>>,
|
||||
/// Ids of the `<g>` elements marked as layers ([`marked_layer`]).
|
||||
sublayers: HashSet<String>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -396,7 +467,7 @@ impl Edits {
|
||||
fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
let mut found = Found::default();
|
||||
// (`:` for prefixed elements such as `<svg:image>`.)
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-"].iter().any(|t| svg.contains(t)) {
|
||||
if !["<a", "display", "<use", ":use", "<image", ":image", vector_effect::NON_SCALING, "data-", "groupmode"].iter().any(|t| svg.contains(t)) {
|
||||
return (svg.into(), found);
|
||||
}
|
||||
let Ok(xml) = roxmltree::Document::parse_with_options(svg, roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }) else {
|
||||
@@ -417,6 +488,7 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
}
|
||||
}
|
||||
}
|
||||
found.sublayers = elements().filter(|g| marked_layer(*g)).filter_map(|g| g.attribute("id")).map(str::to_string).collect();
|
||||
let symbols: HashSet<&str> = elements().filter(|n| n.tag_name().name() == "symbol").filter_map(|n| n.attribute("id")).collect();
|
||||
for u in elements().filter(|n| n.tag_name().name() == "use") {
|
||||
if let Some(sym) = href(u).and_then(|h| h.strip_prefix('#')).filter(|s| symbols.contains(s)) {
|
||||
@@ -440,19 +512,20 @@ fn prepass<'s>(svg: &'s str, opts: &ImportOptions) -> (Cow<'s, str>, Found) {
|
||||
/// The elements that are objects (what [`hidden_objects`] shows).
|
||||
const OBJECTS: &[&str] = &["g", "a", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon", "image", "text", "use"];
|
||||
|
||||
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids.
|
||||
/// Show the undisplayed objects outside `<defs>` (and the like) for usvg, recording their ids. The
|
||||
/// objects in a `<switch>` count too (some apps wrap all their layers in one).
|
||||
fn hidden_objects(svg: &str, xml: &roxmltree::Document, css: &css::Styles, edits: &mut Edits, ids: &mut HashSet<String>) {
|
||||
let linked: HashSet<&str> = xml.descendants().filter_map(href).filter_map(|h| h.strip_prefix('#')).collect();
|
||||
let mut todo: Vec<XNode> = xml.root_element().children().filter(XNode::is_element).collect();
|
||||
while let Some(n) = todo.pop() {
|
||||
let tag = n.tag_name().name();
|
||||
if !OBJECTS.contains(&tag) || n.attribute("id").is_some_and(|id| linked.contains(id)) {
|
||||
if n.attribute("id").is_some_and(|id| linked.contains(id)) {
|
||||
continue;
|
||||
}
|
||||
if matches!(tag, "g" | "a") {
|
||||
if matches!(tag, "g" | "a" | "switch") {
|
||||
todo.extend(n.children().filter(XNode::is_element));
|
||||
}
|
||||
if css.own(n, "display").as_deref() != Some("none") {
|
||||
if !OBJECTS.contains(&tag) || css.own(n, "display").as_deref() != Some("none") {
|
||||
continue;
|
||||
}
|
||||
ids.insert(edits.id(svg, n));
|
||||
@@ -498,7 +571,6 @@ fn link(n: &mut Node, url: &str) {
|
||||
/// The names apps keep beside element ids, by id: `data-name`, `inkscape:label`, `serif:id` or
|
||||
/// `aria-label` (the first one present).
|
||||
fn labels(xml: &roxmltree::Document) -> HashMap<String, String> {
|
||||
const INKSCAPE: &str = "http://www.inkscape.org/namespaces/inkscape";
|
||||
const SERIF: &str = "http://www.serif.com/";
|
||||
xml.descendants()
|
||||
.filter_map(|n| {
|
||||
@@ -609,6 +681,15 @@ impl Importer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The child of `g` when it's all `g` holds and only wraps art: an id-less group that leaves
|
||||
/// it as it is (but for a transform) and isn't a text.
|
||||
fn wrapper<'g>(&self, g: &'g usvg::Group) -> Option<&'g usvg::Group> {
|
||||
match g.children() {
|
||||
[usvg::Node::Group(w)] if w.id().is_empty() && is_plain(w) && self.text_slot(w).is_none() => Some(w),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn children(&mut self, g: &usvg::Group, acc: Affine) -> Vec<Arc<Node>> {
|
||||
g.children().iter().filter_map(|c| self.node(c, acc)).map(Arc::new).collect()
|
||||
}
|
||||
@@ -853,6 +934,9 @@ impl Importer {
|
||||
n.blend = blend(g.blend_mode());
|
||||
n.isolate = g.isolate();
|
||||
n.mask = mask;
|
||||
if !is_text && self.sublayers.contains(g.id()) {
|
||||
self.sublayer_groups.insert(n.id);
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ use std::str::FromStr;
|
||||
|
||||
use usvg::roxmltree;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{CharStyle, Dash, Justify, LineCap, LineJoin, ParaDirection, StrokeLayer, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{CharStyle, Dash, Justify, LineCap, LineJoin, ParaDirection, ParaStyle, StrokeLayer, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect};
|
||||
use vectorcraft_text::{FontDb, TextLayout};
|
||||
@@ -556,11 +556,12 @@ impl Ctx {
|
||||
.collect();
|
||||
let under = stroke_under(&mut cells, label, warnings);
|
||||
|
||||
let anchor = match self.css.prop(cs.chars[0].1, "text-anchor").as_deref() {
|
||||
let anchor_of = |i: usize| match cs.chars.get(i).and_then(|c| self.css.prop(c.1, "text-anchor")).as_deref() {
|
||||
Some("middle") => 0.5,
|
||||
Some("end") => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let anchor = anchor_of(0);
|
||||
let path = cs.path.and_then(|tp| match self.text_path(xml, tp) {
|
||||
Some(p) => Some((tp, p)),
|
||||
None => {
|
||||
@@ -571,6 +572,7 @@ impl Ctx {
|
||||
let vertical = self.css.prop(t, "writing-mode").is_some_and(|m| m.starts_with("tb") || m.starts_with("vertical"));
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
let mut breaks: Vec<Break> = vec![];
|
||||
let mut para_styles: Vec<ParaStyle> = vec![];
|
||||
if let Some((tp, bp)) = path {
|
||||
// Along the path: dx is extra advance, dy shifts off the path.
|
||||
let mut off = 0.0;
|
||||
@@ -610,18 +612,38 @@ impl Ctx {
|
||||
obj.xf = Affine::IDENTITY;
|
||||
} else {
|
||||
let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]);
|
||||
let (justify, left) = lines(&mut cells, &x, &y, &dx, &dy, anchor, origin.x, &mut breaks);
|
||||
let (justify, left, starts) = lines(&mut cells, &x, &y, &dx, &dy, anchor, origin.x, &mut breaks);
|
||||
obj.para.justify = justify;
|
||||
obj.xf = Affine::translate((finite(left), finite(origin.y)));
|
||||
// Lines anchored differently (paragraphs aligned differently): each line's paragraph
|
||||
// takes its alignment, and indents that put it where it was.
|
||||
if let Some(starts) = starts.filter(|st| st.iter().any(|(i, _)| anchor_of(*i) != anchor)) {
|
||||
for (k, &(i, ax)) in starts.iter().enumerate() {
|
||||
let a = anchor_of(i);
|
||||
let d = finite(ax - left);
|
||||
let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() };
|
||||
match pa.justify {
|
||||
Justify::Center if d >= 0.0 => pa.left_indent = 2.0 * d,
|
||||
Justify::Center => pa.right_indent = -2.0 * d,
|
||||
Justify::Right => pa.right_indent = -d,
|
||||
_ => pa.left_indent = d,
|
||||
}
|
||||
let count = if k == 0 { 1 } else { breaks.get(k - 1).map_or(1, |b| b.count) };
|
||||
para_styles.extend(std::iter::repeat_n(pa, count));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (runs, servers) = assemble(&cells, &breaks).0;
|
||||
obj.runs = runs;
|
||||
if !para_styles.is_empty() {
|
||||
obj.set_paragraph_styles(para_styles);
|
||||
}
|
||||
// SVG text runs left to right unless `direction: rtl` says otherwise, whatever its first
|
||||
// strong character: pinned when that would read as right to left.
|
||||
// strong character: pinned (on every paragraph) when that would read as right to left.
|
||||
if self.css.prop(t, "direction").is_some_and(|d| d.trim() == "rtl") {
|
||||
obj.para.direction = Some(ParaDirection::RightToLeft);
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::RightToLeft));
|
||||
} else if obj.plain_text().split('\n').any(|p| vectorcraft_text::paragraph_is_rtl(p, None)) {
|
||||
obj.para.direction = Some(ParaDirection::LeftToRight);
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::LeftToRight));
|
||||
}
|
||||
// The placeholder covers the text (laid out when a paint server needs its bounding box).
|
||||
let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default();
|
||||
@@ -708,8 +730,18 @@ fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The alignment of an SVG text chunk anchored at `anchor` (0 start, 0.5 middle, 1 end).
|
||||
fn justify_of(anchor: f64) -> Justify {
|
||||
match anchor {
|
||||
a if a >= 1.0 => Justify::Right,
|
||||
a if a > 0.0 => Justify::Center,
|
||||
_ => Justify::Left,
|
||||
}
|
||||
}
|
||||
|
||||
/// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the
|
||||
/// justification and the x of the first line's left (or anchor) edge.
|
||||
/// justification, the x of the first line's left (or anchor) edge and, when no character is
|
||||
/// placed on its own, each line's first character and anchor x.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn lines(
|
||||
cells: &mut [Cell],
|
||||
@@ -720,7 +752,7 @@ fn lines(
|
||||
anchor: f64,
|
||||
x0: f64,
|
||||
breaks: &mut Vec<Break>,
|
||||
) -> (Justify, f64) {
|
||||
) -> (Justify, f64, Option<Vec<(usize, f64)>>) {
|
||||
let n = cells.len();
|
||||
let y0 = y[0].unwrap_or(0.0) + dy[0];
|
||||
let (mut base, mut cur) = (y0, y0);
|
||||
@@ -758,12 +790,7 @@ fn lines(
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
let justify = match anchor {
|
||||
a if a >= 1.0 => Justify::Right,
|
||||
a if a > 0.0 => Justify::Center,
|
||||
_ => Justify::Left,
|
||||
};
|
||||
return (justify, x0);
|
||||
return (justify_of(anchor), x0, Some(lines));
|
||||
}
|
||||
// Absolutely placed characters: lay the text out left-aligned and kern each one onto its x.
|
||||
// SVG anchors every absolutely placed chunk on its own, so with a middle/end anchor each
|
||||
@@ -819,7 +846,7 @@ fn lines(
|
||||
break;
|
||||
}
|
||||
}
|
||||
(Justify::Left, left)
|
||||
(Justify::Left, left, None)
|
||||
}
|
||||
|
||||
/// A left-aligned point text of `runs` at the origin (for measuring).
|
||||
@@ -865,7 +892,7 @@ fn assemble(cells: &[Cell], breaks: &[Break]) -> (Runs, Vec<usize>) {
|
||||
r.text.push(ch);
|
||||
return;
|
||||
}
|
||||
runs.push(TextRun { text: ch.into(), style });
|
||||
runs.push(TextRun { text: ch.into(), style, inline: None });
|
||||
keys.push(key);
|
||||
}
|
||||
let mut out: Runs = (vec![], vec![]);
|
||||
|
||||
@@ -26,7 +26,7 @@ fn style(family: &str, font_style: &str) -> CharStyle {
|
||||
|
||||
fn text(at: Point, runs: &[(&str, CharStyle)]) -> Node {
|
||||
let mut t = TextObject::point(at, "", runs[0].1.clone());
|
||||
t.runs = runs.iter().map(|(s, st)| TextRun { text: (*s).into(), style: st.clone() }).collect();
|
||||
t.runs = runs.iter().map(|(s, st)| TextRun { text: (*s).into(), style: st.clone(), inline: None }).collect();
|
||||
Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(t)))
|
||||
}
|
||||
|
||||
|
||||
@@ -18,12 +18,12 @@ fn doc() -> Document {
|
||||
d.insert(Some(l), usize::MAX, a).unwrap();
|
||||
let st = CharStyle { size: 12.0, font_family: "Source Sans 3".into(), fill: Paint::solid(Color::BLACK), ..CharStyle::default() };
|
||||
let mut t = TextObject::point(Point::new(20.0, 120.0), "", st.clone());
|
||||
t.runs = vec![TextRun { text: "one two\nthree".into(), style: st.clone() }];
|
||||
t.runs = vec![TextRun { text: "one two\nthree".into(), style: st.clone(), inline: None }];
|
||||
let i = d.alloc_id();
|
||||
d.insert(Some(l), usize::MAX, Node::new(i, NodeKind::Text(Box::new(t.clone())))).unwrap();
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 60.0)) };
|
||||
t.xf = Affine::translate((20.0, 140.0));
|
||||
t.runs = vec![TextRun { text: "para one\npara two".into(), style: st }];
|
||||
t.runs = vec![TextRun { text: "para one\npara two".into(), style: st, inline: None }];
|
||||
let i = d.alloc_id();
|
||||
d.insert(Some(l), usize::MAX, Node::new(i, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
d
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Symbols export as one `<symbol>` def and a `<use>` per instance (instances the def can't stand
|
||||
//! for get their own art), hidden layers and objects are kept hidden when asked and come back
|
||||
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, and the
|
||||
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, layers and
|
||||
//! sublayers keep their names and nesting (a one-layer file's from its root element), and the
|
||||
//! editing data notices edits made elsewhere.
|
||||
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
@@ -350,6 +351,192 @@ fn hidden_groups_others_use_stay_hidden() {
|
||||
assert_eq!((paths, hidden), (0, 0), "{:?}", d.layers);
|
||||
}
|
||||
|
||||
/// The layer tree: each object by kind (layers and groups with their names), `(hidden)` when
|
||||
/// hidden, its contents indented below it.
|
||||
fn outline(d: &Document) -> Vec<String> {
|
||||
fn walk(n: &Node, depth: usize, out: &mut Vec<String>) {
|
||||
let name = n.children().map(|_| format!(" {}", n.name.as_deref().unwrap_or("-"))).unwrap_or_default();
|
||||
let hidden = if n.visible { "" } else { " (hidden)" };
|
||||
out.push(format!("{}{}{name}{hidden}", " ".repeat(depth), n.kind_label()));
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, depth + 1, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, 0, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Layers as other apps export them (#372): named top-level groups, one hidden; a hidden named
|
||||
/// group and a hidden object inside a layer.
|
||||
const EXPORTED_LAYERS: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300">
|
||||
<g id="Main">
|
||||
<rect id="plainStroke" x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
|
||||
<rect id="hiddenObject" x="200" y="50" width="60" height="60" style="display:none;fill:#fff;stroke:#000"/>
|
||||
<g id="HiddenSub" style="display:none"><circle cx="45" cy="175" r="25" style="fill:#fff;stroke:#000"/></g>
|
||||
</g>
|
||||
<g id="Second" display="none"><rect x="10" y="10" width="5" height="5"/></g>
|
||||
</svg>"##;
|
||||
|
||||
#[test]
|
||||
fn top_level_groups_become_named_layers() {
|
||||
let expected = ["Layer Main", " Path", " Path (hidden)", " Group HiddenSub (hidden)", " Path", "Layer Second (hidden)", " Path"];
|
||||
let d = import(EXPORTED_LAYERS).unwrap();
|
||||
assert_eq!(outline(&d), expected);
|
||||
// A nested group stays a group: nothing in the file says it's a sublayer.
|
||||
// `data-name` names the layer when the id can't (spaces, punctuation).
|
||||
let named = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g id=\"Main_Art\" data-name=\"Main Art\">");
|
||||
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
|
||||
// Layers wrapped in more groups: a transform on all the art, or a `<switch>` choosing them.
|
||||
let moved = EXPORTED_LAYERS.replace("<g id=\"Main\">", "<g transform=\"translate(5 5)\"><g id=\"Main\">").replace("</svg>", "</g></svg>");
|
||||
let d = import(&moved).unwrap();
|
||||
assert_eq!(outline(&d), expected, "{moved}");
|
||||
let stroke = &d.layers[0].children().unwrap()[0];
|
||||
assert_eq!(stroke.geometric_bounds().unwrap(), Rect::new(25.0, 55.0, 145.0, 115.0));
|
||||
let switched = EXPORTED_LAYERS
|
||||
.replace("<g id=\"Main\">", "<switch><foreignObject requiredExtensions=\"urn:example:none\" width=\"1\" height=\"1\"/><g><g id=\"Main\">")
|
||||
.replace("</svg>", "</g></switch></svg>");
|
||||
assert_eq!(outline(&import(&switched).unwrap()), expected, "{switched}");
|
||||
// Art beside the groups puts everything in one layer, as before.
|
||||
let loose = EXPORTED_LAYERS.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
|
||||
assert_eq!(import(&loose).unwrap().layers.iter().map(|l| l.name.as_deref()).collect::<Vec<_>>(), [Some("Layer 1")]);
|
||||
}
|
||||
|
||||
/// Layer "Base" holding a path, a named group, a clipping sublayer and a hidden sublayer "Notes"
|
||||
/// with a sublayer of its own; layer "Top" above it.
|
||||
fn sublayered() -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let square = |d: &mut Document, x: f64| {
|
||||
let ap = Appearance::basic(Paint::solid(Color::rgb8(200, 30, 30)), Paint::None, 0.0);
|
||||
Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, x, x + 10.0, x + 10.0)), ap))
|
||||
};
|
||||
let layer = |children: Vec<Arc<Node>>, d: &mut Document, name: &str| {
|
||||
let mut l = Node::layer(d.alloc_id(), name, vectorcraft_doc::LayerColor::Preset(3));
|
||||
*l.children_mut().unwrap() = children;
|
||||
l
|
||||
};
|
||||
let deep = layer(vec![square(&mut d, 60.0)], &mut d, "Deep");
|
||||
let mut notes = layer(vec![square(&mut d, 50.0), Arc::new(deep)], &mut d, "Notes");
|
||||
notes.visible = false;
|
||||
let mut clip = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 30.0, 30.0)), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let mut window = layer(vec![Arc::new(clip), square(&mut d, 25.0)], &mut d, "Window");
|
||||
window.set_clips(true);
|
||||
let mut group = Node::group(d.alloc_id(), vec![square(&mut d, 30.0), square(&mut d, 40.0)]);
|
||||
group.name = Some("Pair".into());
|
||||
let art = vec![square(&mut d, 10.0), Arc::new(group), Arc::new(window), Arc::new(notes)];
|
||||
let base = Arc::make_mut(&mut d.layers[0]);
|
||||
base.name = Some("Base".into());
|
||||
*base.children_mut().unwrap() = art;
|
||||
let top = layer(vec![square(&mut d, 80.0)], &mut d, "Top");
|
||||
d.layers.push(Arc::new(top));
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sublayers_round_trip() {
|
||||
let d = sublayered();
|
||||
let expected = [
|
||||
"Layer Base",
|
||||
" Path",
|
||||
" Group Pair",
|
||||
" Path",
|
||||
" Path",
|
||||
" Layer Window",
|
||||
" Path",
|
||||
" Path",
|
||||
" Layer Notes (hidden)",
|
||||
" Path",
|
||||
" Layer Deep",
|
||||
" Path",
|
||||
"Layer Top",
|
||||
" Path",
|
||||
];
|
||||
assert_eq!(outline(&d), expected);
|
||||
let styles = [vectorcraft_svg::Styling::PresentationAttributes, vectorcraft_svg::Styling::InlineStyle, vectorcraft_svg::Styling::InternalCss];
|
||||
for styling in styles {
|
||||
// Saved with the hidden sublayer: the same tree comes back.
|
||||
let kept = export(&d, &ExportOptions { hidden_layers: true, styling, ..Default::default() });
|
||||
assert_eq!(kept.matches("data-vc-layer").count(), 3, "sublayers only: {kept}");
|
||||
let back = import(&kept).unwrap();
|
||||
assert_eq!(outline(&back), expected, "{kept}");
|
||||
// A sublayer takes its layer's colour.
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Layer { color, .. } = &n.kind
|
||||
&& n.name.as_deref() != Some("Top")
|
||||
{
|
||||
assert_eq!(*color, vectorcraft_doc::LayerColor::Preset(0), "{:?}", n.name);
|
||||
}
|
||||
});
|
||||
assert!(back.layers[0].children().unwrap()[2].clips());
|
||||
assert_similar(&render_artboard(&back), &render_artboard(&d), 24.0, 0.002);
|
||||
}
|
||||
// Exported without hidden art, the visible sublayer still comes back as one.
|
||||
let plain = import(&export(&d, &ExportOptions::default())).unwrap();
|
||||
assert_eq!(
|
||||
outline(&plain),
|
||||
["Layer Base", " Path", " Group Pair", " Path", " Path", " Layer Window", " Path", " Path", "Layer Top", " Path"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_element_names_the_one_layer() {
|
||||
// A one-layer document exported with its art loose under the root, which carries the name.
|
||||
let svg = r##"<svg version="1.1" id="Main" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300">
|
||||
<rect x="20" y="50" width="120" height="60" style="fill:none;stroke:#000;stroke-width:4"/>
|
||||
<g id="HiddenSub" style="display:none;"><circle cx="45" cy="175" r="25"/></g>
|
||||
</svg>"##;
|
||||
assert_eq!(outline(&import(svg).unwrap()), ["Layer Main", " Path", " Group HiddenSub (hidden)", " Path"]);
|
||||
// `data-name` when the id can't hold the name.
|
||||
let named = svg.replace("id=\"Main\"", "id=\"Main_Art\" data-name=\"Main Art\"");
|
||||
assert_eq!(import(&named).unwrap().layers[0].name.as_deref(), Some("Main Art"));
|
||||
let names = |svg: &str| import(svg).unwrap().layers.iter().map(|l| l.name.clone().unwrap()).collect::<Vec<_>>();
|
||||
// Not when the groups at the top are the layers.
|
||||
assert_eq!(names(&svg.replace("<rect", "<g id=\"Art\"><rect").replace("stroke-width:4\"/>", "stroke-width:4\"/></g>")), ["Art", "HiddenSub"]);
|
||||
// Nor from the id Inkscape gives its root.
|
||||
let inkscape = svg.replace("id=\"Main\"", "id=\"svg8\" xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\" inkscape:version=\"1.3\"");
|
||||
assert_eq!(names(&inkscape), ["Layer 1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_groups_are_sublayers_only_in_layers() {
|
||||
// Inkscape marks its layers and sublayers; one marked group in a plain group stays a group.
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="100" height="100">
|
||||
<g id="layer1" inkscape:groupmode="layer" inkscape:label="Base">
|
||||
<rect x="1" y="1" width="5" height="5"/>
|
||||
<g id="layer2" inkscape:groupmode="layer" inkscape:label="Sub" style="display:none">
|
||||
<rect x="10" y="10" width="5" height="5"/>
|
||||
<g id="layer3" inkscape:groupmode="layer" inkscape:label="Deeper"><rect x="20" y="10" width="5" height="5"/></g>
|
||||
</g>
|
||||
<g id="g1"><rect x="30" y="1" width="5" height="5"/><g id="layer4" data-vc-layer="sublayer"><rect x="40" y="1" width="5" height="5"/></g></g>
|
||||
</g>
|
||||
</svg>"##;
|
||||
let d = import(svg).unwrap();
|
||||
assert_eq!(
|
||||
outline(&d),
|
||||
[
|
||||
"Layer Base",
|
||||
" Path",
|
||||
" Layer Sub (hidden)",
|
||||
" Path",
|
||||
" Layer Deeper",
|
||||
" Path",
|
||||
" Group g1",
|
||||
" Path",
|
||||
" Group layer4",
|
||||
" Path",
|
||||
]
|
||||
);
|
||||
// Art outside layers ("Layer 1" holds it): a marked group there is a sublayer of it.
|
||||
let loose = svg.replace("</svg>", "<rect x=\"1\" y=\"1\" width=\"2\" height=\"2\"/></svg>");
|
||||
let d = import(&loose).unwrap();
|
||||
assert_eq!(outline(&d)[..4], ["Layer Layer 1", " Layer Base", " Path", " Layer Sub (hidden)"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_data_notices_edits_made_elsewhere() {
|
||||
let d = symbol_doc(2.0, &[Affine::translate((50.0, 50.0))]);
|
||||
|
||||
@@ -30,7 +30,7 @@ fn area_doc(runs: Vec<TextRun>, w: f64, justify: Justify) -> Document {
|
||||
}
|
||||
|
||||
fn run(text: &str, st: CharStyle) -> TextRun {
|
||||
TextRun { text: text.into(), style: st }
|
||||
TextRun { text: text.into(), style: st, inline: None }
|
||||
}
|
||||
|
||||
/// The `<tspan …>` start tags.
|
||||
@@ -200,3 +200,37 @@ fn a_viewer_draws_the_text_where_the_canvas_does() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraphs_aligned_differently_keep_their_alignment() {
|
||||
let mut t = TextObject::point(Point::new(20.0, 20.0), "Left words here\nCentred line\nRight line", style(14.0));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 160.0)) };
|
||||
let para = |j| vectorcraft_doc::ParaStyle { justify: j, ..Default::default() };
|
||||
t.set_paragraph_styles(vec![para(Justify::Left), para(Justify::Center), para(Justify::Right)]);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
for fewer_tspans in [false, true] {
|
||||
let svg = export(&d, &ExportOptions { fewer_tspans, ..Default::default() });
|
||||
// Each anchored line carries its own anchor (the <text> has none).
|
||||
assert!(svg.contains("text-anchor=\"middle\"") && svg.contains("text-anchor=\"end\""), "{svg}");
|
||||
assert!(!svg.contains("<text text-anchor"), "{svg}");
|
||||
// A viewer draws each line where the canvas does.
|
||||
let mut viewer = Document::new(300.0, 200.0);
|
||||
let vl = viewer.layers[0].id;
|
||||
for bp in viewer_outlines(&svg) {
|
||||
let ap = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
|
||||
let n = Node::path(viewer.alloc_id(), PathData::from_bezpath(&bp), ap);
|
||||
viewer.insert(Some(vl), usize::MAX, n).unwrap();
|
||||
}
|
||||
assert_similar(&render_artboard(&d), &render_artboard(&viewer), 40.0, 0.01);
|
||||
// Read back: one paragraph per line, each with its alignment, drawn where it was.
|
||||
let back = vectorcraft_svg::import(&svg).unwrap();
|
||||
let text =
|
||||
back.layers[0].children().unwrap().iter().find_map(|n| if let NodeKind::Text(t) = &n.kind { Some(t.clone()) } else { None }).unwrap();
|
||||
let js: Vec<Justify> = text.paragraph_styles().iter().map(|p| p.justify).collect();
|
||||
assert_eq!(js, [Justify::Left, Justify::Center, Justify::Right], "{svg}");
|
||||
assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.01);
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,7 @@ fn character_stroke_options_round_trip_through_live_text() {
|
||||
#[test]
|
||||
fn a_run_without_the_first_runs_stroke_resets_it() {
|
||||
let mut t = TextObject::point(Point::new(20.0, 100.0), "Ab", stroked());
|
||||
t.runs.push(TextRun { text: "cd".into(), style: CharStyle { size: 40.0, ..Default::default() } });
|
||||
t.runs.push(TextRun { text: "cd".into(), style: CharStyle { size: 40.0, ..Default::default() }, inline: None });
|
||||
let svg = export(&text_doc(t, vec![]), &ExportOptions::default());
|
||||
let second = svg.split("<tspan").nth(2).expect("a tspan per run");
|
||||
assert!(
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Hand-written swatch exchange (`.ase`) files for swatch library tests: version 1.0, big-endian,
|
||||
//! with colors in each model and color type, and color groups.
|
||||
|
||||
/// One block of a swatch exchange file.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Block<'a> {
|
||||
/// A color group starts (its name).
|
||||
GroupStart(&'a str),
|
||||
/// The open color group ends.
|
||||
GroupEnd,
|
||||
/// A color: its name, model (`b"RGB "`, `b"CMYK"`, `b"LAB "` or `b"Gray"`), components and
|
||||
/// color type (0 global, 1 spot, 2 process).
|
||||
Color(&'a str, &'a [u8; 4], &'a [f32], u16),
|
||||
}
|
||||
|
||||
/// A name: a `u16` count of UTF-16 code units, the terminating zero included, then the units.
|
||||
fn name(out: &mut Vec<u8>, name: &str) {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
out.extend(u16::try_from(units.len()).unwrap().to_be_bytes());
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks`.
|
||||
pub fn ase(blocks: &[Block]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend(u32::try_from(blocks.len()).unwrap().to_be_bytes());
|
||||
for b in blocks {
|
||||
let mut body = vec![];
|
||||
let kind: u16 = match b {
|
||||
Block::GroupStart(n) => {
|
||||
name(&mut body, n);
|
||||
0xC001
|
||||
}
|
||||
Block::GroupEnd => 0xC002,
|
||||
Block::Color(n, model, values, kind) => {
|
||||
name(&mut body, n);
|
||||
body.extend(*model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
0x0001
|
||||
}
|
||||
};
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend(u32::try_from(body.len()).unwrap().to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A library of four colors: "Sky" (global RGB) and "Ink" (spot CMYK), then the group "Neutrals"
|
||||
/// of the process colors "Mist" (Gray, 25% ink) and "Clay" (Lab 50, 20, −30).
|
||||
pub fn sample() -> Vec<u8> {
|
||||
ase(&[
|
||||
Block::Color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
Block::Color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
Block::GroupStart("Neutrals"),
|
||||
Block::Color("Mist", b"Gray", &[0.75], 2),
|
||||
Block::Color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
Block::GroupEnd,
|
||||
])
|
||||
}
|
||||
@@ -123,6 +123,21 @@ pub fn rich_session() -> Session {
|
||||
));
|
||||
select(&mut s, &[area]);
|
||||
exec(&mut s, "text.areaOptions", json!({"verticalAlign": "center", "inset": 2}));
|
||||
let _ = id_of(&exec(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"x": 300, "y": 330, "size": 14, "text": "Area type shrinks its text to fit the frame.",
|
||||
"area": {"width": 150, "height": 40, "fit": "shrinkText", "fitMinPercent": 40}}),
|
||||
));
|
||||
// Area type whose paragraphs differ (alignment, spacing, tabs).
|
||||
let para = id_of(&exec(
|
||||
&mut s,
|
||||
"text.create",
|
||||
json!({"x": 20, "y": 360, "text": "Heading\nBody one\tx\nBody two", "size": 9, "area": {"width": 160, "height": 36}}),
|
||||
));
|
||||
exec(&mut s, "text.setStyle", json!({"id": para, "justify": "center", "start": 0, "end": 0}));
|
||||
exec(&mut s, "text.setFormat", json!({"ids": [para], "spaceBefore": 3, "firstLineIndent": 6, "start": 9, "end": 9}));
|
||||
exec(&mut s, "text.tabs.set", json!({"ids": [para], "stops": [{"position": 80, "align": "right"}], "start": 9, "end": 9}));
|
||||
exec(&mut s, "layer.new", json!({"name": "Top"}));
|
||||
let d = rect(&mut s, 350.0, 200.0, 80.0, 80.0);
|
||||
let e = ellipse(&mut s, 380.0, 230.0, 80.0, 80.0);
|
||||
@@ -133,6 +148,12 @@ pub fn rich_session() -> Session {
|
||||
exec(&mut s, "paint.setFill", json!({"color": "#22aa44"}));
|
||||
select(&mut s, &[inner, clip]);
|
||||
exec(&mut s, "object.clippingMask.make", json!({}));
|
||||
// Type with an inline graphic: a symbol (a small circle, drawn here) set in a line of text.
|
||||
let dot = ellipse(&mut s, 440.0, 40.0, 12.0, 12.0);
|
||||
select(&mut s, &[dot]);
|
||||
exec(&mut s, "symbol.new", json!({"name": "Dot"}));
|
||||
let t = id_of(&exec(&mut s, "text.create", json!({"x": 250, "y": 370, "text": "Tap to add", "size": 18})));
|
||||
exec(&mut s, "text.insertInline", json!({"id": t.0, "at": 4, "symbol": "Dot"}));
|
||||
let _ = (a, b, c, l);
|
||||
exec(&mut s, "select.none", json!({}));
|
||||
s
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//! - [`raster`]: rendering helpers and image comparison with a perceptual tolerance.
|
||||
//! - [`geom`]: geometry assertions (approximate equality, curve sampling, Hausdorff distance).
|
||||
//! - [`pdf`]: hand-written PDF files (page boxes, colour spaces, encryption) for import tests.
|
||||
//! - [`ase`]: hand-written swatch exchange (`.ase`) files for swatch library tests.
|
||||
//!
|
||||
//! This crate may only be used as a dev-dependency (enforced by `cargo xtask layers`).
|
||||
// Test support only (a dev-dependency of every crate that uses it): a failed setup or assertion
|
||||
@@ -18,6 +19,7 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ase;
|
||||
pub mod fixtures;
|
||||
pub mod geom;
|
||||
pub mod invariants;
|
||||
|
||||
+25
-7
@@ -4,8 +4,15 @@
|
||||
|
||||
use std::ops::Range;
|
||||
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{CharStyle, TextRun};
|
||||
|
||||
/// Is `s` exactly one object replacement character (an inline graphic run's text)?
|
||||
pub fn is_inline_text(s: &str) -> bool {
|
||||
let mut c = s.chars();
|
||||
c.next() == Some(INLINE_CHAR) && c.next().is_none()
|
||||
}
|
||||
|
||||
/// Total byte length of `runs`.
|
||||
pub fn runs_len(runs: &[TextRun]) -> usize {
|
||||
runs.iter().map(|r| r.text.len()).sum()
|
||||
@@ -58,21 +65,25 @@ pub fn insertion_style(runs: &[TextRun], start: usize, end: usize) -> CharStyle
|
||||
}
|
||||
|
||||
/// Merge adjacent runs with equal styles and drop empty runs (keeping one run so the object
|
||||
/// remembers its style).
|
||||
/// remembers its style). Inline graphic runs never merge: each stays one [`INLINE_CHAR`]; one
|
||||
/// whose text is anything else (malformed input) becomes plain text.
|
||||
pub fn normalize(runs: &mut Vec<TextRun>) {
|
||||
let first_style = runs.first().map(|r| r.style.clone());
|
||||
let mut out: Vec<TextRun> = Vec::with_capacity(runs.len());
|
||||
for r in runs.drain(..) {
|
||||
for mut r in runs.drain(..) {
|
||||
if r.text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if r.inline.is_some() && !is_inline_text(&r.text) {
|
||||
r.inline = None;
|
||||
}
|
||||
match out.last_mut() {
|
||||
Some(l) if l.style == r.style => l.text.push_str(&r.text),
|
||||
Some(l) if l.style == r.style && l.inline.is_none() && r.inline.is_none() => l.text.push_str(&r.text),
|
||||
_ => out.push(r),
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(TextRun { text: String::new(), style: first_style.unwrap_or_default() });
|
||||
out.push(TextRun { text: String::new(), style: first_style.unwrap_or_default(), inline: None });
|
||||
}
|
||||
*runs = out;
|
||||
}
|
||||
@@ -90,7 +101,10 @@ fn split_at(runs: &mut Vec<TextRun>, byte: usize) -> usize {
|
||||
let at = floor_char(&runs[i].text, byte - off);
|
||||
let tail = runs[i].text.split_off(at);
|
||||
let style = runs[i].style.clone();
|
||||
runs.insert(i + 1, TextRun { text: tail, style });
|
||||
// An inline graphic is one character: a split lands before it (`at` == 0), the empty
|
||||
// head is dropped by `normalize` and the tail keeps the graphic.
|
||||
let inline = runs[i].inline.clone();
|
||||
runs.insert(i + 1, TextRun { text: tail, style, inline });
|
||||
return i + 1;
|
||||
}
|
||||
off += len;
|
||||
@@ -103,7 +117,7 @@ fn split_at(runs: &mut Vec<TextRun>, byte: usize) -> usize {
|
||||
/// insertion.
|
||||
pub fn replace_range(runs: &mut Vec<TextRun>, start: usize, end: usize, insert: &str) -> usize {
|
||||
let style = insertion_style(runs, start, end);
|
||||
replace_range_styled(runs, start, end, &[TextRun { text: insert.to_string(), style }])
|
||||
replace_range_styled(runs, start, end, &[TextRun { text: insert.to_string(), style, inline: None }])
|
||||
}
|
||||
|
||||
/// Replace `start..end` with styled runs (paste with formatting). Returns the caret after them.
|
||||
@@ -153,7 +167,11 @@ pub fn slice_runs(runs: &[TextRun], start: usize, end: usize) -> Vec<TextRun> {
|
||||
let (a, b) = (start.max(rs), end.min(re));
|
||||
if a < b {
|
||||
let t = &r.text[floor_char(&r.text, a - rs)..floor_char(&r.text, b - rs)];
|
||||
out.push(TextRun { text: t.to_string(), style: r.style.clone() });
|
||||
if t.is_empty() {
|
||||
off = re;
|
||||
continue;
|
||||
}
|
||||
out.push(TextRun { text: t.to_string(), style: r.style.clone(), inline: r.inline.clone() });
|
||||
}
|
||||
off = re;
|
||||
}
|
||||
|
||||
@@ -79,6 +79,19 @@ pub struct FontFace {
|
||||
pub(crate) instance: Option<harfrust::ShaperInstance>,
|
||||
/// [`Self::ideographic_centre`], read once: layout asks for it per glyph.
|
||||
ideographic_centre: std::sync::OnceLock<f64>,
|
||||
/// [`Self::icf_margins`], read once.
|
||||
icf_margins: std::sync::OnceLock<IcfMargins>,
|
||||
}
|
||||
|
||||
/// Where the ideographic character face (ICF) lies inside the ideographic em box: its distance
|
||||
/// from each edge of the em box, in ems. `top` and `bottom` along a horizontal line, `right` and
|
||||
/// `left` across a vertical one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct IcfMargins {
|
||||
pub top: f64,
|
||||
pub bottom: f64,
|
||||
pub right: f64,
|
||||
pub left: f64,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for FontFace {
|
||||
@@ -177,6 +190,69 @@ impl FontFace {
|
||||
gid.and_then(|g| self.vertical_glyph(g)).map_or(0.38, |(advance, origin)| (origin - advance * 0.5) / self.upem)
|
||||
})
|
||||
}
|
||||
/// The ideographic character face as margins inside the em box ([`IcfMargins`]): from the
|
||||
/// font's BASE table as the OpenType baseline tags define it (`icfb`, `icft` against `ideo`,
|
||||
/// `idtp`), else, as that definition allows, from the bounds of some ideographs and kana
|
||||
/// averaged, else none (the ICF is the em box).
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/baselinetags>
|
||||
pub fn icf_margins(&self) -> IcfMargins {
|
||||
*self.icf_margins.get_or_init(|| self.icf_from_base().or_else(|| self.icf_from_glyphs()).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// [`Self::icf_margins`] from the BASE table: the ICF's bottom edge `icfb` (top edge `icft`, else
|
||||
/// as far below the em box top) against the em box `ideo` .. `idtp` (else the OS/2 typographic
|
||||
/// descender, and one em above it); across vertical lines, `icfb` and `icft` of the vertical
|
||||
/// axis against 0 .. `idtp` (else the horizontal margin, and one em).
|
||||
pub(crate) fn icf_from_base(&self) -> Option<IcfMargins> {
|
||||
use skrifa::raw::TableProvider;
|
||||
let f = self.skrifa()?;
|
||||
let base = f.base().ok()?;
|
||||
let em = self.upem;
|
||||
let h = base_values(base.horiz_axis()?.ok()?)?;
|
||||
let icfb = *h.get(b"icfb")?;
|
||||
let em_bottom = match h.get(b"ideo") {
|
||||
Some(v) => *v,
|
||||
None => f64::from(f.os2().ok()?.s_typo_descender()),
|
||||
};
|
||||
let em_top = h.get(b"idtp").copied().unwrap_or(em_bottom + em);
|
||||
let margin = icfb - em_bottom;
|
||||
let icf_top = h.get(b"icft").copied().unwrap_or(em_top - margin);
|
||||
let v = base.vert_axis().and_then(Result::ok).and_then(base_values).unwrap_or_default();
|
||||
let icf_left = v.get(b"icfb").copied().unwrap_or(margin);
|
||||
let em_right = v.get(b"idtp").copied().unwrap_or(em);
|
||||
let icf_right = v.get(b"icft").copied().unwrap_or(em_right - icf_left);
|
||||
let m = IcfMargins { top: (em_top - icf_top) / em, bottom: margin / em, right: (em_right - icf_right) / em, left: icf_left / em };
|
||||
// Inside the em box, short of its middle: anything else is a damaged table.
|
||||
[m.top, m.bottom, m.right, m.left].iter().all(|x| (0.0..0.5).contains(x)).then_some(m)
|
||||
}
|
||||
|
||||
/// [`Self::icf_margins`] from the ink of some ideographs and kana: each edge's margin to the em
|
||||
/// box (its centre [`Self::ideographic_centre`], one em high and wide), averaged.
|
||||
pub(crate) fn icf_from_glyphs(&self) -> Option<IcfMargins> {
|
||||
let f = self.skrifa()?;
|
||||
let metrics = f.glyph_metrics(Size::unscaled(), self.location());
|
||||
let em = self.upem;
|
||||
let (em_bottom, em_top) = ((self.ideographic_centre() - 0.5) * em, (self.ideographic_centre() + 0.5) * em);
|
||||
let boxes: Vec<_> = ['国', '東', '永', '書', 'あ', 'ア']
|
||||
.into_iter()
|
||||
.map(|c| self.glyph_for(c))
|
||||
.filter(|g| *g != 0)
|
||||
.filter_map(|g| metrics.bounds(GlyphId::new(g)))
|
||||
.collect();
|
||||
if boxes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let n = boxes.len() as f64;
|
||||
let mean = |v: &dyn Fn(&skrifa::metrics::BoundingBox) -> f32| boxes.iter().map(|b| f64::from(v(b))).sum::<f64>() / n;
|
||||
let m = IcfMargins {
|
||||
top: (em_top - mean(&|b| b.y_max)) / em,
|
||||
bottom: (mean(&|b| b.y_min) - em_bottom) / em,
|
||||
right: (em - mean(&|b| b.x_max)) / em,
|
||||
left: mean(&|b| b.x_min) / em,
|
||||
};
|
||||
[m.top, m.bottom, m.right, m.left].iter().all(|x| (0.0..0.5).contains(x)).then_some(m)
|
||||
}
|
||||
|
||||
/// Glyph id for `c` (0 = .notdef).
|
||||
pub fn glyph_for(&self, c: char) -> u32 {
|
||||
self.skrifa().and_then(|f| f.charmap().map(c)).map(|g| g.to_u32()).unwrap_or(0)
|
||||
@@ -926,9 +1002,28 @@ fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Option<std::pa
|
||||
index,
|
||||
path,
|
||||
ideographic_centre: std::sync::OnceLock::new(),
|
||||
icf_margins: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// An axis of a BASE table: its default baseline values for Han ideographs (`hani`), else kana
|
||||
/// (`kana`), else its first script, by tag, in font units.
|
||||
fn base_values(axis: skrifa::raw::tables::base::Axis<'_>) -> Option<HashMap<[u8; 4], f64>> {
|
||||
let tags = axis.base_tag_list()?.ok()?;
|
||||
let list = axis.base_script_list().ok()?;
|
||||
let records = list.base_script_records();
|
||||
let record =
|
||||
[b"hani", b"kana"].into_iter().find_map(|t| records.iter().find(|r| r.base_script_tag() == Tag::new(t))).or_else(|| records.first())?;
|
||||
let values = record.base_script(list.offset_data()).ok()?.base_values()?.ok()?;
|
||||
let mut out = HashMap::new();
|
||||
for (tag, coord) in tags.baseline_tags().iter().zip(values.base_coords().iter()) {
|
||||
if let Ok(c) = coord {
|
||||
out.insert(tag.get().to_be_bytes(), f64::from(c.coordinate()));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `s` lowercased, without anything but letters and digits.
|
||||
fn norm_chars(s: &str) -> impl Iterator<Item = char> + '_ {
|
||||
s.chars().filter(|c| c.is_alphanumeric()).flat_map(char::to_lowercase)
|
||||
|
||||
+134
-23
@@ -5,7 +5,7 @@ use std::ops::Range;
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Vec2};
|
||||
use unicode_bidi::{BidiInfo, Level};
|
||||
use vectorcraft_doc::{
|
||||
Burasagari, CharStyle, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject,
|
||||
Burasagari, CharStyle, InlineArt, Justify, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject,
|
||||
};
|
||||
use vectorcraft_geom::{ArcPath, PathData};
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::composer::{Breakpoint, Params, compose};
|
||||
use crate::fontdb::FontDb;
|
||||
use crate::hyphen::hyphen_points;
|
||||
use crate::shape::{Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, no_line_end, no_line_start, punct, shape_range, style_metrics};
|
||||
use crate::{Composer, FirstBaseline, LayoutOptions, LineInfo, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign};
|
||||
use crate::{Composer, FirstBaseline, InlineGlyph, LayoutOptions, LineInfo, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign};
|
||||
|
||||
const EPS: f64 = 1e-6;
|
||||
|
||||
@@ -22,6 +22,8 @@ struct Ctx<'a> {
|
||||
db: &'a FontDb,
|
||||
text: &'a str,
|
||||
runs: Vec<(Range<usize>, &'a CharStyle)>,
|
||||
/// The inline graphic of each run that is one (parallel to `runs`).
|
||||
inlines: Vec<Option<&'a InlineArt>>,
|
||||
default: CharStyle,
|
||||
opts: &'a LayoutOptions,
|
||||
/// Vertical type: lines are laid out as horizontal lines in line space, upright glyphs turned
|
||||
@@ -41,7 +43,7 @@ impl Ctx<'_> {
|
||||
fn shape_para(&self, r: Range<usize>, bidi: Option<&BidiInfo<'_>>) -> Vec<SGlyph> {
|
||||
let mut v = Vec::with_capacity(r.len());
|
||||
let levels = bidi.map_or(&[][..], |b| &b.levels);
|
||||
shape_range(self.db, self.text, r, &self.runs, &self.opts.features, levels, &mut v);
|
||||
shape_range(self.db, self.text, r, &self.runs, &self.inlines, &self.opts.features, levels, &mut v);
|
||||
if self.vertical {
|
||||
tate_chu_yoko(&mut v, |g| self.style_at(g.byte).size);
|
||||
// An upright glyph advances down the column by its vertical advance (the font's vertical
|
||||
@@ -57,13 +59,18 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
fn emit(&mut self, g: &SGlyph, pre: Affine, origin: Point, angle: f64, advance: f64, line: usize) {
|
||||
let src = self.db.outline(&g.face, g.gid);
|
||||
let src = if g.inline.is_some() { std::sync::Arc::new(BezPath::new()) } else { self.db.outline(&g.face, g.gid) };
|
||||
// A glyph whose leading space was taken off (mojikumi) is drawn that much earlier: an
|
||||
// upright one in vertical type by moving it up the column once it stands upright.
|
||||
let upright = self.vertical && !self.on_path && g.tcy.is_none() && stands_upright(g);
|
||||
let lead = if upright { 0.0 } else { g.lead };
|
||||
let local =
|
||||
Affine::rotate(-g.rotation.to_radians()) * Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy);
|
||||
let local = match &g.inline {
|
||||
// Inline graphics: art space to glyph space (no font outline).
|
||||
Some(ib) => Affine::translate((-lead, -g.bshift)) * ib.xf,
|
||||
None => {
|
||||
Affine::rotate(-g.rotation.to_radians()) * Affine::translate((g.dx - lead, g.dy - g.bshift)) * Affine::scale_non_uniform(g.sx, g.sy)
|
||||
}
|
||||
};
|
||||
let mut m = pre * local;
|
||||
if self.vertical && self.on_path {
|
||||
// Vertical path type keeps the baseline path and turns each glyph across it.
|
||||
@@ -99,6 +106,9 @@ impl Ctx<'_> {
|
||||
p
|
||||
};
|
||||
let font_id = g.face.id();
|
||||
if let Some(art) = g.inline.as_ref().and_then(|ib| ib.art) {
|
||||
self.out.inlines.push(InlineGlyph { run: g.run, byte: g.byte, glyph: self.out.glyphs.len(), xf: m, bounds: m.transform_rect_bbox(art) });
|
||||
}
|
||||
self.out.glyphs.push(PositionedGlyph {
|
||||
outline,
|
||||
run: g.run,
|
||||
@@ -128,19 +138,96 @@ pub fn layout(db: &FontDb, t: &TextObject) -> TextLayout {
|
||||
first_baseline: a.first_baseline,
|
||||
first_baseline_min: a.first_baseline_min,
|
||||
vertical_align: a.vertical_align,
|
||||
fit: a.fit,
|
||||
..LayoutOptions::default()
|
||||
};
|
||||
layout_with(db, t, &opts)
|
||||
}
|
||||
|
||||
/// Most layout passes Shrink Text to Fit runs past the first (bisection plus the final pass).
|
||||
const SHRINK_PASSES: usize = 11;
|
||||
|
||||
/// Lay out a text object with explicit options (area type rows/columns, inset, first baseline,
|
||||
/// composer, OpenType features).
|
||||
/// fit, composer, OpenType features).
|
||||
pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout {
|
||||
let first = layout_once(db, t, opts);
|
||||
match (opts.fit.min_scale(), &t.kind) {
|
||||
(Some(min), TextKind::Area { .. }) if first.overflow => shrink_to_fit(db, t, opts, min).unwrap_or(first),
|
||||
_ => first,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shrink Text to Fit for text that overflows at full size: the largest scale in `min..1` at which
|
||||
/// it fits, searched by bisection over the first run's size in steps of 0.1 pt (so its scaled size
|
||||
/// is a whole number of tenths of a point, the same every time). Down at `min` it lays out there,
|
||||
/// still overflowing. None (keep the full-size layout) when the text has no usable size.
|
||||
fn shrink_to_fit(db: &FontDb, t: &TextObject, opts: &LayoutOptions, min: f64) -> Option<TextLayout> {
|
||||
let size = t.runs.first().map(|r| r.style.size).filter(|s| s.is_finite() && *s >= 0.1)?;
|
||||
if !(min.is_finite() && min < 1.0) {
|
||||
return None;
|
||||
}
|
||||
let tenths = size * 10.0;
|
||||
// Candidate sizes k/10 pt for k in lo..hi: `hi` (full size, rounded down) is known to overflow
|
||||
// unless it is below the full size; `lo` is the smallest allowed.
|
||||
let mut lo = (tenths * min).ceil().max(1.0);
|
||||
let mut hi = tenths.floor();
|
||||
if hi < lo {
|
||||
hi = lo;
|
||||
}
|
||||
let at = |k: f64| -> TextLayout {
|
||||
let f = (k / tenths).clamp(min, 1.0);
|
||||
let mut l = layout_once(db, &scaled(t, f), opts);
|
||||
l.fit_scale = f;
|
||||
l
|
||||
};
|
||||
let mut passes = 0;
|
||||
let mut best: Option<TextLayout> = None;
|
||||
// `hi` itself may fit when the size isn't a whole number of tenths.
|
||||
if hi < tenths && hi > lo {
|
||||
let l = at(hi);
|
||||
passes += 1;
|
||||
if !l.overflow {
|
||||
return Some(l);
|
||||
}
|
||||
}
|
||||
// Invariant: everything at `hi` or above overflows; `lo` fits or is the floor.
|
||||
while hi - lo > 1.0 && passes + 1 < SHRINK_PASSES {
|
||||
let mid = ((lo + hi) * 0.5).floor();
|
||||
let l = at(mid);
|
||||
passes += 1;
|
||||
if l.overflow {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
best = Some(l);
|
||||
}
|
||||
}
|
||||
// `best` is the layout at `lo` once `lo` has moved; at the floor it still needs laying out.
|
||||
Some(best.unwrap_or_else(|| at(lo)))
|
||||
}
|
||||
|
||||
/// `t` with every run's size, explicit leading and baseline shift scaled by `f` (auto leading
|
||||
/// follows the size; paragraph spacing stays).
|
||||
fn scaled(t: &TextObject, f: f64) -> TextObject {
|
||||
let mut s = t.clone();
|
||||
for r in &mut s.runs {
|
||||
r.style.size *= f;
|
||||
r.style.leading = r.style.leading.map(|l| l * f);
|
||||
r.style.baseline_shift *= f;
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// One layout pass, without fitting.
|
||||
fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout {
|
||||
let text = t.plain_text();
|
||||
let mut runs = Vec::with_capacity(t.runs.len());
|
||||
let mut inlines = Vec::with_capacity(t.runs.len());
|
||||
let mut off = 0;
|
||||
for r in &t.runs {
|
||||
runs.push((off..off + r.text.len(), &r.style));
|
||||
// Only a well-formed inline run (one object replacement character) is a graphic.
|
||||
inlines.push(r.inline.as_ref().filter(|_| crate::edit::is_inline_text(&r.text)));
|
||||
off += r.text.len();
|
||||
}
|
||||
let mut paras = Vec::new();
|
||||
@@ -161,7 +248,8 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
|
||||
} else {
|
||||
opts
|
||||
};
|
||||
let mut cx = Ctx { on_path: is_on_path, db, text: &text, runs, default: CharStyle::default(), opts, vertical, out: TextLayout::default() };
|
||||
let mut cx =
|
||||
Ctx { on_path: is_on_path, db, text: &text, runs, inlines, default: CharStyle::default(), opts, vertical, out: TextLayout::default() };
|
||||
// Vertical type: line space turned a quarter turn clockwise (lines become columns, each next
|
||||
// one to the left). Point type's anchor is on the first column's centre line. Vertical path
|
||||
// type stays on its path (each glyph turned across it in `emit`).
|
||||
@@ -176,7 +264,7 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
|
||||
_ => QUARTER_TURN,
|
||||
};
|
||||
match &t.kind {
|
||||
TextKind::Point => flow(&mut cx, ¶s, &t.para, None),
|
||||
TextKind::Point => flow(&mut cx, ¶s, t, None),
|
||||
TextKind::Area { frame } => {
|
||||
let to_lines = line_xf.inverse();
|
||||
let wrap: Vec<vectorcraft_doc::WrapShape> = if vertical {
|
||||
@@ -186,9 +274,9 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
|
||||
};
|
||||
let mut regions = Region::cells(&(to_lines * frame.to_bezpath()), opts, &wrap);
|
||||
cx.out.frames = regions.iter().map(|r| line_xf.transform_rect_bbox(r.cell)).collect();
|
||||
flow(&mut cx, ¶s, &t.para, Some(®ions));
|
||||
flow(&mut cx, ¶s, t, Some(®ions));
|
||||
if opts.vertical_align != VerticalAlign::Top {
|
||||
align_vertically(&mut cx, ¶s, &t.para, &mut regions);
|
||||
align_vertically(&mut cx, ¶s, t, &mut regions);
|
||||
}
|
||||
}
|
||||
TextKind::OnPath { path, .. } => on_path(&mut cx, ¶s, t, path),
|
||||
@@ -201,6 +289,10 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
|
||||
g.origin = line_xf * g.origin;
|
||||
g.angle += std::f64::consts::FRAC_PI_2;
|
||||
}
|
||||
for i in &mut cx.out.inlines {
|
||||
i.xf = line_xf * i.xf;
|
||||
i.bounds = line_xf.transform_rect_bbox(i.bounds);
|
||||
}
|
||||
cx.out.vertical = true;
|
||||
cx.out.line_xf = line_xf;
|
||||
}
|
||||
@@ -338,15 +430,23 @@ fn glyph_em(g: &SGlyph) -> f64 {
|
||||
|
||||
/// How far up (line space) Character Alignment `a` moves glyph `g` on a line whose largest em is
|
||||
/// `line_em`: the glyph's em box top, centre or bottom onto the line's (the em box running from
|
||||
/// its centre less half an em to its centre plus half an em above the baseline). Nothing on the
|
||||
/// Roman baseline, or for the line's largest characters.
|
||||
fn align_shift(g: &SGlyph, a: vectorcraft_doc::CharAlign, line_em: f64) -> f64 {
|
||||
/// its centre less half an em to its centre plus half an em above the baseline), or its ICF's top
|
||||
/// or bottom (the em box's less the face's [`crate::IcfMargins`]; across a vertical line, its
|
||||
/// right and left). Nothing on the Roman baseline, or for the line's largest characters.
|
||||
///
|
||||
/// An inline graphic has its run's em (whatever its scale): it counts as one of the line's
|
||||
/// largest characters only when its run's size is, and moves with the text of its run (its art
|
||||
/// stays centred on that text's cap height).
|
||||
fn align_shift(g: &SGlyph, a: vectorcraft_doc::CharAlign, line_em: f64, vertical: bool) -> f64 {
|
||||
use vectorcraft_doc::CharAlign;
|
||||
let icf = || g.face.icf_margins();
|
||||
let k = match a {
|
||||
CharAlign::RomanBaseline => return 0.0,
|
||||
CharAlign::EmBoxTop => 0.5,
|
||||
CharAlign::EmBoxCenter => 0.0,
|
||||
CharAlign::EmBoxBottom => -0.5,
|
||||
CharAlign::IcfTop => 0.5 - if vertical { icf().right } else { icf().top },
|
||||
CharAlign::IcfBottom => -0.5 + if vertical { icf().left } else { icf().bottom },
|
||||
};
|
||||
(g.face.ideographic_centre() + k) * (line_em - glyph_em(g)).max(0.0)
|
||||
}
|
||||
@@ -412,6 +512,9 @@ fn finish_bounds(out: &mut TextLayout) {
|
||||
add(g.outline.bounding_box());
|
||||
}
|
||||
}
|
||||
for i in &out.inlines {
|
||||
add(i.bounds);
|
||||
}
|
||||
if !out.on_path {
|
||||
for l in &out.lines {
|
||||
add(xf.transform_rect_bbox(Rect::new(l.x0.min(l.x1), l.baseline - l.ascent, l.x0.max(l.x1), l.baseline + l.descent)));
|
||||
@@ -452,7 +555,7 @@ fn cell_space(out: &TextLayout, regions: &[Region]) -> Vec<Option<(f64, f64, usi
|
||||
/// Other frames give lines different widths at different heights, so the text flows again with
|
||||
/// each cell's lines started lower (or spaced wider) until it settles, at most eight passes; a
|
||||
/// pass that would push text out of the frame is undone and retried with half the step.
|
||||
fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: &mut [Region]) {
|
||||
fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, regions: &mut [Region]) {
|
||||
let align = cx.opts.vertical_align;
|
||||
let plain = regions.iter().all(|r| (r.rect || r.polys.is_empty()) && r.wraps.is_empty());
|
||||
if plain {
|
||||
@@ -522,7 +625,7 @@ fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle,
|
||||
}
|
||||
let before = laid_out(&cx.out);
|
||||
let prev = (std::mem::take(&mut cx.out.glyphs), std::mem::take(&mut cx.out.lines), std::mem::replace(&mut cx.out.overflow, false));
|
||||
flow(cx, paras, para, Some(regions));
|
||||
flow(cx, paras, t, Some(regions));
|
||||
if laid_out(&cx.out) < before {
|
||||
// Text no longer fits (lines got narrower, or flow around a wrap object): undo the
|
||||
// pass and try a smaller step.
|
||||
@@ -949,9 +1052,9 @@ fn break_line(text: &str, g: &[SGlyph], i: usize, width: f64, hyphenate: bool, b
|
||||
|
||||
/// Can glyph `g` hang outside the line (burasagari)? An East Asian comma or full stop, full width
|
||||
/// (、。,.) or half width (、。); not a closing bracket, nor Latin punctuation (Latin text keeps
|
||||
/// its line breaks and composer).
|
||||
/// its line breaks and composer). Never an inline graphic (U+FFFC).
|
||||
fn hangs(g: &SGlyph) -> bool {
|
||||
matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none()
|
||||
g.inline.is_none() && matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none()
|
||||
}
|
||||
|
||||
/// Does kinsoku allow a line break after glyph `j`? Not after an opening bracket, nor before a
|
||||
@@ -999,6 +1102,7 @@ mod wrapping_tests {
|
||||
xh: 4.0,
|
||||
ch,
|
||||
tcy: None,
|
||||
inline: None,
|
||||
lead: 0.0,
|
||||
level: unicode_bidi::Level::ltr(),
|
||||
})
|
||||
@@ -1054,7 +1158,7 @@ mod wrapping_tests {
|
||||
let bidi = para_bidi(text, None);
|
||||
let levels = bidi.as_ref().map_or(&[][..], |info| &info.levels);
|
||||
let mut shaped = Vec::new();
|
||||
shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &OtFeatures::default(), levels, &mut shaped);
|
||||
shape_range(db, text, 0..text.len(), &[(0..text.len(), &style)], &[], &OtFeatures::default(), levels, &mut shaped);
|
||||
let Some(first) = shaped.first() else { return };
|
||||
let first_end = shaped.iter().take_while(|g| g.byte == first.byte).count();
|
||||
if first.byte != 0 || first_end < 2 || first_end >= shaped.len() {
|
||||
@@ -1217,7 +1321,9 @@ fn compose_para(cx: &Ctx<'_>, sg: &[SGlyph], para: &ParaStyle, pen: &Pen<'_>, rt
|
||||
compose(sg, &width, &start_credit, &cands, ¶ms(strict)).or_else(|| compose(sg, &width, &start_credit, &cands, ¶ms(loose)))
|
||||
}
|
||||
|
||||
fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Option<&[Region]>) {
|
||||
/// Flow paragraphs `paras` (byte ranges) of `t`, each with its own paragraph attributes
|
||||
/// (alignment, indents, spacing, direction, mojikumi, leading model…).
|
||||
fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, regions: Option<&[Region]>) {
|
||||
let mut pen = Pen {
|
||||
regions,
|
||||
ri: 0,
|
||||
@@ -1226,10 +1332,14 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
|
||||
fb: cx.opts.first_baseline,
|
||||
fb_min: cx.opts.first_baseline_min,
|
||||
queued: vec![],
|
||||
model: para.leading_model,
|
||||
model: t.para_at(0).leading_model,
|
||||
next_top: None,
|
||||
};
|
||||
'paras: for (pi, pr) in paras.iter().enumerate() {
|
||||
let para = t.para_at(pi);
|
||||
// The leading model is a paragraph attribute: this paragraph's lines (and the space to
|
||||
// its first line) follow its own.
|
||||
pen.model = para.leading_model;
|
||||
let text = cx.text;
|
||||
let bidi = para_bidi(text.get(pr.clone()).unwrap_or_default(), para.direction);
|
||||
let rtl = is_rtl(bidi.as_ref());
|
||||
@@ -1428,7 +1538,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], para: &ParaStyle, regions: Opt
|
||||
adv += per_gap;
|
||||
}
|
||||
}
|
||||
let y = baseline - align_shift(g, cx.style_at(g.byte).char_align, line_em);
|
||||
let y = baseline - align_shift(g, cx.style_at(g.byte).char_align, line_em, cx.vertical);
|
||||
cx.emit(g, Affine::translate((x, y)), Point::new(x, y), 0.0, adv, li);
|
||||
x += adv;
|
||||
if j < trimmed {
|
||||
@@ -1494,7 +1604,8 @@ fn path_steps(ap: &ArcPath, glyphs: &[SGlyph], from: f64, spacing: f64) -> Vec<f
|
||||
/// Lay type on a path out along `path` (text space), between its brackets.
|
||||
fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, path: &PathData) {
|
||||
cx.out.on_path = true;
|
||||
let para = &t.para;
|
||||
// Type on a path is one line: the first paragraph's attributes align it.
|
||||
let para = t.para_at(0);
|
||||
let mut sg = Vec::new();
|
||||
// The first paragraph's direction aligns the line (Auto) and sets the caret's.
|
||||
let mut rtl = None;
|
||||
|
||||
+62
-4
@@ -25,13 +25,14 @@ pub mod thread;
|
||||
pub use craft_fonts::{CRAFT_FONTS, CraftFont};
|
||||
pub use features::{LIGATURE_TRACKING_LIMITS, OtFeatures, explicit_ligatures, ligatures_suppressed_by};
|
||||
pub use fontdb::{
|
||||
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, PlatformFontFiles, set_platform_font_files, style_weight, system_font_dirs,
|
||||
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, style_weight,
|
||||
system_font_dirs,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
pub use layout::{layout, layout_with};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::{FirstBaseline, VerticalAlign};
|
||||
pub use vectorcraft_doc::{AreaFit, FirstBaseline, VerticalAlign};
|
||||
|
||||
/// Paragraph composer; stored per text object in [`vectorcraft_doc::ParaStyle::composer`].
|
||||
pub use vectorcraft_doc::Composer;
|
||||
@@ -52,6 +53,9 @@ pub struct LayoutOptions {
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column (Area Type Options "Align").
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// Area type only: Shrink Text to Fit scales overflowing text down at layout time (see
|
||||
/// [`TextLayout::fit_scale`]); the other fits are the engine's business and lay out as `None`.
|
||||
pub fit: AreaFit,
|
||||
/// Overrides the object's paragraph composer (`None` = use `ParaStyle::composer`).
|
||||
pub composer: Option<Composer>,
|
||||
pub features: OtFeatures,
|
||||
@@ -67,6 +71,7 @@ impl Default for LayoutOptions {
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
fit: AreaFit::None,
|
||||
composer: None,
|
||||
features: OtFeatures::default(),
|
||||
}
|
||||
@@ -131,7 +136,23 @@ pub struct LineInfo {
|
||||
pub region: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// An inline graphic ([`vectorcraft_doc::TextRun::inline`]) placed by the layout: draw the art of
|
||||
/// the run's symbol through `xf`. Missing symbols reserve their room but get no entry.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct InlineGlyph {
|
||||
/// Index of the run (`TextObject::runs`).
|
||||
pub run: usize,
|
||||
/// Byte offset of its character in the plain text.
|
||||
pub byte: usize,
|
||||
/// Index of its (outline-less) glyph in [`TextLayout::glyphs`].
|
||||
pub glyph: usize,
|
||||
/// The symbol's art at its natural size (`Document::symbol_natural_xf`) → text space.
|
||||
pub xf: Affine,
|
||||
/// The art's bounds in text space.
|
||||
pub bounds: Rect,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TextLayout {
|
||||
/// Lines retain inline/block coordinates; glyph geometry is in physical text space.
|
||||
pub vertical: bool,
|
||||
@@ -149,6 +170,28 @@ pub struct TextLayout {
|
||||
pub on_path: bool,
|
||||
/// Area type: the frame cells text flowed into (one per row/column).
|
||||
pub frames: Vec<Rect>,
|
||||
/// Shrink Text to Fit: the factor the text's sizes, leading and baseline shifts were scaled
|
||||
/// by to fit its frame (1.0 when the text is not shrunk).
|
||||
pub fit_scale: f64,
|
||||
/// Inline graphics, in text order.
|
||||
pub inlines: Vec<InlineGlyph>,
|
||||
}
|
||||
|
||||
impl Default for TextLayout {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
vertical: false,
|
||||
line_xf: Affine::IDENTITY,
|
||||
glyphs: Vec::new(),
|
||||
lines: Vec::new(),
|
||||
bounds: Rect::ZERO,
|
||||
overflow: false,
|
||||
on_path: false,
|
||||
frames: Vec::new(),
|
||||
fit_scale: 1.0,
|
||||
inlines: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextLayout {
|
||||
@@ -194,7 +237,8 @@ impl TextLayout {
|
||||
return false;
|
||||
}
|
||||
let mut moved = false;
|
||||
for g in self.glyphs.iter_mut().filter(|g| g.angle == 0.0) {
|
||||
let mut shifts = vec![];
|
||||
for (gi, g) in self.glyphs.iter_mut().enumerate().filter(|(_, g)| g.angle == 0.0) {
|
||||
let p = to_device * g.origin;
|
||||
let shift = Vec2::new((p.x.round() - p.x) / a, (p.y.round() - p.y) / d);
|
||||
if shift == Vec2::ZERO {
|
||||
@@ -203,8 +247,18 @@ impl TextLayout {
|
||||
g.origin += shift;
|
||||
g.outline.apply_affine(Affine::translate(shift));
|
||||
g.xf = Affine::translate(shift) * g.xf;
|
||||
if !self.inlines.is_empty() {
|
||||
shifts.push((gi, shift));
|
||||
}
|
||||
moved = true;
|
||||
}
|
||||
// Inline graphics move with their glyphs.
|
||||
for i in &mut self.inlines {
|
||||
if let Some(&(_, s)) = shifts.iter().find(|(gi, _)| *gi == i.glyph) {
|
||||
i.xf = Affine::translate(s) * i.xf;
|
||||
i.bounds = i.bounds + s;
|
||||
}
|
||||
}
|
||||
moved
|
||||
}
|
||||
}
|
||||
@@ -450,6 +504,10 @@ mod tests_bidi;
|
||||
#[cfg(test)]
|
||||
mod tests_embed;
|
||||
#[cfg(test)]
|
||||
mod tests_fit;
|
||||
#[cfg(test)]
|
||||
mod tests_inline;
|
||||
#[cfg(test)]
|
||||
mod tests_scripts;
|
||||
#[cfg(test)]
|
||||
mod tests_snap;
|
||||
|
||||
+107
-15
@@ -9,7 +9,8 @@ use unicode_script::{Script, UnicodeScript};
|
||||
use harfrust::{Direction, Feature, ShapeOptions, UnicodeBuffer};
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::instance::Size;
|
||||
use vectorcraft_doc::CharStyle;
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{CharStyle, InlineArt};
|
||||
|
||||
use crate::features::OtFeatures;
|
||||
use crate::fontdb::{FontDb, FontFace};
|
||||
@@ -50,6 +51,19 @@ pub(crate) struct SGlyph {
|
||||
pub lead: f64,
|
||||
/// Resolved Unicode bidi embedding level (logical source order).
|
||||
pub level: Level,
|
||||
/// An inline graphic ([`vectorcraft_doc::TextRun::inline`]) standing in for a glyph.
|
||||
pub inline: Option<InlineBox>,
|
||||
}
|
||||
|
||||
/// Placement of an inline graphic's art, glyph space being points with the pen at the origin on
|
||||
/// the baseline (y down).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct InlineBox {
|
||||
/// The art's bounds in symbol space; `None` when the symbol is missing (the box only takes
|
||||
/// up room).
|
||||
pub art: Option<kurbo::Rect>,
|
||||
/// Art -> glyph space.
|
||||
pub xf: kurbo::Affine,
|
||||
}
|
||||
|
||||
/// A glyph's place in a tate-chu-yoko block: the block takes one em of the column, its glyphs side
|
||||
@@ -68,7 +82,7 @@ pub(crate) struct Tcy {
|
||||
|
||||
impl SGlyph {
|
||||
pub fn is_space(&self) -> bool {
|
||||
matches!(self.ch, ' ' | '\t' | '\u{3000}' | '\u{2002}'..='\u{200B}')
|
||||
self.inline.is_none() && matches!(self.ch, ' ' | '\t' | '\u{3000}' | '\u{2002}'..='\u{200B}')
|
||||
}
|
||||
/// A line may break after this glyph.
|
||||
pub fn break_after(&self) -> bool {
|
||||
@@ -102,6 +116,7 @@ pub(crate) fn hyphen_glyph(g: &SGlyph) -> SGlyph {
|
||||
h.byte = g.byte + g.len;
|
||||
h.len = 0;
|
||||
h.ch = '-';
|
||||
h.inline = None;
|
||||
h
|
||||
}
|
||||
|
||||
@@ -184,14 +199,17 @@ pub(crate) fn cap_x_heights(db: &FontDb, st: &CharStyle) -> (f64, f64) {
|
||||
(face.cap_height * k, face.x_height * k)
|
||||
}
|
||||
|
||||
/// Shape `text[range]`, where `runs` gives each run's byte range in `text` and style, and `levels`
|
||||
/// each byte's bidi embedding level from `range.start` (empty: all left to right). Glyphs come out
|
||||
/// in logical order, right-to-left ones shaped right to left.
|
||||
/// Shape `text[range]`, where `runs` gives each run's byte range in `text` and style, `inlines`
|
||||
/// (parallel to `runs`) the inline graphic of each run that is one, and `levels` each byte's bidi
|
||||
/// embedding level from `range.start` (empty: all left to right). Glyphs come out in logical
|
||||
/// order, right-to-left ones shaped right to left.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn shape_range(
|
||||
db: &FontDb,
|
||||
text: &str,
|
||||
range: Range<usize>,
|
||||
runs: &[(Range<usize>, &CharStyle)],
|
||||
inlines: &[Option<&InlineArt>],
|
||||
feats: &OtFeatures,
|
||||
levels: &[Level],
|
||||
out: &mut Vec<SGlyph>,
|
||||
@@ -205,27 +223,44 @@ pub(crate) fn shape_range(
|
||||
// Text runs also carry non-shaping attributes (fill, stroke, etc.). Coalesce adjacent equal
|
||||
// styles so an editor split does not become an accidental OpenType shaping boundary. Keep
|
||||
// original run spans: each emitted cluster is attributed by its source byte below.
|
||||
let mut spans: Vec<(Range<usize>, &CharStyle, Range<usize>)> = Vec::new();
|
||||
/// A run of text shaped together: its byte range, style and source runs, or one inline graphic.
|
||||
struct ShapeSpan<'a> {
|
||||
bytes: Range<usize>,
|
||||
st: &'a CharStyle,
|
||||
source_runs: Range<usize>,
|
||||
art: Option<&'a InlineArt>,
|
||||
}
|
||||
let mut spans: Vec<ShapeSpan<'_>> = Vec::new();
|
||||
for (ri, (rr, st)) in runs.iter().enumerate() {
|
||||
let a = rr.start.max(range.start);
|
||||
let b = rr.end.min(range.end);
|
||||
if a >= b || text.get(a..b).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some((previous, previous_style, source_runs)) = spans.last_mut()
|
||||
&& previous.end == a
|
||||
&& *previous_style == *st
|
||||
let art = inlines.get(ri).copied().flatten();
|
||||
// An inline graphic is a span of its own: never merged with its neighbours.
|
||||
if art.is_none()
|
||||
&& let Some(previous) = spans.last_mut()
|
||||
&& previous.art.is_none()
|
||||
&& previous.bytes.end == a
|
||||
&& *previous.st == **st
|
||||
{
|
||||
previous.end = b;
|
||||
source_runs.end = ri + 1;
|
||||
previous.bytes.end = b;
|
||||
previous.source_runs.end = ri + 1;
|
||||
continue;
|
||||
}
|
||||
spans.push((a..b, *st, ri..ri + 1));
|
||||
spans.push(ShapeSpan { bytes: a..b, st, source_runs: ri..ri + 1, art });
|
||||
}
|
||||
|
||||
for (span, st, source_runs) in spans {
|
||||
let a = span.start;
|
||||
let b = span.end;
|
||||
for ShapeSpan { bytes, st, source_runs, art } in spans {
|
||||
let a = bytes.start;
|
||||
let b = bytes.end;
|
||||
if let Some(art) = art {
|
||||
if let Some(face) = db.face(&st.font_family, &st.font_style).or_else(|| db.face_covering('a')) {
|
||||
out.push(inline_glyph(&face, st, art, source_runs.start, a..b, text, level_at(a)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(primary) = db.face(&st.font_family, &st.font_style) else { continue };
|
||||
let pmap = primary.skrifa().map(|f| f.charmap());
|
||||
// Synthesized Small Caps shape lowercase letters separately (as smaller capitals).
|
||||
@@ -299,6 +334,62 @@ fn shaping_script(c: char) -> Script {
|
||||
}
|
||||
}
|
||||
|
||||
/// The synthetic glyph of an inline graphic run (`range` = its one character).
|
||||
///
|
||||
/// The art is scaled uniformly to `scale` x the font size tall, its left edge on the pen and its
|
||||
/// vertical centre on the middle of the cap height raised by the inline's shift (see
|
||||
/// [`InlineArt`]). Its advance is the scaled art width plus tracking; the glyph's ascent and
|
||||
/// descent grow to the art's extent so a tall graphic opens up its line. A missing symbol takes a
|
||||
/// square of the same height and draws nothing.
|
||||
fn inline_glyph(face: &Arc<FontFace>, st: &CharStyle, art: &InlineArt, run: usize, range: Range<usize>, text: &str, level: Level) -> SGlyph {
|
||||
let size = if st.size.is_finite() { st.size.max(0.0) } else { 0.0 };
|
||||
let vs = if st.v_scale.is_finite() { st.v_scale / 100.0 } else { 1.0 };
|
||||
let km = size / face.upem;
|
||||
let (ascent, descent, cap, xh) = (face.ascent * km * vs, face.descent * km * vs, face.cap_height * km * vs, face.x_height * km * vs);
|
||||
let h = art.safe_scale() * size;
|
||||
let mid = cap * 0.5 + art.safe_shift();
|
||||
let art_bounds = art.bounds.filter(|b| b.height() > 1e-9 && b.width().is_finite() && b.height().is_finite());
|
||||
let (xf, width, drawn) = match art_bounds {
|
||||
Some(b) if h > 0.0 => {
|
||||
let k = h / b.height();
|
||||
let xf = kurbo::Affine::translate((0.0, -mid)) * kurbo::Affine::scale(k) * kurbo::Affine::translate((-b.x0, -(b.y0 + b.y1) * 0.5));
|
||||
(xf, b.width() * k, Some(b))
|
||||
}
|
||||
_ => (kurbo::Affine::IDENTITY, h, None),
|
||||
};
|
||||
let tracking = st.tracking / 1000.0 * size;
|
||||
let adv = width + if tracking.is_finite() { tracking } else { 0.0 };
|
||||
SGlyph {
|
||||
face: face.clone(),
|
||||
gid: 0,
|
||||
byte: range.start,
|
||||
len: range.len().max(1),
|
||||
run,
|
||||
adv: if adv.is_finite() { adv } else { 0.0 },
|
||||
dx: 0.0,
|
||||
dy: 0.0,
|
||||
// Not used to draw (the art has its own transform), but they make the glyph's em box
|
||||
// its run's em: Character Alignment and Top-to-Top leading treat an inline graphic as a
|
||||
// character of its run's size, whatever its scale (see `layout::glyph_em`).
|
||||
sx: if km.is_finite() { km * vs } else { 0.0 },
|
||||
sy: if km.is_finite() { km * vs } else { 0.0 },
|
||||
bshift: if st.baseline_shift.is_finite() { st.baseline_shift } else { 0.0 },
|
||||
rotation: 0.0,
|
||||
ascent: ascent.max(mid + h * 0.5),
|
||||
descent: descent.max(h * 0.5 - mid),
|
||||
leading: st.effective_leading(),
|
||||
cap,
|
||||
xh,
|
||||
ch: text.get(range.clone()).and_then(|s| s.chars().next()).unwrap_or(INLINE_CHAR),
|
||||
tcy: None,
|
||||
lead: 0.0,
|
||||
// U+FFFC is a bidi neutral (ON): its level, resolved from its neighbours, places it in
|
||||
// RTL text like any other glyph once the line is reordered.
|
||||
level,
|
||||
inline: Some(InlineBox { art: drawn, xf }),
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of one run shaped in one go: one face and, for Small Caps, one case.
|
||||
struct Segment<'a> {
|
||||
range: Range<usize>,
|
||||
@@ -424,6 +515,7 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
|
||||
tcy: None,
|
||||
lead: 0.0,
|
||||
level: *level,
|
||||
inline: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
+105
-5
@@ -209,6 +209,27 @@ fn indents_and_paragraph_spacing() {
|
||||
assert!((l.lines[1].baseline - l.lines[0].baseline - 18.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_paragraph_has_its_own_attributes() {
|
||||
let frame = Rect::new(0.0, 0.0, 200.0, 400.0);
|
||||
let mut t = area("left\ncentred\nright", style(10.0), frame, Justify::Left);
|
||||
let centred = vectorcraft_doc::ParaStyle { justify: Justify::Center, space_before: 20.0, ..Default::default() };
|
||||
let right = vectorcraft_doc::ParaStyle { justify: Justify::Right, left_indent: 7.0, ..Default::default() };
|
||||
t.set_paragraph_styles(vec![t.para.clone(), centred, right]);
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(l.lines.len(), 3);
|
||||
assert!(l.lines[0].x0.abs() < 1e-9, "the first paragraph stays left");
|
||||
let mid = (l.lines[1].x0 + l.lines[1].x1) / 2.0;
|
||||
assert!((mid - 100.0).abs() < 1e-6, "the second is centred: {mid}");
|
||||
assert!((l.lines[2].x1 - 200.0).abs() < 1e-6, "the third is right-aligned");
|
||||
// Space before applies to the second paragraph only (leading 12 + 20).
|
||||
assert!((l.lines[1].baseline - l.lines[0].baseline - 32.0).abs() < 1e-9);
|
||||
assert!((l.lines[2].baseline - l.lines[1].baseline - 12.0).abs() < 1e-9);
|
||||
// Paragraph 0's style is `para` (what readers that predate per-paragraph styles see).
|
||||
assert_eq!(t.paras.len(), 3);
|
||||
assert_eq!(t.para_at(0), &t.para);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_rect_frame_narrows_lines() {
|
||||
// Triangle pointing up: lines get wider towards the bottom.
|
||||
@@ -365,8 +386,8 @@ fn fallback_font_per_character() {
|
||||
fn multiple_runs_and_styles() {
|
||||
let mut t = point("", style(10.0));
|
||||
t.runs = vec![
|
||||
TextRun { text: "Big".into(), style: style(40.0) },
|
||||
TextRun { text: "small".into(), style: CharStyle { font_family: "Inter".into(), ..style(10.0) } },
|
||||
TextRun { text: "Big".into(), style: style(40.0), inline: None },
|
||||
TextRun { text: "small".into(), style: CharStyle { font_family: "Inter".into(), ..style(10.0) }, inline: None },
|
||||
];
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(l.glyphs.len(), 8);
|
||||
@@ -546,7 +567,7 @@ fn em_box_top_leading_hangs_lines_from_the_line_above() {
|
||||
}
|
||||
// 40 pt over 20 pt (leading 60 and 30).
|
||||
let mut mixed = point("", st(40.0));
|
||||
mixed.runs = vec![TextRun { text: "大\n".into(), style: st(40.0) }, TextRun { text: "小".into(), style: st(20.0) }];
|
||||
mixed.runs = vec![TextRun { text: "大\n".into(), style: st(40.0), inline: None }, TextRun { text: "小".into(), style: st(20.0), inline: None }];
|
||||
let roman = lay(&mixed, LeadingModel::RomanBaseline);
|
||||
assert!((roman.lines[1].baseline - roman.lines[0].baseline - 30.0).abs() < 0.01, "the small line's leading, above it");
|
||||
let em = lay(&mixed, LeadingModel::EmBoxTop);
|
||||
@@ -558,6 +579,46 @@ fn em_box_top_leading_hangs_lines_from_the_line_above() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The leading model is a paragraph attribute: in "大 / 小 / 大 / 小" (40 pt over 20 pt) with
|
||||
/// only the second paragraph top-to-top, its line hangs from the big line's em box (the big
|
||||
/// line's leading, below it) while the fourth, baseline to baseline, takes its own leading above
|
||||
/// it; in area type a top-to-top first paragraph puts its em box on the frame's top.
|
||||
#[test]
|
||||
fn leading_model_is_per_paragraph() {
|
||||
use vectorcraft_doc::{LeadingModel, ParaStyle, TextRun};
|
||||
let st = |size: f64| CharStyle { size, leading: Some(size * 1.5), ..style(size) };
|
||||
let model = |m: LeadingModel| ParaStyle { leading_model: m, ..ParaStyle::default() };
|
||||
let top = |size: f64| 0.88 * size;
|
||||
let mut t = point("", st(40.0));
|
||||
t.runs = vec![
|
||||
TextRun { text: "大\n".into(), style: st(40.0), inline: None },
|
||||
TextRun { text: "小\n".into(), style: st(20.0), inline: None },
|
||||
TextRun { text: "大\n".into(), style: st(40.0), inline: None },
|
||||
TextRun { text: "小".into(), style: st(20.0), inline: None },
|
||||
];
|
||||
t.set_paragraph_styles(vec![
|
||||
model(LeadingModel::RomanBaseline),
|
||||
model(LeadingModel::EmBoxTop),
|
||||
model(LeadingModel::RomanBaseline),
|
||||
model(LeadingModel::RomanBaseline),
|
||||
]);
|
||||
assert_eq!(t.paras.len(), 4);
|
||||
let l = layout(db(), &t);
|
||||
let gap = |i: usize| l.lines[i].baseline - l.lines[i - 1].baseline;
|
||||
let em = -top(40.0) + 60.0 + top(20.0);
|
||||
assert!((gap(1) - em).abs() < 0.01, "top to top: {} vs {em}", gap(1));
|
||||
assert!((gap(3) - 30.0).abs() < 0.01, "baseline to baseline: {}", gap(3));
|
||||
// Area type: only a top-to-top first paragraph moves the first line up to the frame's top.
|
||||
let mut a = area("一\n二", st(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left);
|
||||
a.set_paragraph_styles(vec![model(LeadingModel::RomanBaseline), model(LeadingModel::EmBoxTop)]);
|
||||
let roman_first = layout(db(), &a).lines[0].baseline;
|
||||
a.set_paragraph_styles(vec![model(LeadingModel::EmBoxTop), model(LeadingModel::RomanBaseline)]);
|
||||
let em_first = layout(db(), &a);
|
||||
assert!((em_first.lines[0].baseline - top(20.0)).abs() < 0.01, "{}", em_first.lines[0].baseline);
|
||||
assert!((roman_first - em_first.lines[0].baseline).abs() > 0.5);
|
||||
assert!((em_first.lines[1].baseline - em_first.lines[0].baseline - 30.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// Character Alignment: a 20 pt character next to a 40 pt one lines its em box top, centre or
|
||||
/// bottom up with the big one's (the em box from 0.12 em below the baseline to 0.88 em above it,
|
||||
/// in fonts without vertical metrics), or stays on the baseline; in vertical type the same across
|
||||
@@ -570,8 +631,8 @@ fn character_alignment_lines_small_characters_up_with_the_largest_em_box() {
|
||||
let mut t = point("", style(40.0));
|
||||
t.vertical = vertical_type;
|
||||
t.runs = vec![
|
||||
TextRun { text: "大".into(), style: style(40.0) },
|
||||
TextRun { text: "小".into(), style: CharStyle { char_align: a, ..style(20.0) } },
|
||||
TextRun { text: "大".into(), style: style(40.0), inline: None },
|
||||
TextRun { text: "小".into(), style: CharStyle { char_align: a, ..style(20.0) }, inline: None },
|
||||
];
|
||||
let l = layout(db(), &t);
|
||||
// How far the small character's origin sits above the big one's (to the right, vertical).
|
||||
@@ -586,6 +647,45 @@ fn character_alignment_lines_small_characters_up_with_the_largest_em_box() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Character Alignment on the ICF: a 20 pt character next to a 40 pt one lines its ideographic
|
||||
/// character face's top (right, vertical) or bottom (left) up with the big one's, which lies inside
|
||||
/// the em box by the face's ICF margins. A face without ideographs has none (the ICF is the em
|
||||
/// box). The Japanese faces need craft-fonts (skipped without them).
|
||||
#[test]
|
||||
fn character_alignment_on_the_icf_lines_small_characters_up_with_the_largest_face() {
|
||||
use vectorcraft_doc::{CharAlign, TextRun};
|
||||
let place = |family: &str, a: CharAlign, vertical_type: bool| {
|
||||
let st = |size: f64| CharStyle { font_family: family.into(), ..style(size) };
|
||||
let mut t = point("", st(40.0));
|
||||
t.vertical = vertical_type;
|
||||
t.runs = vec![
|
||||
TextRun { text: "大".into(), style: st(40.0), inline: None },
|
||||
TextRun { text: "小".into(), style: CharStyle { char_align: a, ..st(20.0) }, inline: None },
|
||||
];
|
||||
let l = layout(db(), &t);
|
||||
let (big, small) = (l.glyphs[0].origin, l.glyphs[1].origin);
|
||||
if vertical_type { small.x - big.x } else { big.y - small.y }
|
||||
};
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 0.01;
|
||||
// No ideographs: the ICF is the em box.
|
||||
assert_eq!(db().face("Source Sans 3", "Regular").unwrap().icf_margins(), crate::IcfMargins::default());
|
||||
let Some(face) = db().face("Shippori Mincho", "Regular").filter(|f| f.family == "Shippori Mincho") else {
|
||||
return; // no Japanese font here
|
||||
};
|
||||
let m = face.icf_margins();
|
||||
assert!([m.top, m.bottom, m.right, m.left].iter().all(|x| *x > 0.01 && *x < 0.2), "{m:?}");
|
||||
for vertical_type in [false, true] {
|
||||
let (top, bottom) = if vertical_type { (m.right, m.left) } else { (m.top, m.bottom) };
|
||||
// The big character's ICF top is `top` ems below its em box top: 20 pt of difference.
|
||||
let em_top = place("Shippori Mincho", CharAlign::EmBoxTop, vertical_type);
|
||||
let icf_top = place("Shippori Mincho", CharAlign::IcfTop, vertical_type);
|
||||
assert!(near(em_top - icf_top, top * 20.0), "vertical {vertical_type}: {em_top} {icf_top} {m:?}");
|
||||
let em_bottom = place("Shippori Mincho", CharAlign::EmBoxBottom, vertical_type);
|
||||
let icf_bottom = place("Shippori Mincho", CharAlign::IcfBottom, vertical_type);
|
||||
assert!(near(icf_bottom - em_bottom, bottom * 20.0), "vertical {vertical_type}: {em_bottom} {icf_bottom} {m:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Burasagari leaves Latin punctuation alone: in a measure of exactly "abcd", the full stop of
|
||||
/// "abcd. ef" doesn't hang with Standard or Forced (the line breaks as it does with None), and a
|
||||
/// Latin line ending in a full stop isn't shortened by Forced.
|
||||
|
||||
@@ -10,10 +10,16 @@ fn text_layout(s: &str) -> TextLayout {
|
||||
|
||||
fn arabic_test_face(test: &str) -> Option<Arc<FontFace>> {
|
||||
let db = FontDb::global();
|
||||
// OpenType (GSUB) shaping only: AAT fonts such as macOS's Geeza Pro shape with `morx`, which
|
||||
// takes no context from outside the run, so their joining across a style boundary differs.
|
||||
let opentype = |face: &FontFace| {
|
||||
use skrifa::raw::TableProvider;
|
||||
face.skrifa().is_some_and(|f| f.gsub().is_ok())
|
||||
};
|
||||
let face = ["Geeza Pro", "Arial", "Noto Sans Arabic"]
|
||||
.into_iter()
|
||||
.filter_map(|name| db.face(name, "Regular"))
|
||||
.find(|face| face.covers('ب') && face.covers('ل') && face.covers('ا'));
|
||||
.find(|face| face.covers('ب') && face.covers('ل') && face.covers('ا') && opentype(face));
|
||||
if let Some(face) = &face {
|
||||
let path = face.path().map_or_else(|| "bundled font".to_string(), |p| p.display().to_string());
|
||||
eprintln!("ASSERTIONS RUN: {test}; Arabic font {} {} ({path})", face.family, face.style);
|
||||
@@ -142,9 +148,9 @@ fn identical_style_arabic_run_splits_keep_joining_and_source_attribution() {
|
||||
let text = "بب";
|
||||
|
||||
let mut single = TextObject::point(Point::ZERO, text, style.clone());
|
||||
single.runs = vec![TextRun { text: text.to_string(), style: style.clone() }];
|
||||
single.runs = vec![TextRun { text: text.to_string(), style: style.clone(), inline: None }];
|
||||
let mut split = TextObject::point(Point::ZERO, text, style.clone());
|
||||
split.runs = vec![TextRun { text: "ب".into(), style: style.clone() }, TextRun { text: "ب".into(), style }];
|
||||
split.runs = vec![TextRun { text: "ب".into(), style: style.clone(), inline: None }, TextRun { text: "ب".into(), style, inline: None }];
|
||||
|
||||
let single = layout(db, &single);
|
||||
let split = layout(db, &split);
|
||||
@@ -167,8 +173,10 @@ fn different_style_arabic_boundary_receives_joining_context() {
|
||||
assert!(joined.glyphs.iter().any(|glyph| glyph.gid != face.glyph_for('ب')), "reference must use contextual beh forms");
|
||||
|
||||
let mut split = TextObject::point(Point::ZERO, text, style.clone());
|
||||
split.runs =
|
||||
vec![TextRun { text: "ب".into(), style: style.clone() }, TextRun { text: "ب".into(), style: CharStyle { size: style.size * 1.5, ..style } }];
|
||||
split.runs = vec![
|
||||
TextRun { text: "ب".into(), style: style.clone(), inline: None },
|
||||
TextRun { text: "ب".into(), style: CharStyle { size: style.size * 1.5, ..style }, inline: None },
|
||||
];
|
||||
let split = layout(db, &split);
|
||||
assert_eq!(joined.glyphs.len(), 2);
|
||||
assert_eq!(split.glyphs.len(), 2);
|
||||
@@ -188,12 +196,12 @@ fn shape_range_handles_empty_runs_and_selected_utf8_subranges() {
|
||||
let runs = [(0..text.len(), &style)];
|
||||
let mut glyphs = Vec::new();
|
||||
|
||||
shape::shape_range(db, text, 0..0, &runs, &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 0..text.len(), &[], &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 1..2, &runs, &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 0..0, &runs, &[], &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 0..text.len(), &[], &[], &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 1..2, &runs, &[], &OtFeatures::default(), &[], &mut glyphs);
|
||||
assert!(glyphs.is_empty());
|
||||
|
||||
shape::shape_range(db, text, 1..text.len(), &runs, &OtFeatures::default(), &[], &mut glyphs);
|
||||
shape::shape_range(db, text, 1..text.len(), &runs, &[], &OtFeatures::default(), &[], &mut glyphs);
|
||||
assert!(!glyphs.is_empty());
|
||||
assert!(glyphs.iter().all(|g| (1..text.len()).contains(&g.byte)));
|
||||
}
|
||||
@@ -312,3 +320,27 @@ fn visual_text_comes_back_in_logical_order() {
|
||||
assert_eq!(shown, visual);
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph Direction is a paragraph attribute: in one text object a right-to-left paragraph
|
||||
/// reads and aligns (Auto) right to left while the next, left to right, starts on the left.
|
||||
#[test]
|
||||
fn paragraph_direction_is_per_paragraph() {
|
||||
use vectorcraft_doc::{Justify, ParaDirection, ParaStyle};
|
||||
let s = "Hello.\nHello.";
|
||||
let mut t = TextObject::point(Point::ZERO, s, CharStyle::default());
|
||||
let dir = |direction| ParaStyle { justify: Justify::Auto, direction, ..ParaStyle::default() };
|
||||
t.set_paragraph_styles(vec![dir(Some(ParaDirection::RightToLeft)), dir(Some(ParaDirection::LeftToRight))]);
|
||||
assert_eq!(t.paras.len(), 2, "stored per paragraph");
|
||||
let l = layout(FontDb::global(), &t);
|
||||
assert_eq!(l.lines.len(), 2);
|
||||
let shown = |line: &crate::LineInfo| -> String {
|
||||
let mut gs: Vec<_> = l.glyphs.iter().filter(|g| g.byte >= line.start && g.byte < line.end).collect();
|
||||
gs.sort_by(|a, b| a.origin.x.total_cmp(&b.origin.x));
|
||||
gs.iter().filter_map(|g| s.get(g.byte..)?.chars().next()).filter(|c| *c != '\n').collect()
|
||||
};
|
||||
assert!(l.lines[0].rtl && !l.lines[1].rtl);
|
||||
assert_eq!(shown(&l.lines[0]), ".Hello", "the first paragraph runs right to left");
|
||||
assert_eq!(shown(&l.lines[1]), "Hello.", "the second runs left to right");
|
||||
assert!(l.lines[0].x1.abs() < 1e-6, "Auto aligns the right-to-left paragraph right: {}", l.lines[0].x1);
|
||||
assert!(l.lines[1].x0.abs() < 1e-6, "…and the left-to-right one left: {}", l.lines[1].x0);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Area type fitting: Shrink Text to Fit.
|
||||
|
||||
use super::*;
|
||||
use kurbo::Shape;
|
||||
use vectorcraft_doc::{AreaFit, CharStyle, TextKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
const COPY: &str = "Typography is the craft of arranging type to make written language legible, readable and appealing when displayed. \
|
||||
The arrangement of type involves selecting typefaces, point sizes, line lengths, line spacing and letter spacing, and adjusting the space \
|
||||
between pairs of letters.";
|
||||
|
||||
fn db() -> &'static FontDb {
|
||||
FontDb::global()
|
||||
}
|
||||
|
||||
fn area(text: &str, size: f64, frame: Rect, fit: AreaFit) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, text, CharStyle { size, ..CharStyle::default() });
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.area.fit = fit;
|
||||
t
|
||||
}
|
||||
|
||||
fn shrink(min_percent: f64) -> AreaFit {
|
||||
AreaFit::ShrinkText { min_percent }
|
||||
}
|
||||
|
||||
/// `t` laid out without fitting at `size` (every run).
|
||||
fn at_size(t: &TextObject, size: f64) -> TextLayout {
|
||||
let mut p = t.clone();
|
||||
p.area.fit = AreaFit::None;
|
||||
for r in &mut p.runs {
|
||||
r.style.size = size;
|
||||
}
|
||||
layout(db(), &p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_makes_overflowing_text_fit() {
|
||||
let t = area(COPY, 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(30.0));
|
||||
assert!(at_size(&t, 14.0).overflow, "the text overflows at full size");
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow, "shrunk to fit");
|
||||
assert!(l.fit_scale < 1.0 && l.fit_scale >= 0.3, "{}", l.fit_scale);
|
||||
assert!(l.glyphs.len() > 100);
|
||||
// The first run's scaled size is a whole number of tenths of a point.
|
||||
let size = 14.0 * l.fit_scale;
|
||||
assert!((size * 10.0 - (size * 10.0).round()).abs() < 1e-6, "{size}");
|
||||
// Maximal: a tenth of a point larger overflows; and the layout is the one at that size.
|
||||
assert!(at_size(&t, size + 0.1).overflow, "{size} + 0.1 pt still fits");
|
||||
let same = at_size(&t, size);
|
||||
assert_eq!((same.lines.len(), same.glyphs.len(), same.overflow), (l.lines.len(), l.glyphs.len(), false));
|
||||
// Deterministic.
|
||||
assert_eq!(layout(db(), &t).fit_scale, l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_respects_its_minimum() {
|
||||
let t = area(COPY, 14.0, Rect::new(0.0, 0.0, 120.0, 40.0), shrink(90.0));
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.overflow, "still overflows at 90 %");
|
||||
assert!((l.fit_scale - 0.9).abs() < 1e-9, "{}", l.fit_scale);
|
||||
// Out-of-range minimums are clamped (10 %).
|
||||
let l = layout(db(), &area(COPY, 14.0, Rect::new(0.0, 0.0, 120.0, 40.0), shrink(0.0)));
|
||||
assert!(l.fit_scale >= 0.1 - 1e-9, "{}", l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_is_a_no_op_when_the_text_fits() {
|
||||
let t = area("Short text", 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(50.0));
|
||||
let l = layout(db(), &t);
|
||||
let plain = at_size(&t, 14.0);
|
||||
assert!(!l.overflow);
|
||||
assert_eq!(l.fit_scale, 1.0);
|
||||
let o = |l: &TextLayout| l.glyphs.iter().map(|g| g.origin).collect::<Vec<_>>();
|
||||
assert_eq!(o(&l), o(&plain));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_fills_columns() {
|
||||
let mut t = area(COPY, 14.0, Rect::new(0.0, 0.0, 300.0, 70.0), shrink(20.0));
|
||||
t.area.columns = 2;
|
||||
t.area.gutter = 12.0;
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow);
|
||||
assert!(l.fit_scale < 1.0);
|
||||
assert_eq!(l.frames.len(), 2);
|
||||
let second = l.frames[1];
|
||||
assert!(l.glyphs.iter().any(|g| g.origin.x >= second.x0), "text flows into the second column");
|
||||
let size = 14.0 * l.fit_scale;
|
||||
assert!(at_size(&t, size + 0.1).overflow, "maximal across columns too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_scales_leading_and_baseline_shift_not_paragraph_spacing() {
|
||||
let mut t = area(©.repeat(2), 12.0, Rect::new(0.0, 0.0, 200.0, 200.0), shrink(10.0));
|
||||
for r in &mut t.runs {
|
||||
r.style.leading = Some(20.0);
|
||||
}
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow && l.fit_scale < 1.0);
|
||||
let gap = l.lines[2].baseline - l.lines[1].baseline;
|
||||
assert!((gap - 20.0 * l.fit_scale).abs() < 1e-6, "{gap} vs {}", 20.0 * l.fit_scale);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_type_on_a_path_ignore_fit() {
|
||||
let mut t = TextObject::point(Point::ZERO, COPY, CharStyle::default());
|
||||
t.area.fit = shrink(10.0);
|
||||
assert_eq!(layout(db(), &t).fit_scale, 1.0);
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&kurbo::Line::new((0.0, 0.0), (50.0, 0.0)).to_path(0.1)), start: 0.0, end: None };
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.overflow, "text runs past the path end");
|
||||
assert_eq!(l.fit_scale, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_guards_degenerate_sizes() {
|
||||
for size in [0.0, 0.01, f64::NAN, 1296.0] {
|
||||
let l = layout(db(), &area(COPY, size, Rect::new(0.0, 0.0, 50.0, 20.0), shrink(10.0)));
|
||||
assert!(l.fit_scale.is_finite() && l.fit_scale > 0.0 && l.fit_scale <= 1.0, "{size}: {}", l.fit_scale);
|
||||
}
|
||||
// A zero-height frame.
|
||||
let l = layout(db(), &area(COPY, 12.0, Rect::new(0.0, 0.0, 50.0, 0.0), shrink(10.0)));
|
||||
assert!(l.overflow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shrink_text_follows_top_to_top_leading_and_character_alignment() {
|
||||
use vectorcraft_doc::{CharAlign, LeadingModel, TextRun};
|
||||
// Mixed sizes aligned on the em box centre, leading measured from em box top to top.
|
||||
let mut t = area(COPY, 14.0, Rect::new(0.0, 0.0, 200.0, 90.0), shrink(20.0));
|
||||
t.para.leading_model = LeadingModel::EmBoxTop;
|
||||
let big = CharStyle { size: 28.0, leading: Some(32.0), char_align: CharAlign::EmBoxCenter, ..CharStyle::default() };
|
||||
t.runs.insert(0, TextRun { text: "Big ".into(), style: big, inline: None });
|
||||
for r in &mut t.runs {
|
||||
r.style.char_align = CharAlign::EmBoxCenter;
|
||||
}
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow, "shrunk to fit under the top-to-top model");
|
||||
assert!(l.fit_scale < 1.0);
|
||||
// The shrunk layout is the same text laid out at the scaled sizes and leading.
|
||||
let mut manual = t.clone();
|
||||
manual.area.fit = AreaFit::None;
|
||||
for r in &mut manual.runs {
|
||||
r.style.size *= l.fit_scale;
|
||||
r.style.leading = r.style.leading.map(|v| v * l.fit_scale);
|
||||
}
|
||||
let m = layout(db(), &manual);
|
||||
let o = |l: &TextLayout| l.glyphs.iter().map(|g| (g.origin.x, g.origin.y)).collect::<Vec<_>>();
|
||||
assert_eq!(o(&l), o(&m));
|
||||
// First line still touches the frame top (top-to-top: em box top at y = 0, scaled).
|
||||
let first = l.lines.first().map(|li| li.baseline).unwrap_or(0.0);
|
||||
assert!(first > 0.0 && first <= 28.0 * l.fit_scale + 1e-6, "{first}");
|
||||
// Maximal: the next 0.1 pt step of the first run overflows.
|
||||
let step = 0.1 / 28.0;
|
||||
let mut bigger = manual.clone();
|
||||
for (r, orig) in bigger.runs.iter_mut().zip(&t.runs) {
|
||||
r.style.size = orig.style.size * (l.fit_scale + step);
|
||||
r.style.leading = orig.style.leading.map(|v| v * (l.fit_scale + step));
|
||||
}
|
||||
assert!(layout(db(), &bigger).overflow);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Inline graphics in text: a symbol's art laid out like a glyph.
|
||||
|
||||
use super::*;
|
||||
use kurbo::{Affine, Shape};
|
||||
use vectorcraft_doc::text::INLINE_CHAR;
|
||||
use vectorcraft_doc::{CharStyle, InlineArt, Justify, TextKind, TextRun};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
use crate::edit;
|
||||
|
||||
fn db() -> &'static FontDb {
|
||||
static DB: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
|
||||
DB.get_or_init(|| FontDb::with_font_dirs(vec![]))
|
||||
}
|
||||
|
||||
fn style(size: f64) -> CharStyle {
|
||||
CharStyle { size, ..CharStyle::default() }
|
||||
}
|
||||
|
||||
/// Art 20 × 10 (2:1), as a symbol's resolved bounds.
|
||||
fn art(scale: f64) -> InlineArt {
|
||||
InlineArt { scale, bounds: Some(Rect::new(-10.0, -5.0, 10.0, 5.0)), ..InlineArt::new("mana") }
|
||||
}
|
||||
|
||||
/// Point type: `before`, the inline graphic, `after`.
|
||||
fn text(before: &str, a: InlineArt, after: &str, size: f64) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, before, style(size));
|
||||
t.runs.push(TextRun::inline(a, style(size)));
|
||||
t.runs.push(TextRun::new(after, style(size)));
|
||||
t
|
||||
}
|
||||
|
||||
fn inline_glyph(l: &TextLayout) -> &PositionedGlyph {
|
||||
l.glyphs.iter().find(|g| g.run == 1).expect("inline glyph")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_art_advances_by_its_scaled_width_and_centres_on_the_cap_height() {
|
||||
let t = text("A", art(1.0), "B", 20.0);
|
||||
let l = layout(db(), &t);
|
||||
let g = inline_glyph(&l);
|
||||
// 20 pt tall → 40 pt wide (2:1), no outline of its own.
|
||||
assert!((g.advance - 40.0).abs() < 1e-6, "{}", g.advance);
|
||||
assert!(g.outline.elements().is_empty());
|
||||
assert_eq!(g.len, INLINE_CHAR.len_utf8());
|
||||
assert_eq!(l.inlines.len(), 1);
|
||||
let ig = &l.inlines[0];
|
||||
assert_eq!((ig.run, ig.byte, ig.glyph), (1, 1, l.glyphs.iter().position(|g| g.run == 1).unwrap()));
|
||||
// Left edge on the pen; vertical centre half the cap height above the baseline.
|
||||
let face = db().face("Source Sans 3", "Regular").unwrap();
|
||||
let cap = face.cap_height * 20.0 / face.upem;
|
||||
let b = ig.bounds;
|
||||
assert!((b.x0 - g.origin.x).abs() < 1e-6 && (b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "{b:?}");
|
||||
assert!((b.center().y + cap * 0.5).abs() < 1e-6, "{b:?} cap {cap}");
|
||||
// The art's transform maps its bounds there.
|
||||
let mapped = ig.xf.transform_rect_bbox(Rect::new(-10.0, -5.0, 10.0, 5.0));
|
||||
assert!((mapped.x0 - b.x0).abs() < 1e-6 && (mapped.y1 - b.y1).abs() < 1e-6);
|
||||
// `B` follows it; the layout bounds include it.
|
||||
let next = l.glyphs.iter().find(|g| g.run == 2).unwrap();
|
||||
assert!((next.origin.x - (g.origin.x + 40.0)).abs() < 1e-6);
|
||||
assert!(l.bounds.contains(b.origin()) && l.bounds.x1 >= b.x1 - 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_tracking_and_missing_symbols() {
|
||||
let up = InlineArt { baseline_shift: 4.0, ..art(1.0) };
|
||||
let a = layout(db(), &text("A", art(1.0), "B", 20.0)).inlines[0].bounds;
|
||||
let b = layout(db(), &text("A", up, "B", 20.0)).inlines[0].bounds;
|
||||
assert!((a.y0 - b.y0 - 4.0).abs() < 1e-6, "{a:?} {b:?}");
|
||||
// Tracking adds to the advance as it does after a glyph.
|
||||
let mut t = text("A", art(1.0), "B", 20.0);
|
||||
t.runs[1].style.tracking = 100.0;
|
||||
assert!((inline_glyph(&layout(db(), &t)).advance - 42.0).abs() < 1e-6);
|
||||
// Unresolved (missing symbol): a square of the height, nothing to draw.
|
||||
let t = text("A", InlineArt::new("gone"), "B", 20.0);
|
||||
let l = layout(db(), &t);
|
||||
assert!((inline_glyph(&l).advance - 20.0).abs() < 1e-6);
|
||||
assert!(l.inlines.is_empty());
|
||||
// Junk numbers stay finite.
|
||||
let t = text("A", InlineArt { scale: f64::NAN, baseline_shift: f64::INFINITY, ..art(1.0) }, "B", 20.0);
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.bounds.is_finite() && l.glyphs.iter().all(|g| g.advance.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_inline_art_opens_up_its_line() {
|
||||
let plain = layout(db(), &text("Ab", art(1.0), "cd", 20.0));
|
||||
let tall = layout(db(), &text("Ab", art(3.0), "cd", 20.0));
|
||||
let face = db().face("Source Sans 3", "Regular").unwrap();
|
||||
let cap = face.cap_height * 20.0 / face.upem;
|
||||
// At scale 1 the art stays inside the font's ascent and descent: the line doesn't change.
|
||||
let font_only = layout(db(), &TextObject::point(Point::ZERO, "Abcd", style(20.0)));
|
||||
assert!((plain.lines[0].ascent - font_only.lines[0].ascent).abs() < 1e-6);
|
||||
assert!((plain.lines[0].descent - font_only.lines[0].descent).abs() < 1e-6);
|
||||
// 60 pt tall: half above the cap-height middle, half below.
|
||||
assert!((tall.lines[0].ascent - (cap * 0.5 + 30.0)).abs() < 1e-6, "{:?}", tall.lines[0]);
|
||||
assert!((tall.lines[0].descent - (30.0 - cap * 0.5)).abs() < 1e-6);
|
||||
// A second line moves down by the taller leading (Auto: 120% of the size) only where the
|
||||
// art is; the line's band (caret, selection, hit testing) covers the art.
|
||||
let mut t = text("Ab", art(3.0), "cd\nef", 20.0);
|
||||
t.runs[1].style.leading = None;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(l.lines.len(), 2);
|
||||
let (top, bottom) = caret_position(&l, 3);
|
||||
assert!(top.y <= l.inlines[0].bounds.y0 + 1e-6 && bottom.y >= l.inlines[0].bounds.y1 - 1e-6);
|
||||
let mid = l.inlines[0].bounds.center();
|
||||
assert_eq!(l.line_of(hit_byte(&l, mid)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_breaking_moves_an_inline_graphic_like_a_word() {
|
||||
// The frame is just wider than "tap tap ": the 40 pt graphic doesn't fit after it.
|
||||
let w: f64 = layout(db(), &TextObject::point(Point::ZERO, "tap tap ", style(20.0))).glyphs.iter().map(|g| g.advance).sum();
|
||||
let frame = Rect::new(0.0, 0.0, w + 10.0, 200.0);
|
||||
let area = |t: &mut TextObject| {
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame.to_path(0.1)) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.para.justify = Justify::Left;
|
||||
};
|
||||
let mut t = text("tap tap ", art(1.0), " done", 20.0);
|
||||
area(&mut t);
|
||||
let l = layout(db(), &t);
|
||||
let g = inline_glyph(&l);
|
||||
assert_eq!(g.line, 1, "the graphic wraps to the next line");
|
||||
// It starts that line, at the frame's left edge, its art with it.
|
||||
assert!((g.origin.x - l.lines[1].x0).abs() < 1e-6 && l.lines[1].x0.abs() < 1e-6);
|
||||
assert!((l.inlines[0].bounds.x0 - g.origin.x).abs() < 1e-6);
|
||||
assert!(l.inlines[0].bounds.center().y > l.lines[0].baseline);
|
||||
// No break between the graphic and punctuation stuck to it.
|
||||
let mut t2 = text("tap tap ", art(1.0), ".", 20.0);
|
||||
area(&mut t2);
|
||||
let l2 = layout(db(), &t2);
|
||||
assert_eq!(l2.glyphs.iter().find(|g| g.run == 2).unwrap().line, inline_glyph(&l2).line);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_art_on_a_path_and_in_vertical_type_moves_with_the_text() {
|
||||
let mut t = text("ab", art(1.0), "cd", 20.0);
|
||||
let path = kurbo::Line::new((0.0, 0.0), (400.0, 0.0)).to_path(0.1);
|
||||
t.kind = TextKind::OnPath { path: PathData::from_bezpath(&path), start: 0.0, end: None };
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(l.inlines.len(), 1);
|
||||
let g = inline_glyph(&l);
|
||||
assert!((l.inlines[0].bounds.x0 - g.origin.x).abs() < 1e-6);
|
||||
let mut v = text("ab", art(1.0), "cd", 20.0);
|
||||
v.vertical = true;
|
||||
let l = layout(db(), &v);
|
||||
assert_eq!(l.inlines.len(), 1);
|
||||
assert!(l.bounds.contains(l.inlines[0].bounds.center()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapping_moves_inline_art_with_its_glyph() {
|
||||
let mut l = layout(db(), &text("A", art(1.0), "B", 20.0));
|
||||
let before = (l.inlines[0].bounds, inline_glyph(&l).origin);
|
||||
l.snap_to_pixels(Affine::translate((0.3, 0.3)));
|
||||
let after = (l.inlines[0].bounds, inline_glyph(&l).origin);
|
||||
let d = after.1 - before.1;
|
||||
assert!(((after.0.x0 - before.0.x0) - d.x).abs() < 1e-9 && ((after.0.y0 - before.0.y0) - d.y).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_keeps_inline_runs_whole() {
|
||||
let t = text("ab", art(1.0), "cd", 12.0);
|
||||
let mut runs = t.runs.clone();
|
||||
// Same style on both sides: the plain runs still never merge into the graphic.
|
||||
edit::normalize(&mut runs);
|
||||
assert_eq!(runs.len(), 3);
|
||||
assert!(runs[1].inline.is_some() && runs[1].text == INLINE_CHAR.to_string());
|
||||
// Typing next to it makes plain text.
|
||||
let caret = edit::replace_range(&mut runs, 5, 5, "X");
|
||||
assert_eq!(caret, 6);
|
||||
assert_eq!(runs.len(), 3);
|
||||
assert_eq!(runs[2].text, "Xcd");
|
||||
let caret = edit::replace_range(&mut runs, 2, 2, "Y");
|
||||
assert_eq!((caret, runs[0].text.as_str()), (3, "abY"));
|
||||
// An offset inside its character lands before it: nothing splits it.
|
||||
let plain: String = runs.iter().map(|r| r.text.as_str()).collect();
|
||||
let at = plain.find(INLINE_CHAR).unwrap();
|
||||
edit::replace_range(&mut runs, at + 1, at + 1, "Z");
|
||||
assert!(runs.iter().any(|r| r.inline.is_some() && r.text == INLINE_CHAR.to_string()));
|
||||
// Backspace over it (its one character) removes the whole graphic.
|
||||
let plain: String = runs.iter().map(|r| r.text.as_str()).collect();
|
||||
let at = plain.find(INLINE_CHAR).unwrap();
|
||||
let prev = edit::prev_char(&plain, at + INLINE_CHAR.len_utf8());
|
||||
assert_eq!(prev, at);
|
||||
edit::replace_range(&mut runs, prev, at + INLINE_CHAR.len_utf8(), "");
|
||||
assert!(runs.iter().all(|r| r.inline.is_none()));
|
||||
assert!(!runs.iter().any(|r| r.text.contains(INLINE_CHAR)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copying_keeps_the_graphic_and_plain_text_shows_the_replacement_character() {
|
||||
let t = text("ab", art(2.0), "cd", 12.0);
|
||||
let copy = edit::slice_runs(&t.runs, 1, 6);
|
||||
let plain: String = copy.iter().map(|r| r.text.as_str()).collect();
|
||||
assert_eq!(plain, format!("b{INLINE_CHAR}c"));
|
||||
assert_eq!(copy[1].inline.as_ref().map(|a| a.scale), Some(2.0));
|
||||
// Half of its character is nothing (no empty graphic runs).
|
||||
let half = edit::slice_runs(&t.runs, 2, 3);
|
||||
assert!(half.is_empty(), "{half:?}");
|
||||
// Pasting it back keeps it.
|
||||
let mut runs = t.runs.clone();
|
||||
edit::replace_range_styled(&mut runs, 0, 0, ©);
|
||||
assert_eq!(runs.iter().filter(|r| r.inline.is_some()).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_inline_runs_are_plain_text() {
|
||||
let mut runs = vec![TextRun { text: "abc".into(), style: style(12.0), inline: Some(art(1.0)) }];
|
||||
edit::normalize(&mut runs);
|
||||
assert!(runs[0].inline.is_none());
|
||||
let mut t = TextObject::point(Point::ZERO, "", style(12.0));
|
||||
t.runs = vec![TextRun { text: format!("{INLINE_CHAR}{INLINE_CHAR}"), style: style(12.0), inline: Some(art(1.0)) }];
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.inlines.is_empty());
|
||||
}
|
||||
|
||||
/// An inline graphic is an object replacement character (U+FFFC, a bidi neutral): in right-to-left
|
||||
/// text it takes the direction of the text around it and the line's reordering places it, between
|
||||
/// two Hebrew words in reading order (right to left); between two English words set right to left
|
||||
/// it stays between them.
|
||||
#[test]
|
||||
fn inline_art_in_a_right_to_left_paragraph_is_placed_by_the_bidi_reordering() {
|
||||
use vectorcraft_doc::ParaDirection;
|
||||
let db = FontDb::global();
|
||||
let order = |before: &str, after: &str, direction: Option<ParaDirection>| {
|
||||
let mut t = text(before, art(1.0), after, 20.0);
|
||||
(t.para.justify, t.para.direction) = (Justify::Auto, direction);
|
||||
let l = layout(db, &t);
|
||||
let x = |run: usize| l.glyphs.iter().filter(|g| g.run == run).map(|g| g.origin.x).fold(f64::NAN, f64::min);
|
||||
let g = inline_glyph(&l).clone();
|
||||
assert_eq!(l.inlines.len(), 1);
|
||||
// The art sits at its glyph, inside the line.
|
||||
assert!((l.inlines[0].bounds.x0 - g.origin.x).abs() < 1e-6, "{:?} {g:?}", l.inlines[0]);
|
||||
(x(0), g.origin.x, x(2), g.rtl, l.lines[0].rtl)
|
||||
};
|
||||
// Hebrew: the first word on the right, the graphic left of it, the second word further left.
|
||||
let (first, inline, second, inline_rtl, line_rtl) = order("שלום ", " עולם", None);
|
||||
assert!(line_rtl && inline_rtl);
|
||||
assert!(second < inline && inline < first, "{second} < {inline} < {first}");
|
||||
// English set right to left: the words keep their order with the graphic between them.
|
||||
let (first, inline, second, inline_rtl, line_rtl) = order("Hello", "world", Some(ParaDirection::RightToLeft));
|
||||
assert!(line_rtl && !inline_rtl);
|
||||
assert!(first < inline && inline < second, "{first} < {inline} < {second}");
|
||||
// At the end of a right-to-left paragraph it is the leftmost thing on the line.
|
||||
let (first, inline, _, inline_rtl, _) = order("שלום", "", None);
|
||||
assert!(inline_rtl && inline < first);
|
||||
}
|
||||
|
||||
/// Character Alignment: an inline graphic's em box is its run's, whatever its scale. It moves with
|
||||
/// its run's text when that is smaller than the line's largest characters, and a big graphic in
|
||||
/// small text doesn't make its line's small characters move.
|
||||
#[test]
|
||||
fn character_alignment_treats_inline_art_as_a_character_of_its_run_size() {
|
||||
use vectorcraft_doc::CharAlign;
|
||||
let centre_y = |a: CharAlign, scale: f64, big: f64| {
|
||||
let mut t = TextObject::point(Point::ZERO, "M", style(big));
|
||||
t.runs.push(TextRun::inline(art(scale), CharStyle { char_align: a, ..style(20.0) }));
|
||||
t.runs.push(TextRun::new("x", CharStyle { char_align: a, ..style(20.0) }));
|
||||
let l = layout(db(), &t);
|
||||
let x = l.glyphs.iter().find(|g| g.run == 2).map(|g| g.origin.y).unwrap();
|
||||
(l.inlines[0].bounds.center().y, x)
|
||||
};
|
||||
let face = db().face("Source Sans 3", "Regular").unwrap();
|
||||
let c = face.ideographic_centre();
|
||||
// Next to a 40 pt character, the 20 pt run (graphic and letter alike) moves up by the same.
|
||||
let (roman, roman_x) = centre_y(CharAlign::RomanBaseline, 1.0, 40.0);
|
||||
for (a, k) in [(CharAlign::EmBoxTop, 0.5), (CharAlign::EmBoxCenter, 0.0), (CharAlign::EmBoxBottom, -0.5)] {
|
||||
let (y, x) = centre_y(a, 1.0, 40.0);
|
||||
let want = (c + k) * 20.0;
|
||||
assert!((roman - y - want).abs() < 1e-6, "{a:?}: {} vs {want}", roman - y);
|
||||
assert!(((roman_x - x) - (roman - y)).abs() < 1e-6, "{a:?}: the graphic moves with its run's letters");
|
||||
}
|
||||
// A 60 pt tall graphic in a line of 20 pt text: the line's largest em is still 20 pt, so
|
||||
// nothing moves.
|
||||
let (roman, roman_x) = centre_y(CharAlign::RomanBaseline, 3.0, 20.0);
|
||||
let (top, top_x) = centre_y(CharAlign::EmBoxTop, 3.0, 20.0);
|
||||
assert!((roman - top).abs() < 1e-6 && (roman_x - top_x).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Top-to-Top leading measures from the em box tops: an inline graphic's is its run's, so a line
|
||||
/// with a tall graphic is spaced like its text (as Roman leading spaces it by its run's leading).
|
||||
#[test]
|
||||
fn top_to_top_leading_spaces_inline_art_by_its_run() {
|
||||
use vectorcraft_doc::LeadingModel;
|
||||
let lines = |scale: f64| {
|
||||
let mut t = text("Ab", art(scale), "cd\nef", 20.0);
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1)) };
|
||||
t.para.leading_model = LeadingModel::EmBoxTop;
|
||||
let l = layout(db(), &t);
|
||||
assert_eq!(l.lines.len(), 2);
|
||||
(l.lines[0].baseline, l.lines[1].baseline)
|
||||
};
|
||||
let (small0, small1) = lines(1.0);
|
||||
let (tall0, tall1) = lines(3.0);
|
||||
assert!((small0 - tall0).abs() < 1e-6 && (small1 - tall1).abs() < 1e-6, "{small0} {small1} / {tall0} {tall1}");
|
||||
}
|
||||
@@ -15,7 +15,7 @@ fn style(size: f64) -> CharStyle {
|
||||
}
|
||||
|
||||
fn run(text: &str, size: f64) -> TextRun {
|
||||
TextRun { text: text.into(), style: style(size) }
|
||||
TextRun { text: text.into(), style: style(size), inline: None }
|
||||
}
|
||||
|
||||
fn area_path(text: &str, st: CharStyle, frame: &BezPath, justify: Justify) -> TextObject {
|
||||
@@ -613,7 +613,7 @@ fn vertical_align_with_top_to_top_leading() {
|
||||
use vectorcraft_doc::LeadingModel;
|
||||
let st = |size: f64| CharStyle { size, leading: Some(size * 1.5), ..style(size) };
|
||||
let mut t = area("", st(40.0), Rect::new(0.0, 0.0, 200.0, 300.0), Justify::Left);
|
||||
t.runs = vec![TextRun { text: "大\n".into(), style: st(40.0) }, TextRun { text: "小\n中".into(), style: st(20.0) }];
|
||||
t.runs = vec![TextRun { text: "大\n".into(), style: st(40.0), inline: None }, TextRun { text: "小\n中".into(), style: st(20.0), inline: None }];
|
||||
t.para.leading_model = LeadingModel::EmBoxTop;
|
||||
let top = layout(db(), &t);
|
||||
assert_eq!(top.lines.len(), 3);
|
||||
|
||||
+95
-12
@@ -4,7 +4,7 @@
|
||||
//! testing need nothing special; after an edit the engine joins the slices and re-distributes them
|
||||
//! with [`distribute`].
|
||||
|
||||
use vectorcraft_doc::{TextObject, TextRun};
|
||||
use vectorcraft_doc::{ParaStyle, TextObject, TextRun};
|
||||
|
||||
use crate::edit::{normalize, runs_len, slice_runs, style_at};
|
||||
use crate::{FontDb, layout};
|
||||
@@ -16,6 +16,36 @@ pub fn story(frames: &[&TextObject]) -> Vec<TextRun> {
|
||||
runs
|
||||
}
|
||||
|
||||
/// The story's paragraph styles, one per story paragraph. A frame whose slice ends inside a
|
||||
/// paragraph shares that paragraph with the next frame (its first one): the earlier frame's style
|
||||
/// wins unless `later_wins[k]` says frame `k`'s first paragraph should (it was just restyled), or
|
||||
/// the earlier frame's part of the paragraph is empty (its slice ends with a paragraph break).
|
||||
pub fn story_paras(frames: &[&TextObject], later_wins: &[bool]) -> Vec<ParaStyle> {
|
||||
let mut out: Vec<ParaStyle> = vec![];
|
||||
let mut prev_empty_tail = true;
|
||||
for (k, f) in frames.iter().enumerate() {
|
||||
let mut styles = f.paragraph_styles().into_iter();
|
||||
if k > 0
|
||||
&& let Some(first) = styles.next()
|
||||
&& (prev_empty_tail || later_wins.get(k).copied().unwrap_or(false))
|
||||
&& let Some(last) = out.last_mut()
|
||||
{
|
||||
*last = first;
|
||||
}
|
||||
out.extend(styles);
|
||||
let text = f.plain_text();
|
||||
prev_empty_tail = text.is_empty() || text.ends_with('\n') || out.is_empty();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Paragraph styles of the slice `runs` of a story starting at story paragraph `first`.
|
||||
fn slice_paras(paras: &[ParaStyle], first: usize, runs: &[TextRun]) -> Vec<ParaStyle> {
|
||||
let n = 1 + runs.iter().map(|r| r.text.bytes().filter(|&b| b == b'\n').count()).sum::<usize>();
|
||||
let fallback = paras.last().cloned().unwrap_or_default();
|
||||
(first..first + n).map(|i| paras.get(i).cloned().unwrap_or_else(|| fallback.clone())).collect()
|
||||
}
|
||||
|
||||
/// How many bytes of `runs` fit in `frame` (whole lines; a following break space or paragraph
|
||||
/// break stays with the line that ends there).
|
||||
fn fit(db: &FontDb, frame: &TextObject, runs: &[TextRun]) -> usize {
|
||||
@@ -37,21 +67,43 @@ fn fit(db: &FontDb, frame: &TextObject, runs: &[TextRun]) -> usize {
|
||||
end
|
||||
}
|
||||
|
||||
/// The story `runs` split across `frames` in order (the last frame takes any overflow). Empty
|
||||
/// slices keep one empty run carrying the style at the split, so typing there has a style.
|
||||
pub fn distribute(db: &FontDb, frames: &[&TextObject], runs: &[TextRun]) -> Vec<Vec<TextRun>> {
|
||||
/// A frame's share of a story: its runs and its paragraphs' styles (one per paragraph).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Slice {
|
||||
pub runs: Vec<TextRun>,
|
||||
pub paras: Vec<ParaStyle>,
|
||||
}
|
||||
|
||||
/// The story `runs` (with paragraph styles `paras`, one per story paragraph; empty = each
|
||||
/// frame's own) split across `frames` in order (the last frame takes any overflow). Empty slices
|
||||
/// keep one empty run carrying the style at the split, so typing there has a style. A paragraph
|
||||
/// split between frames has its style in both.
|
||||
pub fn distribute(db: &FontDb, frames: &[&TextObject], runs: &[TextRun], paras: &[ParaStyle]) -> Vec<Slice> {
|
||||
let mut rest = runs.to_vec();
|
||||
let mut out = Vec::with_capacity(frames.len());
|
||||
let mut next_para = 0;
|
||||
for (i, f) in frames.iter().enumerate() {
|
||||
let first_para = next_para;
|
||||
let len = runs_len(&rest);
|
||||
let n = if i + 1 == frames.len() { len } else { fit(db, f, &rest) };
|
||||
let own = [f.para.clone()];
|
||||
let (paras, first_para) = if paras.is_empty() { (&own[..], 0) } else { (paras, first_para) };
|
||||
let n = if i + 1 == frames.len() {
|
||||
len
|
||||
} else {
|
||||
let mut probe = (*f).clone();
|
||||
probe.runs = rest.clone();
|
||||
probe.set_paragraph_styles(slice_paras(paras, first_para, &rest));
|
||||
fit(db, &probe, &rest)
|
||||
};
|
||||
let mut head = slice_runs(&rest, 0, n);
|
||||
if head.is_empty() {
|
||||
head.push(TextRun { text: String::new(), style: style_at(&rest, n) });
|
||||
head.push(TextRun { text: String::new(), style: style_at(&rest, n), inline: None });
|
||||
}
|
||||
let tail = slice_runs(&rest, n, len);
|
||||
rest = if tail.is_empty() { vec![TextRun { text: String::new(), style: style_at(&rest, len) }] } else { tail };
|
||||
out.push(head);
|
||||
rest = if tail.is_empty() { vec![TextRun { text: String::new(), style: style_at(&rest, len), inline: None }] } else { tail };
|
||||
let head_paras = slice_paras(paras, first_para, &head);
|
||||
next_para += head_paras.len().saturating_sub(1);
|
||||
out.push(Slice { runs: head, paras: head_paras });
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -59,7 +111,7 @@ pub fn distribute(db: &FontDb, frames: &[&TextObject], runs: &[TextRun]) -> Vec<
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::{CharStyle, TextKind};
|
||||
use vectorcraft_doc::{CharStyle, Justify, TextKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
fn frame(x: f64) -> TextObject {
|
||||
@@ -74,8 +126,8 @@ mod tests {
|
||||
let db = FontDb::global();
|
||||
let (a, b, c) = (frame(0.0), frame(200.0), frame(400.0));
|
||||
let text = "The quick brown fox jumps over the lazy dog. ".repeat(6) + "\nSecond paragraph here.";
|
||||
let story = vec![TextRun { text: text.clone(), style: CharStyle::default() }];
|
||||
let parts = distribute(db, &[&a, &b, &c], &story);
|
||||
let story = vec![TextRun { text: text.clone(), style: CharStyle::default(), inline: None }];
|
||||
let parts: Vec<Vec<TextRun>> = distribute(db, &[&a, &b, &c], &story, &[]).into_iter().map(|s| s.runs).collect();
|
||||
let lens: Vec<usize> = parts.iter().map(|p| runs_len(p)).collect();
|
||||
assert!(lens[0] > 0 && lens[1] > 0, "{lens:?}");
|
||||
let joined: String = parts.iter().flatten().map(|r| r.text.as_str()).collect();
|
||||
@@ -90,12 +142,43 @@ mod tests {
|
||||
assert!(!parts[1][0].text.starts_with(' '));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_styles_flow_with_their_paragraphs() {
|
||||
let db = FontDb::global();
|
||||
let (a, b) = (frame(0.0), frame(200.0));
|
||||
let text = "The quick brown fox jumps over the lazy dog. ".repeat(4) + "\nSecond paragraph.\nThird.";
|
||||
let story = vec![TextRun { text, style: CharStyle::default(), inline: None }];
|
||||
let style = |j| ParaStyle { justify: j, ..Default::default() };
|
||||
use vectorcraft_doc::Justify::*;
|
||||
let paras = vec![style(Left), style(Center), style(Right)];
|
||||
let parts = distribute(db, &[&a, &b], &story, ¶s);
|
||||
assert!(!parts[0].runs.is_empty() && !parts[1].runs.is_empty());
|
||||
// The first paragraph overflows into the second frame: it is in both, with its style.
|
||||
let pa: Vec<Justify> = parts[0].paras.iter().map(|p| p.justify).collect();
|
||||
let pb: Vec<Justify> = parts[1].paras.iter().map(|p| p.justify).collect();
|
||||
assert_eq!(pa, [Left]);
|
||||
assert_eq!(pb, [Left, Center, Right]);
|
||||
// Joined again, the shared paragraph counts once.
|
||||
let mut fa = a.clone();
|
||||
fa.runs = parts[0].runs.clone();
|
||||
fa.set_paragraph_styles(parts[0].paras.clone());
|
||||
let mut fb = b.clone();
|
||||
fb.runs = parts[1].runs.clone();
|
||||
fb.set_paragraph_styles(parts[1].paras.clone());
|
||||
assert_eq!(story_paras(&[&fa, &fb], &[]), paras);
|
||||
// A frame whose shared first paragraph was restyled wins.
|
||||
fb.edit_paras(Some(0..1), |p| p.justify = JustifyAll);
|
||||
assert_eq!(story_paras(&[&fa, &fb], &[false, true])[0].justify, JustifyAll);
|
||||
assert_eq!(story_paras(&[&fa, &fb], &[false, false])[0].justify, Left);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_story_leaves_later_frames_empty_with_a_style() {
|
||||
let db = FontDb::global();
|
||||
let (a, b) = (frame(0.0), frame(200.0));
|
||||
let st = CharStyle { size: 20.0, ..Default::default() };
|
||||
let parts = distribute(db, &[&a, &b], &[TextRun { text: "Hi".into(), style: st }]);
|
||||
let parts: Vec<Vec<TextRun>> =
|
||||
distribute(db, &[&a, &b], &[TextRun { text: "Hi".into(), style: st, inline: None }], &[]).into_iter().map(|s| s.runs).collect();
|
||||
assert_eq!(parts[0][0].text, "Hi");
|
||||
assert_eq!((parts[1][0].text.as_str(), parts[1][0].style.size), ("", 20.0));
|
||||
}
|
||||
|
||||
@@ -105,6 +105,12 @@ pub fn leaf_shapes<'a>(n: &'a Node, out: &mut Vec<&'a Node>) {
|
||||
if !n.visible {
|
||||
return;
|
||||
}
|
||||
if n.shaper.is_some() {
|
||||
for c in n.children().into_iter().flatten().skip(1) {
|
||||
leaf_shapes(c, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => {}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push(n),
|
||||
@@ -256,7 +262,7 @@ impl BuilderMap {
|
||||
}
|
||||
|
||||
/// The regions just either side of the middle of `piece` (None: outside every region).
|
||||
fn sides(&self, piece: &po::Shape) -> [Option<usize>; 2] {
|
||||
pub fn sides(&self, piece: &po::Shape) -> [Option<usize>; 2] {
|
||||
let Some(sp) = piece.path.subpaths.first() else { return [None; 2] };
|
||||
let n = sp.segment_count();
|
||||
if n == 0 {
|
||||
|
||||
+19
-20
@@ -238,43 +238,42 @@ impl Tool for ShaperTool {
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
if !self.points.is_empty() && self.points.last().is_none_or(|l| l.distance(ev.pos) >= cx.tol(1.5)) {
|
||||
if !self.points.is_empty() && self.points.len() < 4095 && self.points.last().is_none_or(|l| l.distance(ev.pos) >= cx.tol(1.5)) {
|
||||
self.points.push(ev.pos);
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Up => {
|
||||
// A fast final segment may arrive only on release; it still closes the stroke.
|
||||
if !self.points.is_empty() && self.points.last().is_none_or(|p| *p != ev.pos) {
|
||||
self.points.push(ev.pos);
|
||||
}
|
||||
let pts = std::mem::take(&mut self.points);
|
||||
let r = |x: vectorcraft_geom::Rect| json!({ "x": x.x0, "y": x.y0, "width": x.width(), "height": x.height() });
|
||||
if pts.first().is_some_and(|first| pts.iter().all(|p| p.distance(*first) < cx.tol(3.0))) {
|
||||
return vec![Action::Exec("shaper.select".into(), json!({"point": [ev.pos.x, ev.pos.y]}))];
|
||||
}
|
||||
let r = |x: vectorcraft_geom::Rect, rotation: f64| json!({ "x": x.x0, "y": x.y0, "width": x.width(), "height": x.height(), "rotation": rotation });
|
||||
match recognize(&pts) {
|
||||
Some(Recognized::Line { a, b }) => vec![Action::Exec("shape.line".into(), json!({ "x1": a.x, "y1": a.y, "x2": b.x, "y2": b.y }))],
|
||||
Some(Recognized::Rectangle(x)) => vec![Action::Exec("shape.rectangle".into(), r(x))],
|
||||
Some(Recognized::Ellipse(x)) => vec![Action::Exec("shape.ellipse".into(), r(x))],
|
||||
Some(Recognized::Rectangle { rect, rotation }) => vec![Action::Exec("shape.rectangle".into(), r(rect, rotation))],
|
||||
Some(Recognized::Ellipse { rect, rotation }) => vec![Action::Exec("shape.ellipse".into(), r(rect, rotation))],
|
||||
Some(Recognized::Polygon { center, radius, sides, rotation }) => {
|
||||
vec![Action::Exec(
|
||||
"shape.polygon".into(),
|
||||
json!({ "cx": center.x, "cy": center.y, "radius": radius, "sides": sides, "rotation": rotation }),
|
||||
)]
|
||||
}
|
||||
Some(Recognized::Scribble(_)) => {
|
||||
// Delete the topmost objects the scribble crosses.
|
||||
let mut ids: Vec<u64> = vec![];
|
||||
for p in &pts {
|
||||
if let Some(h) = vectorcraft_doc::hit::hit_test(cx.doc, *p, cx.hit_options()) {
|
||||
let id = h.top_object(cx.isolation).0;
|
||||
if !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
vec![Action::Exec("select.set".into(), json!({ "ids": ids })), Action::Exec("edit.clear".into(), json!({ "ids": ids }))]
|
||||
}
|
||||
Some(Recognized::Scribble(_)) => vec![Action::Exec(
|
||||
"shaper.scribble".into(),
|
||||
json!({"points": pts.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(), "tolerance": cx.tol(4.0)}),
|
||||
)],
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
PointerKind::DoubleClick => vec![
|
||||
Action::Exec("shaper.select".into(), json!({"point": [ev.pos.x, ev.pos.y], "source": true})),
|
||||
Action::SwitchTool("selection".into()),
|
||||
],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,6 +378,7 @@ impl ToolContext<'_> {
|
||||
outline: self.outline,
|
||||
path_only: self.path_only,
|
||||
type_path_only: self.type_path_only,
|
||||
scope: self.isolation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,6 +364,13 @@ impl Tool for SelectionTool {
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut o = pathtype::overlays(cx);
|
||||
if let Some(source) = cx.isolation.and_then(|id| cx.doc.node(id)).filter(|n| n.name.as_deref() == Some(vectorcraft_doc::shaper::SOURCES)) {
|
||||
for n in source.children().into_iter().flatten() {
|
||||
if let Some(path) = n.path_data() {
|
||||
o.push(Overlay::Path { path: path.to_bezpath(), color: [0x80, 0x80, 0x80], width: 1.0, dashed: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
match &self.state {
|
||||
State::Marquee { start, cur, .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))),
|
||||
State::Corner(c) => o.extend(c.overlays(cx)),
|
||||
|
||||
@@ -44,6 +44,10 @@ enum Mode {
|
||||
struct Typing {
|
||||
base: Vec<TextRun>,
|
||||
cur: Vec<TextRun>,
|
||||
/// The first byte any edit of the session touched (the text before it is unchanged): the
|
||||
/// previewed span starts no later, so Return at a paragraph's end splits that paragraph (its
|
||||
/// style continues), not the next one.
|
||||
lo: usize,
|
||||
}
|
||||
|
||||
/// IME marked text inside the typing session, not yet committed.
|
||||
@@ -174,9 +178,10 @@ impl TypeTool {
|
||||
if self.typing.is_none() {
|
||||
out.push(Action::Begin("Typing".into()));
|
||||
}
|
||||
let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone() });
|
||||
let ty = self.typing.get_or_insert_with(|| Typing { base: t.runs.clone(), cur: t.runs.clone(), lo: usize::MAX });
|
||||
let len = edit::runs_len(&ty.cur);
|
||||
let (a, b) = (self.caret.min(self.anchor).min(len), self.caret.max(self.anchor).min(len));
|
||||
ty.lo = ty.lo.min(a);
|
||||
let caret = match &styled {
|
||||
Some(r) => edit::replace_range_styled(&mut ty.cur, a, b, r),
|
||||
None => edit::replace_range(&mut ty.cur, a, b, insert),
|
||||
@@ -187,7 +192,7 @@ impl TypeTool {
|
||||
// One preview for the whole session: the changed span of base → cur, with its runs.
|
||||
let base: String = ty.base.iter().map(|r| r.text.as_str()).collect();
|
||||
let cur: String = ty.cur.iter().map(|r| r.text.as_str()).collect();
|
||||
let (p, s) = common_affixes(&base, &cur);
|
||||
let (p, s) = common_affixes(&base, &cur, ty.lo);
|
||||
let runs = edit::slice_runs(&ty.cur, p, cur.len() - s);
|
||||
let runs = if runs.is_empty() { json!([]) } else { serde_json::to_value(&runs).unwrap_or(json!([])) };
|
||||
out.push(Action::Preview("text.editRange".into(), json!({"id": id.0, "start": p, "end": base.len() - s, "runs": runs})));
|
||||
@@ -332,11 +337,12 @@ fn char_range_to_bytes(s: &str, r: Range<usize>) -> Option<Range<usize>> {
|
||||
(a <= b).then_some(a..b)
|
||||
}
|
||||
|
||||
/// Lengths of the common prefix and suffix of `a` and `b` (on char boundaries, not overlapping).
|
||||
fn common_affixes(a: &str, b: &str) -> (usize, usize) {
|
||||
/// Lengths of the common prefix (at most `max_prefix`) and suffix of `a` and `b` (on char
|
||||
/// boundaries, not overlapping).
|
||||
fn common_affixes(a: &str, b: &str, max_prefix: usize) -> (usize, usize) {
|
||||
let mut p = 0;
|
||||
for ((i, x), y) in a.char_indices().zip(b.chars()) {
|
||||
if x != y {
|
||||
if x != y || i + x.len_utf8() > max_prefix {
|
||||
break;
|
||||
}
|
||||
p = i + x.len_utf8();
|
||||
|
||||
@@ -211,7 +211,7 @@ fn select_all_and_styled_paste() {
|
||||
let c = cx(&d, &sel, &p);
|
||||
tool.key(&c, ToolKey::Right, SHIFT);
|
||||
assert_eq!(tool.sel(), (0, 3));
|
||||
let big = TextRun { text: "XY".into(), style: CharStyle { size: 40.0, ..Default::default() } };
|
||||
let big = TextRun { text: "XY".into(), style: CharStyle { size: 40.0, ..Default::default() }, inline: None };
|
||||
tool.set_option("copy", &serde_json::to_value(vec![big.clone()]).unwrap());
|
||||
let acts = tool.text_input(&c, "XY");
|
||||
let Action::Preview(_, params) = acts.last().unwrap() else { panic!() };
|
||||
@@ -221,10 +221,13 @@ fn select_all_and_styled_paste() {
|
||||
|
||||
#[test]
|
||||
fn common_affixes_are_char_safe() {
|
||||
assert_eq!(common_affixes("hello", "help"), (3, 0));
|
||||
assert_eq!(common_affixes("aXb", "ab"), (1, 1));
|
||||
assert_eq!(common_affixes("aaa", "aaaa"), (3, 0));
|
||||
assert_eq!(common_affixes("é1", "è1"), (0, 1));
|
||||
assert_eq!(common_affixes("hello", "help", usize::MAX), (3, 0));
|
||||
assert_eq!(common_affixes("aXb", "ab", usize::MAX), (1, 1));
|
||||
assert_eq!(common_affixes("aaa", "aaaa", usize::MAX), (3, 0));
|
||||
assert_eq!(common_affixes("é1", "è1", usize::MAX), (0, 1));
|
||||
// Return at the end of a paragraph: the span starts where the edit did (before the old break).
|
||||
assert_eq!(common_affixes("abc\ndef", "abc\n\ndef", 3), (3, 4));
|
||||
assert_eq!(common_affixes("abc\ndef", "abc\n\ndef", 4), (4, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -259,10 +259,19 @@ impl Tool for ArtboardTool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete/Backspace remove the active artboard ahead of the Clear shortcut, which would only
|
||||
/// delete selected art; with one artboard left (it can't be deleted) they stay the shortcut's.
|
||||
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
|
||||
matches!(key, ToolKey::Delete | ToolKey::Backspace)
|
||||
&& self.drag.is_none()
|
||||
&& cx.doc.artboards.len() > 1
|
||||
&& self.active < cx.doc.artboards.len()
|
||||
}
|
||||
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
match key {
|
||||
ToolKey::Delete | ToolKey::Backspace if self.drag.is_none() => {
|
||||
if cx.doc.artboards.len() <= 1 || self.active >= cx.doc.artboards.len() {
|
||||
ToolKey::Delete | ToolKey::Backspace => {
|
||||
if !self.claims_key(cx, key) {
|
||||
return vec![];
|
||||
}
|
||||
let i = self.active;
|
||||
@@ -522,7 +531,8 @@ mod tests {
|
||||
let a = t.pointer(&cx, &ev(PointerKind::Up, 1100.0, 1050.0));
|
||||
assert_eq!(a[0], Action::Exec("artboard.new".into(), json!({"x": 1000.0, "y": 1000.0, "width": 100.0, "height": 50.0})));
|
||||
assert_eq!(a[1], Action::Notify("created".into()));
|
||||
// Delete removes the active artboard.
|
||||
// Delete removes the active artboard, ahead of the Clear shortcut.
|
||||
assert!(t.claims_key(&cx, ToolKey::Delete) && t.claims_key(&cx, ToolKey::Backspace));
|
||||
assert_eq!(t.key(&cx, ToolKey::Delete, Mods::default()), vec![Action::Exec("artboard.delete".into(), json!({"index": 1}))]);
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("selection".into())]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
//! Create Strokes: the parts of a colour layer no wider than the Stroke width, traced as stroked
|
||||
//! centre lines instead of filled outlines.
|
||||
//!
|
||||
//! 1. **Distance**: a chamfer (3-4) distance transform gives each pixel its distance to the nearest
|
||||
//! pixel outside the layer.
|
||||
//! 2. **Lines**: an 8-connected component whose widest point (twice its largest distance, less
|
||||
//! one) is within the stroke width is a line; wider ones stay filled areas.
|
||||
//! 3. **Skeleton**: the line is thinned to one pixel (Zhang–Suen, applied pixel by pixel so it
|
||||
//! keeps its topology and two-pixel-wide lines don't vanish), then staircase corners that
|
||||
//! don't connect anything are dropped.
|
||||
//! 4. **Graph**: runs of skeleton pixels between ends and junctions (touching junction pixels
|
||||
//! merged into one point) become polylines through the pixel centres; rings without ends
|
||||
//! become closed ones. Short spurs that thinning leaves at junctions are pruned and the runs
|
||||
//! on either side of a junction left with two of them are joined.
|
||||
//! 5. **Curves**: each polyline is fitted like an outline ([`fit::fit_polyline`]); the stroke
|
||||
//! width is the line's mean width (its pixel count over its length).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
use crate::fit::{self, FitOptions};
|
||||
|
||||
/// One line of a colour layer: its centre lines and the width to stroke them with.
|
||||
pub(crate) struct Line {
|
||||
pub path: PathData,
|
||||
/// Stroke width in pixels.
|
||||
pub width: f64,
|
||||
pub pixels: usize,
|
||||
}
|
||||
|
||||
/// The lines of colour `label` in `labels` (`w` × `h`, row-major) no wider than `max_width`
|
||||
/// pixels, and which pixels they cover (to leave out of the filled areas).
|
||||
pub(crate) fn lines(labels: &[u16], label: u16, w: usize, h: usize, max_width: f64, o: &FitOptions) -> (Vec<bool>, Vec<Line>) {
|
||||
let mut thin = vec![false; labels.len()];
|
||||
let mut out = vec![];
|
||||
if w == 0 || h == 0 || labels.len() != w * h {
|
||||
return (thin, out);
|
||||
}
|
||||
let mask = |i: usize| labels.get(i) == Some(&label);
|
||||
let dt = distance(&mask, w, h);
|
||||
let mut seen = vec![false; w * h];
|
||||
let mut stack = vec![];
|
||||
for start in 0..w * h {
|
||||
if !mask(start) || seen[start] {
|
||||
continue;
|
||||
}
|
||||
let mut comp = vec![];
|
||||
seen[start] = true;
|
||||
stack.push(start);
|
||||
while let Some(i) = stack.pop() {
|
||||
comp.push(i);
|
||||
for j in neighbours(i, w, h) {
|
||||
if mask(j) && !seen[j] {
|
||||
seen[j] = true;
|
||||
stack.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
let widest = 2.0 * f64::from(comp.iter().map(|&i| dt[i]).max().unwrap_or(0)) / 3.0 - 1.0;
|
||||
if widest > max_width {
|
||||
continue;
|
||||
}
|
||||
let Some(line) = trace_line(&comp, w, max_width, o) else { continue };
|
||||
for &i in &comp {
|
||||
thin[i] = true;
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
(thin, out)
|
||||
}
|
||||
|
||||
/// The 8 neighbours of pixel `i` inside the `w` × `h` image.
|
||||
fn neighbours(i: usize, w: usize, h: usize) -> impl Iterator<Item = usize> {
|
||||
let (x, y) = ((i % w) as i64, (i / w) as i64);
|
||||
const AROUND: [(i64, i64); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
|
||||
AROUND.into_iter().filter_map(move |(dx, dy)| {
|
||||
let (nx, ny) = (x + dx, y + dy);
|
||||
(nx >= 0 && ny >= 0 && nx < w as i64 && ny < h as i64).then(|| ny as usize * w + nx as usize)
|
||||
})
|
||||
}
|
||||
|
||||
/// Chamfer 3-4 distance (3 per pixel step, saturating) of each pixel in `mask` to the nearest
|
||||
/// pixel outside it; outside the image counts as outside.
|
||||
fn distance(mask: &impl Fn(usize) -> bool, w: usize, h: usize) -> Vec<u16> {
|
||||
let mut d = vec![0u16; w * h];
|
||||
let at = |d: &[u16], x: i64, y: i64| {
|
||||
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 { 0 } else { d.get(y as usize * w + x as usize).copied().unwrap_or(0) }
|
||||
};
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let i = y * w + x;
|
||||
if mask(i) {
|
||||
let (x, y) = (x as i64, y as i64);
|
||||
let steps = [(x - 1, y, 3), (x - 1, y - 1, 4), (x, y - 1, 3), (x + 1, y - 1, 4)];
|
||||
d[i] = steps.iter().map(|&(nx, ny, c)| at(&d, nx, ny).saturating_add(c)).min().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in (0..h).rev() {
|
||||
for x in (0..w).rev() {
|
||||
let i = y * w + x;
|
||||
if mask(i) {
|
||||
let (xi, yi) = (x as i64, y as i64);
|
||||
let steps = [(xi + 1, yi, 3), (xi + 1, yi + 1, 4), (xi, yi + 1, 3), (xi - 1, yi + 1, 4)];
|
||||
let v = steps.iter().map(|&(nx, ny, c)| at(&d, nx, ny).saturating_add(c)).min().unwrap_or(0);
|
||||
d[i] = d[i].min(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// A grid around one line: its pixels with a one-pixel empty border.
|
||||
struct Grid {
|
||||
on: Vec<bool>,
|
||||
w: usize,
|
||||
h: usize,
|
||||
/// Image position of grid pixel (0, 0).
|
||||
x0: i64,
|
||||
y0: i64,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// The 8 neighbours (N, NE, E, SE, S, SW, W, NW) of interior pixel `i`.
|
||||
fn ring(&self, i: usize) -> [bool; 8] {
|
||||
let w = self.w;
|
||||
let g = |j: usize| self.on.get(j).copied().unwrap_or(false);
|
||||
[g(i - w), g(i - w + 1), g(i + 1), g(i + w + 1), g(i + w), g(i + w - 1), g(i - 1), g(i - w - 1)]
|
||||
}
|
||||
fn interior(&self) -> impl Iterator<Item = usize> + use<> {
|
||||
let (w, h) = (self.w, self.h);
|
||||
(1..h.saturating_sub(1)).flat_map(move |y| (1..w.saturating_sub(1)).map(move |x| y * w + x))
|
||||
}
|
||||
fn neighbours(&self, i: usize) -> impl Iterator<Item = usize> + '_ {
|
||||
let w = self.w;
|
||||
[i - w, i - w + 1, i + 1, i + w + 1, i + w, i + w - 1, i - 1, i - w - 1].into_iter().filter(|&j| self.on.get(j).copied().unwrap_or(false))
|
||||
}
|
||||
fn degree(&self, i: usize) -> usize {
|
||||
self.neighbours(i).count()
|
||||
}
|
||||
/// The centre of pixel `i` in image coordinates.
|
||||
fn centre(&self, i: usize) -> Point {
|
||||
Point::new((self.x0 + (i % self.w) as i64) as f64 + 0.5, (self.y0 + (i / self.w) as i64) as f64 + 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
/// Zhang–Suen thinning. Each sub-iteration picks the pixels to remove from the same state, so the
|
||||
/// skeleton stays centred; they are then removed one by one, each only if it still doesn't
|
||||
/// disconnect anything, so a two-pixel-wide line thins to one pixel instead of vanishing.
|
||||
fn thin(g: &mut Grid) {
|
||||
let removable = |p: &[bool; 8]| {
|
||||
let b = p.iter().filter(|v| **v).count();
|
||||
let a = (0..8).filter(|&k| !p[k] && p[(k + 1) % 8]).count();
|
||||
(2..=6).contains(&b) && a == 1
|
||||
};
|
||||
let mut picked = vec![];
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for step in 0..2 {
|
||||
picked.clear();
|
||||
for i in g.interior() {
|
||||
if !g.on[i] {
|
||||
continue;
|
||||
}
|
||||
let p = g.ring(i);
|
||||
let (n, e, s, w) = (p[0], p[2], p[4], p[6]);
|
||||
let side = if step == 0 { !(e && s && (n || w)) } else { !(n && w && (e || s)) };
|
||||
if side && removable(&p) {
|
||||
picked.push(i);
|
||||
}
|
||||
}
|
||||
for &i in &picked {
|
||||
if removable(&g.ring(i)) {
|
||||
g.on[i] = false;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Staircase corners: a pixel whose neighbours stay connected without it (Yokoi's
|
||||
// 8-connectivity number 1) and that doesn't end the line.
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for i in g.interior() {
|
||||
if !g.on[i] || g.degree(i) < 2 {
|
||||
continue;
|
||||
}
|
||||
let p = g.ring(i);
|
||||
// x1 = E, x2 = NE, x3 = N, x4 = NW, x5 = W, x6 = SW, x7 = S, x8 = SE.
|
||||
let x = [p[2], p[1], p[0], p[7], p[6], p[5], p[4], p[3]];
|
||||
let off = |k: usize| !x[k % 8];
|
||||
let c8: usize = [0, 2, 4, 6].iter().map(|&k| usize::from(off(k)) - usize::from(off(k) && off(k + 1) && off(k + 2))).sum();
|
||||
if c8 == 1 {
|
||||
g.on[i] = false;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of skeleton pixels between two nodes (`None`: none, a ring).
|
||||
#[derive(Clone)]
|
||||
struct Run {
|
||||
pts: Vec<Point>,
|
||||
ends: [Option<usize>; 2],
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn length(&self) -> f64 {
|
||||
self.pts.windows(2).map(|p| p[0].distance(p[1])).sum::<f64>()
|
||||
+ if self.closed { self.pts.first().zip(self.pts.last()).map_or(0.0, |(a, b)| a.distance(*b)) } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The centre lines of one line component (pixel indices of the `w`-wide image).
|
||||
fn trace_line(comp: &[usize], w: usize, max_width: f64, o: &FitOptions) -> Option<Line> {
|
||||
let xs = comp.iter().map(|&i| i % w);
|
||||
let ys = comp.iter().map(|&i| i / w);
|
||||
let (x0, x1, y0, y1) = (xs.clone().min()?, xs.max()?, ys.clone().min()?, ys.max()?);
|
||||
let (gw, gh) = (x1 - x0 + 3, y1 - y0 + 3);
|
||||
let mut g = Grid { on: vec![false; gw * gh], w: gw, h: gh, x0: x0 as i64 - 1, y0: y0 as i64 - 1 };
|
||||
for &i in comp {
|
||||
g.on[(i / w - y0 + 1) * gw + (i % w - x0 + 1)] = true;
|
||||
}
|
||||
thin(&mut g);
|
||||
let skeleton: Vec<usize> = g.interior().filter(|&i| g.on[i]).collect();
|
||||
if skeleton.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
// Nodes: line ends, and junctions with the junction pixels touching them.
|
||||
let mut node = vec![usize::MAX; g.on.len()];
|
||||
let mut centres: Vec<Point> = vec![];
|
||||
for &i in &skeleton {
|
||||
let d = g.degree(i);
|
||||
if d == 2 || node[i] != usize::MAX {
|
||||
continue;
|
||||
}
|
||||
let id = centres.len();
|
||||
let mut members = vec![i];
|
||||
node[i] = id;
|
||||
if d > 2 {
|
||||
let mut k = 0;
|
||||
while let Some(&p) = members.get(k) {
|
||||
k += 1;
|
||||
for q in g.neighbours(p).collect::<Vec<_>>() {
|
||||
if node[q] == usize::MAX && g.degree(q) > 2 {
|
||||
node[q] = id;
|
||||
members.push(q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let sum = members.iter().fold(Point::ZERO, |s, &m| s + g.centre(m).to_vec2());
|
||||
centres.push(Point::new(sum.x / members.len() as f64, sum.y / members.len() as f64));
|
||||
}
|
||||
// Runs from each node, then the rings left.
|
||||
let mut used: HashSet<(usize, usize)> = HashSet::new();
|
||||
let edge = |a: usize, b: usize| (a.min(b), a.max(b));
|
||||
let mut runs: Vec<Run> = vec![];
|
||||
for &p in skeleton.iter().filter(|&&i| node[i] != usize::MAX) {
|
||||
for q in g.neighbours(p).collect::<Vec<_>>() {
|
||||
if node[q] == node[p] || !used.insert(edge(p, q)) {
|
||||
continue;
|
||||
}
|
||||
let mut pts = vec![centres[node[p]], g.centre(q)];
|
||||
let (mut prev, mut cur) = (p, q);
|
||||
while node[cur] == usize::MAX {
|
||||
let Some(next) = g.neighbours(cur).find(|&n| n != prev && !used.contains(&edge(cur, n))) else { break };
|
||||
used.insert(edge(cur, next));
|
||||
pts.push(g.centre(next));
|
||||
(prev, cur) = (cur, next);
|
||||
}
|
||||
let end = (node[cur] != usize::MAX).then_some(node[cur]);
|
||||
if let (Some(e), Some(last)) = (end, pts.last_mut()) {
|
||||
*last = centres[e];
|
||||
}
|
||||
runs.push(Run { pts, ends: [Some(node[p]), end], closed: false });
|
||||
}
|
||||
}
|
||||
for &s in &skeleton {
|
||||
if node[s] != usize::MAX || g.neighbours(s).any(|n| used.contains(&edge(s, n))) {
|
||||
continue;
|
||||
}
|
||||
let mut pts = vec![g.centre(s)];
|
||||
let (mut prev, mut cur) = (usize::MAX, s);
|
||||
let mut closed = false;
|
||||
while let Some(next) = g.neighbours(cur).find(|&n| n != prev && !used.contains(&edge(cur, n))) {
|
||||
used.insert(edge(cur, next));
|
||||
if next == s {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
pts.push(g.centre(next));
|
||||
(prev, cur) = (cur, next);
|
||||
}
|
||||
runs.push(Run { pts, ends: [None, None], closed });
|
||||
}
|
||||
// The line's mean width: its pixels over its length (the skeleton stops about half a width
|
||||
// short of each end).
|
||||
let width = |runs: &[Run]| {
|
||||
let length: f64 = runs.iter().map(Run::length).sum();
|
||||
let px = comp.len() as f64;
|
||||
((-length + (length * length + 4.0 * px).sqrt()) / 2.0).clamp(1.0, max_width.max(1.0))
|
||||
};
|
||||
let spur = width(&runs);
|
||||
let runs = join(prune(runs, centres.len(), spur), centres.len());
|
||||
let width = width(&runs);
|
||||
let subs: Vec<_> = runs.iter().filter_map(|r| fit::fit_polyline(&r.pts, r.closed, o)).collect();
|
||||
if subs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Line { path: PathData::new(subs), width, pixels: comp.len() })
|
||||
}
|
||||
|
||||
/// The runs without the spurs thinning leaves: runs shorter than the line's `width` from a line end
|
||||
/// to a junction that keeps at least two other runs.
|
||||
fn prune(runs: Vec<Run>, nodes: usize, width: f64) -> Vec<Run> {
|
||||
let mut degree = vec![0usize; nodes];
|
||||
for e in runs.iter().flat_map(|r| r.ends.iter().flatten()) {
|
||||
degree[*e] += 1;
|
||||
}
|
||||
let mut order: Vec<usize> = (0..runs.len()).collect();
|
||||
order.sort_by(|a, b| runs[*a].length().total_cmp(&runs[*b].length()));
|
||||
let mut keep = vec![true; runs.len()];
|
||||
for i in order {
|
||||
let r = &runs[i];
|
||||
let [Some(a), Some(b)] = r.ends else { continue };
|
||||
let (tip, fork) = if degree[a] == 1 { (a, b) } else { (b, a) };
|
||||
if degree[tip] == 1 && degree[fork] >= 3 && r.length() < width.max(2.0) {
|
||||
keep[i] = false;
|
||||
degree[tip] -= 1;
|
||||
degree[fork] -= 1;
|
||||
}
|
||||
}
|
||||
runs.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect()
|
||||
}
|
||||
|
||||
/// The runs joined through every node exactly two of them meet at (a run meeting itself closes).
|
||||
fn join(runs: Vec<Run>, nodes: usize) -> Vec<Run> {
|
||||
let mut runs: Vec<Option<Run>> = runs.into_iter().map(Some).collect();
|
||||
for n in 0..nodes {
|
||||
let at: Vec<(usize, usize)> = runs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, r)| r.iter().flat_map(move |r| (0..2).filter(move |&k| r.ends[k] == Some(n)).map(move |k| (i, k))))
|
||||
.collect();
|
||||
let [(i, ki), (j, kj)] = at[..] else { continue };
|
||||
if i == j {
|
||||
if let Some(r) = runs[i].as_mut() {
|
||||
r.pts.pop();
|
||||
r.ends = [None, None];
|
||||
r.closed = r.pts.len() >= 3;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (Some(mut a), Some(mut b)) = (runs[i].take(), runs[j].take()) else { continue };
|
||||
// a ends at n, b starts at n.
|
||||
if ki == 0 {
|
||||
a.pts.reverse();
|
||||
a.ends.reverse();
|
||||
}
|
||||
if kj == 1 {
|
||||
b.pts.reverse();
|
||||
b.ends.reverse();
|
||||
}
|
||||
a.pts.extend(b.pts.into_iter().skip(1));
|
||||
a.ends[1] = b.ends[1];
|
||||
runs[i] = Some(a);
|
||||
}
|
||||
runs.into_iter().flatten().collect()
|
||||
}
|
||||
@@ -133,6 +133,49 @@ pub(crate) fn fit_loop(l: &Loop, o: &FitOptions) -> Option<SubPath> {
|
||||
Some(sp)
|
||||
}
|
||||
|
||||
/// Fit a centre line through `pts` (pixel-centre points in order) into a Bézier subpath: the
|
||||
/// points within `polygon_tol` of it are dropped (Douglas–Peucker), then curves are fitted. A
|
||||
/// `closed` line runs back to its first point.
|
||||
pub(crate) fn fit_polyline(pts: &[Point], closed: bool, o: &FitOptions) -> Option<SubPath> {
|
||||
let n = pts.len();
|
||||
let first = *pts.first()?;
|
||||
if n < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut ext = pts.to_vec();
|
||||
let mut keep = vec![false; n + 1];
|
||||
keep[0] = true;
|
||||
if closed {
|
||||
// Split the ring at its first point and the point farthest from it.
|
||||
ext.push(first);
|
||||
let far = (1..n).max_by(|&i, &j| pts[i].distance_squared(first).total_cmp(&pts[j].distance_squared(first))).unwrap_or(n / 2);
|
||||
keep[far] = true;
|
||||
rdp(&ext, 0, far, o.polygon_tol, &mut keep);
|
||||
rdp(&ext, far, n, o.polygon_tol, &mut keep);
|
||||
} else {
|
||||
keep[n - 1] = true;
|
||||
rdp(&ext, 0, n - 1, o.polygon_tol, &mut keep);
|
||||
}
|
||||
let mut poly: Vec<Point> = (0..n).filter(|&i| keep[i]).map(|i| pts[i]).collect();
|
||||
if closed && poly.len() < 3 {
|
||||
poly = pts.to_vec();
|
||||
}
|
||||
if poly.len() < if closed { 3 } else { 2 } {
|
||||
return None;
|
||||
}
|
||||
let sp = SubPath::polyline(&poly, closed);
|
||||
let fitted =
|
||||
simplify_with(&PathData::single(sp), &SimplifyOptions { tolerance: o.fit_tol, corner_angle_deg: o.corner_angle, straight_lines: false });
|
||||
let mut sp = fitted.subpaths.into_iter().next()?;
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
if o.snap_lines {
|
||||
snap_to_lines(&mut sp, (o.fit_tol * 2.0).max(1.5));
|
||||
}
|
||||
Some(sp)
|
||||
}
|
||||
|
||||
/// Retract the handles of curves that stay within `tol` of their chord.
|
||||
fn snap_to_lines(sp: &mut SubPath, tol: f64) {
|
||||
let n = sp.anchors.len();
|
||||
|
||||
+49
-7
@@ -18,10 +18,15 @@
|
||||
//! 5. **Curves**: the polygon is fitted with cubic Béziers (`vectorcraft_pathops::simplify_with`,
|
||||
//! least squares with corner detection); optionally nearly-straight curves snap to lines.
|
||||
//!
|
||||
//! With **Create: Strokes**, the parts of a colour layer no wider than the stroke width are traced
|
||||
//! as stroked centre lines instead (see `centerline`); without Fills, wider parts become stroked
|
||||
//! outlines.
|
||||
//!
|
||||
//! Colour layers are traced either *abutting* (each colour's own area; shapes share edges) or
|
||||
//! *overlapping* (stacked: each layer also covers every layer above it, so no hairline gaps).
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod centerline;
|
||||
mod contour;
|
||||
mod fit;
|
||||
mod mosaic;
|
||||
@@ -152,6 +157,12 @@ pub struct TraceParams {
|
||||
pub ignore_white: bool,
|
||||
/// Replace nearly-straight curves with straight lines.
|
||||
pub snap_curves_to_lines: bool,
|
||||
/// Create: trace areas as filled shapes.
|
||||
pub fills: bool,
|
||||
/// Create: trace lines no wider than `stroke_width` as stroked centre lines.
|
||||
pub strokes: bool,
|
||||
/// Stroke: the widest feature (px) traced as a stroke.
|
||||
pub stroke_width: f64,
|
||||
}
|
||||
|
||||
impl Default for TraceParams {
|
||||
@@ -167,6 +178,9 @@ impl Default for TraceParams {
|
||||
method: Method::Abutting,
|
||||
ignore_white: false,
|
||||
snap_curves_to_lines: false,
|
||||
fills: true,
|
||||
strokes: false,
|
||||
stroke_width: 10.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -250,7 +264,8 @@ pub fn presets() -> Vec<(&'static str, TraceParams)> {
|
||||
PRESET_NAMES.iter().filter_map(|n| Some((*n, preset(n)?))).collect()
|
||||
}
|
||||
|
||||
/// One traced shape: an outer contour plus its holes, filled with `color`.
|
||||
/// One traced shape: an outer contour plus its holes, filled with `color`, or (with `stroke`)
|
||||
/// lines stroked with it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TracedPath {
|
||||
/// In pixel coordinates (x right, y down; the image spans `0..width × 0..height`).
|
||||
@@ -258,6 +273,9 @@ pub struct TracedPath {
|
||||
pub color: [u8; 3],
|
||||
/// Filled pixel count of the component the path came from.
|
||||
pub pixels: usize,
|
||||
/// Create Strokes: the path is stroked this wide (px), not filled (centre lines, or the
|
||||
/// outlines of wider areas without Fills).
|
||||
pub stroke: Option<f64>,
|
||||
}
|
||||
|
||||
/// The traced result, bottom-most path first.
|
||||
@@ -357,15 +375,37 @@ impl Layers<'_> {
|
||||
let (params, opts) = (self.params, &self.opts);
|
||||
let color = *self.q.palette.get(ci)?;
|
||||
let overlapping = params.method == Method::Overlapping;
|
||||
let (w, h) = (self.w, self.h);
|
||||
// Create Strokes: this colour's lines, left out of its areas.
|
||||
let (thin, lines) = if params.strokes {
|
||||
centerline::lines(&self.q.labels, u16::try_from(ci).unwrap_or(TRANSPARENT), w, h, params.stroke_width, opts)
|
||||
} else {
|
||||
(vec![], vec![])
|
||||
};
|
||||
let mask: Vec<bool> = self
|
||||
.q
|
||||
.labels
|
||||
.iter()
|
||||
.map(|&l| l != TRANSPARENT && if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) } else { l as usize == ci })
|
||||
.enumerate()
|
||||
.map(|(i, &l)| {
|
||||
l != TRANSPARENT
|
||||
&& !thin.get(i).copied().unwrap_or(false)
|
||||
&& if overlapping { self.rank.get(l as usize).is_some_and(|&lr| lr >= r) } else { l as usize == ci }
|
||||
})
|
||||
.collect();
|
||||
// Without Fills, areas are outlined with a 1 px stroke.
|
||||
let area_stroke = (params.strokes && !params.fills).then_some(1.0);
|
||||
let min_hole = params.noise.max(1) as i64;
|
||||
let mut paths = vec![];
|
||||
for comp in trace_mask(&mask, self.w, self.h) {
|
||||
let mut add = |path: PathData, pixels: usize, stroke: Option<f64>| {
|
||||
let n = path.anchor_count();
|
||||
if self.anchors.fetch_add(n, Ordering::Relaxed).saturating_add(n) > self.max_anchors {
|
||||
return false;
|
||||
}
|
||||
paths.push(TracedPath { path, color, pixels, stroke });
|
||||
true
|
||||
};
|
||||
for comp in trace_mask(&mask, w, h) {
|
||||
let Some(outer) = fit::fit_loop(&comp.outer, opts) else { continue };
|
||||
let mut subs = vec![outer];
|
||||
for hole in &comp.holes {
|
||||
@@ -374,12 +414,14 @@ impl Layers<'_> {
|
||||
}
|
||||
subs.extend(fit::fit_loop(hole, opts));
|
||||
}
|
||||
let path = PathData::new(subs);
|
||||
let n = path.anchor_count();
|
||||
if self.anchors.fetch_add(n, Ordering::Relaxed).saturating_add(n) > self.max_anchors {
|
||||
if !add(PathData::new(subs), comp.pixels, area_stroke) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for line in lines {
|
||||
if !add(line.path, line.pixels, Some(line.width)) {
|
||||
return None;
|
||||
}
|
||||
paths.push(TracedPath { path, color, pixels: comp.pixels });
|
||||
}
|
||||
Some(paths)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
const BLACK: [u8; 4] = [0, 0, 0, 255];
|
||||
const WHITE: [u8; 4] = [255, 255, 255, 255];
|
||||
@@ -348,3 +349,116 @@ fn an_image_too_large_to_trace_is_refused_before_decoding() {
|
||||
assert!(matches!(err, TraceError::TooLarge { width: 30_000, height: 30_000, .. }), "{err}");
|
||||
assert!(matches!(Raster::decode(&png_header(64, 64)), Err(TraceError::Decode(_))), "a small header goes on to decoding");
|
||||
}
|
||||
|
||||
fn strokes(fills: bool) -> TraceParams {
|
||||
TraceParams { strokes: true, fills, stroke_width: 6.0, noise: 4, ..bw() }
|
||||
}
|
||||
|
||||
/// Endpoints (first and last anchor) of each open subpath of the stroked paths.
|
||||
fn stroked(res: &TraceResult) -> Vec<(&TracedPath, &vectorcraft_geom::SubPath)> {
|
||||
res.paths.iter().filter(|p| p.stroke.is_some()).flat_map(|p| p.path.subpaths.iter().map(move |s| (p, s))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thin_line_traces_as_one_stroked_centre_line() {
|
||||
// A 3 px wide diagonal line from (20, 20) to (180, 100).
|
||||
let img = Raster::from_fn(200, 120, |x, y| {
|
||||
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let t = (((px - 20.0) * 160.0 + (py - 20.0) * 80.0) / (160.0f64.powi(2) + 80.0f64.powi(2))).clamp(0.0, 1.0);
|
||||
let (cx, cy) = (20.0 + 160.0 * t, 20.0 + 80.0 * t);
|
||||
if (px - cx).hypot(py - cy) <= 1.5 { BLACK } else { WHITE }
|
||||
});
|
||||
let res = trace(&img, &strokes(true));
|
||||
assert_eq!(res.paths.len(), 1, "{:?}", res.paths.iter().map(|p| p.stroke).collect::<Vec<_>>());
|
||||
let p = &res.paths[0];
|
||||
let width = p.stroke.expect("stroked");
|
||||
assert!((2.0..=4.0).contains(&width), "width {width}");
|
||||
assert_eq!(p.path.subpaths.len(), 1);
|
||||
let sp = &p.path.subpaths[0];
|
||||
assert!(!sp.closed);
|
||||
let (a, b) = (sp.anchors[0].p, sp.anchors[sp.anchors.len() - 1].p);
|
||||
let (a, b) = if a.x < b.x { (a, b) } else { (b, a) };
|
||||
assert!(a.distance(Point::new(20.0, 20.0)) < 3.0 && b.distance(Point::new(180.0, 100.0)) < 3.0, "{a:?} … {b:?}");
|
||||
// A straight line: a few anchors, all on it.
|
||||
assert!(sp.anchors.len() <= 4, "{} anchors", sp.anchors.len());
|
||||
// Without Create Strokes, the same line is a filled outline.
|
||||
let filled = trace(&img, &bw());
|
||||
assert!(filled.paths.iter().all(|p| p.stroke.is_none()) && filled.paths[0].path.subpaths[0].closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thin_ring_traces_as_a_closed_centre_line() {
|
||||
let img = Raster::from_fn(120, 120, |x, y| {
|
||||
let d = (x as f64 + 0.5 - 60.0).hypot(y as f64 + 0.5 - 60.0);
|
||||
if (d - 40.0).abs() <= 1.5 { BLACK } else { WHITE }
|
||||
});
|
||||
let res = trace(&img, &strokes(true));
|
||||
let lines = stroked(&res);
|
||||
assert_eq!(lines.len(), 1, "one ring");
|
||||
let sp = lines[0].1;
|
||||
assert!(sp.closed);
|
||||
let len = PathData::single(sp.clone()).length();
|
||||
let want = std::f64::consts::TAU * 40.0;
|
||||
assert!((len - want).abs() / want < 0.05, "length {len} vs {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_areas_stay_filled_and_lines_cross_at_junctions() {
|
||||
// A disc (r = 20) and, apart from it, a plus sign of 3 px wide bars.
|
||||
let img = Raster::from_fn(200, 100, |x, y| {
|
||||
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
|
||||
let disc = (px - 50.0).hypot(py - 50.0) <= 20.0;
|
||||
let plus = ((px - 150.0).abs() <= 1.5 && (20.0..=80.0).contains(&py)) || ((py - 50.0).abs() <= 1.5 && (120.0..=180.0).contains(&px));
|
||||
if disc || plus { BLACK } else { WHITE }
|
||||
});
|
||||
let res = trace(&img, &strokes(true));
|
||||
let fills: Vec<_> = res.paths.iter().filter(|p| p.stroke.is_none()).collect();
|
||||
assert_eq!(fills.len(), 1, "the disc");
|
||||
let a = net_area(&fills[0].path);
|
||||
assert!((a - std::f64::consts::PI * 400.0).abs() < 60.0, "disc area {a}");
|
||||
let lines = stroked(&res);
|
||||
assert!((2..=4).contains(&lines.len()), "{} centre lines", lines.len());
|
||||
// The centre lines stop about half a width short of each end of the bars (their round caps
|
||||
// cover it).
|
||||
let total: f64 = lines.iter().map(|(_, s)| PathData::single((*s).clone()).length()).sum();
|
||||
assert!((106.0..=120.0).contains(&total), "both bars' length: {total}");
|
||||
let ends: Vec<Point> = lines.iter().flat_map(|(_, s)| [s.anchors[0].p, s.anchors[s.anchors.len() - 1].p]).collect();
|
||||
for want in [Point::new(150.0, 20.0), Point::new(150.0, 80.0), Point::new(120.0, 50.0), Point::new(180.0, 50.0)] {
|
||||
assert!(ends.iter().any(|e| e.distance(want) < 4.0), "a line ends near {want:?}: {ends:?}");
|
||||
}
|
||||
// Strokes only: the disc is outlined.
|
||||
let res = trace(&img, &strokes(false));
|
||||
assert!(res.paths.iter().all(|p| p.stroke.is_some()));
|
||||
assert!(res.paths.iter().any(|p| p.stroke == Some(1.0) && p.path.subpaths[0].closed), "the disc's outline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_settings_parse_with_defaults() {
|
||||
let p: TraceParams = serde_json::from_value(serde_json::json!({ "strokes": true, "strokeWidth": 4 })).unwrap();
|
||||
assert!(p.fills && p.strokes && p.stroke_width == 4.0);
|
||||
let d = TraceParams::default();
|
||||
assert!(d.fills && !d.strokes && d.stroke_width == 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_strokes_survives_noise_and_tiny_images() {
|
||||
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
|
||||
let mut next = move || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
seed
|
||||
};
|
||||
let noise: Vec<u8> = (0..120 * 120).flat_map(|_| if next() % 3 == 0 { BLACK } else { WHITE }).collect();
|
||||
let noise = Raster::new(120, 120, noise);
|
||||
for img in [noise, Raster::from_fn(1, 1, |_, _| BLACK), Raster::from_fn(3, 2, |x, _| if x == 1 { BLACK } else { WHITE })] {
|
||||
for (fills, width) in [(true, 1.0), (false, 4.0), (true, 100.0)] {
|
||||
for noise in [0, 1, 4] {
|
||||
let p = TraceParams { strokes: true, fills, stroke_width: width, noise, ..TraceParams::default() };
|
||||
for t in trace(&img, &p).paths {
|
||||
assert!(t.stroke.is_none_or(|w| w.is_finite() && w >= 1.0), "{:?}", t.stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+216
-20
@@ -79,6 +79,8 @@ enum Drag {
|
||||
/// A Selection tool move dragged off the canvas: the panels get the art
|
||||
/// ([`widgets::PanelDrag::Art`]).
|
||||
Art,
|
||||
/// Fingers making a touch gesture ([`crate::touch`]): the first one's press does nothing.
|
||||
Gesture,
|
||||
}
|
||||
|
||||
fn drag_id() -> egui::Id {
|
||||
@@ -216,6 +218,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Artwork raster.
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let (w, h) = ((rect.width() * ppp).round().max(1.0) as u32, (rect.height() * ppp).round().max(1.0) as u32);
|
||||
// View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel
|
||||
// is bigger than a screen pixel (below that the screen render already shows it).
|
||||
let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten();
|
||||
let key = CacheKey {
|
||||
doc: st.uid as usize,
|
||||
revision: st.revision,
|
||||
@@ -231,6 +236,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
rot: v.rotation,
|
||||
anti_alias: app.session.prefs.anti_aliased_artwork,
|
||||
placed: vectorcraft_render::placed_document::generation(),
|
||||
pixel,
|
||||
};
|
||||
// Placed documents' bitmaps are being made: draw again when they are ready.
|
||||
if vectorcraft_render::placed_document::busy() {
|
||||
@@ -246,16 +252,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if let Some(done) = app.canvas.worker.as_mut().and_then(|w| w.poll())
|
||||
&& done.key.doc == key.doc
|
||||
{
|
||||
upload(app, ui.ctx(), &done.img);
|
||||
upload(app, ui.ctx(), &done.img, done.key.pixel.is_some());
|
||||
app.canvas.key = Some(done.key);
|
||||
app.perf.render_ms = done.ms;
|
||||
app.canvas.last_ms = done.ms;
|
||||
}
|
||||
if app.canvas.key.as_ref() != Some(&key) || app.canvas.texture.is_none() {
|
||||
let view = Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
|
||||
* Affine::rotate(v.rotation.to_radians())
|
||||
* Affine::scale(v.zoom * ppp as f64)
|
||||
* Affine::translate(-v.center.to_vec2());
|
||||
let (w, h, view) = match pixel {
|
||||
Some([x0, y0, x1, y1]) => ((x1 - x0) as u32, (y1 - y0) as u32, Affine::translate((-x0 as f64, -y0 as f64))),
|
||||
None => (
|
||||
w,
|
||||
h,
|
||||
Affine::translate((w as f64 / 2.0, h as f64 / 2.0))
|
||||
* Affine::rotate(v.rotation.to_radians())
|
||||
* Affine::scale(v.zoom * ppp as f64)
|
||||
* Affine::translate(-v.center.to_vec2()),
|
||||
),
|
||||
};
|
||||
let opts = vectorcraft_render::RenderOptions { outline: app.ui.view.outline, background: None, artboards: false, ..Default::default() };
|
||||
let opts = vectorcraft_render::RenderOptions {
|
||||
proof: vectorcraft_render::proof::active_proof(),
|
||||
@@ -282,7 +295,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
_ => {
|
||||
let t0 = now_ms();
|
||||
let img = app.canvas.renderer.render(&doc, w, h, view, &opts);
|
||||
upload(app, ui.ctx(), &img);
|
||||
upload(app, ui.ctx(), &img, pixel.is_some());
|
||||
app.canvas.key = Some(key.clone());
|
||||
app.perf.render_ms = now_ms() - t0;
|
||||
app.canvas.last_ms = app.perf.render_ms;
|
||||
@@ -291,14 +304,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key)
|
||||
&& k.doc == key.doc
|
||||
&& (k.rot - v.rotation).abs() < 1e-9
|
||||
{
|
||||
// Reproject the last frame if it was rendered for a different view.
|
||||
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
|
||||
let _ = k.rot;
|
||||
let a = xf.to_screen(old.to_doc(rect.min));
|
||||
let b = xf.to_screen(old.to_doc(rect.max));
|
||||
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
match k.pixel {
|
||||
// Document pixels: placed over the document rect they cover, turning with the view.
|
||||
Some([x0, y0, x1, y1]) => {
|
||||
let q = xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64));
|
||||
let mut mesh = egui::Mesh::with_texture(tex.id());
|
||||
for (pos, uv) in q.into_iter().zip([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]) {
|
||||
mesh.vertices.push(egui::epaint::Vertex { pos, uv, color: Color32::WHITE });
|
||||
}
|
||||
mesh.add_triangle(0, 1, 2);
|
||||
mesh.add_triangle(0, 2, 3);
|
||||
painter.add(Shape::mesh(mesh));
|
||||
}
|
||||
None if (k.rot - v.rotation).abs() < 1e-9 => {
|
||||
// Reproject the last frame if it was rendered for a different view.
|
||||
let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot };
|
||||
let a = xf.to_screen(old.to_doc(rect.min));
|
||||
let b = xf.to_screen(old.to_doc(rect.max));
|
||||
painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if let Some(look) = grid_look.filter(|_| !grids_in_back) {
|
||||
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
|
||||
@@ -384,6 +411,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.ui.task_bar && !app.session.tool_busy() && app.ui.screen_mode < 3 {
|
||||
task_bar(app, ui, &xf);
|
||||
}
|
||||
if app.ui.screen_mode < 3 {
|
||||
crate::free_transform::show(app, ui, xf.rect);
|
||||
}
|
||||
// Cursor.
|
||||
if resp.hovered() {
|
||||
let m = ui.input(|i| i.modifiers);
|
||||
@@ -474,6 +504,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
let at = hover.or_else(|| pointer.interact_pos().filter(|p| rect.contains(*p)));
|
||||
app.hover_doc = hover.map(|p| xf.to_doc(p));
|
||||
let view = app.view_info();
|
||||
touch_gestures(app, ui, rect, view);
|
||||
let drag: Option<Drag> = ui.data(|d| d.get_temp(drag_id()));
|
||||
// A modifier pressed or released over the canvas re-hovers the tool, so what it changes shows
|
||||
// without moving the mouse (Alt switches the Shape Builder to erase mode).
|
||||
@@ -565,7 +596,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
vm.rotation = vectorcraft_geom::normalize_deg(deg);
|
||||
}
|
||||
}
|
||||
Drag::ZoomBox { .. } | Drag::Art => {}
|
||||
Drag::ZoomBox { .. } | Drag::Art | Drag::Gesture => {}
|
||||
Drag::Tool if drag_art_out(app, ui, resp, p, view) => {
|
||||
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art));
|
||||
}
|
||||
@@ -609,7 +640,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
let ev = PointerEvent { kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), pressure: pen_pressure(ui, false) };
|
||||
dispatch(app, &ev, view);
|
||||
}
|
||||
Drag::Art => {}
|
||||
Drag::Art | Drag::Gesture => {}
|
||||
Drag::Pan { .. } | Drag::RotateView { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -688,6 +719,50 @@ fn wheel(i: &egui::InputState, wheel_zooms: bool, line: f32, page: f32, alt_turn
|
||||
(zoom, scroll)
|
||||
}
|
||||
|
||||
/// Enable Touch Gestures: this frame's finger contacts on the canvas ([`crate::touch`]). A second
|
||||
/// finger drops the press the first one began (its tool interaction rolled back; the rest of the
|
||||
/// gesture presses nothing), and a tap of two fingers undoes, one of three redoes.
|
||||
fn touch_gestures(app: &mut VectorcraftApp, ui: &Ui, rect: egui::Rect, view: vectorcraft_engine::ViewInfo) {
|
||||
if !app.session.prefs.touch_gestures {
|
||||
return;
|
||||
}
|
||||
let (touches, now): (Vec<_>, f64) = ui.input(|i| {
|
||||
let t = i.events.iter().filter_map(|e| match e {
|
||||
egui::Event::Touch { id, phase, pos, .. } => Some((*id, *phase, *pos)),
|
||||
_ => None,
|
||||
});
|
||||
(t.collect(), i.time)
|
||||
});
|
||||
if touches.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key = egui::Id::new("canvas-touch");
|
||||
let mut taps: crate::touch::Taps = ui.data(|d| d.get_temp(key)).unwrap_or_default();
|
||||
let mut tap = None;
|
||||
for (id, phase, pos) in touches {
|
||||
// A gesture begins on the canvas.
|
||||
if phase == egui::TouchPhase::Start && !taps.is_down() && !rect.contains(pos) {
|
||||
continue;
|
||||
}
|
||||
match taps.feed(id, phase, pos, now) {
|
||||
Some(crate::touch::Touch::Fingers) => {
|
||||
if ui.data(|d| d.get_temp::<Drag>(drag_id())) == Some(Drag::Tool) {
|
||||
// Nothing it began is kept; the tool's mouse-up returns it to rest.
|
||||
let _ = app.session.cancel_interaction();
|
||||
dispatch(app, &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), pressure: 1.0 }, view);
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(drag_id(), Drag::Gesture));
|
||||
}
|
||||
Some(crate::touch::Touch::Tap(n)) => tap = crate::touch::tap_command(n),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(key, taps));
|
||||
if let Some(cmd) = tap {
|
||||
crate::menus::invoke(app, cmd, serde_json::json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Selection tool move dragged off the canvas (to `p`, over a panel) turns into a panel drag of
|
||||
/// the selected art ([`widgets::PanelDrag::Art`]): the move is dropped, so the art stays where it
|
||||
/// was, and the panel it is released on takes it (the Graphic Styles panel makes a style of it).
|
||||
@@ -1072,7 +1147,8 @@ fn too_many_anchors<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> bool {
|
||||
None => return true,
|
||||
}
|
||||
}
|
||||
!matches!(n.kind, NodeKind::Envelope { .. }) && n.children().into_iter().flatten().any(|c| over(c, left))
|
||||
!matches!(n.kind, NodeKind::Envelope { .. })
|
||||
&& n.children().into_iter().flatten().skip(usize::from(n.shaper.is_some())).any(|c| over(c, left))
|
||||
}
|
||||
let mut left = OVERLAY_MAX_ANCHORS;
|
||||
nodes.into_iter().any(|n| over(n, &mut left))
|
||||
@@ -1085,7 +1161,7 @@ fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) {
|
||||
if matches!(n.kind, NodeKind::Envelope { .. }) {
|
||||
return;
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
for c in n.children().into_iter().flatten().skip(usize::from(n.shaper.is_some())) {
|
||||
walk_drawn(c, f);
|
||||
}
|
||||
}
|
||||
@@ -1100,6 +1176,7 @@ fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option<vectorcraft_doc::
|
||||
outline: app.ui.view.outline,
|
||||
path_only: prefs.object_selection_by_path_only,
|
||||
type_path_only: prefs.type_selection_by_path_only,
|
||||
scope: app.session.active().and_then(|st| st.isolation),
|
||||
};
|
||||
vectorcraft_doc::hit::hit_test(&app.session.active()?.doc, p, opt)
|
||||
}
|
||||
@@ -1665,14 +1742,31 @@ fn kurbo_flatten(p: &BezPath, tol: f64, f: &mut impl FnMut(PathEl)) {
|
||||
vectorcraft_geom::kurbo::flatten(p.elements().iter().copied(), tol, f);
|
||||
}
|
||||
|
||||
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered) {
|
||||
/// Upload the art's raster; Pixel Preview's document pixels keep hard edges when magnified.
|
||||
fn upload(app: &mut VectorcraftApp, ctx: &egui::Context, img: &vectorcraft_render::Rendered, pixel: bool) {
|
||||
let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels);
|
||||
let options = if pixel { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
|
||||
match &mut app.canvas.texture {
|
||||
Some(tex) => tex.set(color, egui::TextureOptions::LINEAR),
|
||||
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, egui::TextureOptions::LINEAR)),
|
||||
Some(tex) => tex.set(color, options),
|
||||
None => app.canvas.texture = Some(ctx.load_texture("canvas", color, options)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view
|
||||
/// included. None when the view is degenerate.
|
||||
fn pixel_region(xf: &Xf) -> Option<[i64; 4]> {
|
||||
let r = xf.rect;
|
||||
let corners = [r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()].map(|p| xf.to_doc(p));
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in corners {
|
||||
(x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y));
|
||||
}
|
||||
let (x0, y0, x1, y1) = (x0.floor(), y0.floor(), x1.ceil(), y1.ceil());
|
||||
// A document pixel is bigger than a screen pixel here, so the region is about canvas-sized.
|
||||
let ok = [x0, y0, x1, y1].iter().all(|c| c.is_finite() && c.abs() < 1e9) && x1 > x0 && y1 > y0 && x1 - x0 <= 16384.0 && y1 - y0 <= 16384.0;
|
||||
ok.then_some([x0 as i64, y0 as i64, x1 as i64, y1 as i64])
|
||||
}
|
||||
|
||||
/// The Contextual Task Bar's area.
|
||||
fn task_bar_id() -> egui::Id {
|
||||
egui::Id::new("task-bar")
|
||||
@@ -1837,6 +1931,24 @@ fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Shape as _;
|
||||
|
||||
#[test]
|
||||
fn shaper_selection_highlights_only_the_visible_result() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("shape.ellipse", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap();
|
||||
let line = vectorcraft_doc::NodeId(s.execute("shape.line", &json!({"x1":50,"y1":150,"x2":250,"y2":150})).unwrap()["id"].as_u64().unwrap());
|
||||
for x in [0.0, 150.0] {
|
||||
s.execute("shaper.scribble", &json!({"points":[[60.0+x,140],[70.0+x,160],[80.0+x,140],[90.0+x,160]]})).unwrap();
|
||||
}
|
||||
let st = s.active().unwrap();
|
||||
let g = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
assert!(g.shaper.is_some());
|
||||
let bounds = node_outline(g).bounding_box();
|
||||
assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}");
|
||||
assert_eq!(node_outline(st.doc.node(line).unwrap()).bounding_box().x0, 50.0, "an isolated original still shows its full outline");
|
||||
}
|
||||
|
||||
/// One headless canvas frame on an 800 × 600 window.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
|
||||
@@ -1845,6 +1957,40 @@ mod tests {
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Enable Touch Gestures (#585): a two-finger tap undoes and a three-finger one redoes, and the
|
||||
/// first finger's press (the pointer egui makes of it) draws nothing. Off, a tap does nothing.
|
||||
#[test]
|
||||
fn two_finger_tap_undoes_and_three_finger_tap_redoes() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 40, "height": 40})).unwrap();
|
||||
app.select_tool("rectangle");
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
|
||||
let c = app.canvas_rect.unwrap().center();
|
||||
let touch = |n: u64, phase, pos| egui::Event::Touch { device_id: egui::TouchDeviceId(1), id: egui::TouchId(n), phase, pos, force: None };
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// `fingers` fingers tap at the centre, the first also pressing as the pointer and moving a
|
||||
// little (as a rectangle drag would begin).
|
||||
let tap = |app: &mut VectorcraftApp, fingers: u64| {
|
||||
let at = |n: u64| c + vec2(n as f32 * 50.0, 0.0);
|
||||
frame(app, &ctx, vec![touch(0, egui::TouchPhase::Start, at(0)), egui::Event::PointerMoved(at(0)), button(at(0), true)]);
|
||||
frame(app, &ctx, vec![touch(0, egui::TouchPhase::Move, at(0) + vec2(6.0, 6.0)), egui::Event::PointerMoved(at(0) + vec2(6.0, 6.0))]);
|
||||
frame(app, &ctx, (1..fingers).map(|n| touch(n, egui::TouchPhase::Start, at(n))).collect());
|
||||
frame(app, &ctx, vec![touch(0, egui::TouchPhase::End, at(0)), button(at(0) + vec2(6.0, 6.0), false), egui::Event::PointerGone]);
|
||||
frame(app, &ctx, (1..fingers).map(|n| touch(n, egui::TouchPhase::End, at(n))).collect());
|
||||
frame(app, &ctx, vec![]);
|
||||
};
|
||||
tap(&mut app, 2);
|
||||
assert_eq!(count(&app), 0, "the rectangle undone, none drawn");
|
||||
tap(&mut app, 3);
|
||||
assert_eq!(count(&app), 1, "redone");
|
||||
app.session.prefs.touch_gestures = false;
|
||||
tap(&mut app, 2);
|
||||
assert_eq!(count(&app), 2, "off: the first finger draws as the pointer, and nothing is undone");
|
||||
}
|
||||
|
||||
/// The Artboard tool's label holds the artboard's name (never translated); the tools' own
|
||||
/// labels are interface text.
|
||||
#[test]
|
||||
@@ -2145,6 +2291,56 @@ mod tests {
|
||||
(v, out.textures_delta)
|
||||
}
|
||||
|
||||
/// View › Pixel Preview: magnified, the art shows as the document pixels it rasterizes to (one
|
||||
/// per point, hard-edged), not as smooth vectors; zoomed out or out of Pixel Preview the canvas
|
||||
/// renders for the screen again.
|
||||
#[test]
|
||||
fn pixel_preview_shows_the_document_pixels() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// Its 1 pt stroke covers a quarter of document pixel 99 and most of pixel 100.
|
||||
app.session.execute("shape.rectangle", &json!({"x": 100.25, "y": 50, "width": 200, "height": 200})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
let ctx = egui::Context::default();
|
||||
// The art's raster uploaded by one frame: (width, height, hard-edged, pixels).
|
||||
let upload = |app: &mut VectorcraftApp| {
|
||||
let (_, mut delta) = frame_output(app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).map(|d| {
|
||||
let egui::ImageData::Color(img) = &d.image;
|
||||
(img.width(), img.height(), d.options.magnification == egui::TextureFilter::Nearest, img.pixels.clone())
|
||||
});
|
||||
delta.clear();
|
||||
up.expect("the art re-rendered")
|
||||
};
|
||||
let screen = upload(&mut app); // the first frame fits the view to the artboard
|
||||
assert!(screen.0 > 600 && !screen.2, "out of Pixel Preview: the screen's pixels, smoothed");
|
||||
app.ui.view.pixel_preview = true;
|
||||
let view = app.view_mut().unwrap();
|
||||
(view.zoom, view.center) = (8.0, Point::new(100.0, 150.0));
|
||||
let (w, h, hard, px) = upload(&mut app);
|
||||
assert!(hard, "hard-edged pixels");
|
||||
assert!(w <= screen.0 / 8 + 2 && h <= screen.1 / 8 + 2, "one pixel per point: {w} × {h}");
|
||||
let [x0, y0, x1, y1] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered");
|
||||
assert_eq!(((x1 - x0) as usize, (y1 - y0) as usize), (w, h));
|
||||
// Each document pixel is one texel, anti-aliased by how much of it the art covers.
|
||||
let alpha = |x: i64| px[((150 - y0) * w as i64 + x - x0) as usize].a();
|
||||
assert!((40..=90).contains(&alpha(99)), "a quarter of pixel 99: {}", alpha(99));
|
||||
assert!(alpha(100) > 200, "most of pixel 100: {}", alpha(100));
|
||||
assert_eq!((alpha(98), alpha(101)), (0, 255));
|
||||
// The pixels are placed over the document rect they cover.
|
||||
let s = shapes(&mut app, &ctx);
|
||||
let art = app.canvas.texture.as_ref().unwrap().id();
|
||||
let Some(Shape::Mesh(mesh)) = s.iter().find(|s| matches!(s, Shape::Mesh(m) if m.texture_id == art)) else { panic!("the art") };
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let at = xf.to_screen(Point::new(x0 as f64, y0 as f64));
|
||||
assert!((mesh.vertices[0].pos - at).length() < 0.01, "{:?} at {at:?}", mesh.vertices[0].pos);
|
||||
// Zoomed out, a document pixel is no bigger than a screen pixel: rendered for the screen.
|
||||
app.view_mut().unwrap().zoom = 0.5;
|
||||
let (w, _, hard, _) = upload(&mut app);
|
||||
assert!(w > 600 && !hard, "zoomed out: the screen's pixels");
|
||||
}
|
||||
|
||||
/// General › Anti-aliased Artwork (#394): on (the default), the art's edges are smoothed on
|
||||
/// screen; off, every pixel is either painted or not, and turning it either way re-renders.
|
||||
#[test]
|
||||
|
||||
@@ -84,6 +84,8 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
|
||||
"pinned": app.ui.task_bar_place.pinned,
|
||||
"rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
},
|
||||
// The Free Transform tool's widget, where it shows.
|
||||
"freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])),
|
||||
"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),
|
||||
"canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),
|
||||
"window": [r.width(), r.height()],
|
||||
|
||||
@@ -38,6 +38,7 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
|
||||
match (command, key) {
|
||||
("type.pathOptions", "effect") => Some(crate::menus::PATH_EFFECTS),
|
||||
("type.pathOptions", "alignToPath") => Some(PATH_ALIGN),
|
||||
("text.areaOptions", "fit") => Some(AREA_FIT),
|
||||
("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE),
|
||||
("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN),
|
||||
_ => None,
|
||||
@@ -47,6 +48,9 @@ fn choices(command: &str, key: &str) -> Option<form::Choices> {
|
||||
/// Type on a Path Options › Align to Path.
|
||||
const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")];
|
||||
|
||||
/// Area Type Options › Fit.
|
||||
const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText")];
|
||||
|
||||
/// Area Type Options › First Baseline.
|
||||
const FIRST_BASELINE: form::Choices =
|
||||
&[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")];
|
||||
|
||||
@@ -424,11 +424,8 @@ fn destination(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let pick = app.services.pick_folder.is_some();
|
||||
ui.horizontal(|ui| {
|
||||
form::text(ui, d, "folder", if pick { 300.0 } else { 334.0 });
|
||||
if pick
|
||||
&& widgets::icon_button(ui, "folder-open", tl!("Choose a folder"), false, 26.0).clicked()
|
||||
&& let Some(f) = app.services.pick_folder.as_mut().and_then(|pick| pick())
|
||||
{
|
||||
d.fields.insert("folder".into(), json!(f));
|
||||
if pick && widgets::icon_button(ui, "folder-open", tl!("Choose a folder"), false, 26.0).clicked() {
|
||||
crate::picks::folder_field(app, d, "folder");
|
||||
}
|
||||
});
|
||||
form::check(ui, d, "openLocation", tl!("Open Location after Export"));
|
||||
|
||||
@@ -145,10 +145,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a, &preset.name)
|
||||
{
|
||||
app.status(e);
|
||||
if let Some(a) = act {
|
||||
let r = if matches!(a, Action::Import) {
|
||||
// Its file dialog, shown off the UI thread, imports into the dialog as it is then.
|
||||
let current = preset.name.clone();
|
||||
crate::picks::in_dialog(app, d, move |app, d| run(app, d, Action::Import, ¤t))
|
||||
} else {
|
||||
run(app, d, a, &preset.name)
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -181,7 +188,7 @@ fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) ->
|
||||
return Ok(());
|
||||
}
|
||||
let pick = crate::FilePick { filters: vec![("Flattener presets", PRESET_EXTS)], ..Default::default() };
|
||||
let path = app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?;
|
||||
let path = crate::picks::open(app, &pick).ok_or("cancelled")?;
|
||||
let r = app.run("flattener.presets.import", json!({ "path": path }))?;
|
||||
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
|
||||
select(d, first);
|
||||
|
||||
@@ -122,7 +122,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
p if !p.is_empty() => p,
|
||||
_ => {
|
||||
let pick = crate::FilePick { filters: vectorcraft_engine::cmd::fileio::place_filters().collect(), ..Default::default() };
|
||||
app.services.pick_open.as_mut().and_then(|f| f(&pick)).ok_or("cancelled")?
|
||||
crate::picks::open(app, &pick).ok_or("cancelled")?
|
||||
}
|
||||
};
|
||||
out = app.run("links.relink", json!({ "ids": current["ids"], "path": path }))?;
|
||||
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user