Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
9dec49ed03 | ||
|
|
dc157c6c5b | ||
|
|
aa125bfff1 | ||
|
|
22008b4e68 | ||
|
|
2497713779 | ||
|
|
1d013959cb | ||
|
|
b1f7d5ad7d |
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
+10
-10
@@ -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 |
|
||||
@@ -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).
|
||||
@@ -134,14 +134,14 @@ 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), 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. 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).
|
||||
- **Paint and appearance (M3):**
|
||||
@@ -158,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; 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).
|
||||
@@ -177,7 +177,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
|
||||
| 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, 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, 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 |
|
||||
@@ -213,7 +213,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| 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 | 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, 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 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 |
|
||||
| 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 |
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -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;
|
||||
@@ -83,9 +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::{
|
||||
AreaFit, 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;
|
||||
@@ -608,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")]
|
||||
@@ -700,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(),
|
||||
|
||||
+70
-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).
|
||||
@@ -758,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)]
|
||||
@@ -863,7 +930,7 @@ 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(),
|
||||
|
||||
@@ -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![
|
||||
|
||||
@@ -259,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
|
||||
|
||||
@@ -58,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, 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\" (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",
|
||||
"{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
|
||||
),
|
||||
@@ -447,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,
|
||||
|
||||
@@ -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;
|
||||
@@ -218,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());
|
||||
|
||||
@@ -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 (±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\" (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)",
|
||||
"{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
|
||||
),
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -198,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) };
|
||||
@@ -207,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\"",
|
||||
));
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -468,7 +475,7 @@ 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(),
|
||||
|
||||
@@ -219,7 +219,7 @@ fn release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -187,6 +187,20 @@ fn auto_height(t: &mut TextObject) -> bool {
|
||||
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![];
|
||||
@@ -216,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;
|
||||
@@ -320,7 +343,7 @@ fn set_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style = t.first_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 }];
|
||||
t.runs = vec![vectorcraft_doc::TextRun { text: text.clone(), style, inline: None }];
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
@@ -629,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());
|
||||
@@ -766,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]
|
||||
|
||||
@@ -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;
|
||||
@@ -323,7 +324,18 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
} else if let Some((ri, bi)) = locate(&t.runs, b) {
|
||||
t.splice_paras(b, b, "\n");
|
||||
t.runs[ri].text.insert(bi, '\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.
|
||||
@@ -481,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);
|
||||
}
|
||||
|
||||
@@ -531,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);
|
||||
}
|
||||
@@ -647,7 +664,7 @@ 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.runs = vec![TextRun { text, style: CharStyle::default(), inline: None }];
|
||||
t.set_all_paras(Default::default());
|
||||
refresh_bounds(t);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
@@ -1103,6 +1159,8 @@ impl Session {
|
||||
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.
|
||||
@@ -1388,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;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -501,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"));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -277,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();
|
||||
}
|
||||
@@ -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).
|
||||
|
||||
@@ -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;
|
||||
@@ -1684,7 +1714,9 @@ impl Writer<'_> {
|
||||
self.note_fonts(t, &lay);
|
||||
let lines = text_lines(t, &lay, self.opts.fewer_tspans);
|
||||
// Each line is anchored as its paragraph is aligned. A tab starts a new chunk at its
|
||||
// stop: lines with tabs are never anchored.
|
||||
// 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| {
|
||||
@@ -1693,7 +1725,7 @@ impl Writer<'_> {
|
||||
Justify::Right => Some(("end", 1.0)),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|_| !l.segs.iter().any(|s| s.brk))
|
||||
.filter(|_| !has_inline && !l.segs.iter().any(|s| s.brk))
|
||||
})
|
||||
.collect();
|
||||
// Every line anchored alike (the text's only paragraph style, typically): the <text>
|
||||
@@ -1985,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() {
|
||||
@@ -1998,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;
|
||||
|
||||
+87
-17
@@ -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};
|
||||
@@ -65,6 +65,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 +76,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() {
|
||||
@@ -136,9 +148,48 @@ pub(crate) fn import(svg: &str, opts: &ImportOptions) -> Result<(Document, Vec<S
|
||||
*ch = children;
|
||||
}
|
||||
}
|
||||
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";
|
||||
|
||||
/// 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 +265,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 +381,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 +453,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 +474,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 +498,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 +557,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 +667,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 +920,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)
|
||||
}
|
||||
|
||||
|
||||
@@ -892,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,7 +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
|
||||
//! editing data notices edits made elsewhere.
|
||||
//! hidden with their `data-*` attributes, clipped layers come in as clipping layers, layers and
|
||||
//! sublayers keep their names and nesting, 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 +350,173 @@ 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 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.
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -148,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
|
||||
|
||||
+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)
|
||||
|
||||
+44
-14
@@ -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,
|
||||
@@ -212,9 +222,12 @@ fn scaled(t: &TextObject, f: f64) -> TextObject {
|
||||
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();
|
||||
@@ -235,7 +248,8 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
|
||||
} 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`).
|
||||
@@ -275,6 +289,10 @@ fn layout_once(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLayout
|
||||
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;
|
||||
}
|
||||
@@ -412,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)
|
||||
}
|
||||
@@ -486,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)));
|
||||
@@ -1023,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
|
||||
@@ -1073,6 +1102,7 @@ mod wrapping_tests {
|
||||
xh: 4.0,
|
||||
ch,
|
||||
tcy: None,
|
||||
inline: None,
|
||||
lead: 0.0,
|
||||
level: unicode_bidi::Level::ltr(),
|
||||
})
|
||||
@@ -1128,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() {
|
||||
@@ -1508,7 +1538,7 @@ fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, regions: Optio
|
||||
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 {
|
||||
|
||||
+35
-2
@@ -25,7 +25,8 @@ 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};
|
||||
@@ -135,6 +136,22 @@ pub struct LineInfo {
|
||||
pub region: usize,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -156,6 +173,8 @@ pub struct TextLayout {
|
||||
/// 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 {
|
||||
@@ -170,6 +189,7 @@ impl Default for TextLayout {
|
||||
on_path: false,
|
||||
frames: Vec::new(),
|
||||
fit_scale: 1.0,
|
||||
inlines: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,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 {
|
||||
@@ -226,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
|
||||
}
|
||||
}
|
||||
@@ -475,6 +506,8 @@ 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -386,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);
|
||||
@@ -567,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);
|
||||
@@ -591,10 +591,10 @@ fn leading_model_is_per_paragraph() {
|
||||
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) },
|
||||
TextRun { text: "小\n".into(), style: st(20.0) },
|
||||
TextRun { text: "大\n".into(), style: st(40.0) },
|
||||
TextRun { text: "小".into(), style: st(20.0) },
|
||||
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),
|
||||
@@ -631,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).
|
||||
@@ -647,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.
|
||||
|
||||
@@ -148,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);
|
||||
@@ -173,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);
|
||||
@@ -194,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)));
|
||||
}
|
||||
|
||||
@@ -132,7 +132,7 @@ fn shrink_text_follows_top_to_top_leading_and_character_alignment() {
|
||||
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 });
|
||||
t.runs.insert(0, TextRun { text: "Big ".into(), style: big, inline: None });
|
||||
for r in &mut t.runs {
|
||||
r.style.char_align = CharAlign::EmBoxCenter;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -97,10 +97,10 @@ pub fn distribute(db: &FontDb, frames: &[&TextObject], runs: &[TextRun], paras:
|
||||
};
|
||||
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 };
|
||||
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 });
|
||||
@@ -126,7 +126,7 @@ 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 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:?}");
|
||||
@@ -147,7 +147,7 @@ mod tests {
|
||||
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() }];
|
||||
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)];
|
||||
@@ -178,7 +178,7 @@ mod tests {
|
||||
let (a, b) = (frame(0.0), frame(200.0));
|
||||
let st = CharStyle { size: 20.0, ..Default::default() };
|
||||
let parts: Vec<Vec<TextRun>> =
|
||||
distribute(db, &[&a, &b], &[TextRun { text: "Hi".into(), style: st }], &[]).into_iter().map(|s| s.runs).collect();
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -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!() };
|
||||
|
||||
+194
-18
@@ -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).
|
||||
@@ -1667,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")
|
||||
@@ -1865,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]
|
||||
@@ -2165,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()],
|
||||
|
||||
@@ -134,6 +134,10 @@ struct MenuState {
|
||||
/// The pass the list was last drawn in, and the pass it opened in.
|
||||
last: u64,
|
||||
opened: u64,
|
||||
/// The family the text had as the menu opened. A preview shows another one in the document
|
||||
/// (and the menu's caller), but this one stays the current family: hovering it ends the
|
||||
/// preview (#563).
|
||||
current: String,
|
||||
/// The highlighted row and the query and filters it belongs to.
|
||||
highlight: Option<usize>,
|
||||
query: String,
|
||||
@@ -194,6 +198,7 @@ fn list(ui: &mut Ui, state_id: egui::Id, st: &mut MenuState, current: &str, samp
|
||||
st.opened = pass;
|
||||
st.highlight = None;
|
||||
st.query.clear();
|
||||
st.current = current.to_string();
|
||||
}
|
||||
st.last = pass;
|
||||
// For [`end_stale_preview`]: the menu is open, in this layer.
|
||||
@@ -243,8 +248,9 @@ fn list(ui: &mut Ui, state_id: egui::Id, st: &mut MenuState, current: &str, samp
|
||||
});
|
||||
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// The current family by its own name (a document may name it in Japanese: ヒラギノ角ゴシック).
|
||||
let current = db.canonical(current, "").0;
|
||||
// The current family by its own name (a document may name it in Japanese: ヒラギノ角ゴシック),
|
||||
// as it was before any preview.
|
||||
let current = db.canonical(&st.current, "").0;
|
||||
let current = current.as_str();
|
||||
let favorite = |f: &str| look.favorites.iter().any(|x| x.eq_ignore_ascii_case(f));
|
||||
// The generation is read first: fonts that load meanwhile make the next frame list them.
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! The Free Transform widget (#598): while the Free Transform tool is active, a small floating box
|
||||
//! at the canvas's top left with Constrain (as holding Shift: proportional scaling, moves and
|
||||
//! rotations by 45°) over the tool's three modes, Free Transform, Perspective Distort and Free
|
||||
//! Distort. It sets the tool's options through `tool.setOption` (`constrain`, `mode`), as agents
|
||||
//! do; the modifier keys keep working while dragging.
|
||||
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The tool the widget belongs to.
|
||||
const TOOL: &str = "freeTransform";
|
||||
/// A button's side.
|
||||
const BUTTON: f32 = 28.0;
|
||||
|
||||
/// What a button shows.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Glyph {
|
||||
/// An icon of the set.
|
||||
Icon(&'static str),
|
||||
/// A box narrower at the top than at the bottom, its corners marked.
|
||||
Perspective,
|
||||
/// A box with corners pulled every which way, its corners marked.
|
||||
Distort,
|
||||
}
|
||||
|
||||
/// The tool's modes as its `mode` option names them, with their buttons.
|
||||
fn modes() -> [(&'static str, Glyph, &'static str); 3] {
|
||||
[
|
||||
("free", Glyph::Icon("dc-free-transform"), tl!("Free Transform")),
|
||||
("perspective", Glyph::Perspective, tl!("Perspective Distort")),
|
||||
("distort", Glyph::Distort, tl!("Free Distort")),
|
||||
]
|
||||
}
|
||||
|
||||
/// Where the widget was last drawn (none while it isn't shown).
|
||||
pub(crate) fn rect(ctx: &egui::Context) -> Option<Rect> {
|
||||
let id = egui::Id::new(TOOL);
|
||||
ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten())
|
||||
}
|
||||
|
||||
/// Show the widget in `canvas` (the canvas's area inside the rulers) while the Free Transform
|
||||
/// tool is active.
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &Ui, canvas: Rect) {
|
||||
if app.session.tool_id() != TOOL {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let opts = app.session.tool_options();
|
||||
let mode = opts["mode"].as_str().unwrap_or("free").to_string();
|
||||
let constrain = opts["constrain"].as_bool().unwrap_or(false);
|
||||
let mut set: Option<(&str, Value)> = None;
|
||||
egui::Area::new(egui::Id::new(TOOL)).order(egui::Order::Middle).fixed_pos(canvas.min + vec2(10.0, 10.0)).show(ui.ctx(), |ui| {
|
||||
egui::Frame::NONE
|
||||
.fill(t.panel)
|
||||
.stroke(Stroke::new(1.0, t.button_border))
|
||||
.corner_radius(CornerRadius::same(4))
|
||||
.inner_margin(egui::Margin::same(3))
|
||||
.shadow(egui::epaint::Shadow { offset: [0, 2], blur: 8, spread: 0, color: Color32::from_black_alpha(60) })
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
// Constrain shapes only what the Free Transform mode does.
|
||||
if button(ui, Glyph::Icon("link"), tl!("Constrain"), constrain, mode == "free") {
|
||||
set = Some(("constrain", json!(!constrain)));
|
||||
}
|
||||
let (line, _) = ui.allocate_exact_size(vec2(BUTTON, 3.0), Sense::hover());
|
||||
ui.painter().hline(line.x_range().shrink(4.0), line.center().y, Stroke::new(1.0, t.button_border));
|
||||
for (name, glyph, tip) in modes() {
|
||||
if button(ui, glyph, tip, mode == name, true) && mode != name {
|
||||
set = Some(("mode", json!(name)));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some((key, value)) = set
|
||||
&& let Err(e) = app.run("tool.setOption", json!({ "key": key, "value": value }))
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// A square button showing `glyph`, highlighted when `on`, greyed and inert unless `enabled`.
|
||||
/// Returns whether it was clicked.
|
||||
fn button(ui: &mut Ui, glyph: Glyph, tip: &str, on: bool, enabled: bool) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(BUTTON, BUTTON), if enabled { Sense::click() } else { Sense::hover() });
|
||||
let bg = if on && enabled {
|
||||
t.tool_active
|
||||
} else if enabled && resp.hovered() {
|
||||
t.hover
|
||||
} else {
|
||||
Color32::TRANSPARENT
|
||||
};
|
||||
ui.painter().rect_filled(rect, CornerRadius::same(3), bg);
|
||||
let color = match (enabled, on) {
|
||||
(false, _) => t.text_dim,
|
||||
(true, true) => t.text,
|
||||
(true, false) => t.icon,
|
||||
};
|
||||
paint(ui, glyph, rect.shrink(6.0), color);
|
||||
resp.on_hover_text(tip).clicked() && enabled
|
||||
}
|
||||
|
||||
/// Draw `glyph` in `r`.
|
||||
fn paint(ui: &Ui, glyph: Glyph, r: Rect, color: Color32) {
|
||||
let at = |x: f32, y: f32| pos2(r.left() + x * r.width(), r.top() + y * r.height());
|
||||
let quad: [Pos2; 4] = match glyph {
|
||||
Glyph::Icon(name) => return crate::icons::paint(ui, name, r, color),
|
||||
Glyph::Perspective => [at(0.3, 0.12), at(0.7, 0.12), at(0.95, 0.88), at(0.05, 0.88)],
|
||||
Glyph::Distort => [at(0.08, 0.2), at(0.78, 0.06), at(0.94, 0.9), at(0.2, 0.76)],
|
||||
};
|
||||
let (p, fill) = (ui.painter(), Tokens::get(ui.ctx()).panel);
|
||||
p.add(egui::Shape::closed_line(quad.to_vec(), Stroke::new(1.3, color)));
|
||||
for c in quad {
|
||||
let mark = Rect::from_center_size(c, vec2(3.5, 3.5));
|
||||
p.rect_filled(mark, 0.0, fill);
|
||||
p.rect_stroke(mark, 0.0, Stroke::new(1.0, color), StrokeKind::Middle);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::*;
|
||||
use crate::canvas::Xf;
|
||||
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
|
||||
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() };
|
||||
ctx.run_ui(raw, |ui| crate::canvas::show(app, ui)).textures_delta.clear();
|
||||
}
|
||||
|
||||
/// A press and release at `at`, then a frame to settle.
|
||||
fn click(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2) {
|
||||
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(app, ctx, vec![egui::Event::PointerMoved(at), button(true)]);
|
||||
frame(app, ctx, vec![button(false)]);
|
||||
frame(app, ctx, vec![]);
|
||||
}
|
||||
|
||||
fn options(app: &VectorcraftApp) -> (String, bool) {
|
||||
let o = app.session.tool_options();
|
||||
(o["mode"].as_str().unwrap_or_default().to_string(), o["constrain"].as_bool().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The widget shows with the Free Transform tool only; its buttons set the mode and Constrain
|
||||
/// (inert in the distort modes); a corner dragged in Free Distort moves that corner alone.
|
||||
#[test]
|
||||
fn the_widget_sets_the_mode_and_a_corner_drag_then_distorts() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 60})).unwrap()["id"].clone();
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
app.select_tool("selection");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(rect(&ctx).is_none(), "not with the Selection tool");
|
||||
app.select_tool(TOOL);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let w = rect(&ctx).expect("the widget shows");
|
||||
let canvas = app.canvas_rect.unwrap();
|
||||
assert!(canvas.contains(w.min) && w.left() - canvas.left() < 20.0 && w.top() - canvas.top() < 20.0, "{w:?} in {canvas:?}");
|
||||
// Constrain, a rule, then Free Transform, Perspective Distort and Free Distort.
|
||||
let at = |i: usize| {
|
||||
let rule = if i > 0 { 3.0 + 2.0 } else { 0.0 };
|
||||
pos2(w.center().x, w.top() + 4.0 + BUTTON / 2.0 + i as f32 * (BUTTON + 2.0) + rule)
|
||||
};
|
||||
assert_eq!(options(&app), ("free".into(), false));
|
||||
click(&mut app, &ctx, at(0));
|
||||
assert_eq!(options(&app), ("free".into(), true), "Constrain on");
|
||||
click(&mut app, &ctx, at(3));
|
||||
assert_eq!(options(&app), ("distort".into(), true));
|
||||
click(&mut app, &ctx, at(0));
|
||||
assert_eq!(options(&app), ("distort".into(), true), "Constrain is inert in Free Distort");
|
||||
click(&mut app, &ctx, at(2));
|
||||
assert_eq!(options(&app).0, "perspective");
|
||||
click(&mut app, &ctx, at(3));
|
||||
// Free Distort: the top-left corner dragged alone.
|
||||
let xf = Xf::new(canvas, app.view().unwrap());
|
||||
let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(80.0, 90.0)));
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) / 2.0)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]);
|
||||
frame(&mut app, &ctx, vec![button(to, false)]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let st = app.session.active().unwrap();
|
||||
let node = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap();
|
||||
let pts: Vec<Point> = node.path_data().unwrap().anchors().map(|(.., a)| a.p).collect();
|
||||
let near = |q: Point| pts.iter().any(|p| p.distance(q) < 0.5);
|
||||
assert!(
|
||||
near(Point::new(80.0, 90.0)) && near(Point::new(200.0, 100.0)) && near(Point::new(200.0, 160.0)) && near(Point::new(100.0, 160.0)),
|
||||
"{pts:?}"
|
||||
);
|
||||
assert_eq!(app.session.tool_id(), TOOL);
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,7 @@
|
||||
Create Outlines Převést na křivky
|
||||
Optical Margin Alignment Optické zarovnání okrajů
|
||||
Fill with Placeholder Text Vyplnit zástupným textem
|
||||
Insert Inline Symbol Vložit symbol do textu
|
||||
Show Hidden Characters Zobrazit skryté znaky
|
||||
Hide Hidden Characters Skrýt skryté znaky
|
||||
Type Orientation Orientace textu
|
||||
@@ -639,3 +640,6 @@
|
||||
Expand Shaper Group Rozšířit skupinu Shaper
|
||||
Release Shaper Group Uvolnit skupinu Shaper
|
||||
Select Shaper Face Vybrat oblast Shaper
|
||||
Constrain Omezit
|
||||
Free Transform Volná transformace
|
||||
Perspective Distort Perspektivní deformace
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -773,6 +773,8 @@
|
||||
Em Box Bottom/Left Abajo/izquierda del cuadro eme
|
||||
Em Box Center Centro del cuadro eme
|
||||
Em Box Top/Right Arriba/derecha del cuadro eme
|
||||
ICF Top/Right Arriba/derecha del ICF
|
||||
ICF Bottom/Left Abajo/izquierda del ICF
|
||||
Em Dash Raya
|
||||
Em Space Espacio eme
|
||||
Embed Incrustar
|
||||
@@ -922,6 +924,7 @@
|
||||
Fill New Type Objects With Placeholder Text Rellenar nuevos objetos de texto con texto de muestra
|
||||
Fill Rule Regla de relleno
|
||||
Fill with Placeholder Text Rellenar con texto de muestra
|
||||
Insert Inline Symbol Insertar símbolo en el texto
|
||||
Fill: Relleno:
|
||||
Fill: click for swatches, Shift-click for the color mixer Relleno: clic para muestras, Shift+clic para el mezclador de colores
|
||||
Find Buscar
|
||||
@@ -1492,6 +1495,8 @@
|
||||
New Art Brush from Selection Nuevo pincel de arte a partir de la selección
|
||||
New Art Has Basic Appearance La nueva ilustración tiene apariencia básica
|
||||
New Artboard Nueva mesa de trabajo
|
||||
Artboard Mesa de trabajo
|
||||
Exit Salir
|
||||
New Bristle Brush Nuevo pincel de cerdas
|
||||
New Brush… Nuevo pincel…
|
||||
New Calligraphic Brush Nuevo pincel caligráfico
|
||||
@@ -3603,3 +3608,6 @@ axis Both Ambos
|
||||
Expand Shaper Group Expandir grupo Shaper
|
||||
Release Shaper Group Soltar grupo Shaper
|
||||
Select Shaper Face Seleccionar cara Shaper
|
||||
Constrain Restringir
|
||||
Free Transform Transformación libre
|
||||
Perspective Distort Distorsión de perspectiva
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
File diff suppressed because it is too large.
Load diff
@@ -773,6 +773,8 @@
|
||||
Em Box Bottom/Left Riquadro em in basso/a sinistra
|
||||
Em Box Center Riquadro em al centro
|
||||
Em Box Top/Right Riquadro em in alto/a destra
|
||||
ICF Top/Right ICF in alto/a destra
|
||||
ICF Bottom/Left ICF in basso/a sinistra
|
||||
Em Dash Lineetta
|
||||
Em Space Spazio em
|
||||
Embed Incorpora
|
||||
@@ -1189,6 +1191,7 @@
|
||||
Input White Bianco di input
|
||||
Insert Break Character Inserisci carattere di interruzione
|
||||
Insert Character Inserisci carattere
|
||||
Insert Inline Symbol Inserisci simbolo nel testo
|
||||
Insert Special Character Inserisci carattere speciale
|
||||
Insert Whitespace Character Inserisci carattere spazio
|
||||
Inspect Document Ispeziona documento
|
||||
@@ -1492,6 +1495,8 @@
|
||||
New Art Brush from Selection Nuovo pennello artistico dalla selezione
|
||||
New Art Has Basic Appearance La nuova grafica ha aspetto di base
|
||||
New Artboard Nuova tavola da disegno
|
||||
Artboard Tavola da disegno
|
||||
Exit Esci
|
||||
New Bristle Brush Nuovo pennello a setole
|
||||
New Brush… Nuovo pennello…
|
||||
New Calligraphic Brush Nuovo pennello calligrafico
|
||||
@@ -3603,3 +3608,6 @@ axis Both Entrambi
|
||||
Expand Shaper Group Espandi gruppo Shaper
|
||||
Release Shaper Group Rilascia gruppo Shaper
|
||||
Select Shaper Face Seleziona faccia Shaper
|
||||
Constrain Vincola
|
||||
Free Transform Trasformazione libera
|
||||
Perspective Distort Distorsione prospettica
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -29,6 +29,8 @@
|
||||
Em Box Bottom/Left 仮想ボディの下 / 左
|
||||
Em Box Center 仮想ボディの中央
|
||||
Em Box Top/Right 仮想ボディの上 / 右
|
||||
ICF Top/Right 平均字面の上 / 右
|
||||
ICF Bottom/Left 平均字面の下 / 左
|
||||
Favorites お気に入り
|
||||
Flip 反転
|
||||
Japanese 日本語
|
||||
@@ -319,6 +321,7 @@
|
||||
Create Outlines アウトラインを作成
|
||||
Optical Margin Alignment 最適なマージン揃え
|
||||
Fill with Placeholder Text サンプルテキストの割り付け
|
||||
Insert Inline Symbol インラインシンボルを挿入
|
||||
Show Hidden Characters 制御文字を表示
|
||||
Type Orientation 組み方向
|
||||
Horizontal 横書き
|
||||
@@ -1635,6 +1638,8 @@
|
||||
New Art Brush from Selection 選択範囲から新規アートブラシ
|
||||
New Art Has Basic Appearance 新規アートに基本アピアランスを使用
|
||||
New Artboard 新規アートボード
|
||||
Artboard アートボード
|
||||
Exit 終了
|
||||
New Bristle Brush 新規剛毛ブラシ
|
||||
New Brush… 新規ブラシ…
|
||||
New Calligraphic Brush 新規絵筆ブラシ
|
||||
@@ -3065,3 +3070,6 @@ theme Appearance 外観
|
||||
Expand Shaper Group Shaper グループを拡張
|
||||
Release Shaper Group Shaper グループを解除
|
||||
Select Shaper Face Shaper の面を選択
|
||||
Constrain 制限
|
||||
Free Transform 自由変形
|
||||
Perspective Distort 遠近変形
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -63,6 +63,11 @@ fn plural_czech(n: u64) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
/// French: 0 and 1 are `one` (« 0 calque »), everything else `other`.
|
||||
fn plural_french(n: u64) -> usize {
|
||||
usize::from(n > 1)
|
||||
}
|
||||
|
||||
/// Russian: 1 (but not 11) is `one`, 2–4 (but not 12–14) `few`, everything else `many`.
|
||||
fn plural_russian(n: u64) -> usize {
|
||||
match n % 100 {
|
||||
@@ -76,7 +81,7 @@ fn plural_russian(n: u64) -> usize {
|
||||
}
|
||||
|
||||
/// The registry. English first: it is the fallback and the source language.
|
||||
pub static LANGUAGES: [LangInfo; 9] = [
|
||||
pub static LANGUAGES: [LangInfo; 10] = [
|
||||
LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() },
|
||||
// Japanese: the whole interface (every menu string and `tl!` literal), keeping the product,
|
||||
// workspace and perspective preset names in English (`MENU_KEEP_AS_IS`).
|
||||
@@ -93,6 +98,9 @@ pub static LANGUAGES: [LangInfo; 9] = [
|
||||
complete_menus: true,
|
||||
catalog: OnceLock::new(),
|
||||
},
|
||||
// French: the whole interface and the status and error messages, keeping the same names in
|
||||
// English as Spanish; every `fr-*` locale (`fr-FR`, `fr-BE`, `fr-CA`, `fr-CH` …) resolves here.
|
||||
LangInfo { code: "fr", name: "Français", source: include_str!("fr.tsv"), plural: plural_french, complete_menus: true, catalog: OnceLock::new() },
|
||||
// Italian: the whole interface and the status and error messages, keeping the same names in
|
||||
// English as Spanish; every `it-*` locale (`it-IT`, `it-CH`, `it-SM` …) resolves here.
|
||||
LangInfo {
|
||||
|
||||
@@ -730,6 +730,8 @@
|
||||
Em Box Bottom/Left Base/Esquerda da Caixa Eme
|
||||
Em Box Center Centro da Caixa Eme
|
||||
Em Box Top/Right Topo/Direita da Caixa Eme
|
||||
ICF Top/Right Topo/Direita do ICF
|
||||
ICF Bottom/Left Base/Esquerda do ICF
|
||||
Em Dash Travessão
|
||||
Em Space Espaço Em
|
||||
Embed Incorporar
|
||||
@@ -863,6 +865,7 @@
|
||||
Fill and Stroke Preenchimento e Traçado
|
||||
Fill new strokes Preencher novos traçados
|
||||
Fill with Placeholder Text Preencher com Texto de Placeholder
|
||||
Insert Inline Symbol Inserir Símbolo no Texto
|
||||
Fill: Preenchimento:
|
||||
Find Localizar
|
||||
Find Font Localizar Fonte
|
||||
@@ -2653,3 +2656,6 @@
|
||||
Expand Shaper Group Expandir Grupo Formador
|
||||
Release Shaper Group Liberar Grupo Formador
|
||||
Select Shaper Face Selecionar Face do Formador
|
||||
Constrain Restringir
|
||||
Free Transform Transformação Livre
|
||||
Perspective Distort Distorção de Perspectiva
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -771,6 +771,8 @@
|
||||
Em Box Bottom/Left Низ/лево кегельной площадки
|
||||
Em Box Center Центр кегельной площадки
|
||||
Em Box Top/Right Верх/право кегельной площадки
|
||||
ICF Top/Right Верх/право ICF
|
||||
ICF Bottom/Left Низ/лево ICF
|
||||
Em Dash Длинное тире
|
||||
Em Space Круглая шпация
|
||||
Embed Внедрить
|
||||
@@ -1187,6 +1189,7 @@
|
||||
Input White Входной белый
|
||||
Insert Break Character Вставить символ разрыва
|
||||
Insert Character Вставить символ
|
||||
Insert Inline Symbol Вставить символ в текст
|
||||
Insert Special Character Вставить специальный символ
|
||||
Insert Whitespace Character Вставить символ пробела
|
||||
Inspect Document Проверить документ
|
||||
@@ -3601,3 +3604,8 @@ axis Both Оба
|
||||
Expand Shaper Group Разобрать группу Shaper
|
||||
Release Shaper Group Освободить группу Shaper
|
||||
Select Shaper Face Выбрать область Shaper
|
||||
Constrain Ограничить
|
||||
Free Transform Свободное трансформирование
|
||||
Perspective Distort Искажение перспективы
|
||||
Artboard Монтажная область
|
||||
Exit Выйти
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -8,16 +8,16 @@ fn tags_map_to_languages() {
|
||||
assert_eq!(lang_from_tag("en_US.UTF-8"), Some(Lang::EN));
|
||||
assert_eq!(lang_from_tag("C"), Some(Lang::EN));
|
||||
assert_eq!(lang_from_tag("POSIX"), Some(Lang::EN));
|
||||
assert_eq!(lang_from_tag("fr_FR"), None);
|
||||
assert_eq!(lang_from_tag("de_DE"), None);
|
||||
assert_eq!(lang_from_tag("ja_JP.UTF-8"), Lang::from_code("ja"));
|
||||
assert_eq!(lang_from_tag("ja"), Lang::from_code("ja"));
|
||||
// Spanish: every region (and Latin America as a whole) resolves to the one catalog.
|
||||
for tag in ["es", "es_ES.UTF-8", "es-MX", "es_AR", "es-419", "es-US"] {
|
||||
assert_eq!(lang_from_tag(tag), Lang::from_code("es"), "{tag}");
|
||||
}
|
||||
// Italian: Italy, Switzerland and San Marino share the one catalog.
|
||||
for tag in ["it", "it_IT.UTF-8", "it-CH", "it_SM"] {
|
||||
assert_eq!(lang_from_tag(tag), Lang::from_code("it"), "{tag}");
|
||||
// French: France, Belgium, Canada, Switzerland and the rest share the one catalog.
|
||||
for tag in ["fr", "fr_FR.UTF-8", "fr-BE", "fr_CA", "fr-CH", "fr-LU"] {
|
||||
assert_eq!(lang_from_tag(tag), Lang::from_code("fr"), "{tag}");
|
||||
}
|
||||
// Traditional Chinese: by region, by script, and with a region after the script.
|
||||
assert_eq!(lang_from_tag("zh_TW.UTF-8"), Some(ZH()));
|
||||
@@ -48,7 +48,8 @@ fn candidates_walk_from_specific_to_general() {
|
||||
#[test]
|
||||
fn os_language_lists_are_parsed() {
|
||||
assert_eq!(first_supported("(\n \"zh-Hant-TW\",\n \"en-US\"\n)\n"), Some(ZH()));
|
||||
assert_eq!(first_supported("(\n \"fr-FR\",\n \"en-US\"\n)\n"), Some(Lang::EN));
|
||||
assert_eq!(first_supported("(\n \"de-DE\",\n \"en-US\"\n)\n"), Some(Lang::EN));
|
||||
assert_eq!(first_supported("(\n \"fr-FR\",\n \"en-US\"\n)\n"), Lang::from_code("fr"));
|
||||
assert_eq!(first_supported("("), None);
|
||||
// Windows: `reg query HKCU\Control Panel\International /v LocaleName`.
|
||||
let reg = "\r\nHKEY_CURRENT_USER\\Control Panel\\International\r\n LocaleName REG_SZ zh-TW\r\n\r\n";
|
||||
@@ -418,7 +419,7 @@ fn cs() -> Lang {
|
||||
}
|
||||
|
||||
/// Languages whose catalogs leave [`MENU_KEEP_AS_IS`] in English.
|
||||
const KEEPS_MENU_NAMES: [&str; 6] = ["cs", "es", "it", "ja", "pt-br", "ru"];
|
||||
const KEEPS_MENU_NAMES: [&str; 7] = ["cs", "es", "fr", "it", "ja", "pt-br", "ru"];
|
||||
|
||||
/// Menu labels the menu-complete catalogs (Czech, Spanish, Italian, Japanese, Brazilian Portuguese) show as they are: the product name, a format name, the built-in workspace
|
||||
/// names and the perspective grid presets (names, shown untranslated wherever else they appear).
|
||||
@@ -542,6 +543,10 @@ fn menu_catalogs_translate_every_menu_label() {
|
||||
}
|
||||
assert_eq!(tr(cs(), "File"), "Soubor");
|
||||
assert_eq!(tr(Lang::from_code("ja").expect("ja"), "File"), "ファイル");
|
||||
// Italian: Italy, Switzerland and San Marino share the one catalog.
|
||||
for tag in ["it", "it_IT.UTF-8", "it-CH", "it_SM"] {
|
||||
assert_eq!(lang_from_tag(tag), Lang::from_code("it"), "{tag}");
|
||||
}
|
||||
assert_eq!(tr(Lang::from_code("pt-br").expect("pt-br"), "File"), "Arquivo");
|
||||
assert_eq!(tr(es(), "File"), "Archivo");
|
||||
assert_eq!(tr(it(), "Edit"), "Modifica");
|
||||
@@ -551,6 +556,10 @@ fn es() -> Lang {
|
||||
Lang::from_code("es").expect("es registered")
|
||||
}
|
||||
|
||||
fn fr() -> Lang {
|
||||
Lang::from_code("fr").expect("fr registered")
|
||||
}
|
||||
|
||||
fn it() -> Lang {
|
||||
Lang::from_code("it").expect("it registered")
|
||||
}
|
||||
@@ -580,6 +589,27 @@ fn spanish_reads_as_spanish() {
|
||||
assert_eq!(trn(es(), 3, "{n} Layer", "{n} Layers"), "3 capas");
|
||||
}
|
||||
|
||||
/// French uses the vector-illustration vocabulary its users know, puts zero in the singular (« 0
|
||||
/// calque »), and reads the same in the menus and in the panels.
|
||||
#[test]
|
||||
fn french_reads_as_french() {
|
||||
for (en, want) in [
|
||||
("Artboard Tool", "Outil Plan de travail"),
|
||||
("Swatches", "Nuancier"),
|
||||
("Pathfinder", "Pathfinder"),
|
||||
("Stroke", "Contour"),
|
||||
("Fill", "Fond"),
|
||||
("Direct Selection Tool", "Outil Sélection directe"),
|
||||
("Save As…", "Enregistrer sous…"),
|
||||
("Undo", "Annuler"),
|
||||
] {
|
||||
assert_eq!(tr(fr(), en), want);
|
||||
}
|
||||
assert_eq!(trn(fr(), 0, "{n} Layer", "{n} Layers"), "0 calque");
|
||||
assert_eq!(trn(fr(), 1, "{n} Layer", "{n} Layers"), "1 calque");
|
||||
assert_eq!(trn(fr(), 2, "{n} Layer", "{n} Layers"), "2 calques");
|
||||
}
|
||||
|
||||
/// Italian uses the vector-illustration vocabulary its users know, has two plural forms like
|
||||
/// English (zero takes the plural), and reads the same in the menus and in the panels.
|
||||
#[test]
|
||||
@@ -649,11 +679,11 @@ fn russian_plurals_have_three_forms() {
|
||||
assert_eq!(forms, [2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 0]);
|
||||
}
|
||||
|
||||
/// Czech, Spanish and Italian letters (and the punctuation their text uses) come from each family's own first font, not
|
||||
/// Czech, Spanish, French and Italian letters (and the punctuation their text uses) come from each family's own first font, not
|
||||
/// from a fallback further down the stack. (`has_glyph` can't tell: it counts characters of the
|
||||
/// face that draws missing glyphs, the first one, as missing.)
|
||||
#[test]
|
||||
fn czech_spanish_and_italian_glyphs_are_available_without_system_fonts() {
|
||||
fn latin_script_glyphs_are_available_without_system_fonts() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
|
||||
@@ -664,7 +694,7 @@ fn czech_spanish_and_italian_glyphs_are_available_without_system_fonts() {
|
||||
let first = first.unwrap();
|
||||
let mut font = fonts.fonts.font(&family);
|
||||
let chars = font.characters();
|
||||
for ch in "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“‚‘…–ñÑüÜ¿¡”àèìòùÀÈÌÒÙ«»’".chars()
|
||||
for ch in "áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ„“‚‘…–ñÑüÜ¿¡”àèìòùÀÈÌÒÙ«»’âêîôûçëïÿœæÂÊÎÔÛÇËÏŒÆ\u{a0}".chars()
|
||||
{
|
||||
assert!(chars.get(&ch).is_some_and(|fonts| fonts.contains(&first)), "{first} ({family:?}) has no {ch}");
|
||||
}
|
||||
@@ -764,7 +794,7 @@ fn complete_languages_translate_every_message() {
|
||||
}
|
||||
|
||||
/// Languages whose catalogs cover every status and error message.
|
||||
const COMPLETE_MESSAGES: &[&str] = &["es", "it", "ru"];
|
||||
const COMPLETE_MESSAGES: &[&str] = &["es", "fr", "it", "ru"];
|
||||
|
||||
/// Crates whose error and status messages reach the status bar.
|
||||
const MESSAGE_CRATES: &[&str] = &["ui-egui", "engine", "doc", "format", "svg", "pdf", "eps", "text", "plugins", "metafile", "cad", "trace"];
|
||||
|
||||
@@ -768,6 +768,8 @@
|
||||
Em Box Bottom/Left 全角字框下 / 左
|
||||
Em Box Center 全角字框居中
|
||||
Em Box Top/Right 全角字框上 / 右
|
||||
ICF Top/Right ICF 上 / 右
|
||||
ICF Bottom/Left ICF 下 / 左
|
||||
Em Dash 长破折号
|
||||
Em Space 全角空格
|
||||
Embed 嵌入
|
||||
@@ -916,6 +918,7 @@
|
||||
Fill New Type Objects With Placeholder Text 用占位文本填充新文字对象
|
||||
Fill Rule 填充规则
|
||||
Fill with Placeholder Text 用占位文本填充
|
||||
Insert Inline Symbol 插入行内符号
|
||||
Fill: 填色:
|
||||
Fill: click for swatches, Shift-click for the color mixer 填色:单击开启色板,按住 Shift 单击开启混色器
|
||||
Find 查找
|
||||
@@ -1469,6 +1472,7 @@
|
||||
New Art Brush from Selection 从选区新建艺术画笔
|
||||
New Art Has Basic Appearance 新建图稿使用基本外观
|
||||
New Artboard 新建画板
|
||||
Exit 退出
|
||||
New Bristle Brush 新建鬃毛画笔
|
||||
New Brush… 新建画笔…
|
||||
New Calligraphic Brush 新建书法画笔
|
||||
@@ -3319,3 +3323,5 @@ axis Both 两者
|
||||
Expand Shaper Group 扩展 Shaper 组
|
||||
Release Shaper Group 释放 Shaper 组
|
||||
Select Shaper Face 选择 Shaper 区域
|
||||
Constrain 约束
|
||||
Perspective Distort 透视扭曲
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -788,6 +788,8 @@
|
||||
Em Box Bottom/Left 全形字框下 / 左
|
||||
Em Box Center 全形字框中央
|
||||
Em Box Top/Right 全形字框上 / 右
|
||||
ICF Top/Right ICF 上 / 右
|
||||
ICF Bottom/Left ICF 下 / 左
|
||||
Em Dash 長破折號
|
||||
Em Space 全形空格
|
||||
Embed 嵌入
|
||||
@@ -939,6 +941,7 @@
|
||||
Fill New Type Objects With Placeholder Text 以預留位置文字填滿新文字物件
|
||||
Fill Rule 填色規則
|
||||
Fill with Placeholder Text 以預留位置文字填滿
|
||||
Insert Inline Symbol 插入行內符號
|
||||
Fill: 填色:
|
||||
Fill: click for swatches, Shift-click for the color mixer 填色:按一下開啟色票,按住 Shift 按一下開啟混色器
|
||||
Find 尋找
|
||||
@@ -1509,6 +1512,8 @@
|
||||
New Art Brush from Selection 從選取範圍新增藝術筆刷
|
||||
New Art Has Basic Appearance 新圖稿具有基本外觀
|
||||
New Artboard 新增工作區域
|
||||
Artboard 工作區域
|
||||
Exit 結束
|
||||
New Bristle Brush 新增鬃毛筆刷
|
||||
New Brush… 新增筆刷…
|
||||
New Calligraphic Brush 新增書法筆刷
|
||||
@@ -3095,3 +3100,6 @@ axis Both 兩者
|
||||
Expand Shaper Group 展開 Shaper 群組
|
||||
Release Shaper Group 釋放 Shaper 群組
|
||||
Select Shaper Face 選取 Shaper 區域
|
||||
Constrain 強制
|
||||
Free Transform 任意變形
|
||||
Perspective Distort 透視扭曲
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -27,6 +27,7 @@ pub mod dock;
|
||||
pub mod find_font;
|
||||
pub mod floating;
|
||||
pub mod font_menu;
|
||||
mod free_transform;
|
||||
pub mod graphics;
|
||||
pub mod i18n;
|
||||
pub mod icon_data;
|
||||
@@ -50,6 +51,7 @@ pub mod sysclip;
|
||||
pub mod theme;
|
||||
pub mod titlebar;
|
||||
pub mod toolbar;
|
||||
mod touch;
|
||||
mod ui_fonts;
|
||||
pub mod unsaved;
|
||||
pub mod widgets;
|
||||
@@ -286,6 +288,9 @@ pub struct CacheKey {
|
||||
pub anti_alias: bool,
|
||||
/// [`vectorcraft_render::placed_document::generation`]: placed documents' bitmaps made since.
|
||||
pub placed: u64,
|
||||
/// View › Pixel Preview: the document pixels rendered (x0, y0, x1, y1), one per point, shown
|
||||
/// with hard edges. None: the art is rendered for the screen.
|
||||
pub pixel: Option<[i64; 4]>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
|
||||
@@ -2263,6 +2263,7 @@ pub fn menu_tree() -> Vec<(&'static str, Vec<Item>)> {
|
||||
todo("Optical Margin Alignment"),
|
||||
Sep,
|
||||
c("Fill with Placeholder Text", "type.fillPlaceholder"),
|
||||
c("Insert Inline Symbol", "text.insertInline"),
|
||||
Sep,
|
||||
c("Show Hidden Characters", "type.hiddenCharacters"),
|
||||
sub("Type Orientation", vec![c("Horizontal", "type.orientation.horizontal"), c("Vertical", "type.orientation.vertical")]),
|
||||
|
||||
@@ -13,13 +13,13 @@ use crate::widgets::{self, menu_item};
|
||||
use crate::{VectorcraftApp, icons};
|
||||
|
||||
/// The active artboard (of `n`).
|
||||
fn selected(app: &VectorcraftApp, n: usize) -> usize {
|
||||
pub(crate) fn selected(app: &VectorcraftApp, n: usize) -> usize {
|
||||
app.view().map_or(0, |v| v.artboard).min(n.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Make artboard `i` the active one, leaving the view where it is: the navigator's and, while it
|
||||
/// is the tool, the Artboard tool's.
|
||||
fn select(app: &mut VectorcraftApp, i: usize) {
|
||||
pub(crate) fn select(app: &mut VectorcraftApp, i: usize) {
|
||||
if let Some(v) = app.view_mut() {
|
||||
v.artboard = i;
|
||||
}
|
||||
|
||||
@@ -513,6 +513,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
(tl!("Em Box Top/Right"), CharAlign::EmBoxTop, "emBoxTop"),
|
||||
(tl!("Em Box Center"), CharAlign::EmBoxCenter, "emBoxCenter"),
|
||||
(tl!("Em Box Bottom/Left"), CharAlign::EmBoxBottom, "emBoxBottom"),
|
||||
(tl!("ICF Top/Right"), CharAlign::IcfTop, "icfTop"),
|
||||
(tl!("ICF Bottom/Left"), CharAlign::IcfBottom, "icfBottom"),
|
||||
] {
|
||||
if menu_item(ui, label, true, align == Some(a)) {
|
||||
format(app, json!({"charAlign": key}));
|
||||
|
||||
@@ -24,13 +24,20 @@
|
||||
//! on the trash clears it.
|
||||
//!
|
||||
//! While an opacity mask is edited the panel lists only its art, under an `<Opacity Mask>` entry.
|
||||
//!
|
||||
//! The rows open are the document's ([`OpenRows`], saved in native files): a document opens with
|
||||
//! only its top-level layers open. The rows shown are listed once per document change, and only
|
||||
//! those scrolled into view are laid out, so a document of many thousand objects costs no more
|
||||
//! per frame than a small one.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_engine::OpenRows;
|
||||
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::{Live, PanelDrag};
|
||||
@@ -198,9 +205,97 @@ fn opens(n: &Node, opts: &PanelOptions) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` or anything in it has a name containing `q` (lowercase).
|
||||
fn matches(n: &Node, q: &str) -> bool {
|
||||
n.display_name().to_lowercase().contains(q) || n.children().is_some_and(|c| c.iter().any(|c| matches(c, q)))
|
||||
/// One row of the panel.
|
||||
#[derive(Clone)]
|
||||
struct Row {
|
||||
node: Arc<Node>,
|
||||
/// Nesting level (0: a top-level layer).
|
||||
depth: usize,
|
||||
/// A clipping path: its group or layer clips.
|
||||
clip_path: bool,
|
||||
/// It holds rows ([`opens`]), and shows them.
|
||||
opens: bool,
|
||||
open: bool,
|
||||
/// The colour of its layer (its own, for a layer).
|
||||
colour: Color32,
|
||||
/// Drawn dimmed: hidden itself or in a hidden layer or group, or a template layer.
|
||||
dim: bool,
|
||||
}
|
||||
|
||||
/// What the rows were listed from: listed again when any of it changes.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct RowsKey {
|
||||
uid: u64,
|
||||
revision: u64,
|
||||
open: u64,
|
||||
layers_only: bool,
|
||||
query: String,
|
||||
}
|
||||
|
||||
/// The rows the panel shows, top down: the layers (only the opacity mask's while one is edited)
|
||||
/// with the rows of the open ones inside them. A search shows every row whose name, or the name of
|
||||
/// anything inside it, contains `query` (lowercase).
|
||||
fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str) -> Vec<Row> {
|
||||
let mask_layer = doc.mask_edit.map(|m| m.layer);
|
||||
let mut out = vec![];
|
||||
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
|
||||
push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Add the rows of `n` and those open inside it to `out`; `(colour, shown)` are those of what holds
|
||||
/// it (the layer's colour, and whether it is visible).
|
||||
fn push_rows(
|
||||
n: &Arc<Node>,
|
||||
depth: usize,
|
||||
clip_path: bool,
|
||||
(colour, shown): (Color32, bool),
|
||||
cx: (&OpenRows, &PanelOptions, &str),
|
||||
out: &mut Vec<Row>,
|
||||
) {
|
||||
let (open_rows, opts, query) = cx;
|
||||
if opts.layers_only && !n.is_layer() {
|
||||
return;
|
||||
}
|
||||
let colour = match &n.kind {
|
||||
NodeKind::Layer { color, .. } => {
|
||||
let [r, g, b] = color.rgb();
|
||||
Color32::from_rgb(r, g, b)
|
||||
}
|
||||
_ => colour,
|
||||
};
|
||||
let shown = shown && n.visible;
|
||||
let opens = opens(n, opts);
|
||||
let searching = !query.is_empty();
|
||||
let open = opens && (searching || open_rows.contains(n.id));
|
||||
let at = out.len();
|
||||
out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template() });
|
||||
if open && let Some(children) = n.children() {
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
push_rows(c, depth + 1, i == 0 && n.clips(), (colour, shown), cx, out);
|
||||
}
|
||||
}
|
||||
// Searching, a row stays for its own name or for a row it keeps inside it.
|
||||
if searching && out.len() == at + 1 && !n.display_name().to_lowercase().contains(query) {
|
||||
out.truncate(at);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of the active document as [`list_rows`] lists them, listed again only when the
|
||||
/// document, its open rows, the search or Show Layers Only changed.
|
||||
fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str) -> Arc<Vec<Row>> {
|
||||
let now =
|
||||
RowsKey { uid: st.uid, revision: st.revision, open: st.layers_open.generation(), layers_only: opts.layers_only, query: query.to_string() };
|
||||
let id = key("rows");
|
||||
if let Some((was, rows)) = ui.data(|d| d.get_temp::<(RowsKey, Arc<Vec<Row>>)>(id))
|
||||
&& was == now
|
||||
{
|
||||
return rows;
|
||||
}
|
||||
let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query));
|
||||
ui.data_mut(|d| d.insert_temp(id, (now, rows.clone())));
|
||||
rows
|
||||
}
|
||||
|
||||
/// Everything one frame of the panel reads.
|
||||
@@ -213,8 +308,6 @@ struct View<'a> {
|
||||
opts: PanelOptions,
|
||||
t: Tokens,
|
||||
h: f32,
|
||||
/// The search field's text, lowercase (empty: every row).
|
||||
query: String,
|
||||
column: Option<ColumnDrag>,
|
||||
/// The row to scroll into view.
|
||||
reveal: Option<NodeId>,
|
||||
@@ -224,8 +317,6 @@ struct View<'a> {
|
||||
#[derive(Default)]
|
||||
struct Out {
|
||||
actions: Vec<(String, Value)>,
|
||||
/// The rows shown, top down.
|
||||
order: Vec<NodeId>,
|
||||
/// A row clicked with these modifiers (resolved once every row is listed).
|
||||
click: Option<(NodeId, egui::Modifiers)>,
|
||||
/// The column drag after this frame (`Some(None)`: it ended).
|
||||
@@ -249,23 +340,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
d.insert_temp(shown_doc, st.uid);
|
||||
});
|
||||
}
|
||||
let uid = st.uid;
|
||||
let doc = st.doc.clone();
|
||||
let rows = st.highlighted_rows();
|
||||
// Rows highlighted anew (a click, Locate Object, a new layer): open the layers around them.
|
||||
let seen: Vec<NodeId> = ui.data(|d| d.get_temp(key("seen"))).unwrap_or_default();
|
||||
let mut reveal = None;
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_insert_with(|| doc.layers.iter().map(|l| l.id.0).collect());
|
||||
if rows != seen {
|
||||
for r in &rows {
|
||||
for a in doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default() {
|
||||
expanded.insert(a.0);
|
||||
let around: Vec<NodeId> =
|
||||
rows.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect();
|
||||
if let Some(st) = app.session.active_mut() {
|
||||
for a in around {
|
||||
st.layers_open.set(a, true);
|
||||
}
|
||||
}
|
||||
reveal = rows.first().copied();
|
||||
ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone()));
|
||||
}
|
||||
let query = crate::widgets::search_field(ui, egui::Id::new("layers-search"), tl!("Search All")).trim().to_lowercase();
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query);
|
||||
let view = View {
|
||||
doc: &doc,
|
||||
sel: st.selection.objects.iter().copied().collect(),
|
||||
@@ -275,30 +368,31 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
opts: app.ui.layers_panel.clone(),
|
||||
t,
|
||||
h: app.ui.layers_panel.row(),
|
||||
query,
|
||||
column: ui.data(|d| d.get_temp(key("column"))),
|
||||
reveal,
|
||||
};
|
||||
// While an opacity mask is edited only its art is listed.
|
||||
let mask_layer = doc.mask_edit.map(|m| m.layer);
|
||||
let mut out = Out::default();
|
||||
ui.add_space(6.0);
|
||||
let list_h = ui.available_height() - 34.0;
|
||||
let list = egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show(ui, |ui| {
|
||||
// Only the rows in view are laid out; one revealed out of view is scrolled to.
|
||||
let revealed = reveal.and_then(|id| list.iter().position(|r| r.node.id == id));
|
||||
let scrolled = ui.scope(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_default();
|
||||
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
|
||||
row(ui, &view, l, 0, false, expanded, &mut out);
|
||||
}
|
||||
egui::ScrollArea::vertical().max_height(list_h).auto_shrink([false, false]).show_rows(ui, view.h, list.len(), |ui, range| {
|
||||
if let Some(i) = revealed.filter(|i| !range.contains(i)) {
|
||||
let top = ui.max_rect().top() + (i as f32 - range.start as f32) * view.h;
|
||||
ui.scroll_to_rect(egui::Rect::from_min_size(egui::pos2(ui.max_rect().left(), top), vec2(ui.max_rect().width(), view.h)), None);
|
||||
}
|
||||
for r in list.get(range).unwrap_or_default() {
|
||||
row(ui, &view, r, &mut out);
|
||||
}
|
||||
})
|
||||
});
|
||||
let list_rect = list.inner_rect;
|
||||
resolve_click(ui, &view, &mut out);
|
||||
let expanded = app.ui.layers_expanded.entry(uid).or_default();
|
||||
for (id, open) in out.toggle.drain(..) {
|
||||
if open {
|
||||
expanded.insert(id.0);
|
||||
} else {
|
||||
expanded.remove(&id.0);
|
||||
let list_rect = scrolled.inner.inner_rect;
|
||||
resolve_click(ui, &view, &list, &mut out);
|
||||
if let Some(st) = app.session.active_mut() {
|
||||
for (id, open) in out.toggle.drain(..) {
|
||||
st.layers_open.set(id, open);
|
||||
}
|
||||
}
|
||||
// The column drag: live while it lasts, one undo step when the button is released.
|
||||
@@ -415,15 +509,16 @@ fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc: &Document
|
||||
|
||||
/// Resolve the row clicked this frame: plain (highlight it), Ctrl/Cmd (toggle it) or Shift
|
||||
/// (highlight the rows from the last one clicked down to it).
|
||||
fn resolve_click(ui: &Ui, view: &View, out: &mut Out) {
|
||||
fn resolve_click(ui: &Ui, view: &View, list: &[Row], out: &mut Out) {
|
||||
let Some((id, m)) = out.click.take() else { return };
|
||||
let anchor: Option<NodeId> = ui.data(|d| d.get_temp(key("anchor")));
|
||||
ui.data_mut(|d| d.insert_temp(key("focus"), true));
|
||||
let at = |id: NodeId| list.iter().position(|r| r.node.id == id);
|
||||
if m.shift
|
||||
&& let Some(a) = anchor.or(view.rows.last().copied())
|
||||
&& let (Some(i), Some(j)) = (out.order.iter().position(|r| *r == a), out.order.iter().position(|r| *r == id))
|
||||
&& let (Some(i), Some(j)) = (at(a), at(id))
|
||||
{
|
||||
let range: Vec<u64> = out.order.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.0).collect();
|
||||
let range: Vec<u64> = list.get(i.min(j)..=i.max(j)).unwrap_or_default().iter().map(|r| r.node.id.0).collect();
|
||||
out.actions.push(("layer.highlight".into(), json!({"ids": range, "mode": if m.command { "add" } else { "set" }})));
|
||||
return;
|
||||
}
|
||||
@@ -447,19 +542,14 @@ fn takes(n: &Node, drag: &LayersDrag, doc: &Document) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expanded: &mut HashSet<u64>, out: &mut Out) {
|
||||
/// The widgets of row `item`.
|
||||
fn row(ui: &mut Ui, view: &View, item: &Row, out: &mut Out) {
|
||||
let n = &*item.node;
|
||||
let (depth, clip_path, has_children, open, color) = (item.depth, item.clip_path, item.opens, item.open, item.colour);
|
||||
let doc = view.doc;
|
||||
let t = &view.t;
|
||||
if !view.query.is_empty() && !matches(n, &view.query) {
|
||||
return;
|
||||
}
|
||||
if view.opts.layers_only && !n.is_layer() {
|
||||
return;
|
||||
}
|
||||
let h = view.h;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag());
|
||||
out.order.push(n.id);
|
||||
if view.reveal == Some(n.id) {
|
||||
ui.scroll_to_rect(r, None);
|
||||
}
|
||||
@@ -470,7 +560,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
n.walk(&mut |c| any |= c.id != n.id && view.sel.contains(&c.id));
|
||||
any
|
||||
});
|
||||
let color = layer_colour(doc, n.id);
|
||||
// Highlighted rows (else the current layer's).
|
||||
let highlighted = if view.rows.is_empty() { n.is_layer() && Some(n.id) == view.current } else { view.rows.contains(&n.id) };
|
||||
if highlighted {
|
||||
@@ -490,9 +579,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
colour_bar(ui, n, r, x, color);
|
||||
x += 6.0 + depth as f32 * INDENT;
|
||||
// Disclosure triangle; Alt opens or closes everything inside too.
|
||||
let searching = !view.query.is_empty();
|
||||
let has_children = opens(n, &view.opts);
|
||||
let open = has_children && (searching || expanded.contains(&n.id.0));
|
||||
if has_children {
|
||||
let dr = egui::Rect::from_min_size(egui::pos2(x, r.center().y - 8.0), vec2(14.0, 16.0));
|
||||
let dresp = ui.interact(dr, ui.id().with(("disc", n.id.0)), Sense::click());
|
||||
@@ -548,8 +634,7 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
} else {
|
||||
painted_name(n, &name, crate::i18n::current())
|
||||
};
|
||||
let dim = !doc.is_visible(n.id) || n.is_template();
|
||||
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if dim { t.text_dim } else { t.text });
|
||||
let text = painter.text(egui::pos2(x, r.center().y), egui::Align2::LEFT_CENTER, shown, font, if item.dim { t.text_dim } else { t.text });
|
||||
name_end = text.right();
|
||||
// A clipping path's name is underlined, a masked object's with a dashed line.
|
||||
if clip_path {
|
||||
@@ -605,11 +690,6 @@ fn row(ui: &mut Ui, view: &View, n: &Node, depth: usize, clip_path: bool, expand
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
drop_target(ui, view, n, r, x - 16.0, open, &resp, out);
|
||||
if open && let Some(children) = n.children() {
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
row(ui, view, c, depth + 1, i == 0 && n.clips(), expanded, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Alt-clicking row `n`'s eye (`eye`) or lock: Hide Others or Lock Others, every top-level layer
|
||||
@@ -951,15 +1031,9 @@ pub fn expand(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
v
|
||||
}
|
||||
};
|
||||
let uid = st.uid;
|
||||
let layers: Vec<u64> = st.doc.layers.iter().map(|l| l.id.0).collect();
|
||||
let set = app.ui.layers_expanded.entry(uid).or_insert_with(|| layers.into_iter().collect());
|
||||
let st = app.session.active_mut().ok_or("no document open")?;
|
||||
for i in &ids {
|
||||
if open {
|
||||
set.insert(*i);
|
||||
} else {
|
||||
set.remove(i);
|
||||
}
|
||||
st.layers_open.set(NodeId(*i), open);
|
||||
}
|
||||
Ok(json!({ "count": ids.len() }))
|
||||
}
|
||||
@@ -1623,4 +1697,53 @@ mod tests {
|
||||
assert_eq!(rows_of(&app), vec![sub]);
|
||||
assert_eq!(app.session.active().unwrap().current_layer(), Some(sub));
|
||||
}
|
||||
|
||||
/// A layer of 2,000 groups of 10 paths with every row open: one frame lays out only the rows
|
||||
/// in view, and a row highlighted far below them is scrolled to.
|
||||
#[test]
|
||||
fn only_the_rows_in_view_are_laid_out() {
|
||||
use vectorcraft_doc::Appearance;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let mut groups = vec![];
|
||||
let mut needle = None;
|
||||
for g in 0..2000 {
|
||||
let kids = (0..10)
|
||||
.map(|k| {
|
||||
let r = Rect::new(k as f64, g as f64 * 0.1, k as f64 + 1.0, g as f64 * 0.1 + 1.0);
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default());
|
||||
if g == 0 && k == 0 {
|
||||
n.name = Some("Needle".into());
|
||||
needle = Some(n.id);
|
||||
}
|
||||
Arc::new(n)
|
||||
})
|
||||
.collect();
|
||||
groups.push(Arc::new(Node::group(d.alloc_id(), kids)));
|
||||
}
|
||||
*Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.add_document(d, None);
|
||||
expand(&mut app, &json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
// (shapes drawn, whether the needle's name is among them); a second passes per frame, so
|
||||
// scrolling ends.
|
||||
let mut time = 0.0;
|
||||
let mut frame = |app: &mut VectorcraftApp| {
|
||||
time += 1.0;
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == "Needle"));
|
||||
(out.shapes.len(), found)
|
||||
};
|
||||
let (shapes, found) = frame(&mut app);
|
||||
// 22,001 rows; about 30 fit.
|
||||
assert!(shapes < 1000 && !found, "{shapes} shapes");
|
||||
let needle = needle.unwrap();
|
||||
app.session.execute("layer.highlight", &json!({"ids": [needle.0], "mode": "set"})).unwrap();
|
||||
let found = (0..4).any(|_| frame(&mut app).1);
|
||||
assert_eq!(app.session.active().unwrap().highlighted_rows(), [needle]);
|
||||
assert!(found, "the highlighted row is scrolled into view");
|
||||
}
|
||||
}
|
||||
@@ -346,10 +346,9 @@ pub(crate) fn paint_chip(app: &mut VectorcraftApp, ui: &mut Ui, stroke: bool, si
|
||||
app.run("paint.toggleActive", json!({ "fill": !stroke })).ok();
|
||||
set_pstate(ui.ctx(), MIXER, ui.input(|i| i.modifiers.shift));
|
||||
}
|
||||
egui::Popup::from_toggle_button_response(&resp)
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.width(POPOVER_WIDTH)
|
||||
.show(|ui| paint_popover(app, ui));
|
||||
// A popover that keeps its own open state: the Swatches body opens menus of its own (Swatch
|
||||
// Libraries, Show Swatch Kinds), which a remembered egui popup would close with them (#536).
|
||||
crate::widgets::popover(&resp, resp.clicked(), |ui| paint_popover(app, ui));
|
||||
}
|
||||
|
||||
/// The chip popovers' width (a narrow Swatches or Color panel).
|
||||
|
||||
@@ -18,7 +18,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let n_sel = st.selection.len();
|
||||
let anchors = crate::chrome::anchor_controls(app);
|
||||
let first = first_selected(app);
|
||||
// Edit Artboards (the Artboard tool): the active artboard, whatever is selected.
|
||||
let editing_artboards = app.session.tool_id() == "artboard";
|
||||
let label = match (&first, n_sel) {
|
||||
_ if editing_artboards => tl!("Artboard").to_string(),
|
||||
(None, _) => tl!("Document").to_string(),
|
||||
(_, n) if n > 1 => crate::i18n::tn(n as u64, "{n} Object", "{n} Objects"),
|
||||
(Some(n), _) if crate::panels::image_trace::is_trace(n) => tl!("Image Tracing").to_string(),
|
||||
@@ -26,6 +29,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
};
|
||||
ui.label(egui::RichText::new(label).size(11.5).color(t.text_dim));
|
||||
ui.add_space(4.0);
|
||||
if editing_artboards {
|
||||
artboard_sections(app, ui);
|
||||
return;
|
||||
}
|
||||
if first.is_none() {
|
||||
document_sections(app, ui);
|
||||
return;
|
||||
@@ -188,6 +195,48 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit Artboards (the Artboard tool): the active artboard's name, position and size, New Artboard
|
||||
/// and Delete Artboard, and Exit back to the Selection tool (#530).
|
||||
fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let units = app.session.general_unit();
|
||||
let n = app.session.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let i = super::artboards::selected(app, n);
|
||||
if let Some(ab) = app.session.active().and_then(|d| d.doc.artboards.get(i)).cloned() {
|
||||
// Its name as it is (names are never translated).
|
||||
ui.label(egui::RichText::new(&ab.name).size(13.0).color(Tokens::get(ui.ctx()).text));
|
||||
let fw = ((ui.available_width() - 50.0) / 2.0).clamp(60.0, 110.0);
|
||||
egui::Grid::new("ab-grid").num_columns(4).spacing([4.0, 6.0]).min_col_width(0.0).show(ui, |ui| {
|
||||
let r = ab.rect;
|
||||
for (row, [(l1, k1, v1), (l2, k2, v2)]) in
|
||||
[[("X:", "x", r.x0), ("W:", "width", r.width())], [("Y:", "y", r.y0), ("H:", "height", r.height())]].into_iter().enumerate()
|
||||
{
|
||||
for (label, key, v) in [(l1, k1, v1), (l2, k2, v2)] {
|
||||
dim_label(ui, label);
|
||||
if let Some(v) = widgets::num_field(ui, ("ab", key, row), Some(v), units, fw) {
|
||||
app.run("artboard.setProps", json!({"index": i, key: v})).ok();
|
||||
}
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let w = (ui.available_width() - 6.0) / 2.0;
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::flat_button(ui, tl!("New Artboard"), w).clicked() && app.run("artboard.new", json!({})).is_ok() {
|
||||
super::artboards::select(app, n);
|
||||
}
|
||||
if ui.add_enabled_ui(n > 1, |ui| widgets::flat_button(ui, tl!("Delete Artboard"), w)).inner.clicked() {
|
||||
app.run("artboard.delete", json!({"index": i})).ok();
|
||||
}
|
||||
});
|
||||
divider(ui);
|
||||
section_header(ui, tl!("Quick Actions"));
|
||||
if widgets::flat_button(ui, tl!("Exit"), w).clicked() {
|
||||
app.select_tool("selection");
|
||||
}
|
||||
}
|
||||
|
||||
fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let units = app.session.general_unit();
|
||||
section_header(ui, tl!("Document"));
|
||||
@@ -416,3 +465,58 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use egui::{Event, PointerButton, Pos2, Rect, vec2};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// One frame of the panel with `events` → the texts painted, with their rects.
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) -> Vec<(String, Rect)> {
|
||||
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 700.0))), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
|
||||
out.textures_delta.clear();
|
||||
out.shapes
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
if let egui::Shape::Text(t) = &s.shape {
|
||||
Some((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size())))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn click(app: &mut VectorcraftApp, ctx: &egui::Context, texts: &[(String, Rect)], label: &str) {
|
||||
let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no {label:?} in {texts:?}"));
|
||||
let b = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(app, ctx, vec![Event::PointerMoved(at), b(true)]);
|
||||
frame(app, ctx, vec![b(false)]);
|
||||
}
|
||||
|
||||
/// #530: Edit Artboards shows the active artboard, with New Artboard, Delete Artboard and Exit.
|
||||
#[test]
|
||||
fn edit_artboards_adds_artboards_and_exits() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
click(&mut app, &ctx, &texts, "Edit Artboards");
|
||||
assert_eq!(app.session.tool_id(), "artboard");
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(texts.iter().any(|(t, _)| t == "Artboard 1") && texts.iter().any(|(t, _)| t == "200 pt"), "{texts:?}");
|
||||
click(&mut app, &ctx, &texts, "New Artboard");
|
||||
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.len();
|
||||
assert_eq!(boards(&app), 2);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
assert!(texts.iter().any(|(t, _)| t == "Artboard 2"), "the new artboard is the active one: {texts:?}");
|
||||
click(&mut app, &ctx, &texts, "Delete Artboard");
|
||||
assert_eq!(boards(&app), 1);
|
||||
let texts = frame(&mut app, &ctx, vec![]);
|
||||
click(&mut app, &ctx, &texts, "Exit");
|
||||
assert_eq!(app.session.tool_id(), "selection");
|
||||
}
|
||||
}
|
||||
@@ -365,9 +365,6 @@ pub struct UiState {
|
||||
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only).
|
||||
#[serde(default)]
|
||||
pub layers_panel: crate::panels::layers::PanelOptions,
|
||||
/// The Layers panel's open rows, per open document (`DocState::uid` → node ids).
|
||||
#[serde(skip)]
|
||||
pub layers_expanded: std::collections::HashMap<u64, std::collections::HashSet<u64>>,
|
||||
/// The desktop window's size, position and maximized state, saved when the app quits and
|
||||
/// restored at the next launch (the desktop host reads and writes it; none on the web).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -521,7 +518,6 @@ impl Default for UiState {
|
||||
dxf_import: Value::Null,
|
||||
home: None,
|
||||
layers_panel: Default::default(),
|
||||
layers_expanded: Default::default(),
|
||||
window: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,3 +318,61 @@ fn the_search_field_stays_put_while_the_list_scrolls() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #563: a preview stays on the text while the menu stays on its family. The menu's caller passes
|
||||
/// the text's font, which the preview changed; the menu keeps the font from before the preview as
|
||||
/// the current one, so it doesn't take the previewed family for it and end the preview, then
|
||||
/// preview it again, every frame (the text flickered).
|
||||
#[test]
|
||||
fn a_preview_stays_put_while_the_menu_is_still() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let id = app.session.execute("text.create", &json!({"x": 20, "y": 50, "text": "Gagaku", "font": "Inter"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let font = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.first_style().font_family,
|
||||
_ => String::new(),
|
||||
};
|
||||
let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision;
|
||||
// A panel's frame: the menu shows the text's font, and what it picks is applied.
|
||||
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let input =
|
||||
egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 800.0))), ..Default::default() };
|
||||
let current = font(app);
|
||||
let (mut at, mut picked) = (egui::Pos2::ZERO, None);
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
crate::font_menu::end_stale_preview(app, ui.ctx());
|
||||
at = ui.next_widget_position();
|
||||
picked = font_menu(ui, "test-steady", ¤t, 260.0, None, MenuLook::default());
|
||||
if let Some(p) = picked.clone() {
|
||||
crate::font_menu::apply(app, ui.ctx(), p);
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
(at, picked)
|
||||
};
|
||||
let (at, _) = frame(&mut app, vec![]);
|
||||
let click = at + egui::vec2(40.0, 10.0);
|
||||
let button = |pressed| egui::Event::PointerButton { pos: click, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(click), button(true)]);
|
||||
frame(&mut app, vec![button(false)]);
|
||||
for _ in 0..5 {
|
||||
frame(&mut app, vec![]);
|
||||
}
|
||||
let (_, picked) = frame(&mut app, key(egui::Key::ArrowDown));
|
||||
assert!(matches!(picked, Some(FontPick::Preview(..))), "{picked:?}");
|
||||
let previewed = font(&app);
|
||||
assert_ne!(previewed, "Inter");
|
||||
let rev = revision(&app);
|
||||
for _ in 0..6 {
|
||||
let (_, picked) = frame(&mut app, vec![]);
|
||||
assert_eq!(picked, None, "nothing more to apply");
|
||||
}
|
||||
assert_eq!((font(&app), revision(&app)), (previewed, rev), "the preview stays, untouched");
|
||||
// Back on the text's own family, the preview ends.
|
||||
let (_, picked) = frame(&mut app, key(egui::Key::ArrowUp));
|
||||
assert_eq!(picked, Some(FontPick::EndPreview));
|
||||
assert_eq!(font(&app), "Inter");
|
||||
}
|
||||
@@ -270,3 +270,55 @@ fn the_transform_link_opens_the_transform_panel() {
|
||||
click(&mut app, &ctx, Pos2::new(1300.0, 900.0), Modifiers::NONE, control_bar);
|
||||
assert!(text_rect(&frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar), "Scale Corners").is_none());
|
||||
}
|
||||
|
||||
/// The 24 pt icon buttons of the popover's bottom bar (its Swatch Libraries Menu first), left to
|
||||
/// right.
|
||||
fn popover_bottom_buttons(ctx: &egui::Context) -> Vec<Rect> {
|
||||
let mut r: Vec<Rect> = ctx.viewport(|vp| {
|
||||
vp.prev_pass
|
||||
.widgets
|
||||
.layers()
|
||||
.filter(|(l, _)| l.order != egui::Order::Background)
|
||||
.flat_map(|(_, w)| w.iter())
|
||||
.filter(|w| w.rect.size() == vec2(24.0, 24.0))
|
||||
.map(|w| w.rect)
|
||||
.collect()
|
||||
});
|
||||
let bottom = r.iter().map(|r| r.top()).fold(f32::MIN, f32::max);
|
||||
r.retain(|w| (w.top() - bottom).abs() < 1.0);
|
||||
r.sort_by(|a, b| a.left().total_cmp(&b.left()));
|
||||
r
|
||||
}
|
||||
|
||||
/// A menu row's text (menu labels leave room for a check mark before them).
|
||||
fn menu_item_rect(shapes: &[Shape], s: &str) -> Option<Rect> {
|
||||
shapes.iter().find_map(|sh| match sh {
|
||||
Shape::Text(t) if t.galley.text().trim() == s => Some(t.visual_bounding_rect()),
|
||||
Shape::Vec(v) => menu_item_rect(v, s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// #536: the Swatch Libraries Menu button at the foot of a Fill chip's popover opens the
|
||||
/// libraries menu (it used to close the popover and show nothing), and a library chosen there
|
||||
/// opens in the library panel.
|
||||
#[test]
|
||||
fn the_popover_swatch_libraries_button_opens_the_libraries_menu() {
|
||||
let mut app = app();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let ctx = context();
|
||||
frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
|
||||
let (fill, _) = chips(&ctx);
|
||||
click(&mut app, &ctx, fill.center(), Modifiers::NONE, control_bar);
|
||||
let libraries = *popover_bottom_buttons(&ctx).first().expect("the popover has a bottom bar");
|
||||
click(&mut app, &ctx, libraries.center(), Modifiers::NONE, control_bar);
|
||||
let shapes = frame(&mut app, &ctx, vec![], Modifiers::NONE, control_bar);
|
||||
assert!(text_rect(&shapes, "Swatch Tiles").is_some(), "the popover stays open");
|
||||
let defaults = menu_item_rect(&shapes, "Default Swatches").expect("the libraries menu is open");
|
||||
assert!(menu_item_rect(&shapes, "Other Library…").is_some());
|
||||
let earth = menu_item_rect(&shapes, "Earth Tones").expect("the menu lists the built-in libraries");
|
||||
assert!(earth.top() > defaults.top());
|
||||
click(&mut app, &ctx, earth.center(), Modifiers::NONE, control_bar);
|
||||
let open = app.ui.library_panel.as_ref().map(|o| (o.kind.clone(), o.id.clone()));
|
||||
assert_eq!(open, Some(("swatches".into(), "earth-tones".into())));
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Touch gestures on the canvas (Preferences › Devices › Enable Touch Gestures, #585): a tap with
|
||||
//! two fingers undoes, one with three redoes.
|
||||
//!
|
||||
//! egui hands every finger's contact over as [`egui::Event::Touch`] (winit reads them from the
|
||||
//! system: `WM_POINTER` on Windows), and makes the first finger the mouse pointer too. So the first
|
||||
//! finger has pressed on the canvas by the time a second lands: that press is dropped then
|
||||
//! ([`Taps::feed`] says [`Touch::Fingers`]), and the tap undoes what came before it.
|
||||
|
||||
use egui::{Pos2, TouchId, TouchPhase};
|
||||
|
||||
/// How long the fingers of a tap may stay down, in seconds.
|
||||
const TAP_TIME: f64 = 0.5;
|
||||
/// How far (points) a finger of a tap may move: further, it is a pinch or a pan.
|
||||
const TAP_SLOP: f32 = 16.0;
|
||||
|
||||
/// What a touch event made of the gesture.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Touch {
|
||||
/// A second finger landed: the gesture isn't the first finger's press.
|
||||
Fingers,
|
||||
/// All fingers lifted from a tap of this many fingers (two or more).
|
||||
Tap(usize),
|
||||
}
|
||||
|
||||
/// The fingers down and how the gesture they make has gone so far.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Taps {
|
||||
/// Each finger down and where it landed.
|
||||
down: Vec<(TouchId, Pos2)>,
|
||||
/// The most fingers down at once in this gesture.
|
||||
most: usize,
|
||||
/// When its first finger landed.
|
||||
start: f64,
|
||||
/// A finger moved too far or stayed too long: not a tap.
|
||||
spoilt: bool,
|
||||
}
|
||||
|
||||
impl Taps {
|
||||
/// Follow a finger's `phase` at `pos` (touch `id`) at time `now` (seconds).
|
||||
pub(crate) fn feed(&mut self, id: TouchId, phase: TouchPhase, pos: Pos2, now: f64) -> Option<Touch> {
|
||||
match phase {
|
||||
TouchPhase::Start => {
|
||||
if self.down.is_empty() {
|
||||
*self = Self { start: now, ..Self::default() };
|
||||
}
|
||||
if !self.down.iter().any(|(d, _)| *d == id) {
|
||||
self.down.push((id, pos));
|
||||
}
|
||||
let before = self.most;
|
||||
self.most = self.most.max(self.down.len());
|
||||
(before < 2 && self.most >= 2).then_some(Touch::Fingers)
|
||||
}
|
||||
TouchPhase::Move => {
|
||||
if self.down.iter().any(|(d, at)| *d == id && at.distance(pos) > TAP_SLOP) {
|
||||
self.spoilt = true;
|
||||
}
|
||||
None
|
||||
}
|
||||
TouchPhase::End | TouchPhase::Cancel => {
|
||||
let known = self.down.len();
|
||||
self.down.retain(|(d, _)| *d != id);
|
||||
if self.down.len() == known {
|
||||
return None;
|
||||
}
|
||||
self.spoilt |= phase == TouchPhase::Cancel || now - self.start > TAP_TIME;
|
||||
(self.down.is_empty() && !self.spoilt && self.most >= 2).then_some(Touch::Tap(self.most))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A finger is down.
|
||||
pub(crate) fn is_down(&self) -> bool {
|
||||
!self.down.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The command a tap of `fingers` runs: two undo, three redo.
|
||||
pub(crate) fn tap_command(fingers: usize) -> Option<&'static str> {
|
||||
match fingers {
|
||||
2 => Some("edit.undo"),
|
||||
3 => Some("edit.redo"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn id(n: u64) -> TouchId {
|
||||
TouchId(n)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_and_three_finger_taps() {
|
||||
let mut t = Taps::default();
|
||||
let p = Pos2::new(100.0, 100.0);
|
||||
assert_eq!(t.feed(id(1), TouchPhase::Start, p, 0.0), None);
|
||||
assert_eq!(t.feed(id(2), TouchPhase::Start, p + egui::vec2(60.0, 0.0), 0.05), Some(Touch::Fingers));
|
||||
assert!(t.is_down());
|
||||
assert_eq!(t.feed(id(1), TouchPhase::Move, p + egui::vec2(3.0, 2.0), 0.1), None);
|
||||
assert_eq!(t.feed(id(1), TouchPhase::End, p, 0.15), None, "one finger still down");
|
||||
assert_eq!(t.feed(id(2), TouchPhase::End, p, 0.2), Some(Touch::Tap(2)));
|
||||
assert!(!t.is_down());
|
||||
// Three fingers.
|
||||
for (n, at) in [(4, 0.0), (5, 0.02), (6, 0.04)] {
|
||||
t.feed(id(n), TouchPhase::Start, p, 1.0 + at);
|
||||
}
|
||||
let ends: Vec<_> = [4, 5, 6].into_iter().map(|n| t.feed(id(n), TouchPhase::End, p, 1.2)).collect();
|
||||
assert_eq!(ends, [None, None, Some(Touch::Tap(3))]);
|
||||
assert_eq!((tap_command(2), tap_command(3), tap_command(1)), (Some("edit.undo"), Some("edit.redo"), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinch_a_long_press_a_cancel_or_one_finger_is_no_tap() {
|
||||
let p = Pos2::new(100.0, 100.0);
|
||||
let gesture = |moved: f32, held: f64, last: TouchPhase, fingers: u64| {
|
||||
let mut t = Taps::default();
|
||||
for n in 0..fingers {
|
||||
t.feed(id(n), TouchPhase::Start, p, 0.0);
|
||||
}
|
||||
t.feed(id(0), TouchPhase::Move, p + egui::vec2(moved, 0.0), held / 2.0);
|
||||
(0..fingers).filter_map(|n| t.feed(id(n), if n + 1 == fingers { last } else { TouchPhase::End }, p, held)).last()
|
||||
};
|
||||
assert_eq!(gesture(0.0, 0.2, TouchPhase::End, 2), Some(Touch::Tap(2)));
|
||||
assert_eq!(gesture(40.0, 0.2, TouchPhase::End, 2), None, "a pinch");
|
||||
assert_eq!(gesture(0.0, 0.9, TouchPhase::End, 2), None, "held too long");
|
||||
assert_eq!(gesture(0.0, 0.2, TouchPhase::Cancel, 2), None, "cancelled");
|
||||
assert_eq!(gesture(0.0, 0.2, TouchPhase::End, 1), None, "a pen or one finger");
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ so only enable it while you use it. Transport: `apps/vectorcraft/src/control_ser
|
||||
| `engine.execute` | `{command, params}` | run any engine or UI command (see `engine.commands`) |
|
||||
| `engine.commands` | | every command with label, shortcut, params doc, enablement |
|
||||
| `document.inspect` | `{depth?, childLimit?}` | layer tree, selection, history, paint defaults; the options slice the layer tree as `document.node {summary: true}` does |
|
||||
| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way) |
|
||||
| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way) |
|
||||
| `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item |
|
||||
| `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected |
|
||||
| `ui.tool.select` / `ui.tool.list` | `{tool}` | |
|
||||
@@ -214,6 +214,13 @@ Bar Position (`window.taskBar.reset`), which unpins it and puts it back under th
|
||||
Panel. As in Illustrator, neither the position nor the pin is saved: each launch starts with the bar under the
|
||||
selection.
|
||||
|
||||
The Free Transform widget: while the Free Transform tool (E) is active, a small box at the canvas's top left holds
|
||||
Constrain over the tool's three modes, Free Transform, Perspective Distort and Free Distort. The buttons set the tool's
|
||||
options, as `tool.setOption {key: "mode", value: "free"|"perspective"|"distort"}` and `{key: "constrain", value}` do:
|
||||
Constrain acts as Shift held (proportional scaling, moves and rotations by 45°) and does nothing in the distort modes,
|
||||
where it is greyed. The modifier keys still work while dragging (Cmd on a corner distorts it freely, Cmd+Alt+Shift in
|
||||
perspective, Cmd on a side shears).
|
||||
|
||||
Floating panels: dragging a dock tab, a panel icon or a popped-out panel's title out of the dock floats that panel
|
||||
inside the window, and the strip right of the dock's tabs floats the whole Properties | Layers | Libraries group. A
|
||||
floating group moves by its title bar (or the strip right of its tabs); a tab dragged out of it floats on its own;
|
||||
|
||||
+4
-3
@@ -134,7 +134,8 @@ Languages shipped: English (`en`, the source), Traditional Chinese (`zh-hant`, c
|
||||
in Taiwan; `zh-TW`, `zh-HK`, `zh-MO` and `zh-Hant-*` locales all resolve to it), Simplified Chinese (`zh-hans`,
|
||||
complete, in the vocabulary used in mainland China; `zh-CN`, `zh-SG`, `zh-Hans-*` and a bare `zh` resolve to it,
|
||||
so the two scripts never mix), Japanese (`ja`, complete), Spanish (`es`, complete, in neutral
|
||||
international Spanish; every `es-*` locale such as `es-ES`, `es-MX`, `es-AR` or `es-419` resolves to it), Italian (`it`,
|
||||
international Spanish; every `es-*` locale such as `es-ES`, `es-MX`, `es-AR` or `es-419` resolves to it), French (`fr`,
|
||||
complete; `fr-FR`, `fr-BE`, `fr-CA`, `fr-CH` and every other `fr-*` locale resolve to it), Italian (`it`,
|
||||
complete; `it-IT`, `it-CH` and every other `it-*` locale resolve to it), Russian (`ru`, complete; every `ru-*`
|
||||
locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Czech (`cs`, every menu label) and Brazilian Portuguese
|
||||
(`pt-br`, every menu label and every `tl!` literal). Untranslated text falls back to English until its rows are added.
|
||||
@@ -164,10 +165,10 @@ locale such as `ru-RU`, `ru-BY` or `ru-KZ` resolves to it), Czech (`cs`, every m
|
||||
control channel, MCP and tests read them) and are translated only where the status bar draws them
|
||||
(`i18n::msg`). `@msg` catalog rows hold a whole message or a template such as
|
||||
`Couldn't open {name}: {e}`; `{_1}`, `{_2}` … stand for the format string's `{}`, and the values in the
|
||||
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, Italian and Russian cover every
|
||||
placeholders are translated in turn (the reason after `: {e}` is often a message too). Spanish, French, Italian and Russian cover every
|
||||
message literal the test scan finds (`complete_languages_translate_every_message`, languages listed in
|
||||
`COMPLETE_MESSAGES`): a new `Err("…")`, `Other(…)`, `#[error(…)]` or `status(…)` message needs an `es.tsv`,
|
||||
an `it.tsv` and a `ru.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
|
||||
a `fr.tsv`, an `it.tsv` and a `ru.tsv` row (`VECTORCRAFT_I18N_DUMP_MESSAGES=messages.txt cargo test -p vectorcraft-ui-egui
|
||||
complete_languages_translate_every_message` lists them all). Other languages show messages in English
|
||||
until they add `@msg` rows.
|
||||
- Not translated on purpose: names that are user data (layers, swatches, fonts, documents), the tab
|
||||
|
||||
+39
@@ -775,6 +775,31 @@ some characters, use `text.setRangeStyle {id, start, end, strokeOptions: {weight
|
||||
dashOffset?, alignDashes?}}`. `inspect_document` reports each object's stroke as `strokeOptions` (type: its first
|
||||
run's) in `stroke.set` terms. `stroke.set` on a group leaves the images and symbol instances in it alone.
|
||||
|
||||
## Inline graphics in type
|
||||
|
||||
A document symbol can sit in a line of type like a character (beyond Illustrator; like InDesign's inline
|
||||
anchored objects), e.g. mana symbols in card rules text. `text.insertInline {id?, at?, symbol?, scale?: 1,
|
||||
shift?: 0}` inserts one at byte offset `at` (default: the Type tool's selection, which it replaces) of text `id`
|
||||
(default: the text being edited), showing `symbol` (default: the Symbols panel's current symbol) → `{id, caret}`;
|
||||
Type → Insert Inline Symbol does the same at the caret. The graphic is one character, U+FFFC, in a run of its own:
|
||||
`text.getRange` reports it as `{text: "\uFFFC", style, inline: {symbol, scale, baseline_shift}}`, plain text (and
|
||||
copied text) shows U+FFFC, and `text.editRange` with styled `runs` can insert one. Typing over it, Backspace and
|
||||
Delete remove it whole; neighbouring text never merges into it.
|
||||
|
||||
Layout: the art is scaled uniformly to `scale` × the run's font size tall, its left edge on the pen and its
|
||||
vertical centre on the middle of the cap height raised by `shift` points. Its advance is the scaled art width plus
|
||||
the run's tracking, so it breaks like a word (no break between it and punctuation stuck to it) and justifies like
|
||||
a glyph; a graphic taller than the font's ascent or descent opens up its line. Its art follows the symbol
|
||||
(Redefine Symbol resizes it); a missing or deleted symbol leaves an empty slot one em square that draws nothing.
|
||||
Its em box is its run's, whatever its scale: Character Alignment moves it with its run's text (it is one of
|
||||
the line's largest characters only when its run's size is), and Top-to-Top leading spaces its line by its run's
|
||||
em box (Roman leading by its run's leading). In right-to-left text it is a bidi neutral (U+FFFC): it takes the
|
||||
direction of the text around it and the line's reordering places it.
|
||||
The canvas draws the art inside the type's transparency (its opacity and blend mode apply). SVG keeps the text live
|
||||
(the text after a graphic is positioned after it) and writes each graphic as a `<use>` of the symbol's `<symbol>`
|
||||
def (or a copy of its art); type on a path with graphics is written as outlines. PDF draws the art as vector paths
|
||||
where the layout puts it.
|
||||
|
||||
## Flatten Transparency
|
||||
|
||||
`object.flattenTransparency {ids?, preset?, …options}` turns transparent art into opaque art that looks the same, in
|
||||
@@ -857,6 +882,7 @@ and `layerRows`, the rows highlighted in the panel.
|
||||
dimImages, dimPercent; OK is one undo step), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`:
|
||||
layersOnly, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and
|
||||
`ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside).
|
||||
A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"layer.newSublayer","params":{"name":"Shadows"}}}
|
||||
@@ -2274,6 +2300,19 @@ undo step.
|
||||
{"name":"run_command","arguments":{"command":"text.setFormat","params":{"burasagari":"forced"}}}
|
||||
```
|
||||
|
||||
## Character Alignment
|
||||
|
||||
`text.setFormat {charAlign}` (the selected type, or `ids`) and `text.setRangeStyle {id, start, end, charAlign}` (a range)
|
||||
set where characters smaller than the largest on their line line up with it: `romanBaseline` (the default), the em box's
|
||||
`emBoxTop`, `emBoxCenter` or `emBoxBottom`, or the ideographic character face's (ICF) `icfTop` or `icfBottom`. In
|
||||
vertical type top and bottom are the right and left of the column. The ICF comes from the font's BASE table (`icfb`,
|
||||
`icft`, as the OpenType baseline tags define them), else from the average ink box of some ideographs and kana; a font
|
||||
without ideographs uses its em box. One undo step.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"text.setFormat","params":{"charAlign":"icfTop"}}}
|
||||
```
|
||||
|
||||
## New type in a Japanese interface
|
||||
|
||||
While the interface is in Japanese (VectorCraft › Language, or `auto` on a Japanese system), new type starts with em
|
||||
|
||||
Reference in new issue
Block a user